Skip to main content
Glama
pab1it0

Prometheus MCP Server

Execute PromQL Query

execute_query
Read-onlyIdempotent

Execute PromQL instant queries to retrieve Prometheus metrics data for monitoring and analysis.

Instructions

Execute a PromQL instant query against Prometheus

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
timeNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The execute_query tool handler: an async function decorated with @mcp.tool that executes PromQL instant queries against Prometheus using the make_prometheus_request helper. Handles query and optional time parameters, formats results, adds optional Prometheus UI links, and includes logging.
    @mcp.tool(
        description="Execute a PromQL instant query against Prometheus",
        annotations={
            "title": "Execute PromQL Query",
            "icon": "📊",
            "readOnlyHint": True,
            "destructiveHint": False,
            "idempotentHint": True,
            "openWorldHint": True
        }
    )
    async def execute_query(query: str, time: Optional[str] = None) -> Dict[str, Any]:
        """Execute an instant query against Prometheus.
    
        Args:
            query: PromQL query string
            time: Optional RFC3339 or Unix timestamp (default: current time)
    
        Returns:
            Query result with type (vector, matrix, scalar, string) and values
        """
        params = {"query": query}
        if time:
            params["time"] = time
        
        logger.info("Executing instant query", query=query, time=time)
        data = make_prometheus_request("query", params=params)
    
        result = {
            "resultType": data["resultType"],
            "result": data["result"]
        }
    
        if not config.disable_prometheus_links:
            from urllib.parse import urlencode
            ui_params = {"g0.expr": query, "g0.tab": "0"}
            if time:
                ui_params["g0.moment_input"] = time
            prometheus_ui_link = f"{config.url.rstrip('/')}/graph?{urlencode(ui_params)}"
            result["links"] = [{
                "href": prometheus_ui_link,
                "rel": "prometheus-ui",
                "title": "View in Prometheus UI"
            }]
    
        logger.info("Instant query completed",
                    query=query,
                    result_type=data["resultType"],
                    result_count=len(data["result"]) if isinstance(data["result"], list) else 1)
    
        return result
  • Registration of the execute_query tool via FastMCP's @mcp.tool decorator, including description and annotations for MCP protocol compliance.
    @mcp.tool(
        description="Execute a PromQL instant query against Prometheus",
        annotations={
            "title": "Execute PromQL Query",
            "icon": "📊",
            "readOnlyHint": True,
            "destructiveHint": False,
            "idempotentHint": True,
            "openWorldHint": True
        }
  • Helper function make_prometheus_request that performs authenticated HTTP requests to the Prometheus API /query endpoint, handles errors, SSL, auth, custom headers, and returns the data field. Directly called by execute_query.
    def make_prometheus_request(endpoint, params=None):
        """Make a request to the Prometheus API with proper authentication and headers."""
        if not config.url:
            logger.error("Prometheus configuration missing", error="PROMETHEUS_URL not set")
            raise ValueError("Prometheus configuration is missing. Please set PROMETHEUS_URL environment variable.")
        if not config.url_ssl_verify:
            logger.warning("SSL certificate verification is disabled. This is insecure and should not be used in production environments.", endpoint=endpoint)
    
        url = f"{config.url.rstrip('/')}/api/v1/{endpoint}"
        url_ssl_verify = config.url_ssl_verify
        auth = get_prometheus_auth()
        headers = {}
    
        if isinstance(auth, dict):  # Token auth is passed via headers
            headers.update(auth)
            auth = None  # Clear auth for requests.get if it's already in headers
        
        # Add OrgID header if specified
        if config.org_id:
            headers["X-Scope-OrgID"] = config.org_id
    
        if config.custom_headers:
            headers.update(config.custom_headers)
    
        try:
            logger.debug("Making Prometheus API request", endpoint=endpoint, url=url, params=params, headers=headers)
    
            # Make the request with appropriate headers and auth
            response = requests.get(url, params=params, auth=auth, headers=headers, verify=url_ssl_verify)
            
            response.raise_for_status()
            result = response.json()
            
            if result["status"] != "success":
                error_msg = result.get('error', 'Unknown error')
                logger.error("Prometheus API returned error", endpoint=endpoint, error=error_msg, status=result["status"])
                raise ValueError(f"Prometheus API error: {error_msg}")
            
            data_field = result.get("data", {})
            if isinstance(data_field, dict):
                result_type = data_field.get("resultType")
            else:
                result_type = "list"
            logger.debug("Prometheus API request successful", endpoint=endpoint, result_type=result_type)
            return result["data"]
        
        except requests.exceptions.RequestException as e:
            logger.error("HTTP request to Prometheus failed", endpoint=endpoint, url=url, error=str(e), error_type=type(e).__name__)
            raise
        except json.JSONDecodeError as e:
            logger.error("Failed to parse Prometheus response as JSON", endpoint=endpoint, url=url, error=str(e))
            raise ValueError(f"Invalid JSON response from Prometheus: {str(e)}")
        except Exception as e:
            logger.error("Unexpected error during Prometheus request", endpoint=endpoint, url=url, error=str(e), error_type=type(e).__name__)
            raise
Behavior4/5

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

Annotations already provide key behavioral traits (readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true), indicating a safe, read-only operation. The description adds value by specifying the query type ('instant query') and target ('Prometheus'), which are not covered by annotations, enhancing context without contradiction.

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 essential information (action, resource, target) with zero waste. Every word earns its place, 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.

Completeness4/5

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

Given the tool's complexity (query execution), rich annotations cover safety and behavior, and an output schema exists (so return values need not be explained). The description is complete for basic usage but could benefit from more parameter guidance, though annotations and output schema reduce the burden.

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 0%, so the schema provides no parameter descriptions. The description does not add any details about the 'query' or 'time' parameters, such as format or examples. With two parameters and no semantic information provided, it meets the baseline but lacks compensation for the low 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 ('Execute'), the resource ('PromQL instant query'), and the target system ('against Prometheus'). It precisely distinguishes this tool from its sibling 'execute_range_query' by specifying 'instant query' versus 'range query'.

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

Usage Guidelines4/5

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

The description implies usage context by specifying 'instant query,' which helps differentiate it from 'execute_range_query' for range queries. However, it does not explicitly state when to use this tool versus alternatives like 'list_metrics' or provide exclusions, leaving some guidance implicit.

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/pab1it0/prometheus-mcp-server'

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