Skip to main content
Glama
ghrud92

Loki MCP Server

by ghrud92

get_label_values

Extract distinct values for a specified label from Grafana Loki logs using LogQL queries, enabling efficient log analysis and filtering in the Loki MCP Server.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
labelYesLabel name to get values for

Implementation Reference

  • The MCP tool handler function for 'get_label_values'. It receives the 'label' parameter, calls lokiClient.getLabelValues(label), formats the response as text content, and handles errors.
    async ({ label }, extra) => {
      logger.debug("Label values query tool execution", { label, extra });
    
      try {
        const valuesJson = await lokiClient.getLabelValues(label);
    
        return {
          content: [
            {
              type: "text",
              text: valuesJson,
            },
          ],
        };
      } catch (error) {
        logger.error("Label values query tool execution error", { label, error });
    
        // Create standardized error response
        return createToolErrorResponse(error, "Error getting label values", {
          label,
        });
      }
    }
  • Zod input schema for the 'get_label_values' tool, defining the required 'label' parameter.
    {
      label: z.string().describe("Label name to get values for"),
    },
  • src/index.ts:149-177 (registration)
    Registration of the 'get_label_values' tool on the MCP server using server.tool(), specifying the tool name, input schema, and handler function.
    server.tool(
      "get_label_values",
      {
        label: z.string().describe("Label name to get values for"),
      },
      async ({ label }, extra) => {
        logger.debug("Label values query tool execution", { label, extra });
    
        try {
          const valuesJson = await lokiClient.getLabelValues(label);
    
          return {
            content: [
              {
                type: "text",
                text: valuesJson,
              },
            ],
          };
        } catch (error) {
          logger.error("Label values query tool execution error", { label, error });
    
          // Create standardized error response
          return createToolErrorResponse(error, "Error getting label values", {
            label,
          });
        }
      }
    );
  • LokiClient.getLabelValues helper method that fetches label values via HTTP and returns them as a JSON string. Called by the tool handler.
    async getLabelValues(labelName: string): Promise<string> {
      this.logger.debug("Retrieving label values list", { labelName });
      try {
        const values = await this.getLabelValuesViaHttp(labelName);
        return JSON.stringify({ values });
      } catch (error: unknown) {
        const errorMsg = error instanceof Error ? error.message : String(error);
        this.logger.error("Getting label values failed", {
          error,
          errorMsg,
          labelName,
        });
        if (error instanceof LokiClientError) {
          throw error;
        }
        throw new LokiClientError(
          "execution_failed",
          `Failed to get label values: ${errorMsg}`,
          {
            cause: error as Error,
            details: {
              command: "label values",
              labelName,
            },
          }
        );
      }
    }
  • Private LokiClient.getLabelValuesViaHttp method implementing the HTTP API call to retrieve label values from Loki (/loki/api/v1/label/{label}/values).
    private async getLabelValuesViaHttp(labelName: string): 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: "label values", labelName } }
          );
        }
    
        // Build URL for label values endpoint
        const url = `${config.addr}/loki/api/v1/label/${encodeURIComponent(
          labelName
        )}/values`;
    
        // 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 label values query", {
          url,
          labelName,
          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 label values query failed";
        let errorDetails: Record<string, unknown> = {
          command: "label values",
          labelName,
        };
    
        if (axios.isAxiosError(error)) {
          const axiosError = error as AxiosError;
          errorMsg = `HTTP label values 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 label values query failed: ${error.message}`;
        }
    
        throw new LokiClientError("http_query_error", errorMsg, {
          cause: error as Error,
          details: errorDetails,
        });
      }
    }
Behavior1/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Tool has no description.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness1/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Tool has no description.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness1/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Tool has no description.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Tool has no description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose1/5

Does the description clearly state what the tool does and how it differs from similar tools?

Tool has no description.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Tool has no description.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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