Natural-Language Observability: LLMs That Write PromQL

Natural-language observability means an engineer asks “what is checkout’s p95 latency?” and gets a correct PromQL query and its result. The LLM call is easy. The hard parts are grounding the model in your real metric names and blocking bad queries before they hit Prometheus. You will build a schema-aware translator, a validation gate and an MCP tool agents can call.
How natural-language observability works
One rule drives the design: the model proposes, deterministic code decides. The diagram shows how a question travels from chat to Prometheus or Loki and back.
The schema comes from your own Prometheus, so the model sees real metric names. Every query passes a validation gate before it runs, and every answer includes its query so a human can check it. That balance is the theme of AIOps without the hype.
You need a recent Prometheus 3.x (Loki is optional), Python 3.11+ with pip install anthropic requests promql-parser "mcp[cli]", and an LLM API key. The examples use Anthropic’s SDK; any LLM API works.
Text to PromQL with schema-aware prompts
Without context, a model asked for checkout errors guesses: it invents http_errors_total or a label you never had. Schema-aware prompting fixes that by putting your real metric names, types and help text into the prompt, limited to the ones relevant to the question so the token bill stays small.
# nl2promql.py
import os, re, anthropic, requests
PROM = os.environ["PROM_URL"]
SYSTEM = """Write ONE PromQL query. Use only these metrics and the labels
service, namespace, pod, code, host, status. Counters need rate(). Reply with the query only."""
def schema_for(question, top=40):
meta = requests.get(f"{PROM}/api/v1/metadata", timeout=10).json()["data"]
words = set(re.findall(r"[a-z]{3,}", question.lower()))
rank = lambda kv: sum(w in kv[0] + kv[1][0]["help"].lower() for w in words)
best = sorted(meta.items(), key=rank, reverse=True)[:top] # crude keyword ranking
return "\n".join(f"{name} ({m[0]['type']}): {m[0]['help']}" for name, m in best)
def to_promql(question):
msg = anthropic.Anthropic().messages.create(
model="claude-haiku-5-5", max_tokens=300,
system=SYSTEM + "\nMetrics:\n" + schema_for(question),
messages=[{"role": "user", "content": question}])
return msg.content[0].text.strip()
The metadata endpoint returns every metric with its type and help string. schema_for() keeps the 40 metrics whose name or help text shares the most words with the question. The ranking is crude; add synonyms or embeddings as your catalogue grows. The system prompt names your labels and the counter rule, so the model never graphs a raw counter. Asking for “p95 latency of checkout” should print one line:
histogram_quantile(0.95, sum by (le) (rate(http_server_requests_seconds_bucket{service="checkout"}[5m])))
Getting a code fence or prose back means the last prompt line needs tightening. A small, fast model is enough for one line of output. Treat the prompt and model ID as code: version them together, and run a small eval set of questions with expected queries before every change.
Validate generated queries before they run
A grounded model still makes mistakes, and a wrong query is not harmless. On the 30M+ active-series stack I ran, one unbounded selector could touch millions of series. The flowchart shows the gate every generated query passes, cheapest check first.
Each “no” returns a reason the agent can act on: rephrase, or hand the question back to the engineer. “Unknown metric node_disk_latency_seconds” is specific enough for the model to fix.
# guard.py
import time, promql_parser as pp, requests
from nl2promql import PROM
MAX_SERIES, MAX_RANGE = 5000, 24 * 3600 # tune to your Prometheus
KNOWN = set(requests.get(f"{PROM}/api/v1/label/__name__/values", timeout=10).json()["data"])
def check(query):
try:
nodes = []
pp.walk(pp.parse(query), pre_visit=nodes.append) # every AST node
except Exception as e: # invalid syntax
return [f"does not parse: {e}"]
problems = [f"range over 24h: {n.prettify()}" for n in nodes
if isinstance(n, (pp.MatrixSelector, pp.SubqueryExpr))
and n.range and n.range.total_seconds() > MAX_RANGE]
for vs in [n for n in nodes if isinstance(n, pp.VectorSelector)]:
if vs.name and vs.name not in KNOWN:
problems.append(f"unknown metric {vs.name}")
continue
found = requests.get(f"{PROM}/api/v1/series", timeout=10, params={"match[]": str(vs),
"start": time.time() - 3600, "limit": MAX_SERIES + 1}).json()["data"]
if len(found) > MAX_SERIES:
problems.append(f"{vs} matches over {MAX_SERIES} series")
return problems
py-promql-parser wraps a Rust PromQL parser, so syntax errors never reach the server. walk() collects every node of the parsed query. Ranges and subqueries longer than 24 hours are rejected, and each selector must name a metric that exists. Then one series lookup, with limit set one above the budget, answers “too many series?” without fetching them all. An empty list means the query may run. If every metric comes back unknown, KNOWN is empty, so check PROM_URL.
The gate checks cost, not intent, so keep access read-only too. Leave the admin API disabled (the default) and keep --query.timeout and --query.max-samples as server-side backstops.
LogQL works the same way. Build the schema from Loki’s label endpoints, check syntax with format_query, and estimate cost with index/stats, which reports the bytes a selector would scan (see the Loki HTTP API). It is approximate, but good enough to refuse a 500 GB scan.
Package it as an MCP tool
The Model Context Protocol (MCP) is an open standard that lets AI clients such as Claude Code or a Slack bot call tools. I built a Slack bot that investigates incidents using documentation search, metric plugins and log APIs; this is exactly that kind of metric plugin. Wrap the translator and gate as one tool, and every client inherits the same guardrails. The sequence below shows one call: the agent never talks to Prometheus directly.
# promql_mcp.py
import requests
from mcp.server.mcpserver import MCPServer # MCP Python SDK v2
from mcp.types import ToolAnnotations
from nl2promql import PROM, to_promql
from guard import check
mcp = MCPServer("promql")
@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
def ask_metrics(question: str) -> dict:
"""Answer a question from Prometheus metrics. Always returns the PromQL used."""
query = to_promql(question)
if problems := check(query): # reasons let the agent rephrase
return {"query": query, "rejected": problems}
r = requests.get(f"{PROM}/api/v1/query", params={"query": query, "limit": 50}, timeout=30)
return {"query": query, "result": r.json()["data"]["result"]}
if __name__ == "__main__":
mcp.run() # stdio transport by default
This uses v2 of the MCP Python SDK, where FastMCP became MCPServer; on 1.x, import FastMCP from mcp.server.fastmcp. The docstring is the description the agent reads, so state what the tool is for. readOnlyHint tells clients the tool changes nothing, and limit=50 caps the returned series, protecting the agent’s context window and your token budget. Register it with Claude Code; everything after -- starts the server:
claude mcp add --transport stdio \
--env PROM_URL=http://prometheus.monitoring:9090 \
--env ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" \
promql -- python /opt/promql-mcp/promql_mcp.py
claude mcp list # promql should show as connected
If it fails to connect, run the Python command by hand: a missing package or an unreachable Prometheus URL is the usual cause. Add --scope project to share the config through .mcp.json. Off-the-shelf servers such as Grafana’s mcp-grafana let the agent write raw queries, so there your limits must live in Prometheus itself.
Example questions and generated queries
Typical on-call questions against a Kubernetes stack with node exporter, cAdvisor and ingress-nginx (the series count in row 3 is illustrative):
| Question | Generated query | Gate |
|---|---|---|
| Ingress hosts with most 5xx | topk(5, sum by (host) (rate(nginx_ingress_controller_requests{status=~"5.."}[5m]))) | Pass |
| Disk latency on database nodes | rate(node_disk_latency_seconds[5m]) | Unknown metric |
| Memory of every container | container_memory_working_set_bytes | 41,000 series |
| Checkout timeouts in logs | {app="checkout"} |= "timeout" | json | level="error" | Pass (LogQL) |
The rejections are the useful part. Fed the reason, the model can fix row 2 on retry, because node_disk_io_time_seconds_total exists. Row 1 assumes ingress controller metrics are scraped, as set up in Monitoring NGINX Ingress Controller using open-source tools.
Common pitfalls
- Trusting a query because it parses. A valid query can still answer the wrong question; show it next to the result.
- Sending the whole schema. Thousands of metrics add tokens and latency, and make answers worse.
- Raw counters. Without
rate(), a counter only goes up. Keep an eval case for it. - Unbounded retries. Cap rephrasing at two attempts, then ask a human.
- A stale metric list. Refresh
KNOWNon a timer, or new services look like hallucinations.
Key takeaways
- Ground the model in your own metric names, types and labels from the Prometheus API.
- Parse, check names, cap ranges and count series before any generated query runs.
- Return the query with every answer so a human can verify it.
- Ship it as one read-only MCP tool so every agent inherits the same guardrails.
Related articles

Advanced RAG: Query Rewriting, GraphRAG, Agentic Retrieval
Basic RAG fails on vague, multi-part and "what breaks if X goes down?" questions. Add query rewriting and HyDE, GraphRAG over your Tempo service graph, and an agent that picks its own sources within a hard budget.

Claude Code Multi-Model Setup: Opus, Sonnet and Fable
Stop spending Opus tokens on routine work. Run Opus 5.5 as the planner, Sonnet 5.5 subagents on medium effort and Fable 5.2 as an advisor: the four files to edit, the exact keys, and what silently turns the advisor off.

Rolling Out a JDK Upgrade to 2,000+ Jenkins Agents
A JDK upgrade reached most of a client's 2,000+ Jenkins agents in half an hour and broke builds with a misleading error. How the client's rollouts work, how Claude Code found the deleted JDK, and how they roll out now.