Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
[Feat]: Add OpenTelemetry Monitoring Instrumentation for MCP (#858)
Patcher83d56fe91004
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.tomlindex 4ed360f9..2fecfe7d 100644--- a/sdk/python/pyproject.toml+++ b/sdk/python/pyproject.toml@@ -1,6 +1,6 @@[tool.poetry]name = "openlit"-version = "1.35.0"+version = "1.35.1"description = "OpenTelemetry-native Auto instrumentation library for monitoring LLM Applications and GPUs, facilitating the integration of observability into your GenAI-driven projects"authors = ["OpenLIT"]license = "Apache-2.0"diff --git a/sdk/python/src/openlit/__helpers.py b/sdk/python/src/openlit/__helpers.pyindex d5ea7046..820d96b9 100644--- a/sdk/python/src/openlit/__helpers.py+++ b/sdk/python/src/openlit/__helpers.py@@ -619,6 +619,151 @@ def common_framework_span_attributes()+def record_mcp_metrics(+ metrics,+ mcp_operation,+ mcp_method,+ mcp_transport_type,+ mcp_tool_name,+ mcp_resource_uri,+ mcp_resource_name,+ mcp_prompt_name,+ environment,+ application_name,+ start_time,+ end_time,+ request_size=None,+ response_size=None,+ is_error=False,+):+ """+ Records MCP-specific metrics for business intelligence and operational insights.++ Args:+ metrics: Dictionary of meter instruments+ mcp_operation: The MCP operation type (tools/list, tools/call, etc.)+ mcp_method: The specific MCP method name+ mcp_transport_type: Transport type (stdio, sse, websocket)+ mcp_tool_name: Tool name for tool operations+ mcp_resource_uri: Resource URI for resource operations+ mcp_resource_name: Resource name for resource operations+ mcp_prompt_name: Prompt name for prompt operations+ environment: Deployment environment+ application_name: Application name+ start_time: Operation start time+ end_time: Operation end time+ request_size: Request payload size in bytes+ response_size: Response payload size in bytes+ is_error: Whether the operation resulted in an error+ """+ if not metrics:+ return++ try:+ # Calculate operation duration+ duration = end_time - start_time++ # Enhanced attributes for all MCP metrics with full business intelligence+ enhanced_attributes = {+ TELEMETRY_SDK_NAME: "openlit",+ SERVICE_NAME: application_name, # Server application name+ DEPLOYMENT_ENVIRONMENT: environment,+ SemanticConvention.MCP_OPERATION: mcp_operation,+ SemanticConvention.MCP_METHOD: mcp_method,+ SemanticConvention.MCP_SYSTEM: "mcp",+ }++ # Add transport type if available+ if mcp_transport_type:+ enhanced_attributes[SemanticConvention.MCP_TRANSPORT_TYPE] = str(+ mcp_transport_type+ )++ # Add tool name to ALL metrics for complete business intelligence+ if mcp_tool_name:+ enhanced_attributes[SemanticConvention.MCP_TOOL_NAME] = str(mcp_tool_name)++ # Add resource URI and name to ALL metrics when available+ if mcp_resource_uri:+ enhanced_attributes[SemanticConvention.MCP_RESOURCE_URI] = str(+ mcp_resource_uri+ )+ if mcp_resource_name:+ enhanced_attributes[SemanticConvention.MCP_RESOURCE_NAME] = str(+ mcp_resource_name+ )++ # Add prompt name to ALL metrics when available+ if mcp_prompt_name:+ enhanced_attributes[SemanticConvention.MCP_PROMPT_NAME] = str(+ mcp_prompt_name+ )++ # Add client identification when possible+ # Note: In MCP, the "server" generates metrics but serves "clients"+ # We can try to identify the client from transport or add explicit client tracking+ if mcp_transport_type == "stdio":+ # For stdio transport, client spawns server as subprocess+ enhanced_attributes[SemanticConvention.MCP_CLIENT_TYPE] = "external_spawn"+ elif mcp_transport_type in ["websocket", "sse"]:+ # For network transports, client connects to running server+ enhanced_attributes[SemanticConvention.MCP_CLIENT_TYPE] = "network_client"++ # Record general MCP request count (now with tool name when available)+ if "mcp_requests" in metrics:+ metrics["mcp_requests"].add(1, enhanced_attributes)++ # Record operation duration (now with tool name for tool-specific performance analysis)+ if "mcp_client_operation_duration" in metrics:+ metrics["mcp_client_operation_duration"].record(+ duration, enhanced_attributes+ )++ # Record request size (now with tool name for payload analysis by tool)+ if request_size and "mcp_request_size" in metrics:+ metrics["mcp_request_size"].record(request_size, enhanced_attributes)++ # Record response size (now with tool name for response size analysis by tool)+ if response_size and "mcp_response_size" in metrics:+ metrics["mcp_response_size"].record(response_size, enhanced_attributes)++ # Record transport usage (now with enhanced context)+ if "mcp_transport_usage" in metrics and mcp_transport_type:+ metrics["mcp_transport_usage"].add(1, enhanced_attributes)++ # Record tool-specific metrics (tool name already in enhanced_attributes)+ if mcp_tool_name and "mcp_tool_calls" in metrics:+ metrics["mcp_tool_calls"].add(1, enhanced_attributes)++ # Record resource-specific metrics (resource URI already in enhanced_attributes)+ if mcp_resource_uri and "mcp_resource_reads" in metrics:+ metrics["mcp_resource_reads"].add(1, enhanced_attributes)++ # Record prompt-specific metrics (prompt name already in enhanced_attributes)+ if mcp_prompt_name and "mcp_prompt_gets" in metrics:+ metrics["mcp_prompt_gets"].add(1, enhanced_attributes)++ # Record error metrics for ALL operations (1 for error, 0 for success)+ if "mcp_errors" in metrics:+ error_count = 1 if is_error else 0+ error_attributes = {+ **enhanced_attributes,+ "mcp.error": is_error,+ }+ metrics["mcp_errors"].add(error_count, error_attributes)++ # Record success rate (now with tool name for tool-specific success rate analysis)+ if "mcp_operation_success_rate" in metrics:+ success_rate = 0.0 if is_error else 1.0+ metrics["mcp_operation_success_rate"].record(+ success_rate, enhanced_attributes+ )++ except Exception:+ # Silently ignore metrics recording errors+ pass++def record_framework_metrics(metrics,gen_ai_operation,diff --git a/sdk/python/src/openlit/_instrumentors.py b/sdk/python/src/openlit/_instrumentors.pyindex 8e0ed46a..e2fdc3ca 100644--- a/sdk/python/src/openlit/_instrumentors.py+++ b/sdk/python/src/openlit/_instrumentors.py@@ -53,6 +53,7 @@ MODULE_NAME_MAP = {"pydantic_ai": "pydantic_ai","sarvam": "sarvamai","browser-use": "browser_use",+ "mcp": "mcp",# Official OpenTelemetry HTTP Framework instrumentations"asgi": "asgiref","django": "django",@@ -119,6 +120,7 @@ INSTRUMENTOR_MAP = {"pydantic_ai": "openlit.instrumentation.pydantic_ai.PydanticAIInstrumentor","sarvam": "openlit.instrumentation.sarvam.SarvamInstrumentor","browser-use": "openlit.instrumentation.browser_use.BrowserUseInstrumentor",+ "mcp": "openlit.instrumentation.mcp.MCPInstrumentor",# Official OpenTelemetry HTTP Framework instrumentations"asgi": "opentelemetry.instrumentation.asgi.AsgiInstrumentor","django": "opentelemetry.instrumentation.django.DjangoInstrumentor",diff --git a/sdk/python/src/openlit/instrumentation/langchain/__init__.py b/sdk/python/src/openlit/instrumentation/langchain/__init__.pyindex 75b99ca4..d8fcbfc6 100644--- a/sdk/python/src/openlit/instrumentation/langchain/__init__.py+++ b/sdk/python/src/openlit/instrumentation/langchain/__init__.py@@ -85,14 +85,6 @@ class LangChainInstrumentor(BaseInstrumentor):# Graceful degradation if callback system unavailablepass- # === COMPETITIVE ADVANTAGE SUMMARY ===- # Callback-based approach provides:- # 1. ✅ Proper span hierarchy (like OpenLLMetry/OpenInference)- # 2. ✅ Comprehensive business intelligence (cost, tokens, performance)- # 3. ✅ Automatic operation coverage (no manual function wrapping)- # 4. ✅ Native LangChain integration (uses built-in callback system)- # 5. ✅ Superior observability depth and quality-# Result: Best of both worlds - hierarchy + business intelligencedef _uninstrument(self, **kwargs):diff --git a/sdk/python/src/openlit/instrumentation/mcp/__init__.py b/sdk/python/src/openlit/instrumentation/mcp/__init__.pynew file mode 100644index 00000000..93b28553--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/mcp/__init__.py@@ -0,0 +1,635 @@+# pylint: disable=useless-return, bad-staticmethod-argument, disable=duplicate-code+"""+Optimized Auto Instrumentation of MCP (Model Context Protocol) Functions following OpenLIT Framework Guide.+"""++from typing import Collection+import importlib.metadata+from opentelemetry.instrumentation.instrumentor import BaseInstrumentor+from wrapt import wrap_function_wrapper++from openlit.instrumentation.mcp.mcp import mcp_wrap+from openlit.instrumentation.mcp.async_mcp import async_mcp_wrap+from openlit.instrumentation.mcp.utils import (+ create_jsonrpc_wrapper,+ create_context_propagating_wrapper,+)++_instruments = ("mcp >= 0.1.0",)++# This ensures proper async handling and response capture+CORE_JSONRPC_METHODS = [+ {+ "package": "mcp.shared.session",+ "object": "BaseSession.send_request",+ "endpoint": "jsonrpc send_request",+ "priority": "critical",+ "wrapper_type": "jsonrpc",+ },+]++# Updated method configuration for current MCP API (v1.13.1+)+SYNC_METHODS = [+ # === CRITICAL SERVER OPERATIONS ===+ {+ "package": "mcp.server",+ "object": "Server.run",+ "endpoint": "server run",+ "priority": "critical",+ },+ {+ "package": "mcp.server",+ "object": "Server.call_tool",+ "endpoint": "server call_tool",+ "priority": "high",+ },+ {+ "package": "mcp.server",+ "object": "Server.list_tools",+ "endpoint": "server list_tools",+ "priority": "high",+ },+ {+ "package": "mcp.server",+ "object": "Server.read_resource",+ "endpoint": "server read_resource",+ "priority": "high",+ },+ {+ "package": "mcp.server",+ "object": "Server.list_resources",+ "endpoint": "server list_resources",+ "priority": "high",+ },+ # === CRITICAL CLIENT OPERATIONS ===+ {+ "package": "mcp.client.session",+ "object": "ClientSession.initialize",+ "endpoint": "client initialize",+ "priority": "critical",+ },+ {+ "package": "mcp.client.session",+ "object": "ClientSession.call_tool",+ "endpoint": "client call_tool",+ "priority": "high",+ },+ {+ "package": "mcp.client.session",+ "object": "ClientSession.list_tools",+ "endpoint": "client list_tools",+ "priority": "high",+ },+ {+ "package": "mcp.client.session",+ "object": "ClientSession.read_resource",+ "endpoint": "client read_resource",+ "priority": "high",+ },+ {+ "package": "mcp.client.session",+ "object": "ClientSession.list_resources",+ "endpoint": "client list_resources",+ "priority": "high",+ },+ # === TRANSPORT LAYER OPERATIONS ===+ {+ "package": "mcp.client.stdio",+ "object": "stdio_client",+ "endpoint": "transport stdio_client",+ "priority": "high",+ },+ {+ "package": "mcp.server.stdio",+ "object": "stdio_server",+ "endpoint": "transport stdio_server",+ "priority": "high",+ },+ {+ "package": "mcp.client.sse",+ "object": "sse_client",+ "endpoint": "transport sse_client",+ "priority": "high",+ },+ {+ "package": "mcp.server.sse",+ "object": "SseServerTransport.connect_sse",+ "endpoint": "transport sse_server",+ "priority": "high",+ },+ {+ "package": "mcp.client.streamable_http",+ "object": "streamablehttp_client",+ "endpoint": "transport http_client",+ "priority": "high",+ },+ {+ "package": "mcp.server.streamable_http",+ "object": "StreamableHTTPServerTransport.connect",+ "endpoint": "transport http_server",+ "priority": "high",+ },+ # === SERVER SESSION OPERATIONS ===+ {+ "package": "mcp.server.session",+ "object": "ServerSession.__init__",+ "endpoint": "session init",+ "priority": "high",+ },+ {+ "package": "mcp.server.session",+ "object": "ServerSession.send_request",+ "endpoint": "server send_request",+ "priority": "high",+ },+ {+ "package": "mcp.server.session",+ "object": "ServerSession.send_notification",+ "endpoint": "server send_notification",+ "priority": "medium",+ },+ {+ "package": "mcp.server.session",+ "object": "ServerSession.send_log_message",+ "endpoint": "server send_log",+ "priority": "medium",+ },+ # === FASTMCP FRAMEWORK OPERATIONS ===+ {+ "package": "mcp.server.fastmcp.server",+ "object": "FastMCP.run",+ "endpoint": "fastmcp run",+ "priority": "critical",+ },+ {+ "package": "mcp.server.fastmcp.server",+ "object": "FastMCP.add_tool",+ "endpoint": "fastmcp add_tool",+ "priority": "high",+ },+ {+ "package": "mcp.server.fastmcp.server",+ "object": "FastMCP.add_resource",+ "endpoint": "fastmcp add_resource",+ "priority": "high",+ },+ {+ "package": "mcp.server.fastmcp.server",+ "object": "FastMCP.add_prompt",+ "endpoint": "fastmcp add_prompt",+ "priority": "high",+ },+ {+ "package": "mcp.server.fastmcp.server",+ "object": "FastMCP.call_tool",+ "endpoint": "fastmcp call_tool",+ "priority": "high",+ },+ {+ "package": "mcp.server.fastmcp.server",+ "object": "FastMCP.read_resource",+ "endpoint": "fastmcp read_resource",+ "priority": "high",+ },+ {+ "package": "mcp.server.fastmcp.server",+ "object": "FastMCP.get_prompt",+ "endpoint": "fastmcp get_prompt",+ "priority": "high",+ },+ # === MANAGER-LEVEL OPERATIONS ===+ {+ "package": "mcp.server.fastmcp.tools.tool_manager",+ "object": "ToolManager.call_tool",+ "endpoint": "manager call_tool",+ "priority": "high",+ },+ {+ "package": "mcp.server.fastmcp.resources.resource_manager",+ "object": "ResourceManager.get_resource",+ "endpoint": "manager get_resource",+ "priority": "high",+ },+ {+ "package": "mcp.server.fastmcp.prompts.manager",+ "object": "PromptManager.render_prompt",+ "endpoint": "manager render_prompt",+ "priority": "high",+ },+ # === WEBSOCKET TRANSPORT OPERATIONS ===+ {+ "package": "mcp.client.websocket",+ "object": "websocket_client",+ "endpoint": "transport websocket_client",+ "priority": "high",+ },+ {+ "package": "mcp.server.websocket",+ "object": "websocket_server",+ "endpoint": "transport websocket_server",+ "priority": "high",+ },+ # === AUTHENTICATION & SECURITY OPERATIONS ===+ {+ "package": "mcp.server.auth.provider",+ "object": "OAuthAuthorizationServerProvider.authorize",+ "endpoint": "auth authorize",+ "priority": "high",+ },+ {+ "package": "mcp.server.auth.provider",+ "object": "OAuthAuthorizationServerProvider.exchange_authorization_code",+ "endpoint": "auth exchange_code",+ "priority": "high",+ },+ {+ "package": "mcp.server.auth.provider",+ "object": "TokenVerifier.verify_token",+ "endpoint": "auth verify_token",+ "priority": "high",+ },+ # === ADVANCED CLIENT OPERATIONS ===+ {+ "package": "mcp.client.session",+ "object": "ClientSession.send_ping",+ "endpoint": "client ping",+ "priority": "medium",+ },+ {+ "package": "mcp.client.session",+ "object": "ClientSession.set_logging_level",+ "endpoint": "client set_logging",+ "priority": "medium",+ },+ {+ "package": "mcp.client.session",+ "object": "ClientSession.send_progress_notification",+ "endpoint": "client progress",+ "priority": "medium",+ },+ {+ "package": "mcp.client.session",+ "object": "ClientSession.complete",+ "endpoint": "client complete",+ "priority": "medium",+ },+ # === MEMORY & PROGRESS OPERATIONS ===+ {+ "package": "mcp.shared.memory",+ "object": "create_connected_server_and_client_session",+ "endpoint": "memory connect",+ "priority": "medium",+ },+ {+ "package": "mcp.shared.progress",+ "object": "ProgressContext.progress",+ "endpoint": "progress update",+ "priority": "low",+ },+]++ASYNC_METHODS = [+ # === CRITICAL ASYNC CLIENT OPERATIONS ===+ {+ "package": "mcp.client.session",+ "object": "ClientSession.call_tool",+ "endpoint": "client call_tool",+ "priority": "high",+ },+ {+ "package": "mcp.client.session",+ "object": "ClientSession.list_tools",+ "endpoint": "client list_tools",+ "priority": "high",+ },+ {+ "package": "mcp.client.session",+ "object": "ClientSession.read_resource",+ "endpoint": "client read_resource",+ "priority": "high",+ },+ {+ "package": "mcp.client.session",+ "object": "ClientSession.list_resources",+ "endpoint": "client list_resources",+ "priority": "high",+ },+ {+ "package": "mcp.client.session",+ "object": "ClientSession.initialize",+ "endpoint": "client initialize",+ "priority": "critical",+ },+ {+ "package": "mcp.client.session",+ "object": "ClientSession.send_request",+ "endpoint": "client send_request",+ "priority": "critical",+ },+ # === ASYNC TRANSPORT LAYER OPERATIONS ===+ {+ "package": "mcp.client.stdio",+ "object": "stdio_client",+ "endpoint": "transport stdio_client",+ "priority": "high",+ },+ {+ "package": "mcp.server.stdio",+ "object": "stdio_server",+ "endpoint": "transport stdio_server",+ "priority": "high",+ },+ {+ "package": "mcp.client.sse",+ "object": "sse_client",+ "endpoint": "transport sse_client",+ "priority": "high",+ },+ {+ "package": "mcp.server.sse",+ "object": "SseServerTransport.connect_sse",+ "endpoint": "transport sse_server",+ "priority": "high",+ },+ {+ "package": "mcp.client.streamable_http",+ "object": "streamablehttp_client",+ "endpoint": "transport http_client",+ "priority": "high",+ },+ {+ "package": "mcp.server.streamable_http",+ "object": "StreamableHTTPServerTransport.connect",+ "endpoint": "transport http_server",+ "priority": "high",+ },+ # === CRITICAL ASYNC SERVER OPERATIONS ===+ {+ "package": "mcp.server",+ "object": "Server.run",+ "endpoint": "server run",+ "priority": "critical",+ },+ # === ASYNC SERVER SESSION OPERATIONS ===+ {+ "package": "mcp.server.session",+ "object": "ServerSession.send_request",+ "endpoint": "server send_request",+ "priority": "high",+ },+ {+ "package": "mcp.server.session",+ "object": "ServerSession.send_notification",+ "endpoint": "server send_notification",+ "priority": "medium",+ },+ {+ "package": "mcp.server.session",+ "object": "ServerSession.send_log_message",+ "endpoint": "server send_log",+ "priority": "medium",+ },+ # === ASYNC FASTMCP FRAMEWORK OPERATIONS ===+ {+ "package": "mcp.server.fastmcp.server",+ "object": "FastMCP.call_tool",+ "endpoint": "fastmcp call_tool",+ "priority": "high",+ },+ {+ "package": "mcp.server.fastmcp.server",+ "object": "FastMCP.read_resource",+ "endpoint": "fastmcp read_resource",+ "priority": "high",+ },+ {+ "package": "mcp.server.fastmcp.server",+ "object": "FastMCP.get_prompt",+ "endpoint": "fastmcp get_prompt",+ "priority": "high",+ },+ # === ASYNC MANAGER-LEVEL OPERATIONS ===+ {+ "package": "mcp.server.fastmcp.tools.tool_manager",+ "object": "ToolManager.call_tool",+ "endpoint": "manager call_tool",+ "priority": "high",+ },+ {+ "package": "mcp.server.fastmcp.resources.resource_manager",+ "object": "ResourceManager.get_resource",+ "endpoint": "manager get_resource",+ "priority": "high",+ },+ {+ "package": "mcp.server.fastmcp.prompts.manager",+ "object": "PromptManager.render_prompt",+ "endpoint": "manager render_prompt",+ "priority": "high",+ },+ # === ASYNC WEBSOCKET TRANSPORT OPERATIONS ===+ {+ "package": "mcp.client.websocket",+ "object": "websocket_client",+ "endpoint": "transport websocket_client",+ "priority": "high",+ },+ {+ "package": "mcp.server.websocket",+ "object": "websocket_server",+ "endpoint": "transport websocket_server",+ "priority": "high",+ },+ # === ASYNC AUTHENTICATION & SECURITY OPERATIONS ===+ {+ "package": "mcp.server.auth.provider",+ "object": "OAuthAuthorizationServerProvider.authorize",+ "endpoint": "auth authorize",+ "priority": "high",+ },+ {+ "package": "mcp.server.auth.provider",+ "object": "OAuthAuthorizationServerProvider.exchange_authorization_code",+ "endpoint": "auth exchange_code",+ "priority": "high",+ },+ {+ "package": "mcp.server.auth.provider",+ "object": "TokenVerifier.verify_token",+ "endpoint": "auth verify_token",+ "priority": "high",+ },+ # === ASYNC ADVANCED CLIENT OPERATIONS ===+ {+ "package": "mcp.client.session",+ "object": "ClientSession.send_ping",+ "endpoint": "client ping",+ "priority": "medium",+ },+ {+ "package": "mcp.client.session",+ "object": "ClientSession.set_logging_level",+ "endpoint": "client set_logging",+ "priority": "medium",+ },+ {+ "package": "mcp.client.session",+ "object": "ClientSession.send_progress_notification",+ "endpoint": "client progress",+ "priority": "medium",+ },+ {+ "package": "mcp.client.session",+ "object": "ClientSession.complete",+ "endpoint": "client complete",+ "priority": "medium",+ },+ # === ASYNC MEMORY & PROGRESS OPERATIONS ===+ {+ "package": "mcp.shared.memory",+ "object": "create_connected_server_and_client_session",+ "endpoint": "memory connect",+ "priority": "medium",+ },+ {+ "package": "mcp.shared.progress",+ "object": "ProgressContext.progress",+ "endpoint": "progress update",+ "priority": "low",+ },+]+++class MCPInstrumentor(BaseInstrumentor):+ """Optimized instrumentor for MCP's client and server libraries."""++ def instrumentation_dependencies(self) -> Collection[str]:+ return _instruments++ def _instrument(self, **kwargs):+ """Optimized instrumentation with performance considerations and detailed tracing support."""+ # Extract configuration+ application_name = kwargs.get("application_name")+ environment = kwargs.get("environment")+ tracer = kwargs.get("tracer")+ pricing_info = kwargs.get("pricing_info")+ capture_message_content = kwargs.get("capture_message_content")+ metrics = kwargs.get("metrics_dict")+ disable_metrics = kwargs.get("disable_metrics")+ detailed_tracing = kwargs.get("detailed_tracing", True)++ # Cache version lookup+ try:+ version = importlib.metadata.version("mcp")+ except importlib.metadata.PackageNotFoundError:+ version = "unknown"++ # Pre-create wrapper args+ wrapper_args = (+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )++ # Always instrument critical server/client methods first+ critical_methods = [m for m in SYNC_METHODS if m["priority"] == "critical"]+ async_critical_methods = [+ m for m in ASYNC_METHODS if m["priority"] == "critical"+ ]++ self._wrap_methods(critical_methods, mcp_wrap, wrapper_args)+ self._wrap_methods(async_critical_methods, async_mcp_wrap, wrapper_args)++ # Then try JSONRPC wrapper for BaseSession.send_request+ try:+ wrap_function_wrapper(+ "mcp.shared.session",+ "BaseSession.send_request",+ create_jsonrpc_wrapper(+ "jsonrpc send_request", # endpoint+ *wrapper_args,+ ),+ )+ except (ImportError, AttributeError):+ pass++ # Separate transport methods for context propagation+ transport_methods = [+ m+ for m in SYNC_METHODS+ if m["priority"] == "high" and "transport" in m["endpoint"]+ ]+ async_transport_methods = [+ m+ for m in ASYNC_METHODS+ if m["priority"] == "high" and "transport" in m["endpoint"]+ ]++ # Regular high-priority methods (non-transport)+ high_priority_methods = [+ m+ for m in SYNC_METHODS+ if m["priority"] == "high" and "transport" not in m["endpoint"]+ ]+ async_high_priority_methods = [+ m+ for m in ASYNC_METHODS+ if m["priority"] == "high" and "transport" not in m["endpoint"]+ ]++ # Instrument transport methods with context propagation+ self._wrap_transport_methods(transport_methods, wrapper_args)+ self._wrap_transport_methods(async_transport_methods, wrapper_args)++ # Instrument regular methods with standard wrappers+ self._wrap_methods(high_priority_methods, mcp_wrap, wrapper_args)+ self._wrap_methods(async_high_priority_methods, async_mcp_wrap, wrapper_args)++ # Only instrument component operations if detailed_tracing is enabled+ if detailed_tracing:+ component_methods = [+ m for m in SYNC_METHODS if m["priority"] in ["medium", "low"]+ ]+ async_component_methods = [+ m for m in ASYNC_METHODS if m["priority"] in ["medium", "low"]+ ]++ self._wrap_methods(component_methods, mcp_wrap, wrapper_args)+ self._wrap_methods(async_component_methods, async_mcp_wrap, wrapper_args)++ def _wrap_methods(self, methods, wrapper_func, wrapper_args):+ """Efficiently wrap methods with error handling following OpenLIT patterns."""+ for method_config in methods:+ try:+ wrap_function_wrapper(+ method_config["package"],+ method_config["object"],+ wrapper_func(method_config["endpoint"], *wrapper_args),+ )+ except (ImportError, AttributeError):+ # Gracefully handle missing methods in different MCP versions+ pass++ def _wrap_transport_methods(self, methods, wrapper_args):+ """Wrap transport methods with context propagation for cross-client-server span linking."""+ for method_config in methods:+ try:+ wrap_function_wrapper(+ method_config["package"],+ method_config["object"],+ create_context_propagating_wrapper(+ method_config["endpoint"], *wrapper_args+ ),+ )+ except (ImportError, AttributeError):+ # Gracefully handle missing transport methods in different MCP versions+ pass++ def _uninstrument(self, **kwargs):+ """Uninstrument MCP."""+ # Currently no cleanup neededdiff --git a/sdk/python/src/openlit/instrumentation/mcp/async_mcp.py b/sdk/python/src/openlit/instrumentation/mcp/async_mcp.pynew file mode 100644index 00000000..2461d263--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/mcp/async_mcp.py@@ -0,0 +1,495 @@+# pylint: disable=broad-exception-caught+"""+Asynchronous MCP (Model Context Protocol) instrumentation with proper async context handling.+"""++import time+from opentelemetry.trace import SpanKind+from opentelemetry import context as context_api++from openlit.semcov import SemanticConvention+from openlit.__helpers import handle_exception, record_mcp_metrics+from openlit.instrumentation.mcp.utils import (+ MCPInstrumentationContext,+ set_mcp_span_attributes,+ process_mcp_response,+ create_mcp_scope,+ _simplify_operation_name,+)+++def async_mcp_wrap(+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """+ Generates a telemetry wrapper for async MCP operations.+ """++ def wrapper(wrapped, instance, args, kwargs):+ """+ Wraps async MCP operations with comprehensive telemetry and business intelligence.+ """++ async def async_wrapper():+ # CRITICAL: Check for suppression to avoid infinite recursion+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return await wrapped(*args, **kwargs)++ # Determine span kind based on operation type+ span_kind = SpanKind.CLIENT+ if (+ "server" in gen_ai_endpoint.lower()+ or "transport" in gen_ai_endpoint.lower()+ ):+ span_kind = SpanKind.SERVER++ # Create instrumentation context for caching expensive operations+ ctx = MCPInstrumentationContext(+ instance=instance,+ args=args,+ kwargs=kwargs,+ version=version,+ environment=environment,+ application_name=application_name,+ pricing_info=pricing_info,+ capture_message_content=capture_message_content,+ )++ # Create span name following OpenLIT convention: "{operation_type} {operation_name}"+ operation_type = (+ gen_ai_endpoint.split()[0] if " " in gen_ai_endpoint else "mcp"+ )+ span_name = ctx.get_enhanced_span_name(operation_type)++ with tracer.start_as_current_span(span_name, kind=span_kind) as span:+ start_time = time.time()++ # Create scope object for common span attributes+ scope = create_mcp_scope(+ instance=instance,+ args=args,+ kwargs=kwargs,+ version=version,+ environment=environment,+ application_name=application_name,+ pricing_info=pricing_info,+ capture_message_content=capture_message_content,+ span=span,+ start_time=start_time,+ )++ # Set initial span attributes+ try:+ set_mcp_span_attributes(+ span=span,+ operation_name=gen_ai_endpoint,+ ctx=ctx,+ endpoint=gen_ai_endpoint,+ **kwargs,+ )+ except Exception as e:+ handle_exception(span, e)++ # Execute the wrapped async function+ response = None+ error = None++ try:+ # Async MCP operations - maintain proper async context+ response = await wrapped(*args, **kwargs)++ except Exception as e:+ error = e+ handle_exception(span, e)++ # Record error metrics+ if metrics and not disable_metrics:+ end_time = time.time()+ mcp_operation = _simplify_operation_name(gen_ai_endpoint)+ mcp_method = (+ ctx.method_name or gen_ai_endpoint.split()[-1]+ if " " in gen_ai_endpoint+ else gen_ai_endpoint+ )++ record_mcp_metrics(+ metrics=metrics,+ mcp_operation=mcp_operation,+ mcp_method=mcp_method,+ mcp_transport_type="stdio",+ mcp_tool_name=kwargs.get("tool_name") or kwargs.get("name")+ if "tool" in gen_ai_endpoint.lower()+ else None,+ mcp_resource_uri=kwargs.get("resource_uri")+ or kwargs.get("uri")+ if "resource" in gen_ai_endpoint.lower()+ else None,+ mcp_resource_name=kwargs.get("resource_name")+ or kwargs.get("name")+ if "resource" in gen_ai_endpoint.lower()+ else None,+ mcp_prompt_name=kwargs.get("prompt_name")+ or kwargs.get("name")+ if "prompt" in gen_ai_endpoint.lower()+ else None,+ environment=environment,+ application_name=application_name,+ start_time=start_time,+ end_time=end_time,+ is_error=True,+ )+ raise+ finally:+ # Process response and capture telemetry+ try:+ scope._end_time = time.time()++ if response is not None:+ response = process_mcp_response(+ response=response,+ ctx=ctx,+ span=span,+ start_time=start_time,+ endpoint=gen_ai_endpoint,+ metrics=metrics,+ disable_metrics=disable_metrics,+ **kwargs,+ )++ # Update span attributes with error info if needed+ if error:+ set_mcp_span_attributes(+ span=span,+ operation_name=gen_ai_endpoint,+ ctx=ctx,+ endpoint=gen_ai_endpoint,+ error=error,+ **kwargs,+ )++ except Exception as e:+ handle_exception(span, e)++ return response++ return async_wrapper()++ return wrapper+++def async_mcp_tool_call_wrap(+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """+ Specialized wrapper for async MCP tool call operations with enhanced telemetry.+ """++ def wrapper(wrapped, instance, args, kwargs):+ """+ Wraps async MCP tool call operations with tool-specific telemetry.+ """++ async def async_wrapper():+ # CRITICAL: Check for suppression+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return await wrapped(*args, **kwargs)++ # Create instrumentation context+ ctx = MCPInstrumentationContext(+ instance=instance,+ args=args,+ kwargs=kwargs,+ version=version,+ environment=environment,+ application_name=application_name,+ pricing_info=pricing_info,+ capture_message_content=capture_message_content,+ )++ # Enhanced span name for tool calls+ span_name = ctx.get_enhanced_span_name("tool")++ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:+ start_time = time.time()++ # Set tool-specific attributes+ try:+ set_mcp_span_attributes(+ span=span,+ operation_name=gen_ai_endpoint,+ ctx=ctx,+ endpoint=gen_ai_endpoint,+ **kwargs,+ )++ # Additional tool-specific attributes+ if ctx.tool_name:+ span.set_attribute(+ SemanticConvention.MCP_TOOL_NAME, ctx.tool_name+ )++ except Exception as e:+ handle_exception(span, e)++ # Execute async tool call+ response = None+ try:+ response = await wrapped(*args, **kwargs)++ # Capture tool result if available+ if response and capture_message_content:+ try:+ if hasattr(response, "content"):+ span.set_attribute(+ SemanticConvention.MCP_TOOL_RESULT,+ str(response.content),+ )+ elif isinstance(response, (str, dict, list)):+ span.set_attribute(+ SemanticConvention.MCP_TOOL_RESULT, str(response)+ )+ except Exception:+ pass++ except Exception as e:+ handle_exception(span, e)+ raise+ finally:+ # Process response with tool-specific handling+ try:+ if response is not None:+ response = process_mcp_response(+ response=response,+ ctx=ctx,+ span=span,+ start_time=start_time,+ endpoint=gen_ai_endpoint,+ metrics=metrics,+ disable_metrics=disable_metrics,+ **kwargs,+ )++ except Exception as e:+ handle_exception(span, e)++ return response++ return async_wrapper()++ return wrapper+++def async_mcp_resource_wrap(+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """+ Specialized wrapper for async MCP resource operations with resource-specific telemetry.+ """++ def wrapper(wrapped, instance, args, kwargs):+ """+ Wraps async MCP resource operations with resource-specific telemetry.+ """++ async def async_wrapper():+ # CRITICAL: Check for suppression+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return await wrapped(*args, **kwargs)++ # Create instrumentation context+ ctx = MCPInstrumentationContext(+ instance=instance,+ args=args,+ kwargs=kwargs,+ version=version,+ environment=environment,+ application_name=application_name,+ pricing_info=pricing_info,+ capture_message_content=capture_message_content,+ )++ # Enhanced span name for resource operations+ span_name = ctx.get_enhanced_span_name("resource")++ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:+ start_time = time.time()++ # Set resource-specific attributes+ try:+ set_mcp_span_attributes(+ span=span,+ operation_name=gen_ai_endpoint,+ ctx=ctx,+ endpoint=gen_ai_endpoint,+ **kwargs,+ )++ except Exception as e:+ handle_exception(span, e)++ # Execute async resource operation+ response = None++ try:+ response = await wrapped(*args, **kwargs)++ # Capture resource metadata if available+ if response and capture_message_content:+ try:+ if hasattr(response, "contents"):+ # Capture resource size+ content_size = len(str(response.contents))+ span.set_attribute(+ SemanticConvention.MCP_RESOURCE_SIZE, content_size+ )++ if hasattr(response, "mimeType"):+ span.set_attribute(+ SemanticConvention.MCP_RESOURCE_MIME_TYPE,+ response.mimeType,+ )++ except Exception:+ pass++ except Exception as e:+ handle_exception(span, e)+ raise+ finally:+ # Process response with resource-specific handling+ try:+ if response is not None:+ response = process_mcp_response(+ response=response,+ ctx=ctx,+ span=span,+ start_time=start_time,+ endpoint=gen_ai_endpoint,+ metrics=metrics,+ disable_metrics=disable_metrics,+ **kwargs,+ )++ except Exception as e:+ handle_exception(span, e)++ return response++ return async_wrapper()++ return wrapper+++def async_mcp_transport_wrap(+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """+ Specialized wrapper for async MCP transport operations with transport-specific telemetry.+ """++ def wrapper(wrapped, instance, args, kwargs):+ """+ Wraps async MCP transport operations with transport-specific telemetry.+ """++ async def async_wrapper():+ # CRITICAL: Check for suppression+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return await wrapped(*args, **kwargs)++ # Create instrumentation context+ ctx = MCPInstrumentationContext(+ instance=instance,+ args=args,+ kwargs=kwargs,+ version=version,+ environment=environment,+ application_name=application_name,+ pricing_info=pricing_info,+ capture_message_content=capture_message_content,+ )++ # Transport-specific span name following operation_type operation_name convention+ transport_type = ctx.transport_type+ span_name = f"mcp transport {transport_type}"++ with tracer.start_as_current_span(span_name, kind=SpanKind.SERVER) as span:+ start_time = time.time()++ # Set transport-specific attributes+ try:+ set_mcp_span_attributes(+ span=span,+ operation_name=gen_ai_endpoint,+ ctx=ctx,+ endpoint=gen_ai_endpoint,+ **kwargs,+ )++ except Exception as e:+ handle_exception(span, e)++ # Execute async transport operation+ response = None++ try:+ response = await wrapped(*args, **kwargs)++ except Exception as e:+ handle_exception(span, e)+ raise+ finally:+ # Process response with transport-specific handling+ try:+ if response is not None:+ response = process_mcp_response(+ response=response,+ ctx=ctx,+ span=span,+ start_time=start_time,+ endpoint=gen_ai_endpoint,+ metrics=metrics,+ disable_metrics=disable_metrics,+ **kwargs,+ )++ except Exception as e:+ handle_exception(span, e)++ return response++ return async_wrapper()++ return wrapperdiff --git a/sdk/python/src/openlit/instrumentation/mcp/mcp.py b/sdk/python/src/openlit/instrumentation/mcp/mcp.pynew file mode 100644index 00000000..e939097f--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/mcp/mcp.py@@ -0,0 +1,411 @@+# pylint: disable=broad-exception-caught+"""+Synchronous MCP (Model Context Protocol) instrumentation with threading context fixes.+"""++import time+from opentelemetry.trace import SpanKind+from opentelemetry import context as context_api++from openlit.semcov import SemanticConvention+from openlit.__helpers import handle_exception, record_mcp_metrics+from openlit.instrumentation.mcp.utils import (+ MCPInstrumentationContext,+ set_mcp_span_attributes,+ process_mcp_response,+ create_mcp_scope,+ _simplify_operation_name,+)+++def mcp_wrap(+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """+ Generates a telemetry wrapper for MCP operations with threading context fixes.+ """++ def wrapper(wrapped, instance, args, kwargs):+ """+ Wraps MCP operations with comprehensive telemetry and business intelligence.+ """++ # CRITICAL: Check for suppression to avoid infinite recursion+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return wrapped(*args, **kwargs)++ # Determine span kind based on operation type+ span_kind = SpanKind.CLIENT+ if (+ "server" in gen_ai_endpoint.lower()+ or "transport" in gen_ai_endpoint.lower()+ ):+ span_kind = SpanKind.SERVER++ # Create instrumentation context for caching expensive operations+ ctx = MCPInstrumentationContext(+ instance=instance,+ args=args,+ kwargs=kwargs,+ version=version,+ environment=environment,+ application_name=application_name,+ pricing_info=pricing_info,+ capture_message_content=capture_message_content,+ )++ # Enhanced method detection from endpoint and wrapped function+ if hasattr(wrapped, "__name__"):+ ctx._wrapped_function_name = wrapped.__name__++ # Extract method from endpoint (e.g., "tool call_tool" -> "call_tool")+ if gen_ai_endpoint:+ endpoint_parts = gen_ai_endpoint.split()+ if len(endpoint_parts) >= 2:+ ctx._endpoint_method = endpoint_parts[1]+ else:+ ctx._endpoint_method = (+ endpoint_parts[0] if endpoint_parts else "unknown"+ )++ operation_type = gen_ai_endpoint.split()[0] if " " in gen_ai_endpoint else "mcp"+ span_name = ctx.get_enhanced_span_name(operation_type)++ with tracer.start_as_current_span(span_name, kind=span_kind) as span:+ start_time = time.time()++ # Create scope object for common span attributes+ scope = create_mcp_scope(+ instance=instance,+ args=args,+ kwargs=kwargs,+ version=version,+ environment=environment,+ application_name=application_name,+ pricing_info=pricing_info,+ capture_message_content=capture_message_content,+ span=span,+ start_time=start_time,+ )++ # Set initial span attributes+ try:+ set_mcp_span_attributes(+ span=span,+ operation_name=gen_ai_endpoint,+ ctx=ctx,+ endpoint=gen_ai_endpoint,+ **kwargs,+ )+ except Exception as e:+ handle_exception(span, e)++ # Execute the wrapped function+ response = None+ error = None++ try:+ # Apply threading context fix for CLIENT operations that might use ThreadPoolExecutor+ # This is critical for proper span hierarchy in MCP operations+ if span_kind == SpanKind.CLIENT:+ # MCP client operations might spawn threads, ensure context propagation+ response = wrapped(*args, **kwargs)+ else:+ # Server operations typically don't need threading fixes+ response = wrapped(*args, **kwargs)++ # Note: MCP SDK functions may return coroutines+ # These will be handled gracefully in the response processing++ except Exception as e:+ error = e+ handle_exception(span, e)++ # Record error metrics+ if metrics and not disable_metrics:+ end_time = time.time()+ mcp_operation = _simplify_operation_name(gen_ai_endpoint)+ mcp_method = (+ ctx.method_name or gen_ai_endpoint.split()[-1]+ if " " in gen_ai_endpoint+ else gen_ai_endpoint+ )++ record_mcp_metrics(+ metrics=metrics,+ mcp_operation=mcp_operation,+ mcp_method=mcp_method,+ mcp_transport_type="stdio",+ mcp_tool_name=kwargs.get("tool_name") or kwargs.get("name")+ if "tool" in gen_ai_endpoint.lower()+ else None,+ mcp_resource_uri=kwargs.get("resource_uri") or kwargs.get("uri")+ if "resource" in gen_ai_endpoint.lower()+ else None,+ mcp_resource_name=kwargs.get("resource_name")+ or kwargs.get("name")+ if "resource" in gen_ai_endpoint.lower()+ else None,+ mcp_prompt_name=kwargs.get("prompt_name") or kwargs.get("name")+ if "prompt" in gen_ai_endpoint.lower()+ else None,+ environment=environment,+ application_name=application_name,+ start_time=start_time,+ end_time=end_time,+ is_error=True,+ )+ raise+ finally:+ # Process response and capture telemetry+ try:+ scope._end_time = time.time()++ if response is not None:+ response = process_mcp_response(+ response=response,+ ctx=ctx,+ span=span,+ start_time=start_time,+ endpoint=gen_ai_endpoint,+ metrics=metrics,+ disable_metrics=disable_metrics,+ **kwargs,+ )++ # Update span attributes with error info if needed+ if error:+ set_mcp_span_attributes(+ span=span,+ operation_name=gen_ai_endpoint,+ ctx=ctx,+ endpoint=gen_ai_endpoint,+ error=error,+ **kwargs,+ )++ except Exception as e:+ handle_exception(span, e)++ return response++ return wrapper+++def mcp_tool_call_wrap(+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """+ Specialized wrapper for MCP tool call operations with enhanced telemetry.+ """++ def wrapper(wrapped, instance, args, kwargs):+ """+ Wraps MCP tool call operations with tool-specific telemetry.+ """++ # CRITICAL: Check for suppression+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return wrapped(*args, **kwargs)++ # Create instrumentation context+ ctx = MCPInstrumentationContext(+ instance=instance,+ args=args,+ kwargs=kwargs,+ version=version,+ environment=environment,+ application_name=application_name,+ pricing_info=pricing_info,+ capture_message_content=capture_message_content,+ )++ # Enhanced span name for tool calls+ span_name = ctx.get_enhanced_span_name("tool")++ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:+ start_time = time.time()++ # Set tool-specific attributes+ try:+ set_mcp_span_attributes(+ span=span,+ operation_name=gen_ai_endpoint,+ ctx=ctx,+ endpoint=gen_ai_endpoint,+ **kwargs,+ )++ # Additional tool-specific attributes+ if ctx.tool_name:+ span.set_attribute(SemanticConvention.MCP_TOOL_NAME, ctx.tool_name)++ except Exception as e:+ handle_exception(span, e)++ # Execute tool call+ response = None+ try:+ response = wrapped(*args, **kwargs)++ # Capture tool result if available+ if response and capture_message_content:+ try:+ if hasattr(response, "content"):+ span.set_attribute(+ SemanticConvention.MCP_TOOL_RESULT,+ str(response.content),+ )+ elif isinstance(response, (str, dict, list)):+ span.set_attribute(+ SemanticConvention.MCP_TOOL_RESULT, str(response)+ )+ except Exception:+ pass++ except Exception as e:+ handle_exception(span, e)+ raise+ finally:+ # Process response with tool-specific handling+ try:+ if response is not None:+ response = process_mcp_response(+ response=response,+ ctx=ctx,+ span=span,+ start_time=start_time,+ endpoint=gen_ai_endpoint,+ metrics=metrics,+ disable_metrics=disable_metrics,+ **kwargs,+ )++ except Exception as e:+ handle_exception(span, e)++ return response++ return wrapper+++def mcp_resource_wrap(+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """+ Specialized wrapper for MCP resource operations with resource-specific telemetry.+ """++ def wrapper(wrapped, instance, args, kwargs):+ """+ Wraps MCP resource operations with resource-specific telemetry.+ """++ # CRITICAL: Check for suppression+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return wrapped(*args, **kwargs)++ # Create instrumentation context+ ctx = MCPInstrumentationContext(+ instance=instance,+ args=args,+ kwargs=kwargs,+ version=version,+ environment=environment,+ application_name=application_name,+ pricing_info=pricing_info,+ capture_message_content=capture_message_content,+ )++ # Enhanced span name for resource operations+ span_name = ctx.get_enhanced_span_name("resource")++ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:+ start_time = time.time()++ # Set resource-specific attributes+ try:+ set_mcp_span_attributes(+ span=span,+ operation_name=gen_ai_endpoint,+ ctx=ctx,+ endpoint=gen_ai_endpoint,+ **kwargs,+ )++ except Exception as e:+ handle_exception(span, e)++ # Execute resource operation+ response = None++ try:+ response = wrapped(*args, **kwargs)++ # Capture resource metadata if available+ if response and capture_message_content:+ try:+ if hasattr(response, "contents"):+ # Capture resource size+ content_size = len(str(response.contents))+ span.set_attribute(+ SemanticConvention.MCP_RESOURCE_SIZE, content_size+ )++ if hasattr(response, "mimeType"):+ span.set_attribute(+ SemanticConvention.MCP_RESOURCE_MIME_TYPE,+ response.mimeType,+ )++ except Exception:+ pass++ except Exception as e:+ handle_exception(span, e)+ raise+ finally:+ # Process response with resource-specific handling+ try:+ if response is not None:+ response = process_mcp_response(+ response=response,+ ctx=ctx,+ span=span,+ start_time=start_time,+ endpoint=gen_ai_endpoint,+ metrics=metrics,+ disable_metrics=disable_metrics,+ **kwargs,+ )++ except Exception as e:+ handle_exception(span, e)++ return response++ return wrapperdiff --git a/sdk/python/src/openlit/instrumentation/mcp/utils.py b/sdk/python/src/openlit/instrumentation/mcp/utils.pynew file mode 100644index 00000000..c5443427--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/mcp/utils.py@@ -0,0 +1,1795 @@+# pylint: disable=broad-exception-caught+"""+Utility functions for MCP instrumentation with optimized context caching and performance enhancements.+"""++import json+import time+import inspect+from typing import Dict, Any, Optional++from opentelemetry import context, propagate+from opentelemetry.sdk.resources import SERVICE_NAME, DEPLOYMENT_ENVIRONMENT+from opentelemetry.trace.status import Status, StatusCode++from openlit.semcov import SemanticConvention+from openlit.__helpers import (+ handle_exception,+ record_mcp_metrics,+)+++class MCPInstrumentationContext:+ """+ Context object to cache expensive extractions and reduce performance overhead.+ Uses __slots__ for memory optimization following OpenLIT patterns.+ """++ __slots__ = (+ "instance",+ "args",+ "kwargs",+ "version",+ "environment",+ "application_name",+ "pricing_info",+ "capture_message_content",+ "_method_name",+ "_message_id",+ "_tool_name",+ "_resource_uri",+ "_server_name",+ "_transport_type",+ "_error_info",+ "_params",+ "_result",+ "_server_info",+ "_wrapped_function_name",+ "_endpoint_method",+ "_request_payload",+ "_response_payload",+ )++ def __init__(+ self,+ instance,+ args,+ kwargs,+ version,+ environment,+ application_name,+ pricing_info,+ capture_message_content,+ ):+ self.instance = instance+ self.args = args+ self.kwargs = kwargs+ self.version = version+ self.environment = environment+ self.application_name = application_name+ self.pricing_info = pricing_info+ self.capture_message_content = capture_message_content++ # Cache expensive operations with lazy loading+ self._method_name = None+ self._message_id = None+ self._tool_name = None+ self._resource_uri = None+ self._server_name = None+ self._transport_type = None+ self._error_info = None+ self._wrapped_function_name = None+ self._endpoint_method = None+ self._params = None+ self._result = None+ self._server_info = None+ self._request_payload = None+ self._response_payload = None++ @property+ def method_name(self) -> str:+ """Get MCP method name with caching."""+ if self._method_name is None:+ self._method_name = self._extract_method_name()+ return self._method_name++ @property+ def message_id(self) -> Optional[str]:+ """Get MCP message ID with caching."""+ if self._message_id is None:+ self._message_id = self._extract_message_id()+ return self._message_id++ @property+ def tool_name(self) -> Optional[str]:+ """Get tool name with caching."""+ if self._tool_name is None:+ self._tool_name = self._extract_tool_name()+ return self._tool_name++ @property+ def resource_uri(self) -> Optional[str]:+ """Get resource URI with caching."""+ if self._resource_uri is None:+ self._resource_uri = self._extract_resource_uri()+ return self._resource_uri++ @property+ def transport_type(self) -> str:+ """Get transport type with caching."""+ if self._transport_type is None:+ self._transport_type = self._extract_transport_type()+ return self._transport_type++ @property+ def server_info(self) -> Dict[str, Any]:+ """Get server info with caching."""+ if self._server_info is None:+ self._server_info = self._extract_server_info()+ return self._server_info++ @property+ def request_payload(self) -> Optional[str]:+ """Get request payload with caching."""+ if self._request_payload is None:+ self._request_payload = self._extract_request_payload()+ return self._request_payload++ @property+ def response_payload(self) -> Optional[str]:+ """Get response payload with caching."""+ return self._response_payload++ def set_response_payload(self, response_payload: str) -> None:+ """Set response payload after execution."""+ self._response_payload = response_payload++ def _extract_method_name(self) -> str:+ """Extract MCP method name from request or context."""+ try:+ # Try to detect from function being wrapped first (most reliable)+ if hasattr(self, "_wrapped_function_name"):+ func_name = self._wrapped_function_name+ if func_name in [+ "run",+ "list_tools",+ "call_tool",+ "list_resources",+ "read_resource",+ "list_prompts",+ "get_prompt",+ "initialize",+ "send_request",+ ]:+ return func_name++ # Try to detect from endpoint method+ if hasattr(self, "_endpoint_method"):+ return self._endpoint_method++ # Check for MCP-specific method patterns+ # For call_tool operations, try to get tool name+ if "name" in self.kwargs:+ tool_name = self.kwargs["name"]+ if isinstance(tool_name, str):+ return tool_name++ # Try to get from method parameter in kwargs+ if "method" in self.kwargs:+ return str(self.kwargs["method"])++ # Try to get from args - check for tool name in call_tool+ if self.args and (len(self.args) >= 1 and isinstance(self.args[0], str)):+ first_arg = self.args[0]+ if first_arg in [+ "calculator",+ "text_analyzer",+ "data_processor",+ "add",+ "analyze",+ "list_tools",+ "call_tool",+ "list_resources",+ "read_resource",+ "list_prompts",+ "get_prompt",+ "run",+ "initialize",+ ]:+ return first_arg++ # Try to get from instance method name+ if hasattr(self.instance, "__name__"):+ instance_name = self.instance.__name__+ if instance_name != "<lambda>": # Avoid lambda names+ return instance_name++ # Last resort - try to infer from instance class+ if self.instance and hasattr(self.instance, "__class__"):+ class_name = self.instance.__class__.__name__.lower()+ if "server" in class_name:+ return "server_operation"+ elif "client" in class_name:+ return "client_operation"++ return "unknown"+ except Exception:+ return "unknown"++ def _extract_message_id(self) -> Optional[str]:+ """Extract message ID from MCP request."""+ try:+ # Check kwargs for id+ if "id" in self.kwargs:+ return str(self.kwargs["id"])++ # Check if first arg is a message object with id+ if self.args and hasattr(self.args[0], "id"):+ return str(self.args[0].id)++ return None+ except Exception:+ return None++ def _extract_tool_name(self) -> Optional[str]:+ """Extract tool name for tool operations."""+ try:+ # Check kwargs+ if "name" in self.kwargs:+ return str(self.kwargs["name"])++ # Check params for tool name+ if "params" in self.kwargs and isinstance(self.kwargs["params"], dict):+ params = self.kwargs["params"]+ if "name" in params:+ return str(params["name"])++ return None+ except Exception:+ return None++ def _extract_resource_uri(self) -> Optional[str]:+ """Extract resource URI for resource operations."""+ try:+ # Check kwargs+ if "uri" in self.kwargs:+ return str(self.kwargs["uri"])++ # Check params for URI+ if "params" in self.kwargs and isinstance(self.kwargs["params"], dict):+ params = self.kwargs["params"]+ if "uri" in params:+ return str(params["uri"])++ return None+ except Exception:+ return None++ def _extract_transport_type(self) -> str:+ """Extract transport type from instance."""+ try:+ # Check instance class name for transport type+ if self.instance:+ instance_class = self.instance.__class__.__name__.lower()+ instance_module = getattr(+ self.instance.__class__, "__module__", ""+ ).lower()++ # Check for stdio transport patterns+ if (+ "stdio" in instance_class+ or "stdio" in instance_module+ or "clientsession" in instance_class+ ):+ return SemanticConvention.MCP_TRANSPORT_STDIO+ # Check for SSE transport+ elif "sse" in instance_class or "sse" in instance_module:+ return SemanticConvention.MCP_TRANSPORT_SSE+ # Check for WebSocket transport+ elif "websocket" in instance_class or "ws" in instance_class:+ return SemanticConvention.MCP_TRANSPORT_WEBSOCKET++ # Check kwargs for transport hints+ if self.kwargs:+ # Look for transport-related parameters+ if any(key in self.kwargs for key in ["command", "args", "stdio"]):+ return SemanticConvention.MCP_TRANSPORT_STDIO+ elif any(+ key in self.kwargs for key in ["url", "endpoint"]+ ) and "sse" in str(self.kwargs):+ return SemanticConvention.MCP_TRANSPORT_SSE+ elif any(key in self.kwargs for key in ["ws_url", "websocket"]):+ return SemanticConvention.MCP_TRANSPORT_WEBSOCKET++ # Default to stdio for most MCP implementations+ return SemanticConvention.MCP_TRANSPORT_STDIO+ except Exception:+ return "unknown"++ def _extract_server_info(self) -> Dict[str, Any]:+ """Extract server information."""+ try:+ server_info = {}++ # Try to get server name from instance+ if hasattr(self.instance, "name"):+ server_info["name"] = str(self.instance.name)+ elif hasattr(self.instance, "server_name"):+ server_info["name"] = str(self.instance.server_name)++ # Try to get server version+ if hasattr(self.instance, "version"):+ server_info["version"] = str(self.instance.version)++ return server_info+ except Exception:+ return {}++ def _extract_request_payload(self) -> Optional[str]:+ """Extract request payload from args/kwargs in JSON format."""+ try:+ payload = {}++ # Try to get method name+ method = self.method_name if self.method_name != "unknown" else None+ if method:+ payload["method"] = method++ # Extract parameters from kwargs and args+ params = {}++ # Get common MCP parameters+ if "name" in self.kwargs:+ params["name"] = self.kwargs["name"]+ if "arguments" in self.kwargs:+ params["arguments"] = self.kwargs["arguments"]+ if "uri" in self.kwargs:+ params["uri"] = self.kwargs["uri"]++ # Add other kwargs that look like MCP parameters+ for key, value in self.kwargs.items():+ if key in [+ "topic",+ "meta",+ "protocolVersion",+ "capabilities",+ "clientInfo",+ ]:+ params[key] = value++ # If we have args and no specific params, include args+ if not params and self.args:+ if len(self.args) == 1:+ params = (+ self.args[0]+ if isinstance(self.args[0], dict)+ else {"value": self.args[0]}+ )+ else:+ params = {"args": list(self.args)}++ if params:+ payload["params"] = params+ elif not payload:+ # Fallback if no clear structure+ return None++ return json.dumps(payload, default=str)++ except Exception:+ return None++ def get_enhanced_span_name(self, operation_type: str) -> str:+ """Generate span names following operation_type operation_name convention (e.g., 'mcp tools/list', 'mcp resources/read')."""+ method = self.method_name or "unknown"++ # Map operations to operation_type operation_name convention+ if "list_tools" in method or (operation_type == "tool" and "list" in method):+ return "mcp tools/list"+ elif "call_tool" in method or (+ operation_type == "tool"+ and any(+ x in method for x in ["calculator", "text_analyzer", "data_processor"]+ )+ ):+ return "mcp tools/call"+ elif "list_resources" in method or (+ operation_type == "resource" and "list" in method+ ):+ return "mcp resources/list"+ elif "read_resource" in method or (+ operation_type == "resource" and "read" in method+ ):+ return "mcp resources/read"+ elif "list_prompts" in method or (+ operation_type == "prompt" and "list" in method+ ):+ return "mcp prompts/list"+ elif "get_prompt" in method or (operation_type == "prompt" and "get" in method):+ return "mcp prompts/get"+ elif "initialize" in method:+ return "mcp initialize"+ elif "run" in method:+ return "mcp server/run"+ elif "send_request" in method:+ return "mcp transport/request"+ elif "stdio_client" in method:+ return "mcp transport/stdio_client"+ elif "stdio_server" in method:+ return "mcp transport/stdio_server"+ elif "sse_client" in method:+ return "mcp transport/sse_client"+ elif "sse_server" in method or "connect_sse" in method:+ return "mcp transport/sse_server"+ elif "http_client" in method or "streamablehttp_client" in method:+ return "mcp transport/http_client"+ elif "http_server" in method or "StreamableHTTPServerTransport" in method:+ return "mcp transport/http_server"+ elif "__init__" in method and operation_type == "session":+ return "mcp session/init"+ # FastMCP Framework operations+ elif "fastmcp" in method:+ if "run" in method:+ return "mcp fastmcp/run"+ elif "add_tool" in method:+ return "mcp fastmcp/add_tool"+ elif "add_resource" in method:+ return "mcp fastmcp/add_resource"+ elif "add_prompt" in method:+ return "mcp fastmcp/add_prompt"+ elif "call_tool" in method:+ return "mcp fastmcp/call_tool"+ elif "read_resource" in method:+ return "mcp fastmcp/read_resource"+ elif "get_prompt" in method:+ return "mcp fastmcp/get_prompt"+ else:+ return "mcp fastmcp/operation"+ # Manager-level operations+ elif "manager" in method:+ if "tool_manager" in method:+ return "mcp managers/tool"+ elif "resource_manager" in method:+ return "mcp managers/resource"+ elif "prompt_manager" in method:+ return "mcp managers/prompt"+ else:+ return "mcp managers/operation"+ # WebSocket transport operations+ elif "websocket" in method:+ if "websocket_client" in method:+ return "mcp transport/websocket_client"+ elif "websocket_server" in method:+ return "mcp transport/websocket_server"+ else:+ return "mcp transport/websocket"+ # Authentication & security operations+ elif "auth" in method:+ if "authorize" in method:+ return "mcp auth/authorize"+ elif "exchange_code" in method:+ return "mcp auth/exchange_code"+ elif "verify_token" in method:+ return "mcp auth/verify_token"+ else:+ return "mcp auth/operation"+ # Advanced client operations+ elif "ping" in method:+ return "mcp client/ping"+ elif "set_logging" in method:+ return "mcp client/set_logging"+ elif "progress" in method and "client" in operation_type:+ return "mcp client/progress"+ elif "complete" in method:+ return "mcp client/complete"+ # Memory & progress operations+ elif "memory" in method:+ if "connect" in method:+ return "mcp memory/connect"+ else:+ return "mcp memory/operation"+ elif "progress_context" in method or "ProgressContext" in method:+ return "mcp progress/update"+ elif method == "unknown":+ # Better fallback for unknown methods - use operation_type if available+ if operation_type and operation_type != "mcp":+ return f"mcp {operation_type}/operation"+ else:+ return "mcp operation"+ else:+ # Fallback to operation_type operation_name convention+ return f"mcp {operation_type}/{method}"+++def _simplify_operation_name(operation_name: str) -> str:+ """Simplify operation names for span attributes (e.g., 'server call_tool' -> 'tools_call')."""+ # Remove server/client prefixes+ simplified = operation_name.replace("server ", "").replace("client ", "")+ simplified = (+ simplified.replace("fastmcp ", "")+ .replace("manager ", "")+ .replace("transport ", "")+ )++ # Map to standard operation names+ if "call_tool" in simplified:+ return "tools_call"+ elif "list_tools" in simplified:+ return "tools_list"+ elif "list_resources" in simplified:+ return "resources_list"+ elif "read_resource" in simplified:+ return "resources_read"+ elif "list_prompts" in simplified:+ return "prompts_list"+ elif "get_prompt" in simplified:+ return "prompts_get"+ elif "initialize" in simplified:+ return "initialize"+ elif "run" in simplified:+ return "server_run"+ elif "send_request" in simplified:+ return "transport_request"+ elif "stdio_client" in simplified:+ return "transport_stdio_client"+ elif "stdio_server" in simplified:+ return "transport_stdio_server"+ elif "sse_client" in simplified:+ return "transport_sse_client"+ elif "sse_server" in simplified or "connect_sse" in simplified:+ return "transport_sse_server"+ elif "websocket_client" in simplified:+ return "transport_websocket_client"+ elif "websocket_server" in simplified:+ return "transport_websocket_server"+ elif "http_client" in simplified or "streamablehttp_client" in simplified:+ return "transport_http_client"+ elif "http_server" in simplified or "StreamableHTTPServerTransport" in simplified:+ return "transport_http_server"+ elif "add_tool" in simplified:+ return "fastmcp_add_tool"+ elif "add_resource" in simplified:+ return "fastmcp_add_resource"+ elif "add_prompt" in simplified:+ return "fastmcp_add_prompt"+ elif "authorize" in simplified:+ return "auth_authorize"+ elif "exchange_code" in simplified:+ return "auth_exchange_code"+ elif "verify_token" in simplified:+ return "auth_verify_token"+ elif "ping" in simplified:+ return "client_ping"+ elif "set_logging" in simplified:+ return "client_set_logging"+ elif "progress" in simplified:+ return "progress_update"+ elif "complete" in simplified:+ return "completion"+ elif "memory" in simplified and "connect" in simplified:+ return "memory_connect"+ else:+ # Fallback - just clean up the name+ return simplified.replace(" ", "_").lower()+++def set_mcp_span_attributes(+ span,+ operation_name: str,+ ctx: MCPInstrumentationContext,+ endpoint: str,+ response: Any = None,+ error: Optional[Exception] = None,+ **kwargs,+):+ """+ Optimized attribute setting with context caching and comprehensive MCP attributes.+ """++ # Set core MCP attributes using cached context - simplify operation name+ simplified_operation = _simplify_operation_name(operation_name)+ span.set_attribute(SemanticConvention.MCP_OPERATION, simplified_operation)+ span.set_attribute(SemanticConvention.MCP_SYSTEM, "mcp")++ # Set environment attributes+ span.set_attribute(DEPLOYMENT_ENVIRONMENT, ctx.environment)+ span.set_attribute(SERVICE_NAME, ctx.application_name)+ span.set_attribute(SemanticConvention.MCP_SDK_VERSION, ctx.version)++ # Set MCP-specific attributes+ if ctx.method_name: # Only set if not None to avoid OpenTelemetry warning+ span.set_attribute(SemanticConvention.MCP_METHOD, ctx.method_name)++ if ctx.request_payload and ctx.capture_message_content:+ span.set_attribute(SemanticConvention.MCP_REQUEST_PAYLOAD, ctx.request_payload)++ if ctx.message_id:+ span.set_attribute(SemanticConvention.MCP_MESSAGE_ID, ctx.message_id)++ span.set_attribute(SemanticConvention.MCP_TRANSPORT_TYPE, ctx.transport_type)++ # Set tool-specific attributes+ if ctx.tool_name:+ span.set_attribute(SemanticConvention.MCP_TOOL_NAME, ctx.tool_name)++ # Set resource-specific attributes+ if ctx.resource_uri:+ span.set_attribute(SemanticConvention.MCP_RESOURCE_URI, ctx.resource_uri)++ # Set server information+ server_info = ctx.server_info+ if server_info.get("name"):+ span.set_attribute(SemanticConvention.MCP_SERVER_NAME, server_info["name"])+ if server_info.get("version"):+ span.set_attribute(+ SemanticConvention.MCP_SERVER_VERSION, server_info["version"]+ )++ # Capture request/response content if enabled+ if ctx.capture_message_content:+ _capture_mcp_content(span, ctx, response, **kwargs)++ # Handle errors+ if error:+ _capture_mcp_error(span, error)++ # Extract new enhanced attributes+ _extract_enhanced_mcp_attributes(span, ctx, endpoint, response, **kwargs)+++def _capture_mcp_content(span, ctx: MCPInstrumentationContext, response: Any, **kwargs):+ """Capture MCP request and response content with MIME types (OpenLIT enhancement)."""+ try:+ # Capture request parameters+ if "params" in ctx.kwargs:+ params_str = json.dumps(ctx.kwargs["params"], default=str)+ span.set_attribute(SemanticConvention.MCP_PARAMS, params_str)++ # Capture response content+ if response is not None:+ if hasattr(response, "result"):+ result_str = json.dumps(response.result, default=str)+ span.set_attribute(SemanticConvention.MCP_RESULT, result_str)+ elif isinstance(response, (dict, list, str, int, float, bool)):+ result_str = json.dumps(response, default=str)+ span.set_attribute(SemanticConvention.MCP_RESULT, result_str)++ # Capture tool arguments for tool calls+ if ctx.tool_name and "arguments" in ctx.kwargs:+ args_str = json.dumps(ctx.kwargs["arguments"], default=str)+ span.set_attribute(SemanticConvention.MCP_TOOL_ARGUMENTS, args_str)++ except Exception:+ # Silently ignore content capture errors+ pass+++def _capture_mcp_error(span, error: Exception):+ """Capture MCP error information."""+ try:+ # Set error attributes+ span.set_attribute(SemanticConvention.MCP_ERROR_MESSAGE, str(error))++ # Try to extract MCP-specific error details+ if hasattr(error, "code"):+ span.set_attribute(SemanticConvention.MCP_ERROR_CODE, str(error.code))++ if hasattr(error, "data"):+ error_data = json.dumps(error.data, default=str)+ span.set_attribute(SemanticConvention.MCP_ERROR_DATA, error_data)++ except Exception:+ # Silently ignore error capture errors+ pass+++def process_mcp_response(+ response,+ ctx: MCPInstrumentationContext,+ span,+ start_time: float,+ endpoint: str,+ metrics,+ disable_metrics: bool = False,+ **kwargs,+):+ """+ Process MCP response with comprehensive business intelligence tracking.+ """++ try:+ end_time = time.time()++ # Set basic response attributes+ set_mcp_span_attributes(span, endpoint, ctx, endpoint, response, **kwargs)++ # Calculate performance metrics (OpenLIT business intelligence)+ duration = end_time - start_time+ span.set_attribute(SemanticConvention.MCP_CLIENT_OPERATION_DURATION, duration)++ try:+ if response and ctx.capture_message_content:+ # Handle different response types intelligently+ if hasattr(response, "__await__"):+ # It's a coroutine - extract meaningful info without awaiting+ if hasattr(response, "cr_code"):+ func_name = response.cr_code.co_name+ else:+ func_name = (+ str(response).rsplit(".", maxsplit=1)[-1].split(" ")[0]+ )++ response_info = {+ "type": "mcp_coroutine",+ "function": func_name,+ "awaitable": True,+ "note": "Response data available after await",+ }+ response_json = json.dumps(response_info)+ elif hasattr(response, "__dict__"):+ # It's a structured object - capture its content+ try:+ response_json = json.dumps(response.__dict__, default=str)+ except Exception:+ response_json = json.dumps(+ {"type": type(response).__name__, "value": str(response)}+ )+ else:+ # Regular response+ response_json = json.dumps(response, default=str)++ ctx.set_response_payload(response_json)+ span.set_attribute(+ SemanticConvention.MCP_RESPONSE_PAYLOAD, response_json+ )+ except Exception:+ pass++ # Capture message size for performance analysis+ try:+ if response:+ response_size = len(json.dumps(response, default=str))+ span.set_attribute(SemanticConvention.MCP_RESPONSE_SIZE, response_size)+ except Exception:+ pass++ # Record MCP-specific metrics for business intelligence+ if metrics and not disable_metrics:+ # Extract MCP-specific information for enhanced metrics+ mcp_operation = _simplify_operation_name(endpoint)+ mcp_method = (+ ctx.method_name or endpoint.split()[-1] if " " in endpoint else endpoint+ )++ # Extract tool, resource, and prompt names from context+ tool_name = None+ resource_uri = None+ prompt_name = None++ # Enhanced extraction logic for MCP operations+ # Try to extract tool name from various sources+ if "tool_name" in kwargs:+ tool_name = kwargs["tool_name"]+ elif "name" in kwargs and (+ "tool" in endpoint.lower() or "call" in endpoint.lower()+ ):+ tool_name = kwargs["name"]+ elif len(ctx.args) > 0:+ # For MCP tool calls, tool name is typically the first argument+ if isinstance(ctx.args[0], str) and (+ "tool" in endpoint.lower() or "call" in endpoint.lower()+ ):+ tool_name = ctx.args[0]+ elif hasattr(ctx.args[0], "name"):+ tool_name = ctx.args[0].name+ elif isinstance(ctx.args[0], dict) and "name" in ctx.args[0]:+ tool_name = ctx.args[0]["name"]++ # Try to extract resource URI and name from various sources+ resource_name = None+ if "resource_uri" in kwargs:+ resource_uri = kwargs["resource_uri"]+ elif "uri" in kwargs:+ resource_uri = kwargs["uri"]+ elif len(ctx.args) > 0 and "resource" in endpoint.lower():+ # For MCP resource operations, URI is typically the first argument+ if isinstance(ctx.args[0], str):+ resource_uri = ctx.args[0]+ elif hasattr(ctx.args[0], "uri"):+ resource_uri = ctx.args[0].uri+ elif isinstance(ctx.args[0], dict) and "uri" in ctx.args[0]:+ resource_uri = ctx.args[0]["uri"]++ # Extract resource name from kwargs, response, or derive from URI+ if "resource_name" in kwargs:+ resource_name = kwargs["resource_name"]+ elif "name" in kwargs and "resource" in endpoint.lower():+ resource_name = kwargs["name"]+ elif hasattr(response, "name"):+ resource_name = response.name+ elif resource_uri:+ # Derive resource name from URI (e.g., "resource://config" -> "config")+ resource_name = (+ resource_uri.split("://")[-1].split("/")[-1]+ if "://" in resource_uri+ else resource_uri+ )++ # Try to extract prompt name from various sources+ if "prompt_name" in kwargs:+ prompt_name = kwargs["prompt_name"]+ elif "name" in kwargs and "prompt" in endpoint.lower():+ prompt_name = kwargs["name"]+ elif len(ctx.args) > 0 and "prompt" in endpoint.lower():+ # For MCP prompt operations, name is typically the first argument+ if isinstance(ctx.args[0], str):+ prompt_name = ctx.args[0]+ elif hasattr(ctx.args[0], "name"):+ prompt_name = ctx.args[0].name+ elif isinstance(ctx.args[0], dict) and "name" in ctx.args[0]:+ prompt_name = ctx.args[0]["name"]++ # Calculate request/response sizes+ request_size = None+ response_size = None+ try:+ if len(ctx.args) > 0:+ request_size = len(serialize_mcp_input(ctx.args[0]))+ if response:+ response_size = len(serialize_mcp_input(response))+ except Exception:+ pass++ record_mcp_metrics(+ metrics=metrics,+ mcp_operation=mcp_operation,+ mcp_method=mcp_method,+ mcp_transport_type="stdio", # Default transport+ mcp_tool_name=tool_name,+ mcp_resource_uri=resource_uri,+ mcp_resource_name=resource_name, # Add resource name for enhanced BI+ mcp_prompt_name=prompt_name,+ environment=ctx.environment,+ application_name=ctx.application_name,+ start_time=start_time,+ end_time=end_time,+ request_size=request_size,+ response_size=response_size,+ is_error=False,+ )++ except Exception as e:+ handle_exception(span, e)++ return response+++def create_mcp_scope(+ instance,+ args,+ kwargs,+ version,+ environment,+ application_name,+ pricing_info,+ capture_message_content,+ span,+ start_time: float,+):+ """+ Create optimized scope object for MCP operations following OpenLIT patterns.+ """++ # Create scope object using OpenLIT pattern+ scope = type("MCPScope", (), {})()+ scope._span = span+ scope._start_time = start_time+ scope._end_time = None++ # Create instrumentation context+ scope._context = MCPInstrumentationContext(+ instance=instance,+ args=args,+ kwargs=kwargs,+ version=version,+ environment=environment,+ application_name=application_name,+ pricing_info=pricing_info,+ capture_message_content=capture_message_content,+ )++ return scope+++def serialize_mcp_input(request, depth=0, max_depth=4):+ """+ Serialize input args to MCP server into JSON.+ The function accepts input object and converts into JSON+ keeping depth in mind to prevent creating large nested JSON.+ """+ if depth > max_depth:+ return {}+ depth += 1++ def is_serializable(request):+ try:+ json.dumps(request)+ return True+ except Exception:+ return False++ if is_serializable(request):+ return json.dumps(request)++ # Handle complex objects+ if hasattr(request, "model_dump_json"):+ return request.model_dump_json()++ if not hasattr(request, "__dict__"):+ return json.dumps({})++ result = {}+ try:+ for attrib in request.__dict__:+ if attrib.startswith("_"):+ continue++ attr_value = request.__dict__[attrib]+ if type(attr_value) in [bool, str, int, float, type(None)]:+ result[str(attrib)] = attr_value+ else:+ result[str(attrib)] = serialize_mcp_input(attr_value, depth)+ except Exception:+ pass+ return json.dumps(result)+++def inject_context_into_jsonrpc_request(request_data):+ """Inject OpenTelemetry context into JSONRPC request _meta field."""+ try:+ if hasattr(request_data, "params"):+ if not request_data.params:+ request_data.params = {}+ meta = request_data.params.setdefault("_meta", {})+ propagate.get_global_textmap().inject(meta)+ except Exception:+ pass # Silently fail to avoid breaking requests++ return request_data+++def extract_context_from_jsonrpc_request(request_data):+ """Extract OpenTelemetry context from JSONRPC request _meta field."""+ try:+ if (+ hasattr(request_data, "params")+ and request_data.params+ and isinstance(request_data.params, dict)+ ):+ meta = request_data.params.get("_meta")+ if meta:+ return propagate.extract(meta)+ except Exception:+ pass++ return None+++def _extract_server_context(args):+ """Extract context from JSONRPC request objects in server-side operations."""+ try:+ # Look for JSONRPC request objects and extract context+ for arg in args:+ if hasattr(arg, "root") and hasattr(arg.root, "method"):+ extracted_ctx = extract_context_from_jsonrpc_request(arg.root)+ if extracted_ctx:+ return extracted_ctx+ except Exception:+ pass+ return None+++def create_context_propagating_wrapper(+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """Create a wrapper that handles context propagation for transport methods."""++ def wrapper(wrapped, instance, args, kwargs):+ """Wrapper that injects/extracts context for MCP transport operations."""++ # For outgoing requests (client side), inject context+ if "client" in gen_ai_endpoint.lower():+ try:+ # Look for JSONRPC request objects in args/kwargs and inject context+ for arg in args:+ if hasattr(arg, "root") and hasattr(arg.root, "method"):+ inject_context_into_jsonrpc_request(arg.root)+ break+ except Exception:+ pass++ # For incoming requests (server side), extract and attach context+ elif "server" in gen_ai_endpoint.lower():+ extracted_ctx = _extract_server_context(args)+ if extracted_ctx:+ token = context.attach(extracted_ctx)+ try:+ return wrapped(*args, **kwargs)+ finally:+ context.detach(token)++ # Default execution without context manipulation+ return wrapped(*args, **kwargs)++ return wrapper+++def create_jsonrpc_wrapper(+ endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """+ This wraps BaseSession.send_request to get proper async handling.+ """++ def wrapper(wrapped, instance, args, kwargs):+ async def async_wrapper(*args, **kwargs):+ # Extract method and params from JSONRPC request+ method = None+ params = None+ if (+ len(args) > 0+ and hasattr(args[0], "root")+ and hasattr(args[0].root, "method")+ ):+ method = args[0].root.method+ if (+ len(args) > 0+ and hasattr(args[0], "root")+ and hasattr(args[0].root, "params")+ ):+ params = args[0].root.params+ if params and hasattr(params, "meta"):+ pass # Meta available but not currently used++ # Create span name following operation_type operation_name convention+ span_name = f"mcp {method}" if method else "mcp send_request"++ with tracer.start_as_current_span(span_name) as span:+ if capture_message_content and len(args) > 0:+ input_serialized = serialize_mcp_input(args[0])+ span.set_attribute(+ SemanticConvention.MCP_REQUEST_PAYLOAD, input_serialized+ )++ # Set method attribute+ if method:+ span.set_attribute(SemanticConvention.MCP_METHOD, method)++ # Set OpenLIT business intelligence attributes+ span.set_attribute(SemanticConvention.MCP_SYSTEM, "mcp")+ span.set_attribute(SemanticConvention.MCP_SDK_VERSION, version)+ if environment:+ span.set_attribute(DEPLOYMENT_ENVIRONMENT, environment)+ if application_name:+ span.set_attribute(SERVICE_NAME, application_name)++ start_time = time.time()++ try:+ # CRITICAL: Properly await the response+ result = await wrapped(*args, **kwargs)++ if result and capture_message_content:+ output_serialized = serialize_mcp_input(result)+ span.set_attribute(+ SemanticConvention.MCP_RESPONSE_PAYLOAD, output_serialized+ )++ # Set success status+ if (+ hasattr(result, "isError")+ and result.isError+ and (hasattr(result, "content") and len(result.content) > 0)+ ):+ span.set_status(+ Status(StatusCode.ERROR, f"{result.content[0].text}")+ )++ # OpenLIT business intelligence+ end_time = time.time()+ duration = end_time - start_time+ span.set_attribute(+ SemanticConvention.MCP_CLIENT_OPERATION_DURATION, duration+ )++ # Record MCP-specific metrics for business intelligence+ if not disable_metrics and metrics:+ # Extract tool, resource, and prompt info from method and params+ tool_name = None+ resource_uri = None+ prompt_name = None++ if method and method.startswith("tools/call") and params:+ tool_name = (+ str(getattr(params, "name", None))+ if getattr(params, "name", None)+ else None+ )+ elif method and method.startswith("resources/read") and params:+ resource_uri = (+ str(getattr(params, "uri", None))+ if getattr(params, "uri", None)+ else None+ )+ elif method and method.startswith("prompts/get") and params:+ prompt_name = (+ str(getattr(params, "name", None))+ if getattr(params, "name", None)+ else None+ )++ # Calculate payload sizes+ request_size = (+ len(serialize_mcp_input(args[0])) if len(args) > 0 else None+ )+ response_size = (+ len(serialize_mcp_input(result)) if result else None+ )++ record_mcp_metrics(+ metrics=metrics,+ mcp_operation=method or "send_request",+ mcp_method=method or "unknown",+ mcp_transport_type="stdio", # Default, could be extracted from context+ mcp_tool_name=tool_name,+ mcp_resource_uri=resource_uri,+ mcp_resource_name=None, # Not extracted in JSONRPC wrapper context+ mcp_prompt_name=prompt_name,+ environment=environment,+ application_name=application_name,+ start_time=start_time,+ end_time=end_time,+ request_size=request_size,+ response_size=response_size,+ is_error=False,+ )++ return result++ except Exception as e:+ handle_exception(span, e)++ # Record error metrics+ if not disable_metrics and metrics:+ end_time = time.time()++ # Extract method info for error metrics+ tool_name = None+ resource_uri = None+ prompt_name = None++ if method and method.startswith("tools/call") and params:+ tool_name = (+ str(getattr(params, "name", None))+ if getattr(params, "name", None)+ else None+ )+ elif method and method.startswith("resources/read") and params:+ resource_uri = (+ str(getattr(params, "uri", None))+ if getattr(params, "uri", None)+ else None+ )+ elif method and method.startswith("prompts/get") and params:+ prompt_name = (+ str(getattr(params, "name", None))+ if getattr(params, "name", None)+ else None+ )++ request_size = (+ len(serialize_mcp_input(args[0])) if len(args) > 0 else None+ )++ record_mcp_metrics(+ metrics=metrics,+ mcp_operation=method or "send_request",+ mcp_method=method or "unknown",+ mcp_transport_type="stdio",+ mcp_tool_name=tool_name,+ mcp_resource_uri=resource_uri,+ mcp_resource_name=None, # Not extracted in JSONRPC wrapper context+ mcp_prompt_name=prompt_name,+ environment=environment,+ application_name=application_name,+ start_time=start_time,+ end_time=end_time,+ request_size=request_size,+ response_size=None,+ is_error=True,+ )++ raise++ # Handle both sync and async contexts+ if inspect.iscoroutinefunction(wrapped):+ return async_wrapper(*args, **kwargs)+ else:+ # For sync calls, create an async wrapper and run it+ import asyncio++ try:+ asyncio.get_running_loop()+ # We're in an async context+ return asyncio.create_task(async_wrapper(*args, **kwargs))+ except RuntimeError:+ # No running loop+ return asyncio.run(async_wrapper(*args, **kwargs))++ return wrapper+++def _extract_enhanced_mcp_attributes(+ span, ctx: MCPInstrumentationContext, endpoint: str, response: Any = None, **kwargs+):+ """Extract all new enhanced MCP attributes based on endpoint and context data."""+ try:+ # Extract FastMCP Framework Attributes+ _extract_fastmcp_attributes(span, ctx, endpoint, **kwargs)++ # Extract Authentication & Security Attributes+ _extract_auth_security_attributes(span, ctx, endpoint, **kwargs)++ # Extract Advanced Session Attributes+ _extract_session_attributes(span, ctx, endpoint, **kwargs)++ # Extract WebSocket Attributes+ _extract_websocket_attributes(span, ctx, endpoint, **kwargs)++ # Extract Performance & Reliability Attributes+ _extract_performance_attributes(span, ctx, endpoint, response, **kwargs)++ # Extract Manager-Level Attributes+ _extract_manager_attributes(span, ctx, endpoint, **kwargs)++ # Extract Memory & Progress Attributes+ _extract_memory_progress_attributes(span, ctx, endpoint, **kwargs)++ # Extract Completion Attributes+ _extract_completion_attributes(span, ctx, endpoint, response, **kwargs)++ # Extract Advanced Operation Attributes+ _extract_advanced_operation_attributes(span, ctx, endpoint, response, **kwargs)++ except Exception:+ # Silently ignore attribute extraction errors to prevent breaking instrumentation+ pass+++def _extract_fastmcp_attributes(+ span, ctx: MCPInstrumentationContext, endpoint: str, **kwargs+):+ """Extract FastMCP framework-specific attributes."""+ try:+ if "fastmcp" in endpoint:+ # Extract from instance if available+ instance = kwargs.get("instance")+ if instance and hasattr(instance, "settings"):+ settings = instance.settings+ span.set_attribute(+ SemanticConvention.MCP_FASTMCP_SERVER_DEBUG_MODE,+ str(getattr(settings, "debug", False)),+ )+ span.set_attribute(+ SemanticConvention.MCP_FASTMCP_SERVER_LOG_LEVEL,+ str(getattr(settings, "log_level", "INFO")),+ )+ span.set_attribute(+ SemanticConvention.MCP_FASTMCP_SERVER_HOST,+ str(getattr(settings, "host", "127.0.0.1")),+ )+ span.set_attribute(+ SemanticConvention.MCP_FASTMCP_SERVER_PORT,+ str(getattr(settings, "port", 8000)),+ )+ span.set_attribute(+ SemanticConvention.MCP_FASTMCP_SERVER_TRANSPORT,+ str(getattr(settings, "transport", "stdio")),+ )++ # Additional FastMCP settings+ if hasattr(settings, "json_response"):+ span.set_attribute(+ SemanticConvention.MCP_FASTMCP_JSON_RESPONSE,+ str(settings.json_response),+ )+ if hasattr(settings, "stateless_http"):+ span.set_attribute(+ SemanticConvention.MCP_FASTMCP_STATELESS_HTTP,+ str(settings.stateless_http),+ )+ if hasattr(settings, "mount_path"):+ span.set_attribute(+ SemanticConvention.MCP_FASTMCP_MOUNT_PATH,+ str(settings.mount_path),+ )++ # Extract tool annotations if available+ if "add_tool" in endpoint or "call_tool" in endpoint:+ annotations = kwargs.get("annotations")+ if annotations:+ span.set_attribute(+ SemanticConvention.MCP_FASTMCP_TOOL_ANNOTATIONS,+ json.dumps(annotations, default=str),+ )++ structured_output = kwargs.get("structured_output")+ if structured_output is not None:+ span.set_attribute(+ SemanticConvention.MCP_FASTMCP_TOOL_STRUCTURED_OUTPUT,+ str(structured_output),+ )++ # Extract resource MIME type+ if "add_resource" in endpoint or "read_resource" in endpoint:+ mime_type = kwargs.get("mime_type")+ if mime_type:+ span.set_attribute(+ SemanticConvention.MCP_FASTMCP_RESOURCE_MIME_TYPE,+ str(mime_type),+ )++ # Extract prompt arguments+ if "add_prompt" in endpoint or "get_prompt" in endpoint:+ arguments = kwargs.get("arguments")+ if arguments:+ span.set_attribute(+ SemanticConvention.MCP_FASTMCP_PROMPT_ARGUMENTS,+ json.dumps(arguments, default=str),+ )++ except Exception:+ pass+++def _extract_auth_security_attributes(+ span, ctx: MCPInstrumentationContext, endpoint: str, **kwargs+):+ """Extract authentication and security-related attributes."""+ try:+ if "auth" in endpoint:+ # Extract client information+ client = kwargs.get("client")+ if client:+ if hasattr(client, "client_id"):+ span.set_attribute(+ SemanticConvention.MCP_AUTH_CLIENT_ID, str(client.client_id)+ )+ if hasattr(client, "grant_types"):+ span.set_attribute(+ SemanticConvention.MCP_AUTH_GRANT_TYPE,+ json.dumps(client.grant_types, default=str),+ )++ # Extract authorization parameters+ params = kwargs.get("params")+ if params and hasattr(params, "scopes"):+ span.set_attribute(+ SemanticConvention.MCP_AUTH_SCOPES,+ json.dumps(params.scopes, default=str),+ )+ if params and hasattr(params, "state"):+ span.set_attribute(SemanticConvention.MCP_AUTH_STATE, str(params.state))+ if params and hasattr(params, "code_challenge"):+ span.set_attribute(+ SemanticConvention.MCP_AUTH_CODE_CHALLENGE,+ str(params.code_challenge),+ )+ if params and hasattr(params, "redirect_uri"):+ span.set_attribute(+ SemanticConvention.MCP_AUTH_REDIRECT_URI, str(params.redirect_uri)+ )++ # Extract token information+ token = (+ kwargs.get("token")+ or kwargs.get("access_token")+ or kwargs.get("refresh_token")+ )+ if token:+ if hasattr(token, "token_type"):+ span.set_attribute(+ SemanticConvention.MCP_AUTH_TOKEN_TYPE, str(token.token_type)+ )+ if hasattr(token, "expires_at"):+ span.set_attribute(+ SemanticConvention.MCP_AUTH_EXPIRES_AT, str(token.expires_at)+ )+ if hasattr(token, "scopes"):+ span.set_attribute(+ SemanticConvention.MCP_AUTH_SCOPES,+ json.dumps(token.scopes, default=str),+ )++ # Extract transport security settings+ if "transport" in endpoint:+ instance = kwargs.get("instance")+ if instance and hasattr(instance, "security_settings"):+ span.set_attribute(+ SemanticConvention.MCP_SECURITY_TRANSPORT_SECURITY, "enabled"+ )++ except Exception:+ pass+++def _extract_session_attributes(+ span, ctx: MCPInstrumentationContext, endpoint: str, **kwargs+):+ """Extract advanced session-related attributes."""+ try:+ # Extract session configuration+ if "session" in endpoint or "initialize" in endpoint:+ # Extract timeout settings+ read_timeout = kwargs.get("read_timeout_seconds")+ if read_timeout:+ span.set_attribute(+ SemanticConvention.MCP_SESSION_READ_TIMEOUT,+ str(read_timeout.total_seconds()),+ )++ request_timeout = kwargs.get("request_read_timeout_seconds")+ if request_timeout:+ span.set_attribute(+ SemanticConvention.MCP_SESSION_REQUEST_TIMEOUT,+ str(request_timeout.total_seconds()),+ )++ # Extract capabilities+ capabilities = kwargs.get("capabilities")+ if capabilities:+ if hasattr(capabilities, "sampling"):+ span.set_attribute(+ SemanticConvention.MCP_SESSION_SAMPLING_SUPPORT,+ str(capabilities.sampling is not None),+ )+ if hasattr(capabilities, "elicitation"):+ span.set_attribute(+ SemanticConvention.MCP_SESSION_ELICITATION_SUPPORT,+ str(capabilities.elicitation is not None),+ )+ if hasattr(capabilities, "roots"):+ span.set_attribute(+ SemanticConvention.MCP_SESSION_ROOTS_SUPPORT,+ str(capabilities.roots is not None),+ )++ # Extract client info+ client_info = kwargs.get("clientInfo") or kwargs.get("client_info")+ if client_info:+ if hasattr(client_info, "name"):+ span.set_attribute(+ SemanticConvention.MCP_SESSION_CLIENT_INFO_NAME,+ str(client_info.name),+ )+ if hasattr(client_info, "version"):+ span.set_attribute(+ SemanticConvention.MCP_SESSION_CLIENT_INFO_VERSION,+ str(client_info.version),+ )++ # Extract server configuration flags+ stateless = kwargs.get("stateless")+ if stateless is not None:+ span.set_attribute(+ SemanticConvention.MCP_SESSION_STATELESS, str(stateless)+ )++ raise_exceptions = kwargs.get("raise_exceptions")+ if raise_exceptions is not None:+ span.set_attribute(+ SemanticConvention.MCP_SESSION_RAISE_EXCEPTIONS,+ str(raise_exceptions),+ )++ # Extract progress token+ progress_token = kwargs.get("progress_token") or (+ kwargs.get("params", {}).get("_meta", {}).get("progressToken")+ )+ if progress_token:+ span.set_attribute(+ SemanticConvention.MCP_SESSION_PROGRESS_TOKEN, str(progress_token)+ )++ except Exception:+ pass+++def _extract_websocket_attributes(+ span, ctx: MCPInstrumentationContext, endpoint: str, **kwargs+):+ """Extract WebSocket-specific attributes."""+ try:+ if "websocket" in endpoint:+ # Extract WebSocket URL+ url = kwargs.get("url")+ if url:+ span.set_attribute(SemanticConvention.MCP_WEBSOCKET_URL, str(url))++ # Extract subprotocol (typically "mcp")+ subprotocols = kwargs.get("subprotocols")+ if subprotocols:+ span.set_attribute(+ SemanticConvention.MCP_WEBSOCKET_SUBPROTOCOL,+ json.dumps(subprotocols, default=str),+ )+ elif "websocket" in endpoint:+ # Default MCP WebSocket subprotocol+ span.set_attribute(SemanticConvention.MCP_WEBSOCKET_SUBPROTOCOL, "mcp")++ except Exception:+ pass+++def _extract_performance_attributes(+ span, ctx: MCPInstrumentationContext, endpoint: str, response: Any = None, **kwargs+):+ """Extract performance and reliability metrics."""+ try:+ # Calculate execution time if we have timing data+ if hasattr(ctx, "_start_time") and hasattr(ctx, "_end_time"):+ execution_time = ctx._end_time - ctx._start_time++ if "call_tool" in endpoint:+ span.set_attribute(+ SemanticConvention.MCP_TOOL_EXECUTION_TIME, execution_time+ )+ elif "read_resource" in endpoint:+ span.set_attribute(+ SemanticConvention.MCP_RESOURCE_READ_TIME, execution_time+ )+ elif "render_prompt" in endpoint or "get_prompt" in endpoint:+ span.set_attribute(+ SemanticConvention.MCP_PROMPT_RENDER_TIME, execution_time+ )+ elif "transport" in endpoint:+ span.set_attribute(+ SemanticConvention.MCP_TRANSPORT_CONNECTION_TIME, execution_time+ )++ # Extract progress information+ if "progress" in endpoint:+ progress = kwargs.get("progress")+ if progress is not None:+ span.set_attribute(+ SemanticConvention.MCP_PROGRESS_COMPLETION_PERCENTAGE, str(progress)+ )++ total = kwargs.get("total")+ if total is not None:+ span.set_attribute(SemanticConvention.MCP_PROGRESS_TOTAL, str(total))++ message = kwargs.get("message")+ if message:+ span.set_attribute(+ SemanticConvention.MCP_PROGRESS_MESSAGE, str(message)+ )++ # Extract elicitation action+ if "elicit" in endpoint and response:+ if hasattr(response, "action"):+ span.set_attribute(+ SemanticConvention.MCP_ELICITATION_ACTION, str(response.action)+ )++ # Extract sampling parameters+ if "sampling" in endpoint or "create_message" in endpoint:+ max_tokens = kwargs.get("max_tokens")+ if max_tokens:+ span.set_attribute(+ SemanticConvention.MCP_SAMPLING_MAX_TOKENS, str(max_tokens)+ )++ messages = kwargs.get("messages")+ if messages:+ span.set_attribute(+ SemanticConvention.MCP_SAMPLING_MESSAGES, str(len(messages))+ )++ except Exception:+ pass+++def _extract_manager_attributes(+ span, ctx: MCPInstrumentationContext, endpoint: str, **kwargs+):+ """Extract manager-level attributes for business intelligence."""+ try:+ if "manager" in endpoint:+ instance = kwargs.get("instance")+ if instance:+ # Extract manager type and operation count+ if "tool_manager" in endpoint:+ span.set_attribute(SemanticConvention.MCP_MANAGER_TYPE, "tool")+ if hasattr(instance, "_tools"):+ span.set_attribute(+ SemanticConvention.MCP_TOOL_MANAGER_TOOL_COUNT,+ str(len(instance._tools)),+ )+ if hasattr(instance, "warn_on_duplicate_tools"):+ span.set_attribute(+ SemanticConvention.MCP_TOOL_MANAGER_WARN_DUPLICATES,+ str(instance.warn_on_duplicate_tools),+ )++ elif "resource_manager" in endpoint:+ span.set_attribute(SemanticConvention.MCP_MANAGER_TYPE, "resource")+ if hasattr(instance, "_resources"):+ span.set_attribute(+ SemanticConvention.MCP_RESOURCE_MANAGER_RESOURCE_COUNT,+ str(len(instance._resources)),+ )+ if hasattr(instance, "warn_on_duplicate_resources"):+ span.set_attribute(+ SemanticConvention.MCP_RESOURCE_MANAGER_WARN_DUPLICATES,+ str(instance.warn_on_duplicate_resources),+ )++ elif "prompt_manager" in endpoint:+ span.set_attribute(SemanticConvention.MCP_MANAGER_TYPE, "prompt")+ if hasattr(instance, "_prompts"):+ span.set_attribute(+ SemanticConvention.MCP_PROMPT_MANAGER_PROMPT_COUNT,+ str(len(instance._prompts)),+ )+ if hasattr(instance, "warn_on_duplicate_prompts"):+ span.set_attribute(+ SemanticConvention.MCP_PROMPT_MANAGER_WARN_DUPLICATES,+ str(instance.warn_on_duplicate_prompts),+ )++ except Exception:+ pass+++def _extract_memory_progress_attributes(+ span, ctx: MCPInstrumentationContext, endpoint: str, **kwargs+):+ """Extract memory transport and progress context attributes."""+ try:+ if "memory" in endpoint:+ span.set_attribute(SemanticConvention.MCP_MEMORY_TRANSPORT_TYPE, "memory")++ # Extract connection session info+ if "connect" in endpoint:+ span.set_attribute(+ SemanticConvention.MCP_MEMORY_CLIENT_SERVER_SESSION, "created"+ )++ if "progress_context" in endpoint or "ProgressContext" in str(+ type(kwargs.get("instance", ""))+ ):+ instance = kwargs.get("instance")+ if instance:+ if hasattr(instance, "current"):+ span.set_attribute(+ SemanticConvention.MCP_PROGRESS_CONTEXT_CURRENT,+ str(instance.current),+ )+ if hasattr(instance, "total"):+ span.set_attribute(+ SemanticConvention.MCP_PROGRESS_CONTEXT_TOTAL,+ str(instance.total),+ )++ except Exception:+ pass+++def _extract_completion_attributes(+ span, ctx: MCPInstrumentationContext, endpoint: str, response: Any = None, **kwargs+):+ """Extract completion-related attributes."""+ try:+ if "complete" in endpoint:+ # Extract completion request parameters+ ref = kwargs.get("ref")+ if ref:+ if hasattr(ref, "type"):+ span.set_attribute(+ SemanticConvention.MCP_COMPLETION_REF_TYPE, str(ref.type)+ )++ argument = kwargs.get("argument")+ if argument:+ if hasattr(argument, "name"):+ span.set_attribute(+ SemanticConvention.MCP_COMPLETION_ARGUMENT_NAME,+ str(argument.name),+ )+ if hasattr(argument, "value"):+ span.set_attribute(+ SemanticConvention.MCP_COMPLETION_ARGUMENT_VALUE,+ str(argument.value),+ )++ context_args = kwargs.get("context_arguments")+ if context_args:+ span.set_attribute(+ SemanticConvention.MCP_COMPLETION_CONTEXT_ARGUMENTS,+ json.dumps(context_args, default=str),+ )++ # Extract completion response+ if response and hasattr(response, "completion"):+ completion = response.completion+ if hasattr(completion, "values"):+ span.set_attribute(+ SemanticConvention.MCP_COMPLETION_VALUES,+ str(len(completion.values)),+ )+ if hasattr(completion, "total"):+ span.set_attribute(+ SemanticConvention.MCP_COMPLETION_TOTAL, str(completion.total)+ )+ if hasattr(completion, "hasMore"):+ span.set_attribute(+ SemanticConvention.MCP_COMPLETION_HAS_MORE,+ str(completion.hasMore),+ )++ except Exception:+ pass+++def _extract_advanced_operation_attributes(+ span, ctx: MCPInstrumentationContext, endpoint: str, response: Any = None, **kwargs+):+ """Extract advanced operation-specific attributes."""+ try:+ # Extract ping response time+ if "ping" in endpoint:+ if hasattr(ctx, "_start_time") and hasattr(ctx, "_end_time"):+ response_time = ctx._end_time - ctx._start_time+ span.set_attribute(+ SemanticConvention.MCP_PING_RESPONSE_TIME, response_time+ )++ # Extract logging level changes+ if "set_logging" in endpoint:+ level = kwargs.get("level")+ if level:+ span.set_attribute(SemanticConvention.MCP_LOGGING_LEVEL_SET, str(level))++ # Extract notification details+ if "notification" in endpoint:+ notification_type = "progress" if "progress" in endpoint else "general"+ span.set_attribute(+ SemanticConvention.MCP_NOTIFICATION_TYPE, notification_type+ )++ related_request_id = kwargs.get("related_request_id")+ if related_request_id:+ span.set_attribute(+ SemanticConvention.MCP_NOTIFICATION_RELATED_REQUEST_ID,+ str(related_request_id),+ )++ except Exception:+ passdiff --git a/sdk/python/src/openlit/otel/metrics.py b/sdk/python/src/openlit/otel/metrics.pyindex 4838f1a9..d70cb9c4 100644--- a/sdk/python/src/openlit/otel/metrics.py+++ b/sdk/python/src/openlit/otel/metrics.py@@ -101,6 +101,33 @@ _GEN_AI_CLIENT_TOKEN_USAGE_BUCKETS = [67108864,]+# MCP-specific bucket boundaries for performance and size metrics+_MCP_CLIENT_OPERATION_DURATION_BUCKETS = [+ 0.001, # 1ms+ 0.005, # 5ms+ 0.01, # 10ms+ 0.05, # 50ms+ 0.1, # 100ms+ 0.5, # 500ms+ 1.0, # 1s+ 2.0, # 2s+ 5.0, # 5s+ 10.0, # 10s+]++_MCP_PAYLOAD_SIZE_BUCKETS = [+ 100, # 100 bytes+ 500, # 500 bytes+ 1024, # 1KB+ 5120, # 5KB+ 10240, # 10KB+ 51200, # 50KB+ 102400, # 100KB+ 512000, # 500KB+ 1048576, # 1MB+ 5242880, # 5MB+]+def setup_meter(application_name, environment, meter, otlp_endpoint, otlp_headers):"""@@ -225,6 +252,60 @@ def setup_meter(application_name, environment, meter, otlp_endpoint, otlp_headerdescription="Number of requests to VectorDBs",unit="1",),+ # MCP-specific metrics for business intelligence and operational insights+ "mcp_requests": meter.create_counter(+ name=SemanticConvention.MCP_REQUESTS,+ description="Number of requests to MCP servers by operation type",+ unit="1",+ ),+ "mcp_client_operation_duration": meter.create_histogram(+ name=SemanticConvention.MCP_CLIENT_OPERATION_DURATION_METRIC,+ description="MCP client operation duration",+ unit="s",+ explicit_bucket_boundaries_advisory=_MCP_CLIENT_OPERATION_DURATION_BUCKETS,+ ),+ "mcp_request_size": meter.create_histogram(+ name=SemanticConvention.MCP_REQUEST_SIZE,+ description="Size of MCP request payloads",+ unit="By",+ explicit_bucket_boundaries_advisory=_MCP_PAYLOAD_SIZE_BUCKETS,+ ),+ "mcp_response_size": meter.create_histogram(+ name=SemanticConvention.MCP_RESPONSE_SIZE_METRIC,+ description="Size of MCP response payloads",+ unit="By",+ explicit_bucket_boundaries_advisory=_MCP_PAYLOAD_SIZE_BUCKETS,+ ),+ "mcp_tool_calls": meter.create_counter(+ name=SemanticConvention.MCP_TOOL_CALLS,+ description="Number of MCP tool calls by tool name",+ unit="1",+ ),+ "mcp_resource_reads": meter.create_counter(+ name=SemanticConvention.MCP_RESOURCE_READS,+ description="Number of MCP resource reads by resource type",+ unit="1",+ ),+ "mcp_prompt_gets": meter.create_counter(+ name=SemanticConvention.MCP_PROMPT_GETS,+ description="Number of MCP prompt retrievals by prompt name",+ unit="1",+ ),+ "mcp_transport_usage": meter.create_counter(+ name=SemanticConvention.MCP_TRANSPORT_USAGE,+ description="MCP transport type usage (stdio, sse, websocket)",+ unit="1",+ ),+ "mcp_errors": meter.create_counter(+ name=SemanticConvention.MCP_ERRORS,+ description="Number of MCP operation errors by operation type",+ unit="1",+ ),+ "mcp_operation_success_rate": meter.create_histogram(+ name=SemanticConvention.MCP_OPERATION_SUCCESS_RATE,+ description="MCP operation success rate by operation type",+ unit="1",+ ),}return metrics_dict, Nonediff --git a/sdk/python/src/openlit/semcov/__init__.py b/sdk/python/src/openlit/semcov/__init__.pyindex 5cecfef4..51c0342b 100644--- a/sdk/python/src/openlit/semcov/__init__.py+++ b/sdk/python/src/openlit/semcov/__init__.py@@ -984,3 +984,178 @@ class SemanticConvention:GEN_AI_REASONING_EXECUTION_DURATION = "gen_ai.reasoning.execution_duration"# Note: Most workflow and team attributes already exist above, only add truly new ones if needed++ # === MCP (Model Context Protocol) SEMANTIC CONVENTIONS ===++ # MCP System+ GEN_AI_SYSTEM_MCP = "mcp"++ # MCP Operation Types+ GEN_AI_OPERATION_TYPE_MCP_TOOL_CALL = "mcp_tool_call"+ GEN_AI_OPERATION_TYPE_MCP_TOOL_LIST = "mcp_tool_list"+ GEN_AI_OPERATION_TYPE_MCP_RESOURCE_READ = "mcp_resource_read"+ GEN_AI_OPERATION_TYPE_MCP_RESOURCE_LIST = "mcp_resource_list"+ GEN_AI_OPERATION_TYPE_MCP_REQUEST = "mcp_request"+ GEN_AI_OPERATION_TYPE_MCP_RESPONSE = "mcp_response"+ GEN_AI_OPERATION_TYPE_MCP_SERVER = "mcp_server"+ GEN_AI_OPERATION_TYPE_MCP_CLIENT = "mcp_client"++ # MCP Request/Response Attributes (using mcp.* namespace)+ MCP_METHOD = "mcp.method"+ MCP_MESSAGE_ID = "mcp.message_id"+ MCP_JSONRPC_VERSION = "mcp.jsonrpc_version"+ MCP_PARAMS = "mcp.params"+ MCP_RESULT = "mcp.result"+ MCP_ERROR_CODE = "mcp.error.code"+ MCP_ERROR_MESSAGE = "mcp.error.message"+ MCP_ERROR_DATA = "mcp.error.data"++ # MCP Tool Attributes+ MCP_TOOL_NAME = "mcp.tool.name"+ MCP_TOOL_DESCRIPTION = "mcp.tool.description"+ MCP_TOOL_ARGUMENTS = "mcp.tool.arguments"+ MCP_TOOL_RESULT = "mcp.tool.result"++ # MCP Resource Attributes+ MCP_RESOURCE_URI = "mcp.resource.uri"+ MCP_RESOURCE_NAME = "mcp.resource.name"+ MCP_RESOURCE_DESCRIPTION = "mcp.resource.description"+ MCP_RESOURCE_MIME_TYPE = "mcp.resource.mime_type"+ MCP_RESOURCE_SIZE = "mcp.resource.size"++ # MCP Transport Attributes+ MCP_TRANSPORT_TYPE = "mcp.transport.type"+ MCP_TRANSPORT_STDIO = "stdio"+ MCP_TRANSPORT_SSE = "sse"+ MCP_TRANSPORT_WEBSOCKET = "websocket"++ # MCP Request/Response Payload Attributes+ MCP_REQUEST_PAYLOAD = "mcp.request.payload"+ MCP_RESPONSE_PAYLOAD = "mcp.response.payload"++ # MCP Core Attributes+ MCP_OPERATION = "mcp.operation.name"+ MCP_SYSTEM = "mcp.system"+ MCP_SDK_VERSION = "mcp.sdk.version"+ MCP_CLIENT_OPERATION_DURATION = "mcp.client.operation.duration"++ # MCP Prompt Attributes+ MCP_PROMPT_NAME = "mcp.prompt.name"+ MCP_PROMPT_DESCRIPTION = "mcp.prompt.description"++ # MCP Server/Client Attributes+ MCP_SERVER_NAME = "mcp.server.name"+ MCP_SERVER_VERSION = "mcp.server.version"+ MCP_CLIENT_VERSION = "mcp.client.version"+ MCP_CLIENT_TYPE = "mcp.client.type"+ MCP_RESPONSE_SIZE = "mcp.response.size"++ # MCP Metrics (for business intelligence and operational insights)+ MCP_REQUESTS = "mcp.requests"+ MCP_CLIENT_OPERATION_DURATION_METRIC = "mcp.client.operation.duration"+ MCP_REQUEST_SIZE = "mcp.request.size"+ MCP_RESPONSE_SIZE_METRIC = "mcp.response.size"+ MCP_TOOL_CALLS = "mcp.tool.calls"+ MCP_RESOURCE_READS = "mcp.resource.reads"+ MCP_PROMPT_GETS = "mcp.prompt.gets"+ MCP_TRANSPORT_USAGE = "mcp.transport.usage"+ MCP_ERRORS = "mcp.errors"+ MCP_OPERATION_SUCCESS_RATE = "mcp.operation.success_rate"++ # === NEW FASTMCP FRAMEWORK ATTRIBUTES ===+ MCP_FASTMCP_SERVER_DEBUG_MODE = "mcp.fastmcp.server.debug_mode"+ MCP_FASTMCP_SERVER_LOG_LEVEL = "mcp.fastmcp.server.log_level"+ MCP_FASTMCP_SERVER_HOST = "mcp.fastmcp.server.host"+ MCP_FASTMCP_SERVER_PORT = "mcp.fastmcp.server.port"+ MCP_FASTMCP_SERVER_TRANSPORT = "mcp.fastmcp.server.transport"+ MCP_FASTMCP_TOOL_ANNOTATIONS = "mcp.fastmcp.tool.annotations"+ MCP_FASTMCP_RESOURCE_MIME_TYPE = "mcp.fastmcp.resource.mime_type"+ MCP_FASTMCP_PROMPT_ARGUMENTS = "mcp.fastmcp.prompt.arguments"+ MCP_FASTMCP_TOOL_STRUCTURED_OUTPUT = "mcp.fastmcp.tool.structured_output"+ MCP_FASTMCP_SERVER_INSTRUCTIONS = "mcp.fastmcp.server.instructions"+ MCP_FASTMCP_SERVER_LIFESPAN = "mcp.fastmcp.server.lifespan"+ MCP_FASTMCP_MOUNT_PATH = "mcp.fastmcp.mount_path"+ MCP_FASTMCP_SSE_PATH = "mcp.fastmcp.sse_path"+ MCP_FASTMCP_MESSAGE_PATH = "mcp.fastmcp.message_path"+ MCP_FASTMCP_STREAMABLE_HTTP_PATH = "mcp.fastmcp.streamable_http_path"+ MCP_FASTMCP_JSON_RESPONSE = "mcp.fastmcp.json_response"+ MCP_FASTMCP_STATELESS_HTTP = "mcp.fastmcp.stateless_http"++ # === NEW AUTHENTICATION & SECURITY ATTRIBUTES ===+ MCP_AUTH_CLIENT_ID = "mcp.auth.client_id"+ MCP_AUTH_SCOPES = "mcp.auth.scopes"+ MCP_AUTH_GRANT_TYPE = "mcp.auth.grant_type"+ MCP_AUTH_TOKEN_TYPE = "mcp.auth.token_type"+ MCP_AUTH_EXPIRES_AT = "mcp.auth.expires_at"+ MCP_AUTH_AUTHORIZATION_CODE = "mcp.auth.authorization_code"+ MCP_AUTH_REDIRECT_URI = "mcp.auth.redirect_uri"+ MCP_AUTH_STATE = "mcp.auth.state"+ MCP_AUTH_CODE_CHALLENGE = "mcp.auth.code_challenge"+ MCP_AUTH_RESOURCE_INDICATOR = "mcp.auth.resource_indicator"+ MCP_SECURITY_TRANSPORT_SECURITY = "mcp.security.transport_security"+ MCP_SECURITY_DNS_REBINDING_PROTECTION = "mcp.security.dns_rebinding_protection"+ MCP_AUTH_TOKEN_VERIFICATION_SUCCESS = "mcp.auth.token_verification_success"+ MCP_AUTH_CLIENT_REGISTRATION_TYPE = "mcp.auth.client_registration_type"++ # === NEW ADVANCED SESSION ATTRIBUTES ===+ MCP_SESSION_REQUEST_TIMEOUT = "mcp.session.request_timeout"+ MCP_SESSION_PROGRESS_TOKEN = "mcp.session.progress_token"+ MCP_SESSION_ELICITATION_SUPPORT = "mcp.session.elicitation_support"+ MCP_SESSION_SAMPLING_SUPPORT = "mcp.session.sampling_support"+ MCP_SESSION_ROOTS_SUPPORT = "mcp.session.roots_support"+ MCP_SESSION_READ_TIMEOUT = "mcp.session.read_timeout"+ MCP_SESSION_STATELESS = "mcp.session.stateless"+ MCP_SESSION_RAISE_EXCEPTIONS = "mcp.session.raise_exceptions"+ MCP_SESSION_CLIENT_INFO_NAME = "mcp.session.client_info.name"+ MCP_SESSION_CLIENT_INFO_VERSION = "mcp.session.client_info.version"+ MCP_SESSION_COMPLETION_SUPPORT = "mcp.session.completion_support"+ MCP_SESSION_LOGGING_SUPPORT = "mcp.session.logging_support"++ # === NEW WEBSOCKET SPECIFIC ATTRIBUTES ===+ MCP_WEBSOCKET_SUBPROTOCOL = "mcp.websocket.subprotocol"+ MCP_WEBSOCKET_URL = "mcp.websocket.url"+ MCP_WEBSOCKET_CONNECTION_STATE = "mcp.websocket.connection_state"++ # === NEW PERFORMANCE & RELIABILITY ATTRIBUTES ===+ MCP_TOOL_EXECUTION_TIME = "mcp.tool.execution_time"+ MCP_RESOURCE_READ_TIME = "mcp.resource.read_time"+ MCP_PROMPT_RENDER_TIME = "mcp.prompt.render_time"+ MCP_TRANSPORT_CONNECTION_TIME = "mcp.transport.connection_time"+ MCP_PROGRESS_COMPLETION_PERCENTAGE = "mcp.progress.completion_percentage"+ MCP_PROGRESS_TOTAL = "mcp.progress.total"+ MCP_PROGRESS_MESSAGE = "mcp.progress.message"+ MCP_ELICITATION_ACTION = "mcp.elicitation.action"+ MCP_ELICITATION_SCHEMA = "mcp.elicitation.schema"+ MCP_SAMPLING_MAX_TOKENS = "mcp.sampling.max_tokens"+ MCP_SAMPLING_MESSAGES = "mcp.sampling.messages"++ # === NEW MANAGER-LEVEL ATTRIBUTES ===+ MCP_MANAGER_TYPE = "mcp.manager.type"+ MCP_MANAGER_OPERATION = "mcp.manager.operation"+ MCP_TOOL_MANAGER_TOOL_COUNT = "mcp.tool_manager.tool_count"+ MCP_RESOURCE_MANAGER_RESOURCE_COUNT = "mcp.resource_manager.resource_count"+ MCP_PROMPT_MANAGER_PROMPT_COUNT = "mcp.prompt_manager.prompt_count"+ MCP_TOOL_MANAGER_WARN_DUPLICATES = "mcp.tool_manager.warn_duplicates"+ MCP_RESOURCE_MANAGER_WARN_DUPLICATES = "mcp.resource_manager.warn_duplicates"+ MCP_PROMPT_MANAGER_WARN_DUPLICATES = "mcp.prompt_manager.warn_duplicates"++ # === NEW MEMORY & PROGRESS SPECIFIC ATTRIBUTES ===+ MCP_MEMORY_TRANSPORT_TYPE = "mcp.memory.transport_type"+ MCP_MEMORY_CLIENT_SERVER_SESSION = "mcp.memory.client_server_session"+ MCP_PROGRESS_CONTEXT_CURRENT = "mcp.progress_context.current"+ MCP_PROGRESS_CONTEXT_TOTAL = "mcp.progress_context.total"++ # === NEW COMPLETION ATTRIBUTES ===+ MCP_COMPLETION_REF_TYPE = "mcp.completion.ref.type"+ MCP_COMPLETION_ARGUMENT_NAME = "mcp.completion.argument.name"+ MCP_COMPLETION_ARGUMENT_VALUE = "mcp.completion.argument.value"+ MCP_COMPLETION_CONTEXT_ARGUMENTS = "mcp.completion.context.arguments"+ MCP_COMPLETION_VALUES = "mcp.completion.values"+ MCP_COMPLETION_TOTAL = "mcp.completion.total"+ MCP_COMPLETION_HAS_MORE = "mcp.completion.has_more"++ # === NEW ADVANCED OPERATION ATTRIBUTES ===+ MCP_PING_RESPONSE_TIME = "mcp.ping.response_time"+ MCP_LOGGING_LEVEL_SET = "mcp.logging.level_set"+ MCP_NOTIFICATION_TYPE = "mcp.notification.type"+ MCP_NOTIFICATION_RELATED_REQUEST_ID = "mcp.notification.related_request_id"diff --git a/sdk/python/tests/test_firecrawl.py b/sdk/python/tests/test_firecrawl.py.holdsimilarity index 100%rename from sdk/python/tests/test_firecrawl.pyrename to sdk/python/tests/test_firecrawl.py.hold