Skip to main content
Glama
0xteamhq

Grafana MCP Server

by 0xteamhq

query_prometheus

Execute PromQL queries against Prometheus data sources to retrieve instant metrics or time series data for monitoring and analysis.

Instructions

Query Prometheus using a PromQL expression. Supports both instant and range queries.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
datasourceUidYesThe UID of the datasource to query
endTimeNoThe end time for range queries
exprYesThe PromQL expression to query
queryTypeYesThe type of query to use
startTimeYesThe start time (RFC3339 or relative like "now-1h")
stepSecondsNoThe time series step size in seconds for range queries

Implementation Reference

  • Full ToolDefinition object for 'query_prometheus' tool, including the async handler function that executes PromQL queries (instant or range) via PrometheusClient.
    export const queryPrometheus: ToolDefinition = {
      name: 'query_prometheus',
      description: 'Query Prometheus using a PromQL expression. Supports both instant and range queries.',
      inputSchema: QueryPrometheusSchema,
      handler: async (params, context: ToolContext) => {
        try {
          const client = new PrometheusClient(context.config.grafanaConfig, params.datasourceUid);
          
          let result;
          if (params.queryType === 'instant') {
            result = await client.query(params.expr, parseTime(params.startTime));
          } else {
            const start = parseTime(params.startTime);
            const end = params.endTime ? parseTime(params.endTime) : 'now';
            const step = params.stepSeconds ? `${params.stepSeconds}s` : '60s';
            result = await client.queryRange(params.expr, start, end, step);
          }
          
          return createToolResult(result);
        } catch (error: any) {
          return createErrorResult(error.message);
        }
      },
    };
  • Zod schema defining the input parameters for the query_prometheus tool.
    const QueryPrometheusSchema = z.object({
      datasourceUid: z.string().describe('The UID of the datasource to query'),
      expr: z.string().describe('The PromQL expression to query'),
      queryType: z.enum(['range', 'instant']).describe('The type of query to use'),
      startTime: z.string().describe('The start time (RFC3339 or relative like "now-1h")'),
      endTime: z.string().optional().describe('The end time for range queries'),
      stepSeconds: z.number().optional().describe('The time series step size in seconds for range queries'),
    });
  • Registration function that registers the query_prometheus tool (and other Prometheus tools) with the MCP server.
    export function registerPrometheusTools(server: any) {
      server.registerTool(queryPrometheus);
      server.registerTool(listPrometheusMetricNames);
      server.registerTool(listPrometheusLabelNames);
      server.registerTool(listPrometheusLabelValues);
      server.registerTool(listPrometheusMetricMetadata);
    }
  • Helper function parseTime used by the query_prometheus handler to convert relative times (e.g., 'now-1h') to Unix timestamps.
    function parseTime(time: string): string {
      if (time === 'now') {
        return Math.floor(Date.now() / 1000).toString();
      }
      
      const relativeMatch = time.match(/^now-(\d+)([smhd])$/);
      if (relativeMatch) {
        const value = parseInt(relativeMatch[1]);
        const unit = relativeMatch[2];
        let seconds = 0;
        
        switch (unit) {
          case 's': seconds = value; break;
          case 'm': seconds = value * 60; break;
          case 'h': seconds = value * 3600; break;
          case 'd': seconds = value * 86400; break;
        }
        
        return Math.floor((Date.now() / 1000) - seconds).toString();
      }
      
      // Assume it's already a Unix timestamp or RFC3339
      return time;
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions support for instant and range queries, but does not cover critical aspects such as authentication requirements, rate limits, error handling, or the format of returned data. For a query tool with no annotation coverage, this leaves significant gaps in understanding its behavior.

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, efficient sentence that front-loads the core purpose ('Query Prometheus using a PromQL expression') and adds a useful detail ('Supports both instant and range queries'). There is no wasted language, making it highly concise and well-structured.

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

Completeness3/5

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

Given the complexity of a Prometheus query tool with 6 parameters and no output schema, the description is incomplete. It lacks details on return values, error conditions, or behavioral traits, which are crucial for effective use. However, the high schema coverage mitigates some gaps, but overall it does not provide sufficient context for a tool of this nature.

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?

Schema description coverage is 100%, so the input schema already documents all parameters thoroughly. The description adds minimal value by mentioning 'instant and range queries,' which loosely relates to the queryType parameter, but does not provide additional semantics beyond what the schema specifies. This meets the baseline for high schema coverage.

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 ('Query Prometheus'), the method ('using a PromQL expression'), and the scope ('both instant and range queries'). It distinguishes itself from sibling tools like query_loki_logs or query_loki_stats by specifying Prometheus and PromQL, making the purpose unambiguous and distinct.

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

Usage Guidelines3/5

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

The description implies usage for Prometheus queries with PromQL, but does not explicitly state when to use this tool versus alternatives like list_prometheus_metric_names or query_loki_logs. It mentions support for instant and range queries, which provides some context, but lacks explicit guidance on scenarios or prerequisites.

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