Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(metrics): accept relative dates and a default range in query-metrics (#113967)

Daniel Visca68c4ef97aa0d
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.py
index 3a923cc4431f..adea7ecdc372 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -4,14 +4,17 @@ Mirrors the shape of `products/logs/backend/api.py` so the two surfaces stay
recognizable.
"""
+import re
import datetime as dt
from dataclasses import asdict
from typing import cast
+from zoneinfo import ZoneInfo
from django.db import models
from django.utils import timezone
-from drf_spectacular.utils import extend_schema
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import extend_schema, extend_schema_field
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import ParseError, PermissionDenied
@@ -25,6 +28,7 @@ from posthog.event_usage import report_user_action
from posthog.models import User
from posthog.permissions import PostHogFeatureFlagPermission, posthog_feature_flag_enabled
from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle
+from posthog.utils import relative_date_parse
from products.metrics.backend.facade.api import (
characterize_metric_anomaly,
@@ -179,6 +183,30 @@ class MetricQueryInterval(models.TextChoices):
WEEK = "week", "week"
+# ASCII digits with a length cap: `\d` also matches other scripts, which makes the parser backtrack quadratically.
+_RELATIVE_DATE_RE = re.compile(r"^-[0-9]{1,6}[hdwmy]$")
+_DEFAULT_QUERY_LOOKBACK = dt.timedelta(hours=24)
+
+
+@extend_schema_field(OpenApiTypes.STR)
+class _RelativeOrIsoDateTimeField(serializers.DateTimeField):
+ # Relative offsets stay strings so the body serializer resolves both bounds against one "now";
+ # two separate clock reads would push a maximum-span lookback past the runner's limit.
+ def to_internal_value(self, value: dt.datetime | str) -> dt.datetime | str: # type: ignore[override]
+ if isinstance(value, str) and _RELATIVE_DATE_RE.match(value.strip()):
+ return value.strip()
+ return super().to_internal_value(value)
+
+
+def _resolve_query_bound(value: dt.datetime | str | None, *, now: dt.datetime, field: str) -> dt.datetime | None:
+ if not isinstance(value, str):
+ return value
+ try:
+ return relative_date_parse(value, ZoneInfo("UTC"), now=now)
+ except (ValueError, OverflowError):
+ raise serializers.ValidationError({field: f"'{value}' is too far back to be a valid date."})
+
+
class _MetricQueryBodySerializer(serializers.Serializer):
metricName = serializers.CharField(
max_length=255,
@@ -240,15 +268,26 @@ class _MetricQueryBodySerializer(serializers.Serializer):
max_length=512,
help_text="Arithmetic over clause names evaluated server-side per grid point, e.g. '(a - b) / a'. Supports + - * / and parentheses; division by zero yields 0. When set, only the formula result series are returned.",
)
- dateFrom = serializers.DateTimeField(
- help_text="Lower bound (inclusive) for the query range. ISO 8601.",
+ dateFrom = _RelativeOrIsoDateTimeField(
+ required=False,
+ help_text="Lower bound (inclusive) for the query range. ISO 8601, or a relative offset back from now such as '-1h', '-7d', '-2w', '-1m' (months). Defaults to 24 hours before dateTo.",
)
- dateTo = serializers.DateTimeField(
+ dateTo = _RelativeOrIsoDateTimeField(
required=False,
- help_text="Upper bound (exclusive) for the query range. Defaults to now if omitted.",
+ help_text="Upper bound (exclusive) for the query range. ISO 8601 or a relative offset like dateFrom. Defaults to now if omitted.",
)
def validate(self, attrs: dict) -> dict:
+ now = timezone.now()
+ date_to = _resolve_query_bound(attrs.get("dateTo"), now=now, field="dateTo") or now
+ date_from = _resolve_query_bound(attrs.get("dateFrom"), now=now, field="dateFrom")
+ if date_from is None:
+ try:
+ date_from = date_to - _DEFAULT_QUERY_LOOKBACK
+ except OverflowError:
+ raise serializers.ValidationError({"dateTo": "Too early to leave 'dateFrom' unset."})
+ attrs["dateFrom"] = date_from
+ attrs["dateTo"] = date_to
has_single = bool(attrs.get("metricName"))
has_clauses = bool(attrs.get("clauses"))
if has_single == has_clauses:
diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.py
index b1cf5a4604e5..56e4d3156fbd 100644
--- a/products/metrics/backend/tests/test_metric_query_runner.py
+++ b/products/metrics/backend/tests/test_metric_query_runner.py
@@ -395,6 +395,60 @@ class TestMetricsQueryAPI(ClickhouseTestMixin, APIBaseTest):
self.assertTrue(all(series["points"] == [] for series in response.json()["results"]))
self.assertIn("metric-names-list", response.json()["hint"])
+ @parameterized.expand([("relative", {"dateFrom": "-1h"}), ("max_lookback", {"dateFrom": "-31d"}), ("omitted", {})])
+ def test_query_accepts_relative_or_omitted_date_from(self, _name: str, date_params: dict[str, str]):
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ points=[(timezone.now().replace(microsecond=0) - dt.timedelta(minutes=10), 4.0)],
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/metrics/query",
+ data={"query": {"metricName": "m1", "aggregation": "sum", **date_params}},
+ content_type="application/json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ self.assertEqual(sum(point["value"] for point in response.json()["results"][0]["points"]), 4.0)
+
+ def test_omitted_date_from_covers_the_24_hours_before_date_to(self):
+ anchor = timezone.now().replace(microsecond=0)
+ seed_metric(team_id=self.team.id, metric_name="m1", points=[(anchor - dt.timedelta(hours=2), 1.0)])
+ seed_metric(team_id=self.team.id, metric_name="m1", points=[(anchor - dt.timedelta(hours=30), 10.0)])
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/metrics/query",
+ data={
+ "query": {
+ "metricName": "m1",
+ "aggregation": "sum",
+ "dateTo": (anchor - dt.timedelta(hours=1)).isoformat(),
+ }
+ },
+ content_type="application/json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ self.assertEqual(sum(point["value"] for point in response.json()["results"][0]["points"]), 1.0)
+
+ @parameterized.expand(
+ [
+ ("days", {"dateFrom": "-1000000000d"}),
+ ("years", {"dateFrom": "-10000y"}),
+ ("non_ascii_digits", {"dateFrom": "-1\u0661h"}),
+ ("default_window_before_year_one", {"dateTo": "0001-01-01T12:00:00Z"}),
+ ]
+ )
+ def test_query_rejects_out_of_range_relative_date(self, _name: str, date_params: dict[str, str]):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/metrics/query",
+ data={"query": {"metricName": "m1", "aggregation": "sum", **date_params}},
+ content_type="application/json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
def test_query_returns_aggregated_points(self):
anchor = timezone.now().replace(microsecond=0)
seed_metric(
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index 38720d3829b6..8507f0aca885 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -1038,9 +1038,9 @@ export interface _MetricQueryBodyApi {
* @nullable
*/
formula?: string | null
- /** Lower bound (inclusive) for the query range. ISO 8601. */
- dateFrom: string
- /** Upper bound (exclusive) for the query range. Defaults to now if omitted. */
+ /** Lower bound (inclusive) for the query range. ISO 8601, or a relative offset back from now such as '-1h', '-7d', '-2w', '-1m' (months). Defaults to 24 hours before dateTo. */
+ dateFrom?: string
+ /** Upper bound (exclusive) for the query range. ISO 8601 or a relative offset like dateFrom. Defaults to now if omitted. */
dateTo?: string
}
diff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.ts
index c734af6ffe3b..2369d28bd77c 100644
--- a/products/metrics/frontend/generated/api.zod.ts
+++ b/products/metrics/frontend/generated/api.zod.ts
@@ -599,13 +599,18 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
.describe(
"Arithmetic over clause names evaluated server-side per grid point, e.g. '(a - b) \/ a'. Supports + - \* \/ and parentheses; division by zero yields 0. When set, only the formula result series are returned."
),
- dateFrom: zod.iso
- .datetime({ offset: true })
- .describe('Lower bound (inclusive) for the query range. ISO 8601.'),
- dateTo: zod.iso
- .datetime({ offset: true })
+ dateFrom: zod
+ .string()
.optional()
- .describe('Upper bound (exclusive) for the query range. Defaults to now if omitted.'),
+ .describe(
+ "Lower bound (inclusive) for the query range. ISO 8601, or a relative offset back from now such as '-1h', '-7d', '-2w', '-1m' (months). Defaults to 24 hours before dateTo."
+ ),
+ dateTo: zod
+ .string()
+ .optional()
+ .describe(
+ 'Upper bound (exclusive) for the query range. ISO 8601 or a relative offset like dateFrom. Defaults to now if omitted.'
+ ),
})
.describe('The metric query to execute.'),
})
diff --git a/products/metrics/mcp/prompts/query-metrics.md b/products/metrics/mcp/prompts/query-metrics.md
index 6fd554f71bba..6edd64f3f95b 100644
--- a/products/metrics/mcp/prompts/query-metrics.md
+++ b/products/metrics/mcp/prompts/query-metrics.md
@@ -31,4 +31,4 @@ Two request forms:
4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.
5. Correlate the onset window across signals: query logs (`query-logs`, filtered to the same `service.name` and time window, severity error) and traces (APM span tools, same service/window) to find the cause and its blast radius.
-CRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now. `dateFrom` snaps down to its bucket boundary, so the first point can be labelled up to one interval earlier than requested but always covers a whole bucket.
+CRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` and `dateTo` take ISO 8601 or a relative offset back from now (`-1h`, `-24h`, `-7d`, `-2w`; `m` means months, not minutes). `dateTo` defaults to now and `dateFrom` to 24 hours before `dateTo`. `dateFrom` snaps down to its bucket boundary, so the first point can be labelled up to one interval earlier than requested but always covers a whole bucket.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index d4a7c3b96edf..580fe372b084 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -10783,7 +10783,7 @@
"system_prompt_hint": "One MCP tool's top callers — calls, error rate, harnesses, person email/name"
},
"query-metrics": {
- "description": "Query server/infrastructure metrics (OTel- or Prometheus-ingested) as bucketed time series. The response is a list of series — `{labels, points: [{time, value}], metric_name, clause}` — where every series shares one time grid (missing buckets are zero-filled). A single ungrouped query returns exactly one series with empty labels.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"metricName\": \"m\", \"aggregation\": \"rate\", \"dateFrom\": \"2026-01-01T00:00:00Z\" } }\n```\n\nTwo request forms:\n\n- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).\n- **Multi-clause / formula:** set `clauses: [{name, metricName, aggregation, quantile?, filters?, groupBy?}, ...]` and optionally `formula` (e.g. `\"(a - b) / a\"` over clause names; `+ - * /` and parentheses; division by zero yields 0). With a formula set, only the formula result series are returned.\n\n# Workflow — follow this order every time\n\n1. **Discover names first.** Call `metric-names-list` with a substring (`value`) before querying — metric names must match exactly, and the returned `metric_type` tells you the right aggregation.\n2. **Pick the aggregation by metric type:**\n - `sum` counters (usually `_total`): use `rate` (per-second) or `increase` — both are counter-reset safe and temporality-aware. Do NOT use `sum`/`avg` on cumulative counters; absolute counter values are meaningless.\n - `gauge`: `avg` (typical), `p95`, `sum`.\n - Every aggregation combines across series, never across raw samples, so a result never scales with the scrape rate: `sum`/`avg`/`p95` reduce each series to its latest value in the bucket and combine those, and `count` is the number of series that reported.\n - `histogram`: `histogram_quantile` with `quantile` (e.g. 0.95). All selected series must share one bucket layout — narrow with `filters` if you get a bounds-mismatch error.\n3. **Narrow with filters.** `filters: [{key, op, value, scope?}]`, ANDed. Ops: `eq`, `neq`, `regex`, `not_regex` (RE2). Leave `scope` at its default `auto` unless you know whether the attribute is per-target (`resource`) or per-datapoint (`attribute`). Negative ops also match rows lacking the key, like Prometheus negative matchers.\n4. **Split with groupBy.** `groupBy: [{key}]` returns one series per label value (capped at the 100 largest). The service name is always available — `service_name` and `service.name` both resolve to it in metrics (logs only accept the dotted `service.name`); discover other keys from a sample query's labels or ask the user.\n5. **Control the grid with `interval`.** One of `second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week`. Omit to auto-pick (~60 buckets across the range). Use the same interval when comparing windows.\n\n# Investigating an anomaly (\"metric X is rising — why?\")\n\n1. Query the metric over a window that includes the anomaly AND an equal-length healthy baseline before it (one call, auto interval).\n2. Find the onset: the first bucket where the value clearly departs from the baseline range.\n3. Re-query grouped by `service_name` (then by other candidate keys) over the same window to see WHICH series moved — a single label value moving points at the culprit; all moving together points at something shared (upstream dependency, infra).\n4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.\n5. Correlate the onset window across signals: query logs (`query-logs`, filtered to the same `service.name` and time window, severity error) and traces (APM span tools, same service/window) to find the cause and its blast radius.\n\nCRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now. `dateFrom` snaps down to its bucket boundary, so the first point can be labelled up to one interval earlier than requested but always covers a whole bucket.",
+ "description": "Query server/infrastructure metrics (OTel- or Prometheus-ingested) as bucketed time series. The response is a list of series — `{labels, points: [{time, value}], metric_name, clause}` — where every series shares one time grid (missing buckets are zero-filled). A single ungrouped query returns exactly one series with empty labels.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"metricName\": \"m\", \"aggregation\": \"rate\", \"dateFrom\": \"2026-01-01T00:00:00Z\" } }\n```\n\nTwo request forms:\n\n- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).\n- **Multi-clause / formula:** set `clauses: [{name, metricName, aggregation, quantile?, filters?, groupBy?}, ...]` and optionally `formula` (e.g. `\"(a - b) / a\"` over clause names; `+ - * /` and parentheses; division by zero yields 0). With a formula set, only the formula result series are returned.\n\n# Workflow — follow this order every time\n\n1. **Discover names first.** Call `metric-names-list` with a substring (`value`) before querying — metric names must match exactly, and the returned `metric_type` tells you the right aggregation.\n2. **Pick the aggregation by metric type:**\n - `sum` counters (usually `_total`): use `rate` (per-second) or `increase` — both are counter-reset safe and temporality-aware. Do NOT use `sum`/`avg` on cumulative counters; absolute counter values are meaningless.\n - `gauge`: `avg` (typical), `p95`, `sum`.\n - Every aggregation combines across series, never across raw samples, so a result never scales with the scrape rate: `sum`/`avg`/`p95` reduce each series to its latest value in the bucket and combine those, and `count` is the number of series that reported.\n - `histogram`: `histogram_quantile` with `quantile` (e.g. 0.95). All selected series must share one bucket layout — narrow with `filters` if you get a bounds-mismatch error.\n3. **Narrow with filters.** `filters: [{key, op, value, scope?}]`, ANDed. Ops: `eq`, `neq`, `regex`, `not_regex` (RE2). Leave `scope` at its default `auto` unless you know whether the attribute is per-target (`resource`) or per-datapoint (`attribute`). Negative ops also match rows lacking the key, like Prometheus negative matchers.\n4. **Split with groupBy.** `groupBy: [{key}]` returns one series per label value (capped at the 100 largest). The service name is always available — `service_name` and `service.name` both resolve to it in metrics (logs only accept the dotted `service.name`); discover other keys from a sample query's labels or ask the user.\n5. **Control the grid with `interval`.** One of `second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week`. Omit to auto-pick (~60 buckets across the range). Use the same interval when comparing windows.\n\n# Investigating an anomaly (\"metric X is rising — why?\")\n\n1. Query the metric over a window that includes the anomaly AND an equal-length healthy baseline before it (one call, auto interval).\n2. Find the onset: the first bucket where the value clearly departs from the baseline range.\n3. Re-query grouped by `service_name` (then by other candidate keys) over the same window to see WHICH series moved — a single label value moving points at the culprit; all moving together points at something shared (upstream dependency, infra).\n4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.\n5. Correlate the onset window across signals: query logs (`query-logs`, filtered to the same `service.name` and time window, severity error) and traces (APM span tools, same service/window) to find the cause and its blast radius.\n\nCRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` and `dateTo` take ISO 8601 or a relative offset back from now (`-1h`, `-24h`, `-7d`, `-2w`; `m` means months, not minutes). `dateTo` defaults to now and `dateFrom` to 24 hours before `dateTo`. `dateFrom` snaps down to its bucket boundary, so the first point can be labelled up to one interval earlier than requested but always covers a whole bucket.",
"category": "Metrics",
"feature": "metrics",
"summary": "Query metrics",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 4f0bf9d1f13a..d3c7bcbe6c53 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -11374,7 +11374,7 @@
"system_prompt_hint": "One MCP tool's top callers — calls, error rate, harnesses, person email/name"
},
"query-metrics": {
- "description": "Query server/infrastructure metrics (OTel- or Prometheus-ingested) as bucketed time series. The response is a list of series — `{labels, points: [{time, value}], metric_name, clause}` — where every series shares one time grid (missing buckets are zero-filled). A single ungrouped query returns exactly one series with empty labels.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"metricName\": \"m\", \"aggregation\": \"rate\", \"dateFrom\": \"2026-01-01T00:00:00Z\" } }\n```\n\nTwo request forms:\n\n- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).\n- **Multi-clause / formula:** set `clauses: [{name, metricName, aggregation, quantile?, filters?, groupBy?}, ...]` and optionally `formula` (e.g. `\"(a - b) / a\"` over clause names; `+ - * /` and parentheses; division by zero yields 0). With a formula set, only the formula result series are returned.\n\n# Workflow — follow this order every time\n\n1. **Discover names first.** Call `metric-names-list` with a substring (`value`) before querying — metric names must match exactly, and the returned `metric_type` tells you the right aggregation.\n2. **Pick the aggregation by metric type:**\n - `sum` counters (usually `_total`): use `rate` (per-second) or `increase` — both are counter-reset safe and temporality-aware. Do NOT use `sum`/`avg` on cumulative counters; absolute counter values are meaningless.\n - `gauge`: `avg` (typical), `p95`, `sum`.\n - Every aggregation combines across series, never across raw samples, so a result never scales with the scrape rate: `sum`/`avg`/`p95` reduce each series to its latest value in the bucket and combine those, and `count` is the number of series that reported.\n - `histogram`: `histogram_quantile` with `quantile` (e.g. 0.95). All selected series must share one bucket layout — narrow with `filters` if you get a bounds-mismatch error.\n3. **Narrow with filters.** `filters: [{key, op, value, scope?}]`, ANDed. Ops: `eq`, `neq`, `regex`, `not_regex` (RE2). Leave `scope` at its default `auto` unless you know whether the attribute is per-target (`resource`) or per-datapoint (`attribute`). Negative ops also match rows lacking the key, like Prometheus negative matchers.\n4. **Split with groupBy.** `groupBy: [{key}]` returns one series per label value (capped at the 100 largest). The service name is always available — `service_name` and `service.name` both resolve to it in metrics (logs only accept the dotted `service.name`); discover other keys from a sample query's labels or ask the user.\n5. **Control the grid with `interval`.** One of `second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week`. Omit to auto-pick (~60 buckets across the range). Use the same interval when comparing windows.\n\n# Investigating an anomaly (\"metric X is rising — why?\")\n\n1. Query the metric over a window that includes the anomaly AND an equal-length healthy baseline before it (one call, auto interval).\n2. Find the onset: the first bucket where the value clearly departs from the baseline range.\n3. Re-query grouped by `service_name` (then by other candidate keys) over the same window to see WHICH series moved — a single label value moving points at the culprit; all moving together points at something shared (upstream dependency, infra).\n4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.\n5. Correlate the onset window across signals: query logs (`query-logs`, filtered to the same `service.name` and time window, severity error) and traces (APM span tools, same service/window) to find the cause and its blast radius.\n\nCRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now. `dateFrom` snaps down to its bucket boundary, so the first point can be labelled up to one interval earlier than requested but always covers a whole bucket.",
+ "description": "Query server/infrastructure metrics (OTel- or Prometheus-ingested) as bucketed time series. The response is a list of series — `{labels, points: [{time, value}], metric_name, clause}` — where every series shares one time grid (missing buckets are zero-filled). A single ungrouped query returns exactly one series with empty labels.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"metricName\": \"m\", \"aggregation\": \"rate\", \"dateFrom\": \"2026-01-01T00:00:00Z\" } }\n```\n\nTwo request forms:\n\n- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).\n- **Multi-clause / formula:** set `clauses: [{name, metricName, aggregation, quantile?, filters?, groupBy?}, ...]` and optionally `formula` (e.g. `\"(a - b) / a\"` over clause names; `+ - * /` and parentheses; division by zero yields 0). With a formula set, only the formula result series are returned.\n\n# Workflow — follow this order every time\n\n1. **Discover names first.** Call `metric-names-list` with a substring (`value`) before querying — metric names must match exactly, and the returned `metric_type` tells you the right aggregation.\n2. **Pick the aggregation by metric type:**\n - `sum` counters (usually `_total`): use `rate` (per-second) or `increase` — both are counter-reset safe and temporality-aware. Do NOT use `sum`/`avg` on cumulative counters; absolute counter values are meaningless.\n - `gauge`: `avg` (typical), `p95`, `sum`.\n - Every aggregation combines across series, never across raw samples, so a result never scales with the scrape rate: `sum`/`avg`/`p95` reduce each series to its latest value in the bucket and combine those, and `count` is the number of series that reported.\n - `histogram`: `histogram_quantile` with `quantile` (e.g. 0.95). All selected series must share one bucket layout — narrow with `filters` if you get a bounds-mismatch error.\n3. **Narrow with filters.** `filters: [{key, op, value, scope?}]`, ANDed. Ops: `eq`, `neq`, `regex`, `not_regex` (RE2). Leave `scope` at its default `auto` unless you know whether the attribute is per-target (`resource`) or per-datapoint (`attribute`). Negative ops also match rows lacking the key, like Prometheus negative matchers.\n4. **Split with groupBy.** `groupBy: [{key}]` returns one series per label value (capped at the 100 largest). The service name is always available — `service_name` and `service.name` both resolve to it in metrics (logs only accept the dotted `service.name`); discover other keys from a sample query's labels or ask the user.\n5. **Control the grid with `interval`.** One of `second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week`. Omit to auto-pick (~60 buckets across the range). Use the same interval when comparing windows.\n\n# Investigating an anomaly (\"metric X is rising — why?\")\n\n1. Query the metric over a window that includes the anomaly AND an equal-length healthy baseline before it (one call, auto interval).\n2. Find the onset: the first bucket where the value clearly departs from the baseline range.\n3. Re-query grouped by `service_name` (then by other candidate keys) over the same window to see WHICH series moved — a single label value moving points at the culprit; all moving together points at something shared (upstream dependency, infra).\n4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.\n5. Correlate the onset window across signals: query logs (`query-logs`, filtered to the same `service.name` and time window, severity error) and traces (APM span tools, same service/window) to find the cause and its blast radius.\n\nCRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` and `dateTo` take ISO 8601 or a relative offset back from now (`-1h`, `-24h`, `-7d`, `-2w`; `m` means months, not minutes). `dateTo` defaults to now and `dateFrom` to 24 hours before `dateTo`. `dateFrom` snaps down to its bucket boundary, so the first point can be labelled up to one interval earlier than requested but always covers a whole bucket.",
"category": "Metrics",
"feature": "metrics",
"summary": "Query metrics",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f70ee340dbd0..5f045916c882 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -116250,9 +116250,9 @@ export namespace Schemas {
* @nullable
*/
formula?: string | null;
- /** Lower bound (inclusive) for the query range. ISO 8601. */
- dateFrom: string;
- /** Upper bound (exclusive) for the query range. Defaults to now if omitted. */
+ /** Lower bound (inclusive) for the query range. ISO 8601, or a relative offset back from now such as '-1h', '-7d', '-2w', '-1m' (months). Defaults to 24 hours before dateTo. */
+ dateFrom?: string;
+ /** Upper bound (exclusive) for the query range. ISO 8601 or a relative offset like dateFrom. Defaults to now if omitted. */
dateTo?: string;
}
diff --git a/services/mcp/src/generated/metrics/api.ts b/services/mcp/src/generated/metrics/api.ts
index 470ad06f11f6..0d914bfa4b56 100644
--- a/services/mcp/src/generated/metrics/api.ts
+++ b/services/mcp/src/generated/metrics/api.ts
@@ -684,13 +684,18 @@ export const MetricsQueryCreateBody = () => zod.object({
.describe(
"Arithmetic over clause names evaluated server-side per grid point, e.g. '(a - b) \/ a'. Supports + - \* \/ and parentheses; division by zero yields 0. When set, only the formula result series are returned."
),
- dateFrom: zod.iso
- .datetime({ offset: true })
- .describe('Lower bound (inclusive) for the query range. ISO 8601.'),
- dateTo: zod.iso
- .datetime({ offset: true })
+ dateFrom: zod
+ .string()
.optional()
- .describe('Upper bound (exclusive) for the query range. Defaults to now if omitted.'),
+ .describe(
+ "Lower bound (inclusive) for the query range. ISO 8601, or a relative offset back from now such as '-1h', '-7d', '-2w', '-1m' (months). Defaults to 24 hours before dateTo."
+ ),
+ dateTo: zod
+ .string()
+ .optional()
+ .describe(
+ 'Upper bound (exclusive) for the query range. ISO 8601 or a relative offset like dateFrom. Defaults to now if omitted.'
+ ),
})
.describe('The metric query to execute.'),
})