Skip to main content
Glama
pab1it0

Prometheus MCP Server

Execute PromQL Query

execute_query
Read-onlyIdempotent

Run PromQL instant queries to retrieve current metrics from Prometheus for real-time 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

  • Registration of the execute_query tool with FastMCP decorator, including metadata annotations (readOnly, idempotent, etc.) and the prefixed tool name via _tool_name() helper.
    @mcp.tool(
        name=_tool_name("execute_query"),
        description="Execute a PromQL instant query against Prometheus",
        annotations={
            "title": "Execute PromQL Query",
            "icon": "📊",
            "readOnlyHint": True,
            "destructiveHint": False,
            "idempotentHint": True,
            "openWorldHint": True
        }
    )
  • Handler function for execute_query. Accepts a PromQL query string and optional time parameter, calls make_prometheus_request to the /api/v1/query endpoint, extracts resultType and result, optionally appends a Prometheus UI link, and returns the result dictionary.
    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
  • Helper function that makes HTTP requests to the Prometheus API. Handles authentication (bearer token, basic auth), SSL verification, custom headers, OrgID, client TLS certs, request timeout, and error handling. Called by execute_query with endpoint='query' and the PromQL params.
    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)
    
        # Build client certificate tuple for mutual TLS authentication
        client_cert = None
        if config.client_cert:
            if config.client_key:
                client_cert = (config.client_cert, config.client_key)
            else:
                client_cert = config.client_cert
    
        try:
            logger.debug("Making Prometheus API request", endpoint=endpoint, url=url, params=params, headers=headers, timeout=config.request_timeout)
    
            # Make the request with appropriate headers, auth, and timeout (DDoS protection)
            response = requests.get(url, params=params, auth=auth, headers=headers, verify=url_ssl_verify, cert=client_cert, timeout=config.request_timeout)
    
            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
  • Helper function that adds an optional TOOL_PREFIX environment variable prefix to the tool name. Used by execute_query and all other tools to support namespacing.
    def _tool_name(name: str) -> str:
        """Build tool name with optional prefix."""
        return f"{TOOL_PREFIX}_{name}" if TOOL_PREFIX else name
  • Configuration initialization that feeds into execute_query's behavior, particularly the disable_prometheus_links setting which controls whether the Prometheus UI link is appended to results.
    config = PrometheusConfig(
        url=os.environ.get("PROMETHEUS_URL", ""),
        url_ssl_verify=os.environ.get("PROMETHEUS_URL_SSL_VERIFY", "True").lower() in ("true", "1", "yes"),
        disable_prometheus_links=os.environ.get("PROMETHEUS_DISABLE_LINKS", "False").lower() in ("true", "1", "yes"),
        username=os.environ.get("PROMETHEUS_USERNAME", ""),
        password=os.environ.get("PROMETHEUS_PASSWORD", ""),
        token=os.environ.get("PROMETHEUS_TOKEN", ""),
        org_id=os.environ.get("ORG_ID", ""),
        mcp_server_config=MCPServerConfig(
            mcp_server_transport=os.environ.get("PROMETHEUS_MCP_SERVER_TRANSPORT", "stdio").lower(),
            mcp_bind_host=os.environ.get("PROMETHEUS_MCP_BIND_HOST", "127.0.0.1"),
            mcp_bind_port=int(os.environ.get("PROMETHEUS_MCP_BIND_PORT", "8080")),
            stateless_http=os.environ.get("PROMETHEUS_MCP_STATELESS_HTTP", "False").lower() in ("true", "1", "yes"),
        ),
        client_cert=os.environ.get("PROMETHEUS_CLIENT_CERT", "") or None,
        client_key=os.environ.get("PROMETHEUS_CLIENT_KEY", "") or None,
        custom_headers=json.loads(os.environ.get("PROMETHEUS_CUSTOM_HEADERS")) if os.environ.get("PROMETHEUS_CUSTOM_HEADERS") else None,
        request_timeout=int(os.environ.get("PROMETHEUS_REQUEST_TIMEOUT", "30")),
    )
Behavior2/5

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

Annotations already provide readOnlyHint, destructiveHint, idempotentHint, and openWorldHint. The description adds no behavioral context beyond what is in the schema and annotations.

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

Conciseness3/5

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

The description is a single sentence, which is concise but overly terse. It could be improved with more structure while remaining short.

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?

With 0% schema coverage and no description of parameters, the tool is incomplete for an agent. The output schema exists, but the description does not mention it or the nature of the return value.

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

Parameters1/5

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

Schema description coverage is 0%, yet the description does not explain the parameters. It fails to clarify that 'query' is the PromQL expression and 'time' is optional evaluation time.

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 action ('Execute') and the resource ('PromQL instant query against Prometheus'). It distinguishes from the sibling tool 'execute_range_query' which handles range queries.

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?

No guidance is provided on when to use this tool versus alternatives like 'execute_range_query'. There is no mention of typical use cases or exclusions.

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