Skip to main content
Glama
DrDroidLab

Grafana MCP Server

grafana_promql_query

Execute PromQL queries to fetch and analyze metrics data from Grafana's Prometheus datasource, optimizing time series responses for efficient data retrieval.

Instructions

Executes PromQL queries against Grafana's Prometheus datasource. Fetches metrics data using PromQL expressions, optimizes time series responses to reduce token size.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
datasource_uidYesPrometheus datasource UID
queryYesPromQL query string
start_timeNoStart time in RFC3339 or relative string (e.g., 'now-2h', '2023-01-01T00:00:00Z')
end_timeNoEnd time in RFC3339 or relative string (e.g., 'now-2h', '2023-01-01T00:00:00Z')
durationNoDuration string for the time window (e.g., '2h', '90m')

Implementation Reference

  • The core logic for executing the PromQL query using the Grafana /api/ds/query endpoint.
    def grafana_promql_query(
        self,
        datasource_uid: str,
        query: str,
        start_time: Optional[str] = None,
        end_time: Optional[str] = None,
        duration: Optional[str] = None,
    ) -> dict[str, Any]:
        """
        Executes PromQL queries against Grafana's Prometheus datasource.
    
        Args:
            datasource_uid: Prometheus datasource UID
            query: PromQL query string
            start_time: Start time in RFC3339 or relative string (e.g., 'now-2h', '2023-01-01T00:00:00Z')
            end_time: End time in RFC3339 or relative string (e.g., 'now-2h', '2023-01-01T00:00:00Z')
            duration: Duration string for the time window (e.g., '2h', '90m')
    
        Returns:
            Dict containing query results with optimized time series data
        """
        try:
            # Use standardized time range logic
            start_dt, end_dt = self._get_time_range(start_time, end_time, duration, default_hours=3)
    
            # Convert to milliseconds since epoch (Grafana format)
            start_ms = int(start_dt.timestamp() * 1000)
            end_ms = int(end_dt.timestamp() * 1000)
    
            payload = {
                "queries": [
                    {
                        "refId": "A",
                        "expr": query,
                        "editorMode": "code",
                        "legendFormat": "__auto",
                        "range": True,
                        "exemplar": False,
                        "requestId": "A",
                        "utcOffsetSec": 0,
                        "scopes": [],
                        "adhocFilters": [],
                        "interval": "",
                        "datasource": {"type": "prometheus", "uid": datasource_uid},
                        "intervalMs": 30000,
                        "maxDataPoints": 1000,
                    }
                ],
                "from": str(start_ms),
                "to": str(end_ms),
            }
    
            url = f"{self.__host}/api/ds/query"
            logger.info(f"Executing PromQL query: {query} from {start_dt.isoformat()} to {end_dt.isoformat()}")
    
            response = requests.post(
                url,
                headers=self.headers,
                json=payload,
                verify=self.__ssl_verify,
                timeout=30,
            )
    
            if response.status_code == 200:
  • The MCP server wrapper function that calls the grafana_processor logic.
    def grafana_promql_query(datasource_uid, query, start_time=None, end_time=None, duration=None):
        """Execute PromQL query against Grafana's Prometheus datasource"""
        try:
            grafana_processor = current_app.config.get("grafana_processor")
            if not grafana_processor:
                return {
                    "status": "error",
                    "message": "Grafana processor not initialized. Check configuration.",
                }
    
            result = grafana_processor.grafana_promql_query(datasource_uid, query, start_time, end_time, duration)
            return result
        except Exception as e:
            logger.error(f"Error executing PromQL query: {e!s}")
            return {"status": "error", "message": f"PromQL query failed: {e!s}"}
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. It mentions 'optimizes time series responses to reduce token size', which adds some behavioral context about output handling. However, it lacks critical details: whether this is a read-only operation, potential rate limits, authentication requirements, error behaviors, or what the response format looks like (especially with no output schema).

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

Conciseness4/5

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

The description is concise and front-loaded with the core purpose in the first sentence. The second sentence adds useful behavioral context about optimization. Both sentences earn their place, though it could be slightly more structured (e.g., separating purpose from behavioral notes).

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 5 parameters, no annotations, and no output schema, the description is incomplete. It lacks guidance on usage versus siblings, doesn't fully cover behavioral aspects (e.g., safety, errors, response format), and provides no parameter semantics beyond the schema. The optimization note is helpful but insufficient for overall completeness.

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 schema fully documents all 5 parameters. The description adds no parameter-specific information beyond what's in the schema—it doesn't explain relationships between parameters (e.g., how 'duration' interacts with 'start_time'/'end_time') or provide examples. Baseline 3 is appropriate when the schema does all the work.

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 tool's purpose: executing PromQL queries against Grafana's Prometheus datasource to fetch metrics data. It specifies the verb 'executes' and resource 'PromQL queries' with the target 'Grafana's Prometheus datasource'. However, it doesn't explicitly differentiate from sibling tools like 'grafana_loki_query' or 'grafana_query_dashboard_panels' beyond mentioning Prometheus specifically.

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 'grafana_loki_query' (for Loki queries) or 'grafana_query_dashboard_panels' (for dashboard panel queries), nor does it specify prerequisites or appropriate contexts for PromQL queries versus other data-fetching tools in the set.

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/DrDroidLab/grafana-mcp-server'

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