Skip to main content
Glama
0xteamhq

Grafana MCP Server

by 0xteamhq

query_loki_logs

Execute LogQL queries against Loki datasources to retrieve log entries and metric values within specified time ranges for monitoring and analysis.

Instructions

Executes a LogQL query against a Loki datasource to retrieve log entries or metric values

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
datasourceUidYesThe UID of the datasource to query
directionNoDirection of the query
endRfc3339NoThe end time of the query in RFC3339 format
limitNoMaximum number of log lines to return (default: 10, max: 100)
logqlYesThe LogQL query to execute against Loki
startRfc3339NoThe start time of the query in RFC3339 format

Implementation Reference

  • The ToolDefinition object for 'query_loki_logs', including the async handler function that creates a LokiClient instance and executes the LogQL query to retrieve logs.
    export const queryLokiLogs: ToolDefinition = {
      name: 'query_loki_logs',
      description: 'Executes a LogQL query against a Loki datasource to retrieve log entries or metric values',
      inputSchema: QueryLokiLogsSchema,
      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 logs = await client.queryLogs(
            params.logql,
            params.startRfc3339 || timeRange.start,
            params.endRfc3339 || timeRange.end,
            Math.min(params.limit || 10, 100),
            params.direction || 'backward'
          );
          
          return createToolResult(logs);
        } catch (error: any) {
          return createErrorResult(error.message);
        }
      },
    };
  • Zod input schema defining parameters for the query_loki_logs tool: datasourceUid, logql query, optional time range, limit, and direction.
    const QueryLokiLogsSchema = z.object({
      datasourceUid: z.string().describe('The UID of the datasource to query'),
      logql: z.string().describe('The LogQL query to execute against Loki'),
      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'),
      limit: z.number().optional().describe('Maximum number of log lines to return (default: 10, max: 100)'),
      direction: z.enum(['forward', 'backward']).optional().describe('Direction of the query'),
    });
  • Registration function for all Loki tools, including server.registerTool(queryLokiLogs) which registers the query_loki_logs tool.
    export function registerLokiTools(server: any) {
      server.registerTool(listLokiLabelNames);
      server.registerTool(listLokiLabelValues);
      server.registerTool(queryLokiLogs);
      server.registerTool(queryLokiStats);
      server.registerTool(findErrorPatternLogs);
    }
  • src/cli.ts:110-112 (registration)
    Invocation of registerLokiTools(server) in the CLI entrypoint, conditionally enabling Loki tools including query_loki_logs.
    if (enabledTools.has('loki')) {
      registerLokiTools(server);
    }
  • Helper function used by the query_loki_logs handler to provide default time range (last hour) if not specified.
    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 mentions the tool executes queries and retrieves data but fails to describe critical behaviors: whether it's read-only or mutative, potential rate limits, authentication requirements, error handling, or the format of returned results. This leaves significant gaps for an AI agent.

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 tool's purpose without redundancy. It front-loads the key action and outcome, making it easy to parse, with no wasted words or unnecessary elaboration.

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?

For a tool with 6 parameters, no annotations, and no output schema, the description is incomplete. It lacks behavioral context (e.g., safety, limits), usage guidance, and details on return values. While concise, it doesn't compensate for the missing structured information, leaving the AI agent with insufficient operational understanding.

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 schema description coverage is 100%, providing detailed documentation for all 6 parameters. The description adds minimal value beyond the schema, only implying that 'logql' is the core query parameter and 'datasourceUid' identifies the target. No additional syntax, format examples, or constraints are provided beyond what's in the schema.

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

Purpose5/5

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

The description clearly states the specific action ('Executes a LogQL query'), target resource ('against a Loki datasource'), and outcome ('to retrieve log entries or metric values'). It distinguishes itself from sibling tools like query_loki_stats and query_prometheus by focusing on LogQL queries for log retrieval rather than statistics or Prometheus metrics.

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. It doesn't mention sibling tools like query_loki_stats (for statistics) or query_prometheus (for Prometheus queries), nor does it specify prerequisites such as needing a valid datasource UID or appropriate permissions.

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