|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""Location: ./plugins/tools_telemetry_exporter/telemetry_exporter.py |
| 3 | +Copyright 2025 |
| 4 | +SPDX-License-Identifier: Apache-2.0 |
| 5 | +
|
| 6 | +Tools Telemetry Exporter Plugin. |
| 7 | +This plugin exports comprehensive tool invocation telemetry to OpenTelemetry. |
| 8 | +""" |
| 9 | + |
| 10 | +# Standard |
| 11 | +import json |
| 12 | +from typing import Dict |
| 13 | + |
| 14 | +# First-Party |
| 15 | +from mcpgateway.common.models import Gateway, Tool |
| 16 | +from mcpgateway.plugins.framework import Plugin, PluginConfig, PluginContext |
| 17 | +from mcpgateway.plugins.framework.constants import GATEWAY_METADATA, TOOL_METADATA |
| 18 | +from mcpgateway.plugins.framework.hooks.tools import ToolPostInvokePayload, ToolPostInvokeResult, ToolPreInvokePayload, ToolPreInvokeResult |
| 19 | +from mcpgateway.services.logging_service import LoggingService |
| 20 | + |
| 21 | +# Initialize logging service first |
| 22 | +logging_service = LoggingService() |
| 23 | +logger = logging_service.get_logger(__name__) |
| 24 | + |
| 25 | + |
| 26 | +class ToolsTelemetryExporterPlugin(Plugin): |
| 27 | + """Export comprehensive tool invocation telemetry to OpenTelemetry.""" |
| 28 | + |
| 29 | + def __init__(self, config: PluginConfig): |
| 30 | + """Initialize the ToolsTelemetryExporterPlugin. |
| 31 | +
|
| 32 | + Args: |
| 33 | + config: Plugin configuration containing telemetry settings. |
| 34 | + """ |
| 35 | + super().__init__(config) |
| 36 | + self.is_open_telemetry_available = self._is_open_telemetry_available() |
| 37 | + self.telemetry_config = config.config |
| 38 | + |
| 39 | + @staticmethod |
| 40 | + def _is_open_telemetry_available() -> bool: |
| 41 | + """Check if OpenTelemetry is available for import. |
| 42 | +
|
| 43 | + Returns: |
| 44 | + True if OpenTelemetry can be imported, False otherwise. |
| 45 | + """ |
| 46 | + try: |
| 47 | + # Third-Party |
| 48 | + from opentelemetry import trace # noqa: F401 # pylint: disable=import-outside-toplevel,unused-import |
| 49 | + |
| 50 | + return True |
| 51 | + except ImportError: |
| 52 | + logger.warning("ToolsTelemetryExporter: OpenTelemetry is not available. Telemetry export will be disabled.") |
| 53 | + return False |
| 54 | + |
| 55 | + @staticmethod |
| 56 | + def _get_base_context_attributes(context: PluginContext) -> Dict: |
| 57 | + """Extract base context attributes from plugin context. |
| 58 | +
|
| 59 | + Args: |
| 60 | + context: Plugin execution context containing global context. |
| 61 | +
|
| 62 | + Returns: |
| 63 | + Dictionary with base attributes (request_id, user, tenant_id, server_id). |
| 64 | + """ |
| 65 | + global_context = context.global_context |
| 66 | + return { |
| 67 | + "request_id": global_context.request_id or "", |
| 68 | + "user": global_context.user or "", |
| 69 | + "tenant_id": global_context.tenant_id or "", |
| 70 | + "server_id": global_context.server_id or "", |
| 71 | + } |
| 72 | + |
| 73 | + def _get_pre_invoke_context_attributes(self, context: PluginContext) -> Dict: |
| 74 | + """Extract pre-invocation context attributes including tool and gateway metadata. |
| 75 | +
|
| 76 | + Args: |
| 77 | + context: Plugin execution context containing tool and gateway metadata. |
| 78 | +
|
| 79 | + Returns: |
| 80 | + Dictionary with base attributes plus tool and target MCP server details. |
| 81 | + """ |
| 82 | + global_context = context.global_context |
| 83 | + tool_metadata: Tool = global_context.metadata.get(TOOL_METADATA) |
| 84 | + target_mcp_server_metadata: Gateway = global_context.metadata.get(GATEWAY_METADATA) |
| 85 | + |
| 86 | + return { |
| 87 | + **self._get_base_context_attributes(context), |
| 88 | + "tool": { |
| 89 | + "name": tool_metadata.name or "", |
| 90 | + "target_tool_name": tool_metadata.original_name or "", |
| 91 | + "description": tool_metadata.description or "", |
| 92 | + }, |
| 93 | + "target_mcp_server": { |
| 94 | + "id": target_mcp_server_metadata.id or "", |
| 95 | + "name": target_mcp_server_metadata.name or "", |
| 96 | + "url": str(target_mcp_server_metadata.url or ""), |
| 97 | + }, |
| 98 | + } |
| 99 | + |
| 100 | + def _get_post_invoke_context_attributes(self, context: PluginContext) -> Dict: |
| 101 | + """Extract post-invocation context attributes. |
| 102 | +
|
| 103 | + Args: |
| 104 | + context: Plugin execution context. |
| 105 | +
|
| 106 | + Returns: |
| 107 | + Dictionary with base context attributes for post-invocation telemetry. |
| 108 | + """ |
| 109 | + return { |
| 110 | + **self._get_base_context_attributes(context), |
| 111 | + } |
| 112 | + |
| 113 | + async def tool_pre_invoke(self, payload: ToolPreInvokePayload, context: PluginContext) -> ToolPreInvokeResult: |
| 114 | + """Capture pre-invocation telemetry for tools. |
| 115 | +
|
| 116 | + Args: |
| 117 | + payload: The tool payload containing arguments. |
| 118 | + context: Plugin execution context. |
| 119 | +
|
| 120 | + Returns: |
| 121 | + Result with potentially modified tool arguments. |
| 122 | + """ |
| 123 | + logger.info("ToolsTelemetryExporter: Capturing pre-invocation tool telemetry.") |
| 124 | + context_attributes = self._get_pre_invoke_context_attributes(context) |
| 125 | + |
| 126 | + export_attributes = { |
| 127 | + "request_id": context_attributes["request_id"], |
| 128 | + "user": context_attributes["user"], |
| 129 | + "tenant_id": context_attributes["tenant_id"], |
| 130 | + "server_id": context_attributes["server_id"], |
| 131 | + "target_mcp_server.id": context_attributes["target_mcp_server"]["id"], |
| 132 | + "target_mcp_server.name": context_attributes["target_mcp_server"]["name"], |
| 133 | + "target_mcp_server.url": context_attributes["target_mcp_server"]["url"], |
| 134 | + "tool.name": context_attributes["tool"]["name"], |
| 135 | + "tool.target_tool_name": context_attributes["tool"]["target_tool_name"], |
| 136 | + "tool.description": context_attributes["tool"]["description"], |
| 137 | + "tool.invocation.args": json.dumps(payload.args), |
| 138 | + "headers": payload.headers.model_dump_json() if payload.headers else "{}", |
| 139 | + } |
| 140 | + |
| 141 | + await self._export_telemetry(attributes=export_attributes, span_name="tool.pre_invoke") |
| 142 | + return ToolPreInvokeResult(continue_processing=True) |
| 143 | + |
| 144 | + async def tool_post_invoke(self, payload: ToolPostInvokePayload, context: PluginContext) -> ToolPostInvokeResult: |
| 145 | + """Capture post-invocation telemetry. |
| 146 | +
|
| 147 | + Args: |
| 148 | + payload: Tool result payload containing the tool name and execution result. |
| 149 | + context: Plugin context with state from pre-invoke hook. |
| 150 | +
|
| 151 | + Returns: |
| 152 | + ToolPostInvokeResult allowing execution to continue. |
| 153 | + """ |
| 154 | + logger.info("ToolsTelemetryExporter: Capturing post-invocation tool telemetry.") |
| 155 | + context_attributes = self._get_post_invoke_context_attributes(context) |
| 156 | + |
| 157 | + export_attributes = { |
| 158 | + "request_id": context_attributes["request_id"], |
| 159 | + "user": context_attributes["user"], |
| 160 | + "tenant_id": context_attributes["tenant_id"], |
| 161 | + "server_id": context_attributes["server_id"], |
| 162 | + } |
| 163 | + |
| 164 | + result = payload.result if payload.result else {} |
| 165 | + has_error = result.get("isError", False) |
| 166 | + if self.telemetry_config.get("export_full_payload", False) and not has_error: |
| 167 | + max_payload_bytes_size = self.telemetry_config.get("max_payload_bytes_size", 10000) |
| 168 | + result_content = result.get("content") |
| 169 | + if result_content: |
| 170 | + result_content_str = json.dumps(result_content, default=str) |
| 171 | + if len(result_content_str) <= max_payload_bytes_size: |
| 172 | + export_attributes["tool.invocation.result"] = result_content_str |
| 173 | + else: |
| 174 | + truncated_content = result_content_str[:max_payload_bytes_size] |
| 175 | + export_attributes["tool.invocation.result"] = truncated_content + "...<truncated>" |
| 176 | + else: |
| 177 | + export_attributes["tool.invocation.result"] = "<No content in result>" |
| 178 | + export_attributes["tool.invocation.has_error"] = has_error |
| 179 | + |
| 180 | + await self._export_telemetry(attributes=export_attributes, span_name="tool.post_invoke") |
| 181 | + return ToolPostInvokeResult(continue_processing=True) |
| 182 | + |
| 183 | + async def _export_telemetry(self, attributes: Dict, span_name: str) -> None: |
| 184 | + """Export telemetry attributes to OpenTelemetry. |
| 185 | +
|
| 186 | + Args: |
| 187 | + attributes: Dictionary of telemetry attributes to export. |
| 188 | + span_name: Name of the OpenTelemetry span to create. |
| 189 | + """ |
| 190 | + if not self.is_open_telemetry_available: |
| 191 | + logger.debug("ToolsTelemetryExporter: OpenTelemetry not available. Skipping telemetry export.") |
| 192 | + return |
| 193 | + |
| 194 | + # Third-Party |
| 195 | + from opentelemetry import trace # pylint: disable=import-outside-toplevel |
| 196 | + |
| 197 | + try: |
| 198 | + tracer = trace.get_tracer(__name__) |
| 199 | + current_span = trace.get_current_span() |
| 200 | + if not current_span or not current_span.is_recording(): |
| 201 | + logger.warning("ToolsTelemetryExporter: No active span found. Skipping telemetry export.") |
| 202 | + return |
| 203 | + |
| 204 | + with tracer.start_as_current_span(span_name) as span: |
| 205 | + for key, value in attributes.items(): |
| 206 | + span.set_attribute(key, value) |
| 207 | + logger.debug(f"ToolsTelemetryExporter: Exported telemetry for span '{span_name}' with attributes: {attributes}") |
| 208 | + except Exception as e: |
| 209 | + logger.error(f"ToolsTelemetryExporter: Error creating span '{span_name}': {e}", exc_info=True) |
0 commit comments