""" MCP tool for listing Loki label names. This tool allows authorized AI agents and developers to discover all available label names in Loki for log filtering and querying. Returns JSON in Loki API format: {"status": "success", "data": ["label1", "label2", ...]}. """ import json from typing import Any from pydantic import ValidationError as PydanticValidationError from src.models.loki_queries import LokiLabelsRequest from src.services.auth import get_valid_server_auth from src.services.loki_resolve import get_loki_client_for_cluster from src.tools.query_range import mcp from src.utils.errors import ( AuthorizationError, AuthServiceError, LokiAPIError, LokiTimeoutError, NetworkError, ValidationError, ) from src.utils.tool_response import format_tool_error, tool_text_response @mcp.tool() async def list_loki_labels( cluster_id: str, env: str, deploy_type: str, start: str | None = None, end: str | None = None, query: str | None = None, ) -> list[dict[str, Any]]: """ List all available label names in Loki for log filtering and querying. Returns JSON in the same format as Loki /loki/api/v1/labels: {"status": "success", "data": ["label1", "label2", ...]}. Args: cluster_id: Cluster identifier. env: Environment name (e.g. prod, staging, dev). deploy_type: Deploy type (dedicated, premium, resource_pool, starter, essential). start: Optional start timestamp in RFC3339 format for time range end: Optional end timestamp in RFC3339 format for time range query: Optional LogQL query to filter which labels are returned Returns: List containing a single dict with 'type': 'text' and 'text': Loki-format JSON Raises: Various errors for authorization, validation, network, and timeout issues Examples: # List all labels # No start/end/query parameters needed # List labels for a specific time range start='2024-01-01T00:00:00Z' end='2024-01-01T23:59:59Z' # List labels filtered by a query query='{app="mysql"}' """ try: await get_valid_server_auth() try: request = LokiLabelsRequest( cluster_id=cluster_id.strip(), env=env.strip(), deploy_type=deploy_type.strip(), start=start, end=end, query=query, ) except (ValueError, PydanticValidationError) as e: raise ValidationError(f"Invalid Loki labels request parameters: {str(e)}") from e client, region = await get_loki_client_for_cluster( cluster_id=request.cluster_id, env=request.env, deploy_type=request.deploy_type, timeout=15.0, ) labels = await client.list_labels( start=request.start, end=request.end, query=request.query, ) response = {"status": "success", "data": labels} return tool_text_response(json.dumps(response, ensure_ascii=False)) except ( AuthServiceError, AuthorizationError, ValidationError, NetworkError, LokiTimeoutError, LokiAPIError, ) as e: return tool_text_response(format_tool_error(e)) except Exception as e: return tool_text_response(format_tool_error(e))