Skip to main content
Glama
ghrud92

Loki MCP Server

by ghrud92

get_labels

Extract and retrieve label sets from Grafana Loki logs using LogQL queries, enabling efficient log data organization and analysis.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • MCP tool handler for "get_labels". Logs execution, calls lokiClient.getLabels(), returns result as text content or standardized error.
    server.tool("get_labels", {}, async (_args, extra) => {
      logger.debug("All labels query tool execution", { extra });
    
      try {
        const labelsJson = await lokiClient.getLabels();
    
        return {
          content: [
            {
              type: "text",
              text: labelsJson,
            },
          ],
        };
      } catch (error) {
        logger.error("Labels query tool execution error", { error });
    
        // Create standardized error response
        return createToolErrorResponse(error, "Error getting labels");
      }
    });
  • LokiClient.getLabels() public method: fetches labels via HTTP helper and returns JSON string {"labels": [...]}, with error handling.
    async getLabels(): Promise<string> {
      this.logger.debug("Retrieving label list");
      try {
        const labels = await this.getLabelsViaHttp();
        return JSON.stringify({ labels });
      } catch (error: unknown) {
        const errorMsg = error instanceof Error ? error.message : String(error);
        this.logger.error("Getting labels failed", { error, errorMsg });
        if (error instanceof LokiClientError) {
          throw error;
        }
        throw new LokiClientError(
          "execution_failed",
          `Failed to get labels: ${errorMsg}`,
          {
            cause: error as Error,
            details: {
              command: "labels",
            },
          }
        );
      }
    }
  • Private getLabelsViaHttp(): Performs HTTP GET to /loki/api/v1/labels endpoint with auth headers, returns array of label names or throws LokiClientError.
    private async getLabelsViaHttp(): Promise<string[]> {
      try {
        const config = this.auth.getConfig();
    
        if (!config.addr) {
          throw new LokiClientError(
            "http_query_error",
            "Loki server address (addr) is not configured",
            { details: { command: "labels" } }
          );
        }
    
        // Build URL for labels endpoint
        const url = `${config.addr}/loki/api/v1/labels`;
    
        // Prepare request headers
        const headers: Record<string, string> = {};
    
        // Add authentication headers
        if (config.username && config.password) {
          const auth = Buffer.from(
            `${config.username}:${config.password}`
          ).toString("base64");
          headers["Authorization"] = `Basic ${auth}`;
        } else if (config.bearer_token) {
          headers["Authorization"] = `Bearer ${config.bearer_token}`;
        }
    
        if (config.tenant_id) {
          headers["X-Scope-OrgID"] = config.tenant_id;
        }
    
        if (config.org_id) {
          headers["X-Org-ID"] = config.org_id;
        }
    
        this.logger.debug("Executing HTTP labels query", {
          url,
          headers: {
            ...headers,
            Authorization: headers.Authorization ? "[REDACTED]" : undefined,
          },
        });
    
        // Make the HTTP request
        const response = await axios.get<{ status: string; data: string[] }>(
          url,
          {
            headers,
            // Handle TLS options
            ...(config.tls_skip_verify
              ? { httpsAgent: { rejectUnauthorized: false } }
              : {}),
          }
        );
    
        if (
          response.data &&
          response.data.data &&
          Array.isArray(response.data.data)
        ) {
          return response.data.data;
        }
    
        return [];
      } catch (error: unknown) {
        let errorMsg = "HTTP labels query failed";
        let errorDetails: Record<string, unknown> = { command: "labels" };
    
        if (axios.isAxiosError(error)) {
          const axiosError = error as AxiosError;
          errorMsg = `HTTP labels query failed: ${axiosError.message}`;
          errorDetails = {
            ...errorDetails,
            status: axiosError.response?.status,
            statusText: axiosError.response?.statusText,
            responseData: axiosError.response?.data,
          };
        } else if (error instanceof Error) {
          errorMsg = `HTTP labels query failed: ${error.message}`;
        }
    
        throw new LokiClientError("http_query_error", errorMsg, {
          cause: error as Error,
          details: errorDetails,
        });
      }
    }
  • src/index.ts:180-200 (registration)
    Registration of the "get_labels" MCP tool with empty input schema and inline handler.
    server.tool("get_labels", {}, async (_args, extra) => {
      logger.debug("All labels query tool execution", { extra });
    
      try {
        const labelsJson = await lokiClient.getLabels();
    
        return {
          content: [
            {
              type: "text",
              text: labelsJson,
            },
          ],
        };
      } catch (error) {
        logger.error("Labels query tool execution error", { error });
    
        // Create standardized error response
        return createToolErrorResponse(error, "Error getting labels");
      }
    });

Tool Definition Quality

Score is being calculated. Check back soon.

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ghrud92/loki-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server