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");
      }
    });
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