Skip to main content
Glama
0xteamhq

Grafana MCP Server

by 0xteamhq

query_loki_stats

Retrieve statistics about log streams matching a LogQL selector from a Loki datasource within specified time ranges to analyze log volume and stream metrics.

Instructions

Retrieves statistics about log streams matching a given LogQL selector within a Loki datasource

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
datasourceUidYesThe UID of the datasource to query
endRfc3339NoThe end time of the query in RFC3339 format
logqlYesThe LogQL matcher expression to execute
startRfc3339NoThe start time of the query in RFC3339 format

Implementation Reference

  • The handler function that defines and implements the core logic of the 'query_loki_stats' tool, using LokiClient to fetch stats.
    export const queryLokiStats: ToolDefinition = {
      name: 'query_loki_stats',
      description: 'Retrieves statistics about log streams matching a given LogQL selector within a Loki datasource',
      inputSchema: QueryLokiStatsSchema,
      handler: async (params, context: ToolContext) => {
        try {
          const client = new LokiClient(context.config.grafanaConfig, params.datasourceUid);
          const timeRange: TimeRange = params.startRfc3339 || params.endRfc3339 
            ? { start: '', end: '' } 
            : getDefaultTimeRange();
          
          const stats = await client.queryStats(
            params.logql,
            params.startRfc3339 || timeRange.start,
            params.endRfc3339 || timeRange.end
          );
          
          return createToolResult(stats);
        } catch (error: any) {
          return createErrorResult(error.message);
        }
      },
    };
  • Zod schema defining the input parameters for the query_loki_stats tool.
    const QueryLokiStatsSchema = z.object({
      datasourceUid: z.string().describe('The UID of the datasource to query'),
      logql: z.string().describe('The LogQL matcher expression to execute'),
      startRfc3339: z.string().optional().describe('The start time of the query in RFC3339 format'),
      endRfc3339: z.string().optional().describe('The end time of the query in RFC3339 format'),
    });
  • Function that registers the query_loki_stats tool (and other Loki tools) with the MCP server.
    export function registerLokiTools(server: any) {
      server.registerTool(listLokiLabelNames);
      server.registerTool(listLokiLabelValues);
      server.registerTool(queryLokiLogs);
      server.registerTool(queryLokiStats);
      server.registerTool(findErrorPatternLogs);
    }
  • The LokiClient.queryStats method that performs the HTTP request to Loki's /index/stats endpoint to retrieve log statistics.
    async queryStats(query: string, start?: string, end?: string): Promise<LokiStats> {
      try {
        const params: any = { query };
        if (start) params.start = start;
        if (end) params.end = end;
    
        const response = await this.client.get('/loki/api/v1/index/stats', { params });
    
        if (response.data.status !== 'success') {
          throw new Error(`Loki stats query failed: ${response.data.error || 'Unknown error'}`);
        }
    
        return response.data.data;
      } catch (error) {
        this.handleError(error);
      }
    }
  • Helper function to provide default time range (last hour) if not specified in tool parameters.
    function getDefaultTimeRange(): { start: string; end: string } {
      const now = Math.floor(Date.now() / 1000);
      const oneHourAgo = now - 3600;
      return {
        start: oneHourAgo.toString(),
        end: now.toString(),
      };
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool retrieves statistics but doesn't specify what types of statistics (e.g., count, rate, volume), whether it's a read-only operation, potential rate limits, authentication needs, or error handling. This leaves significant gaps in understanding how the tool behaves beyond its basic purpose.

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

Conciseness5/5

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

The description is a single, well-structured sentence that efficiently conveys the core purpose without unnecessary details. It's front-loaded with the main action and resource, making it easy to parse, and every word contributes to understanding the tool's function.

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

Completeness2/5

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

Given the complexity of querying logs with LogQL and no annotations or output schema, the description is insufficient. It doesn't explain what statistics are returned, how results are formatted, or any behavioral traits like performance implications. For a tool with four parameters and no structured output information, more context is needed to ensure effective use.

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

Parameters3/5

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

The input schema has 100% description coverage, clearly documenting all four parameters. The description adds minimal value beyond the schema by mentioning 'LogQL selector' and 'Loki datasource', which align with the 'logql' and 'datasourceUid' parameters. However, it doesn't provide additional context like parameter interactions or examples, so the baseline score of 3 is appropriate.

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

Purpose4/5

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

The description clearly states the action ('Retrieves statistics') and target ('about log streams matching a given LogQL selector within a Loki datasource'), making the purpose evident. However, it doesn't explicitly differentiate from its sibling 'query_loki_logs', which appears to retrieve log content rather than statistics, leaving some ambiguity about sibling distinction.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives like 'query_loki_logs' or other query tools in the sibling list. It lacks context about prerequisites, such as needing a valid datasource or LogQL knowledge, and offers no exclusions or comparison to other tools.

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

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/0xteamhq/mcp-grafana'

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