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): characterize-metric-anomaly endpoint and MCP tool (#63131)

Daniel Visca0eb877d1c9bc
diff --git a/products/metrics/backend/anomaly.py b/products/metrics/backend/anomaly.py
new file mode 100644
index 000000000000..48925d8bf5a4
--- /dev/null
+++ b/products/metrics/backend/anomaly.py
@@ -0,0 +1,263 @@
+"""Anomaly characterization for one metric.
+
+Given an anomaly window (and an optional explicit baseline window), this
+compares the windows statistically, finds the onset bucket, and drills into
+candidate label keys to find which label values moved — the "what changed,
+when, and where" an on-call investigator (or agent) needs before
+correlating into logs and traces.
+"""
+
+from __future__ import annotations
+
+import math
+import datetime as dt
+import statistics
+from collections.abc import Callable
+from typing import Any
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import Workload
+from posthog.models import Team
+
+from products.metrics.backend.facade.contracts import (
+ MetricAnomalyDimension,
+ MetricAnomalyReport,
+ MetricFilter,
+ MetricGroupBy,
+ MetricPoint,
+ MetricSeries,
+)
+from products.metrics.backend.metric_names_query_runner import MetricNamesQueryRunner
+from products.metrics.backend.metric_query_runner import MetricQueryRunner, _pick_interval
+
+# How many label keys to drill into and how many movers to report.
+MAX_CANDIDATE_KEYS = 4
+MAX_TOP_MOVERS = 8
+
+# Onset = first anomaly-window bucket beyond this many baseline stddevs
+# (with a relative-change floor for near-constant baselines).
+ONSET_STDDEV_THRESHOLD = 3.0
+ONSET_RELATIVE_FLOOR = 0.5
+
+_AGGREGATION_BY_TYPE = {
+ "sum": "rate",
+ "gauge": "avg",
+ "histogram": "histogram_quantile",
+ "exponential_histogram": "p95",
+ "summary": "avg",
+}
+
+
+def _default_aggregation(team: Team, metric_name: str) -> tuple[str, float | None]:
+ """Pick an aggregation from the metric's OTel type: counters get `rate`,
+ gauges `avg`, histograms `histogram_quantile(0.95)`."""
+ for row in MetricNamesQueryRunner(team=team, search=metric_name, limit=5).run():
+ if row["name"] == metric_name:
+ aggregation = _AGGREGATION_BY_TYPE.get(row["metric_type"], "avg")
+ return aggregation, 0.95 if aggregation == "histogram_quantile" else None
+ return "avg", None
+
+
+def _mean(values: list[float]) -> float:
+ return sum(values) / len(values) if values else 0.0
+
+
+def _find_onset(
+ points: list[MetricPoint], anomaly_from_iso: str, baseline_mean: float, baseline_stddev: float, direction: str
+) -> str | None:
+ threshold = max(
+ ONSET_STDDEV_THRESHOLD * baseline_stddev,
+ ONSET_RELATIVE_FLOOR * abs(baseline_mean),
+ 1e-9,
+ )
+ for point in points:
+ if point.time < anomaly_from_iso:
+ continue
+ deviation = point.value - baseline_mean
+ if direction == "down":
+ deviation = -deviation
+ if deviation > threshold:
+ return point.time
+ return None
+
+
+def characterize_anomaly(
+ *,
+ team: Team,
+ metric_name: str,
+ anomaly_from: dt.datetime,
+ anomaly_to: dt.datetime,
+ baseline_from: dt.datetime | None = None,
+ baseline_to: dt.datetime | None = None,
+ aggregation: str | None = None,
+ quantile: float | None = None,
+ filters: tuple[MetricFilter, ...] = (),
+ candidate_keys: tuple[str, ...] | None = None,
+) -> MetricAnomalyReport:
+ if anomaly_to <= anomaly_from:
+ raise ValueError("anomaly_to must be after anomaly_from")
+ if baseline_to is None:
+ baseline_to = anomaly_from
+ if baseline_from is None:
+ baseline_from = baseline_to - (anomaly_to - anomaly_from)
+ if baseline_to > anomaly_from:
+ raise ValueError("the baseline window must end at or before anomaly_from")
+
+ if aggregation is None:
+ aggregation, default_quantile = _default_aggregation(team, metric_name)
+ quantile = quantile if quantile is not None else default_quantile
+ if aggregation == "histogram_quantile" and quantile is None:
+ quantile = 0.95
+
+ # One query over the combined window keeps baseline and anomaly on a
+ # single grid; the interval comes from the combined span.
+ interval = _pick_interval(baseline_from, anomaly_to)
+ anomaly_from_iso = anomaly_from.isoformat()
+
+ def _run(group_by: tuple[MetricGroupBy, ...] = ()) -> list[dict[str, Any]]:
+ return MetricQueryRunner(
+ team=team,
+ metric_name=metric_name,
+ aggregation=aggregation,
+ date_from=baseline_from,
+ date_to=anomaly_to,
+ filters=filters,
+ group_by=group_by,
+ interval=interval,
+ quantile=quantile if aggregation == "histogram_quantile" else None,
+ ).run()
+
+ rows = _run()
+ points = [MetricPoint(time=row["time"], value=row["value"]) for row in rows]
+ baseline_values = [p.value for p in points if p.time < anomaly_from_iso]
+ anomaly_values = [p.value for p in points if p.time >= anomaly_from_iso]
+
+ baseline_mean = _mean(baseline_values)
+ baseline_stddev = statistics.pstdev(baseline_values) if len(baseline_values) > 1 else 0.0
+ anomaly_mean = _mean(anomaly_values)
+ anomaly_peak = max(anomaly_values, default=0.0)
+ change_ratio = anomaly_mean / baseline_mean if baseline_mean else anomaly_mean
+
+ if math.isclose(anomaly_mean, baseline_mean, rel_tol=0.05, abs_tol=1e-12):
+ direction = "flat"
+ else:
+ direction = "up" if anomaly_mean > baseline_mean else "down"
+
+ onset_time = (
+ None
+ if direction == "flat"
+ else _find_onset(points, anomaly_from_iso, baseline_mean, baseline_stddev, direction)
+ )
+
+ movers = _find_top_movers(
+ run=_run,
+ team=team,
+ metric_name=metric_name,
+ anomaly_from_iso=anomaly_from_iso,
+ anomaly_from=anomaly_from,
+ anomaly_to=anomaly_to,
+ filters=filters,
+ candidate_keys=candidate_keys,
+ )
+
+ return MetricAnomalyReport(
+ metric_name=metric_name,
+ aggregation=aggregation,
+ interval=interval,
+ baseline_from=baseline_from.isoformat(),
+ baseline_to=baseline_to.isoformat(),
+ anomaly_from=anomaly_from_iso,
+ anomaly_to=anomaly_to.isoformat(),
+ baseline_mean=baseline_mean,
+ baseline_stddev=baseline_stddev,
+ anomaly_mean=anomaly_mean,
+ anomaly_peak=anomaly_peak,
+ change_ratio=change_ratio,
+ direction=direction,
+ onset_time=onset_time,
+ top_movers=movers,
+ series=MetricSeries(labels={}, points=tuple(points), metric_name=metric_name, clause="anomaly"),
+ )
+
+
+def _discover_candidate_keys(
+ team: Team, metric_name: str, date_from: dt.datetime, date_to: dt.datetime
+) -> tuple[str, ...]:
+ """Most common attribute keys on the metric's rows in the window, with
+ service_name always considered (it's a first-class column duplicated
+ into the labels)."""
+ query = parse_select(
+ """
+ SELECT key, count() AS occurrences
+ FROM (
+ SELECT arrayJoin(arrayConcat(mapKeys(attributes), mapKeys(resource_attributes))) AS key
+ FROM posthog.metrics
+ WHERE metric_name = {metric_name}
+ AND timestamp >= {date_from}
+ AND timestamp < {date_to}
+ )
+ GROUP BY key
+ ORDER BY occurrences DESC
+ LIMIT {limit}
+ """,
+ placeholders={
+ "metric_name": ast.Constant(value=metric_name),
+ "date_from": ast.Constant(value=date_from),
+ "date_to": ast.Constant(value=date_to),
+ "limit": ast.Constant(value=MAX_CANDIDATE_KEYS),
+ },
+ )
+ response = execute_hogql_query(query_type="MetricQuery", query=query, team=team, workload=Workload.LOGS)
+ keys = [row[0] for row in response.results]
+ if "service_name" not in keys:
+ keys = ["service_name", *keys][:MAX_CANDIDATE_KEYS]
+ return tuple(keys)
+
+
+def _find_top_movers(
+ *,
+ run: Callable[..., list[dict[str, Any]]],
+ team: Team,
+ metric_name: str,
+ anomaly_from_iso: str,
+ anomaly_from: dt.datetime,
+ anomaly_to: dt.datetime,
+ filters: tuple[MetricFilter, ...],
+ candidate_keys: tuple[str, ...] | None,
+) -> tuple[MetricAnomalyDimension, ...]:
+ keys = candidate_keys or _discover_candidate_keys(team, metric_name, anomaly_from, anomaly_to)
+
+ movers: list[MetricAnomalyDimension] = []
+ for key in keys[:MAX_CANDIDATE_KEYS]:
+ rows = run(group_by=(MetricGroupBy(key=key),))
+ per_label: dict[str, dict[str, list[float]]] = {}
+ for row in rows:
+ label = row["labels"].get(key, "")
+ bucket = "anomaly" if row["time"] >= anomaly_from_iso else "baseline"
+ per_label.setdefault(label, {"baseline": [], "anomaly": []})[bucket].append(row["value"])
+ for label, windows in per_label.items():
+ baseline_value = _mean(windows["baseline"])
+ anomaly_value = _mean(windows["anomaly"])
+ if math.isclose(baseline_value, anomaly_value, rel_tol=0.05, abs_tol=1e-12):
+ continue
+ ratio = anomaly_value / baseline_value if baseline_value else anomaly_value
+ movers.append(
+ MetricAnomalyDimension(
+ key=key,
+ label=label,
+ baseline_value=baseline_value,
+ anomaly_value=anomaly_value,
+ change_ratio=ratio,
+ )
+ )
+
+ def _magnitude(mover: MetricAnomalyDimension) -> float:
+ if mover.baseline_value == 0 or mover.change_ratio <= 0:
+ return abs(mover.anomaly_value - mover.baseline_value)
+ return abs(math.log(mover.change_ratio)) * max(abs(mover.anomaly_value), abs(mover.baseline_value))
+
+ movers.sort(key=lambda m: (-_magnitude(m), m.key, m.label))
+ return tuple(movers[:MAX_TOP_MOVERS])
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index 0ddf045e8552..b9fc0eebbd0a 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -5,11 +5,20 @@ allowed to import. Internal modules (query runners) stay behind this seam
so import-linter's strict-mode contract holds.
"""
+import datetime as dt
from typing import Any
from posthog.models import Team
-from products.metrics.backend.facade.contracts import MetricPoint, MetricQueryClause, MetricQueryRequest, MetricSeries
+from products.metrics.backend.anomaly import characterize_anomaly as _characterize_anomaly
+from products.metrics.backend.facade.contracts import (
+ MetricAnomalyReport,
+ MetricFilter,
+ MetricPoint,
+ MetricQueryClause,
+ MetricQueryRequest,
+ MetricSeries,
+)
from products.metrics.backend.facade.enums import MetricAggregation
from products.metrics.backend.formula import evaluate, parse_formula
from products.metrics.backend.has_metrics_query_runner import team_has_metrics as _team_has_metrics
@@ -183,3 +192,41 @@ def list_metric_names(
"""
runner = MetricNamesQueryRunner(team=team, search=search, limit=limit)
return runner.run()
+
+
+def characterize_metric_anomaly(
+ *,
+ team: Team,
+ metric_name: str,
+ anomaly_from: dt.datetime,
+ anomaly_to: dt.datetime,
+ baseline_from: dt.datetime | None = None,
+ baseline_to: dt.datetime | None = None,
+ aggregation: str | None = None,
+ quantile: float | None = None,
+ filters: tuple[MetricFilter, ...] = (),
+ candidate_keys: tuple[str, ...] | None = None,
+) -> MetricAnomalyReport:
+ """Characterize how a metric behaves in an anomaly window vs a baseline:
+ summary statistics, change magnitude/direction, the onset bucket, and
+ the label values that moved the most (drilling into up to four candidate
+ keys, auto-discovered from the metric's attributes when not given).
+
+ The baseline defaults to the window of equal length immediately before
+ `anomaly_from`. `aggregation` defaults by the metric's OTel type
+ (counter -> rate, gauge -> avg, histogram -> histogram_quantile 0.95).
+ Raises `ValueError` for invalid windows/aggregations — the presentation
+ layer surfaces these as 400s.
+ """
+ return _characterize_anomaly(
+ team=team,
+ metric_name=metric_name,
+ anomaly_from=anomaly_from,
+ anomaly_to=anomaly_to,
+ baseline_from=baseline_from,
+ baseline_to=baseline_to,
+ aggregation=aggregation,
+ quantile=quantile,
+ filters=filters,
+ candidate_keys=candidate_keys,
+ )
diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.py
index da6adedf74d1..27732dd29d48 100644
--- a/products/metrics/backend/facade/contracts.py
+++ b/products/metrics/backend/facade/contracts.py
@@ -113,3 +113,41 @@ class MetricSeries:
points: tuple[MetricPoint, ...]
metric_name: str | None = None
clause: str | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class MetricAnomalyDimension:
+ """One label value's behavior across the baseline/anomaly windows."""
+
+ key: str
+ label: str
+ baseline_value: float
+ anomaly_value: float
+ # anomaly_value / baseline_value; 0.0 baselines yield the anomaly value
+ # itself (treat as "new" traffic).
+ change_ratio: float
+
+
+@dataclass(frozen=True, slots=True)
+class MetricAnomalyReport:
+ """Everything an investigator needs to characterize 'metric X looks
+ wrong': how the anomaly window compares to the baseline, when it
+ started, and which label values moved the most."""
+
+ metric_name: str
+ aggregation: str
+ interval: str
+ baseline_from: str
+ baseline_to: str
+ anomaly_from: str
+ anomaly_to: str
+ baseline_mean: float
+ baseline_stddev: float
+ anomaly_mean: float
+ anomaly_peak: float
+ # anomaly_mean / baseline_mean; 0.0 baselines yield anomaly_mean.
+ change_ratio: float
+ direction: str # "up" | "down" | "flat"
+ onset_time: str | None
+ top_movers: tuple[MetricAnomalyDimension, ...]
+ series: MetricSeries
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.py
index 85fddc196007..ca4b4076368c 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -22,7 +22,12 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.event_usage import report_user_action
-from products.metrics.backend.facade.api import list_metric_names, run_metric_query, team_has_metrics
+from products.metrics.backend.facade.api import (
+ characterize_metric_anomaly,
+ list_metric_names,
+ run_metric_query,
+ team_has_metrics,
+)
from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy, MetricQueryClause, MetricQueryRequest
from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation
@@ -224,6 +229,99 @@ class _MetricQueryResponseSerializer(serializers.Serializer):
)
+class _MetricAnomalyBodySerializer(serializers.Serializer):
+ metricName = serializers.CharField(
+ max_length=255,
+ help_text="Exact metric name to characterize (e.g. 'metrics_rate_limiter_message_lag_seconds').",
+ )
+ anomalyFrom = serializers.DateTimeField(
+ help_text="Start of the suspicious window (inclusive). ISO 8601 — e.g. when the alert fired or the graph started looking wrong.",
+ )
+ anomalyTo = serializers.DateTimeField(
+ required=False,
+ help_text="End of the suspicious window (exclusive). Defaults to now.",
+ )
+ baselineFrom = serializers.DateTimeField(
+ required=False,
+ help_text="Start of the healthy comparison window. Defaults to one anomaly-window-length before baselineTo.",
+ )
+ baselineTo = serializers.DateTimeField(
+ required=False,
+ help_text="End of the healthy comparison window. Defaults to anomalyFrom. Must not extend past anomalyFrom.",
+ )
+ aggregation = serializers.ChoiceField(
+ choices=["sum", "avg", "count", "p95", "rate", "increase", "histogram_quantile"],
+ required=False,
+ allow_null=True,
+ help_text="Aggregation to characterize. Omit to auto-pick from the metric's OTel type (counter -> rate, gauge -> avg, histogram -> histogram_quantile 0.95).",
+ )
+ quantile = serializers.FloatField(
+ required=False,
+ allow_null=True,
+ min_value=0.0,
+ max_value=1.0,
+ help_text="Quantile for histogram_quantile. Defaults to 0.95.",
+ )
+ filters = _MetricFilterSerializer(
+ many=True,
+ required=False,
+ default=list,
+ help_text="Label predicates narrowing which series are characterized.",
+ )
+ candidateKeys = serializers.ListField(
+ child=serializers.CharField(max_length=255),
+ required=False,
+ help_text="Label keys to drill into when finding which label values moved. Omit to auto-discover the most common keys on this metric (plus service_name). Max 4 are used.",
+ )
+
+
+class _MetricAnomalyRequestSerializer(serializers.Serializer):
+ query = _MetricAnomalyBodySerializer(help_text="The anomaly characterization to run.")
+
+
+class _MetricAnomalyDimensionSerializer(serializers.Serializer):
+ key = serializers.CharField(help_text="Label key that was drilled into.")
+ # the name shadows rest_framework Field.label as far as mypy can tell;
+ # DRF itself handles declared fields named `label` fine
+ label = serializers.CharField(help_text="Label value this row describes.") # type: ignore[assignment]
+ baseline_value = serializers.FloatField(help_text="Mean value over the baseline window for this label value.")
+ anomaly_value = serializers.FloatField(help_text="Mean value over the anomaly window for this label value.")
+ change_ratio = serializers.FloatField(
+ help_text="anomaly_value / baseline_value. A zero baseline yields the anomaly value itself (new traffic)."
+ )
+
+
+class _MetricAnomalyReportSerializer(serializers.Serializer):
+ metric_name = serializers.CharField(help_text="Metric that was characterized.")
+ aggregation = serializers.CharField(help_text="Aggregation used (auto-picked when not specified).")
+ interval = serializers.CharField(help_text="Bucket size of the analysis grid.")
+ baseline_from = serializers.CharField(help_text="Baseline window start, ISO 8601.")
+ baseline_to = serializers.CharField(help_text="Baseline window end, ISO 8601.")
+ anomaly_from = serializers.CharField(help_text="Anomaly window start, ISO 8601.")
+ anomaly_to = serializers.CharField(help_text="Anomaly window end, ISO 8601.")
+ baseline_mean = serializers.FloatField(help_text="Mean over the baseline window.")
+ baseline_stddev = serializers.FloatField(help_text="Population stddev over the baseline window.")
+ anomaly_mean = serializers.FloatField(help_text="Mean over the anomaly window.")
+ anomaly_peak = serializers.FloatField(help_text="Maximum bucket value in the anomaly window.")
+ change_ratio = serializers.FloatField(
+ help_text="anomaly_mean / baseline_mean. A zero baseline yields anomaly_mean itself."
+ )
+ direction = serializers.ChoiceField(
+ choices=["up", "down", "flat"], help_text="Which way the metric moved versus the baseline."
+ )
+ onset_time = serializers.CharField(
+ allow_null=True,
+ help_text="First bucket clearly outside the baseline range (3 stddevs or 50% relative change), or null if no clear onset.",
+ )
+ top_movers = _MetricAnomalyDimensionSerializer(
+ many=True,
+ help_text="Label values whose behavior changed the most between windows, largest change first. Empty when nothing moved or the metric has no labels.",
+ )
+ series = _MetricSeriesSerializer(
+ help_text="The metric across baseline + anomaly windows on one grid, for plotting or further inspection."
+ )
+
+
class _MetricNameSerializer(serializers.Serializer):
name = serializers.CharField(help_text="Metric name as it appears in the team's data.")
metric_type = serializers.CharField(
@@ -333,3 +431,48 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
)
return Response({"results": [asdict(s) for s in series]}, status=status.HTTP_200_OK)
+
+ @extend_schema(request=_MetricAnomalyRequestSerializer, responses={200: _MetricAnomalyReportSerializer})
+ @action(detail=False, methods=["POST"], required_scopes=["metrics:read"])
+ def characterize(self, request: Request, *args, **kwargs) -> Response:
+ """Characterize a metric anomaly: compare an anomaly window against a
+ baseline, find the onset, and rank which label values moved."""
+ tag_queries(product=Product.METRICS, feature=Feature.QUERY)
+
+ body = _MetricAnomalyRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ query_data = body.validated_data["query"]
+
+ filters = tuple(
+ MetricFilter(key=f["key"], op=FilterOp(f["op"]), value=f["value"], scope=AttributeScope(f["scope"]))
+ for f in query_data.get("filters") or []
+ )
+ try:
+ report = characterize_metric_anomaly(
+ team=self.team,
+ metric_name=query_data["metricName"],
+ anomaly_from=query_data["anomalyFrom"],
+ anomaly_to=query_data.get("anomalyTo") or timezone.now(),
+ baseline_from=query_data.get("baselineFrom"),
+ baseline_to=query_data.get("baselineTo"),
+ aggregation=query_data.get("aggregation"),
+ quantile=query_data.get("quantile"),
+ filters=filters,
+ candidate_keys=tuple(query_data["candidateKeys"]) if query_data.get("candidateKeys") else None,
+ )
+ except ValueError as exc:
+ raise ParseError(str(exc))
+
+ report_user_action(
+ request.user,
+ "metrics anomaly characterized",
+ {
+ "aggregation": report.aggregation,
+ "direction": report.direction,
+ "mover_count": len(report.top_movers),
+ },
+ team=self.team,
+ request=request,
+ )
+
+ return Response(asdict(report), status=status.HTTP_200_OK)
diff --git a/products/metrics/backend/tests/test_anomaly.py b/products/metrics/backend/tests/test_anomaly.py
new file mode 100644
index 000000000000..2cc6aa2508bf
--- /dev/null
+++ b/products/metrics/backend/tests/test_anomaly.py
@@ -0,0 +1,135 @@
+import datetime as dt
+from typing import Any
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from django.utils import timezone
+
+from rest_framework import status
+
+from posthog.clickhouse.client import sync_execute
+
+from products.metrics.backend.facade.api import characterize_metric_anomaly
+from products.metrics.backend.tests._seeder import seed_metric
+
+
+class TestCharacterizeAnomaly(ClickhouseTestMixin, APIBaseTest):
+ CLASS_DATA_LEVEL_SETUP = True
+
+ def setUp(self):
+ super().setUp()
+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ # 20-minute window: minutes 0-9 baseline (steady ~10), minutes 10-19
+ # anomaly (jumps to ~100 from minute 12).
+ self.start = (timezone.now() - dt.timedelta(hours=1)).replace(second=0, microsecond=0)
+ self.anomaly_from = self.start + dt.timedelta(minutes=10)
+ self.anomaly_to = self.start + dt.timedelta(minutes=20)
+ baseline_points = [(self.start + dt.timedelta(minutes=m), 10.0) for m in range(10)]
+ quiet_points = [(self.start + dt.timedelta(minutes=m), 10.0) for m in (10, 11)]
+ spike_points = [(self.start + dt.timedelta(minutes=m), 100.0) for m in range(12, 20)]
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="queue_depth",
+ metric_type="gauge",
+ points=baseline_points + quiet_points + spike_points,
+ labels={"shard": "a"},
+ )
+ # A second, steady shard that should NOT show up as a mover.
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="queue_depth",
+ metric_type="gauge",
+ points=[(self.start + dt.timedelta(minutes=m), 5.0) for m in range(20)],
+ labels={"shard": "b"},
+ )
+
+ def _characterize(self, **overrides):
+ defaults: dict[str, Any] = {
+ "team": self.team,
+ "metric_name": "queue_depth",
+ "anomaly_from": self.anomaly_from,
+ "anomaly_to": self.anomaly_to,
+ }
+ defaults.update(overrides)
+ return characterize_metric_anomaly(**defaults)
+
+ def test_characterizes_magnitude_direction_and_onset(self):
+ report = self._characterize()
+
+ self.assertEqual(report.aggregation, "avg") # gauge auto-pick
+ self.assertEqual(report.direction, "up")
+ self.assertAlmostEqual(report.baseline_mean, 7.5) # (10 + 5) / 2 averaged over shards
+ self.assertGreater(report.change_ratio, 3.0)
+ self.assertEqual(report.onset_time, (self.start + dt.timedelta(minutes=12)).isoformat())
+ self.assertGreater(report.anomaly_peak, 50.0)
+ self.assertTrue(report.series.points)
+
+ def test_top_movers_blame_the_right_label(self):
+ report = self._characterize(candidate_keys=("shard",))
+
+ self.assertTrue(report.top_movers)
+ top = report.top_movers[0]
+ self.assertEqual((top.key, top.label), ("shard", "a"))
+ self.assertGreater(top.change_ratio, 3.0)
+ # shard b never moved, so it must not be reported
+ self.assertNotIn("b", [m.label for m in report.top_movers])
+
+ def test_auto_discovers_candidate_keys(self):
+ report = self._characterize()
+ self.assertIn("shard", [m.key for m in report.top_movers])
+
+ def test_flat_metric_reports_flat(self):
+ report = self._characterize(metric_name="nonexistent_metric")
+ self.assertEqual(report.direction, "flat")
+ self.assertIsNone(report.onset_time)
+ self.assertEqual(report.top_movers, ())
+
+ def test_rejects_inverted_windows(self):
+ with self.assertRaises(ValueError):
+ self._characterize(anomaly_to=self.anomaly_from - dt.timedelta(minutes=1))
+ with self.assertRaises(ValueError):
+ self._characterize(baseline_to=self.anomaly_from + dt.timedelta(minutes=5))
+
+ def test_counter_auto_picks_rate(self):
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="reqs_total",
+ metric_type="sum",
+ is_monotonic=True,
+ points=[(self.start + dt.timedelta(minutes=m), float(m * 60)) for m in range(20)],
+ )
+ report = self._characterize(metric_name="reqs_total")
+ self.assertEqual(report.aggregation, "rate")
+
+ def test_characterize_via_api(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/metrics/characterize",
+ data={
+ "query": {
+ "metricName": "queue_depth",
+ "anomalyFrom": self.anomaly_from.isoformat(),
+ "anomalyTo": self.anomaly_to.isoformat(),
+ "candidateKeys": ["shard"],
+ }
+ },
+ content_type="application/json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ body = response.json()
+ self.assertEqual(body["direction"], "up")
+ self.assertEqual(body["top_movers"][0]["label"], "a")
+ self.assertIsNotNone(body["onset_time"])
+
+ def test_characterize_via_api_rejects_bad_window(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/metrics/characterize",
+ data={
+ "query": {
+ "metricName": "queue_depth",
+ "anomalyFrom": self.anomaly_to.isoformat(),
+ "anomalyTo": self.anomaly_from.isoformat(),
+ }
+ },
+ content_type="application/json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index 40c6a1160454..7e7f2d0db40b 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -95,6 +95,149 @@ export interface _MetricFilterApi {
scope?: MetricAttributeScopeEnumApi
}
+export interface _MetricAnomalyBodyApi {
+ /**
+ * Exact metric name to characterize (e.g. 'metrics_rate_limiter_message_lag_seconds').
+ * @maxLength 255
+ */
+ metricName: string
+ /** Start of the suspicious window (inclusive). ISO 8601 — e.g. when the alert fired or the graph started looking wrong. */
+ anomalyFrom: string
+ /** End of the suspicious window (exclusive). Defaults to now. */
+ anomalyTo?: string
+ /** Start of the healthy comparison window. Defaults to one anomaly-window-length before baselineTo. */
+ baselineFrom?: string
+ /** End of the healthy comparison window. Defaults to anomalyFrom. Must not extend past anomalyFrom. */
+ baselineTo?: string
+ /** Aggregation to characterize. Omit to auto-pick from the metric's OTel type (counter -> rate, gauge -> avg, histogram -> histogram_quantile 0.95).
+ *
+ * * `sum` - sum
+ * * `avg` - avg
+ * * `count` - count
+ * * `p95` - p95
+ * * `rate` - rate
+ * * `increase` - increase
+ * * `histogram_quantile` - histogram_quantile */
+ aggregation?: AggregationEnumApi | null
+ /**
+ * Quantile for histogram_quantile. Defaults to 0.95.
+ * @minimum 0
+ * @maximum 1
+ * @nullable
+ */
+ quantile?: number | null
+ /** Label predicates narrowing which series are characterized. */
+ filters?: _MetricFilterApi[]
+ /**
+ * Label keys to drill into when finding which label values moved. Omit to auto-discover the most common keys on this metric (plus service_name). Max 4 are used.
+ * @items.maxLength 255
+ */
+ candidateKeys?: string[]
+}
+
+export interface _MetricAnomalyRequestApi {
+ /** The anomaly characterization to run. */
+ query: _MetricAnomalyBodyApi
+}
+
+/**
+ * * `up` - up
+ * * `down` - down
+ * * `flat` - flat
+ */
+export type _MetricAnomalyReportDirectionEnumApi =
+ (typeof _MetricAnomalyReportDirectionEnumApi)[keyof typeof _MetricAnomalyReportDirectionEnumApi]
+
+export const _MetricAnomalyReportDirectionEnumApi = {
+ Up: 'up',
+ Down: 'down',
+ Flat: 'flat',
+} as const
+
+export interface _MetricAnomalyDimensionApi {
+ /** Label key that was drilled into. */
+ key: string
+ /** Label value this row describes. */
+ label: string
+ /** Mean value over the baseline window for this label value. */
+ baseline_value: number
+ /** Mean value over the anomaly window for this label value. */
+ anomaly_value: number
+ /** anomaly_value / baseline_value. A zero baseline yields the anomaly value itself (new traffic). */
+ change_ratio: number
+}
+
+export interface _MetricQueryPointApi {
+ /** Bucket start as ISO 8601 timestamp. */
+ time: string
+ /** Aggregated value for the bucket. */
+ value: number
+}
+
+/**
+ * Label values identifying this series. Empty for an ungrouped query.
+ */
+export type _MetricSeriesApiLabels = { [key: string]: string }
+
+export interface _MetricSeriesApi {
+ /** Label values identifying this series. Empty for an ungrouped query. */
+ labels: _MetricSeriesApiLabels
+ /** Time-bucketed points, ordered by time ascending. */
+ points: _MetricQueryPointApi[]
+ /**
+ * Metric the series was computed from. Null for formula results.
+ * @nullable
+ */
+ metric_name?: string | null
+ /**
+ * Name of the query clause that produced this series.
+ * @nullable
+ */
+ clause?: string | null
+}
+
+export interface _MetricAnomalyReportApi {
+ /** Metric that was characterized. */
+ metric_name: string
+ /** Aggregation used (auto-picked when not specified). */
+ aggregation: string
+ /** Bucket size of the analysis grid. */
+ interval: string
+ /** Baseline window start, ISO 8601. */
+ baseline_from: string
+ /** Baseline window end, ISO 8601. */
+ baseline_to: string
+ /** Anomaly window start, ISO 8601. */
+ anomaly_from: string
+ /** Anomaly window end, ISO 8601. */
+ anomaly_to: string
+ /** Mean over the baseline window. */
+ baseline_mean: number
+ /** Population stddev over the baseline window. */
+ baseline_stddev: number
+ /** Mean over the anomaly window. */
+ anomaly_mean: number
+ /** Maximum bucket value in the anomaly window. */
+ anomaly_peak: number
+ /** anomaly_mean / baseline_mean. A zero baseline yields anomaly_mean itself. */
+ change_ratio: number
+ /** Which way the metric moved versus the baseline.
+ *
+ * * `up` - up
+ * * `down` - down
+ * * `flat` - flat */
+ direction: _MetricAnomalyReportDirectionEnumApi
+ /**
+ * First bucket clearly outside the baseline range (3 stddevs or 50% relative change), or null if no clear onset.
+ * @nullable
+ */
+ onset_time: string | null
+ /** Label values whose behavior changed the most between windows, largest change first. Empty when nothing moved or the metric has no labels. */
+ top_movers: _MetricAnomalyDimensionApi[]
+ /** The metric across baseline + anomaly windows on one grid, for plotting or further inspection. */
+ series: _MetricSeriesApi
+}
+
export interface _MetricGroupByApi {
/**
* Attribute name to split series by (e.g. 'k8s.pod.name', 'env').
@@ -223,35 +366,6 @@ export interface _MetricQueryRequestApi {
query: _MetricQueryBodyApi
}
-export interface _MetricQueryPointApi {
- /** Bucket start as ISO 8601 timestamp. */
- time: string
- /** Aggregated value for the bucket. */
- value: number
-}
-
-/**
- * Label values identifying this series. Empty for an ungrouped query.
- */
-export type _MetricSeriesApiLabels = { [key: string]: string }
-
-export interface _MetricSeriesApi {
- /** Label values identifying this series. Empty for an ungrouped query. */
- labels: _MetricSeriesApiLabels
- /** Time-bucketed points, ordered by time ascending. */
- points: _MetricQueryPointApi[]
- /**
- * Metric the series was computed from. Null for formula results.
- * @nullable
- */
- metric_name?: string | null
- /**
- * Name of the query clause that produced this series.
- * @nullable
- */
- clause?: string | null
-}
-
export interface _MetricQueryResponseApi {
/** One series per (clause, label-set). A single ungrouped query returns exactly one series with empty labels. */
results: _MetricSeriesApi[]
diff --git a/products/metrics/frontend/generated/api.ts b/products/metrics/frontend/generated/api.ts
index 32bd2c343e99..86148679ab5b 100644
--- a/products/metrics/frontend/generated/api.ts
+++ b/products/metrics/frontend/generated/api.ts
@@ -13,6 +13,8 @@ import type {
AppMetricsTotalsResponseApi,
MetricsHasMetricsRetrieve200,
MetricsValuesRetrieveParams,
+ _MetricAnomalyReportApi,
+ _MetricAnomalyRequestApi,
_MetricNamesResponseApi,
_MetricQueryRequestApi,
_MetricQueryResponseApi,
@@ -60,6 +62,27 @@ export const eventFilterMetricsTotalsRetrieve = async (
})
}
+export const getMetricsCharacterizeCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/metrics/characterize/`
+}
+
+/**
+ * Characterize a metric anomaly: compare an anomaly window against a
+ * baseline, find the onset, and rank which label values moved.
+ */
+export const metricsCharacterizeCreate = async (
+ projectId: string,
+ _metricAnomalyRequestApi: _MetricAnomalyRequestApi,
+ options?: RequestInit
+): Promise<_MetricAnomalyReportApi> => {
+ return apiMutator<_MetricAnomalyReportApi>(getMetricsCharacterizeCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(_metricAnomalyRequestApi),
+ })
+}
+
export const getMetricsHasMetricsRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/metrics/has_metrics/`
}
diff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.ts
index 19b14eb58b8d..6269dfe6844b 100644
--- a/products/metrics/frontend/generated/api.zod.ts
+++ b/products/metrics/frontend/generated/api.zod.ts
@@ -9,6 +9,108 @@
*/
import * as zod from 'zod'
+/**
+ * Characterize a metric anomaly: compare an anomaly window against a
+ * baseline, find the onset, and rank which label values moved.
+ */
+export const metricsCharacterizeCreateBodyQueryOneMetricNameMax = 255
+
+export const metricsCharacterizeCreateBodyQueryOneQuantileMin = 0
+export const metricsCharacterizeCreateBodyQueryOneQuantileMax = 1
+
+export const metricsCharacterizeCreateBodyQueryOneFiltersItemKeyMax = 255
+
+export const metricsCharacterizeCreateBodyQueryOneFiltersItemOpDefault = `eq`
+export const metricsCharacterizeCreateBodyQueryOneFiltersItemScopeDefault = `auto`
+export const metricsCharacterizeCreateBodyQueryOneCandidateKeysItemMax = 255
+
+export const MetricsCharacterizeCreateBody = /* @__PURE__ */ zod.object({
+ query: zod
+ .object({
+ metricName: zod
+ .string()
+ .max(metricsCharacterizeCreateBodyQueryOneMetricNameMax)
+ .describe("Exact metric name to characterize (e.g. 'metrics_rate_limiter_message_lag_seconds')."),
+ anomalyFrom: zod.iso
+ .datetime({ offset: true })
+ .describe(
+ 'Start of the suspicious window (inclusive). ISO 8601 — e.g. when the alert fired or the graph started looking wrong.'
+ ),
+ anomalyTo: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe('End of the suspicious window (exclusive). Defaults to now.'),
+ baselineFrom: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'Start of the healthy comparison window. Defaults to one anomaly-window-length before baselineTo.'
+ ),
+ baselineTo: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'End of the healthy comparison window. Defaults to anomalyFrom. Must not extend past anomalyFrom.'
+ ),
+ aggregation: zod
+ .union([
+ zod
+ .enum(['sum', 'avg', 'count', 'p95', 'rate', 'increase', 'histogram_quantile'])
+ .describe(
+ '\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95\n\* `rate` - rate\n\* `increase` - increase\n\* `histogram_quantile` - histogram_quantile'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Aggregation to characterize. Omit to auto-pick from the metric's OTel type (counter -> rate, gauge -> avg, histogram -> histogram_quantile 0.95).\n\n\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95\n\* `rate` - rate\n\* `increase` - increase\n\* `histogram_quantile` - histogram_quantile"
+ ),
+ quantile: zod
+ .number()
+ .min(metricsCharacterizeCreateBodyQueryOneQuantileMin)
+ .max(metricsCharacterizeCreateBodyQueryOneQuantileMax)
+ .nullish()
+ .describe('Quantile for histogram_quantile. Defaults to 0.95.'),
+ filters: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .max(metricsCharacterizeCreateBodyQueryOneFiltersItemKeyMax)
+ .describe(
+ "Attribute name to filter on, without any type-tag suffix (e.g. 'k8s.pod.name', 'env')."
+ ),
+ op: zod
+ .enum(['eq', 'neq', 'regex', 'not_regex'])
+ .describe('\* `eq` - eq\n\* `neq` - neq\n\* `regex` - regex\n\* `not_regex` - not_regex')
+ .default(metricsCharacterizeCreateBodyQueryOneFiltersItemOpDefault)
+ .describe(
+ "Comparison operator. 'regex'\/'not_regex' use RE2 syntax. Negative operators also match rows that lack the key entirely, mirroring Prometheus negative matchers.\n\n\* `eq` - eq\n\* `neq` - neq\n\* `regex` - regex\n\* `not_regex` - not_regex"
+ ),
+ value: zod
+ .string()
+ .describe('Value to compare against. For regex operators this is the pattern.'),
+ scope: zod
+ .enum(['resource', 'attribute', 'auto'])
+ .describe('\* `resource` - resource\n\* `attribute` - attribute\n\* `auto` - auto')
+ .default(metricsCharacterizeCreateBodyQueryOneFiltersItemScopeDefault)
+ .describe(
+ "Where the attribute lives: 'resource' = per-target resource attributes (k8s.pod.name, service.version), 'attribute' = per-datapoint attributes (http.method, path), 'auto' = resource first with per-datapoint fallback. Use 'auto' unless you know the exact scope.\n\n\* `resource` - resource\n\* `attribute` - attribute\n\* `auto` - auto"
+ ),
+ })
+ )
+ .optional()
+ .describe('Label predicates narrowing which series are characterized.'),
+ candidateKeys: zod
+ .array(zod.string().max(metricsCharacterizeCreateBodyQueryOneCandidateKeysItemMax))
+ .optional()
+ .describe(
+ 'Label keys to drill into when finding which label values moved. Omit to auto-discover the most common keys on this metric (plus service_name). Max 4 are used.'
+ ),
+ })
+ .describe('The anomaly characterization to run.'),
+})
+
export const metricsQueryCreateBodyQueryOneMetricNameMax = 255
export const metricsQueryCreateBodyQueryOneAggregationDefault = `sum`
diff --git a/products/metrics/mcp/prompts/characterize-metric-anomaly.md b/products/metrics/mcp/prompts/characterize-metric-anomaly.md
new file mode 100644
index 000000000000..45f1697f95c3
--- /dev/null
+++ b/products/metrics/mcp/prompts/characterize-metric-anomaly.md
@@ -0,0 +1,14 @@
+Characterize how a metric behaves in a suspicious window compared to a healthy baseline. This is the FIRST call to make when investigating "metric X is rising/dropping — why?": one call answers how big the change is, exactly when it started, and which label values moved.
+
+Required: `metricName` (exact — discover via `metric-names-list` first) and `anomalyFrom` (when things started looking wrong; the alert fire time works). `anomalyTo` defaults to now. The baseline defaults to the equal-length window immediately before `anomalyFrom`; pass `baselineFrom`/`baselineTo` to compare against a known-good period instead (e.g. same time yesterday).
+
+The aggregation is auto-picked from the metric's OTel type (counter -> rate, gauge -> avg, histogram -> p95); override with `aggregation` if you need a different lens. Use `filters` to scope to a service or region. `candidateKeys` controls which label keys are drilled into for the movers analysis — omit it to auto-discover.
+
+Read the report in this order:
+
+1. `direction` + `change_ratio` + `anomaly_peak`: how bad is it? (`flat` means the windows don't meaningfully differ — widen the anomaly window or check you have the right metric.)
+2. `onset_time`: when it started. Use this exact timestamp as the pivot for cross-signal correlation.
+3. `top_movers`: which label values changed. One label value moving alone (e.g. a single pod or shard) points at a localized culprit; everything moving together points at a shared cause upstream.
+4. `series`: the full baseline+anomaly time series if you need to eyeball the shape.
+
+Then correlate: query logs (`query-logs` with the same service and a window around `onset_time`, severity error first) and traces (APM span tools, same service/window) to find what broke and its blast radius. All parameters are nested inside a `query` object.
diff --git a/products/metrics/mcp/tools.yaml b/products/metrics/mcp/tools.yaml
index 9a4d065e5344..323fcf2c5948 100644
--- a/products/metrics/mcp/tools.yaml
+++ b/products/metrics/mcp/tools.yaml
@@ -9,6 +9,19 @@ feature: metrics
url_prefix: /metrics
ui_apps: {}
tools:
+ characterize-metric-anomaly:
+ operation: metrics_characterize_create
+ enabled: true
+ scopes:
+ - metrics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Characterize metric anomaly
+ description_file: ./prompts/characterize-metric-anomaly.md
+ system_prompt_hint: First call when investigating "metric X looks wrong" — magnitude, onset, which labels moved
+ feature_flag: metrics
metric-names-list:
operation: metrics_values_retrieve
enabled: true
diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.ts
index be11f337d7f7..0195c0279ce9 100644
--- a/products/web_analytics/frontend/generated/api.schemas.ts
+++ b/products/web_analytics/frontend/generated/api.schemas.ts
@@ -273,9 +273,9 @@ export interface PatchedSavedHeatmapRequestApi {
* * `Up` - Up
* * `Down` - Down
*/
-export type DirectionEnumApi = (typeof DirectionEnumApi)[keyof typeof DirectionEnumApi]
+export type WoWChangeDirectionEnumApi = (typeof WoWChangeDirectionEnumApi)[keyof typeof WoWChangeDirectionEnumApi]
-export const DirectionEnumApi = {
+export const WoWChangeDirectionEnumApi = {
Up: 'Up',
Down: 'Down',
} as const
@@ -287,7 +287,7 @@ export interface WoWChangeApi {
*
* * `Up` - Up
* * `Down` - Down */
- direction: DirectionEnumApi
+ direction: WoWChangeDirectionEnumApi
/** Hex color indicating whether the change is a positive or negative signal. */
color: string
/** Short label, e.g. 'Up 12%'. */
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 7cc9f04228ab..108ffc965204 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1430,6 +1430,22 @@
"readOnlyHint": true
}
},
+ "characterize-metric-anomaly": {
+ "description": "Characterize how a metric behaves in a suspicious window compared to a healthy baseline. This is the FIRST call to make when investigating \"metric X is rising/dropping — why?\": one call answers how big the change is, exactly when it started, and which label values moved.\n\nRequired: `metricName` (exact — discover via `metric-names-list` first) and `anomalyFrom` (when things started looking wrong; the alert fire time works). `anomalyTo` defaults to now. The baseline defaults to the equal-length window immediately before `anomalyFrom`; pass `baselineFrom`/`baselineTo` to compare against a known-good period instead (e.g. same time yesterday).\n\nThe aggregation is auto-picked from the metric's OTel type (counter -> rate, gauge -> avg, histogram -> p95); override with `aggregation` if you need a different lens. Use `filters` to scope to a service or region. `candidateKeys` controls which label keys are drilled into for the movers analysis — omit it to auto-discover.\n\nRead the report in this order:\n\n1. `direction` + `change_ratio` + `anomaly_peak`: how bad is it? (`flat` means the windows don't meaningfully differ — widen the anomaly window or check you have the right metric.)\n2. `onset_time`: when it started. Use this exact timestamp as the pivot for cross-signal correlation.\n3. `top_movers`: which label values changed. One label value moving alone (e.g. a single pod or shard) points at a localized culprit; everything moving together points at a shared cause upstream.\n4. `series`: the full baseline+anomaly time series if you need to eyeball the shape.\n\nThen correlate: query logs (`query-logs` with the same service and a window around `onset_time`, severity error first) and traces (APM span tools, same service/window) to find what broke and its blast radius. All parameters are nested inside a `query` object.",
+ "category": "Metrics",
+ "feature": "metrics",
+ "summary": "Characterize metric anomaly",
+ "title": "Characterize metric anomaly",
+ "required_scopes": ["metrics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "metrics",
+ "system_prompt_hint": "First call when investigating \"metric X looks wrong\" — magnitude, onset, which labels moved"
+ },
"cohorts-add-persons-to-static-cohort-partial-update": {
"description": "Add persons to a static cohort by their UUIDs. Only works for static cohorts (is_static: true).\n\nIntended for small, ad-hoc additions — pass at most ~20 person UUIDs per call. To build or grow a static cohort from a larger set, do NOT loop this tool over many UUIDs; instead create the cohort from a query ('cohorts-create' with 'is_static: true' and a 'query'), or add to an existing static cohort by setting a 'query' on it via 'cohorts-partial-update'. The server then runs the query and inserts every matching person in a single call, with no row limit.",
"category": "Cohorts",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 6603158513ff..aa9dde26ba5a 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1446,6 +1446,22 @@
"readOnlyHint": true
}
},
+ "characterize-metric-anomaly": {
+ "description": "Characterize how a metric behaves in a suspicious window compared to a healthy baseline. This is the FIRST call to make when investigating \"metric X is rising/dropping — why?\": one call answers how big the change is, exactly when it started, and which label values moved.\n\nRequired: `metricName` (exact — discover via `metric-names-list` first) and `anomalyFrom` (when things started looking wrong; the alert fire time works). `anomalyTo` defaults to now. The baseline defaults to the equal-length window immediately before `anomalyFrom`; pass `baselineFrom`/`baselineTo` to compare against a known-good period instead (e.g. same time yesterday).\n\nThe aggregation is auto-picked from the metric's OTel type (counter -> rate, gauge -> avg, histogram -> p95); override with `aggregation` if you need a different lens. Use `filters` to scope to a service or region. `candidateKeys` controls which label keys are drilled into for the movers analysis — omit it to auto-discover.\n\nRead the report in this order:\n\n1. `direction` + `change_ratio` + `anomaly_peak`: how bad is it? (`flat` means the windows don't meaningfully differ — widen the anomaly window or check you have the right metric.)\n2. `onset_time`: when it started. Use this exact timestamp as the pivot for cross-signal correlation.\n3. `top_movers`: which label values changed. One label value moving alone (e.g. a single pod or shard) points at a localized culprit; everything moving together points at a shared cause upstream.\n4. `series`: the full baseline+anomaly time series if you need to eyeball the shape.\n\nThen correlate: query logs (`query-logs` with the same service and a window around `onset_time`, severity error first) and traces (APM span tools, same service/window) to find what broke and its blast radius. All parameters are nested inside a `query` object.",
+ "category": "Metrics",
+ "feature": "metrics",
+ "summary": "Characterize metric anomaly",
+ "title": "Characterize metric anomaly",
+ "required_scopes": ["metrics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "metrics",
+ "system_prompt_hint": "First call when investigating \"metric X looks wrong\" — magnitude, onset, which labels moved"
+ },
"cohorts-add-persons-to-static-cohort-partial-update": {
"description": "Add persons to a static cohort by their UUIDs. Only works for static cohorts (is_static: true).\n\nIntended for small, ad-hoc additions — pass at most ~20 person UUIDs per call. To build or grow a static cohort from a larger set, do NOT loop this tool over many UUIDs; instead create the cohort from a query ('cohorts-create' with 'is_static: true' and a 'query'), or add to an existing static cohort by setting a 'query' on it via 'cohorts-partial-update'. The server then runs the query and inserts every matching person in a single call, with no row limit.",
"category": "Cohorts",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2dffd6d76e4b..d7522ee85dea 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -16723,18 +16723,6 @@ export namespace Schemas {
checks: DiagnosticCheckResult[];
}
- /**
- * * `Up` - Up
- * * `Down` - Down
- */
- export type DirectionEnum = typeof DirectionEnum[keyof typeof DirectionEnum];
-
-
- export const DirectionEnum = {
- Up: 'Up',
- Down: 'Down',
- } as const;
-
export type DistanceFunc = typeof DistanceFunc[keyof typeof DistanceFunc];
@@ -16850,6 +16838,18 @@ export namespace Schemas {
has_draft: boolean;
}
+ /**
+ * * `Up` - Up
+ * * `Down` - Down
+ */
+ export type WoWChangeDirectionEnum = typeof WoWChangeDirectionEnum[keyof typeof WoWChangeDirectionEnum];
+
+
+ export const WoWChangeDirectionEnum = {
+ Up: 'Up',
+ Down: 'Down',
+ } as const;
+
export interface WoWChange {
/** Absolute percentage change, rounded to nearest integer. */
percent: number;
@@ -16857,7 +16857,7 @@ export namespace Schemas {
*
* * `Up` - Up
* * `Down` - Down */
- direction: DirectionEnum;
+ direction: WoWChangeDirectionEnum;
/** Hex color indicating whether the change is a positive or negative signal. */
color: string;
/** Short label, e.g. 'Up 12%'. */
@@ -48289,6 +48289,149 @@ export namespace Schemas {
scope?: MetricAttributeScopeEnum;
}
+ export interface _MetricAnomalyBody {
+ /**
+ * Exact metric name to characterize (e.g. 'metrics_rate_limiter_message_lag_seconds').
+ * @maxLength 255
+ */
+ metricName: string;
+ /** Start of the suspicious window (inclusive). ISO 8601 — e.g. when the alert fired or the graph started looking wrong. */
+ anomalyFrom: string;
+ /** End of the suspicious window (exclusive). Defaults to now. */
+ anomalyTo?: string;
+ /** Start of the healthy comparison window. Defaults to one anomaly-window-length before baselineTo. */
+ baselineFrom?: string;
+ /** End of the healthy comparison window. Defaults to anomalyFrom. Must not extend past anomalyFrom. */
+ baselineTo?: string;
+ /** Aggregation to characterize. Omit to auto-pick from the metric's OTel type (counter -> rate, gauge -> avg, histogram -> histogram_quantile 0.95).
+ *
+ * * `sum` - sum
+ * * `avg` - avg
+ * * `count` - count
+ * * `p95` - p95
+ * * `rate` - rate
+ * * `increase` - increase
+ * * `histogram_quantile` - histogram_quantile */
+ aggregation?: AggregationEnum | null;
+ /**
+ * Quantile for histogram_quantile. Defaults to 0.95.
+ * @minimum 0
+ * @maximum 1
+ * @nullable
+ */
+ quantile?: number | null;
+ /** Label predicates narrowing which series are characterized. */
+ filters?: _MetricFilter[];
+ /**
+ * Label keys to drill into when finding which label values moved. Omit to auto-discover the most common keys on this metric (plus service_name). Max 4 are used.
+ * @items.maxLength 255
+ */
+ candidateKeys?: string[];
+ }
+
+ export interface _MetricAnomalyDimension {
+ /** Label key that was drilled into. */
+ key: string;
+ /** Label value this row describes. */
+ label: string;
+ /** Mean value over the baseline window for this label value. */
+ baseline_value: number;
+ /** Mean value over the anomaly window for this label value. */
+ anomaly_value: number;
+ /** anomaly_value / baseline_value. A zero baseline yields the anomaly value itself (new traffic). */
+ change_ratio: number;
+ }
+
+ /**
+ * * `up` - up
+ * * `down` - down
+ * * `flat` - flat
+ */
+ export type _MetricAnomalyReportDirectionEnum = typeof _MetricAnomalyReportDirectionEnum[keyof typeof _MetricAnomalyReportDirectionEnum];
+
+
+ export const _MetricAnomalyReportDirectionEnum = {
+ Up: 'up',
+ Down: 'down',
+ Flat: 'flat',
+ } as const;
+
+ export interface _MetricQueryPoint {
+ /** Bucket start as ISO 8601 timestamp. */
+ time: string;
+ /** Aggregated value for the bucket. */
+ value: number;
+ }
+
+ /**
+ * Label values identifying this series. Empty for an ungrouped query.
+ */
+ export type _MetricSeriesLabels = {[key: string]: string};
+
+ export interface _MetricSeries {
+ /** Label values identifying this series. Empty for an ungrouped query. */
+ labels: _MetricSeriesLabels;
+ /** Time-bucketed points, ordered by time ascending. */
+ points: _MetricQueryPoint[];
+ /**
+ * Metric the series was computed from. Null for formula results.
+ * @nullable
+ */
+ metric_name?: string | null;
+ /**
+ * Name of the query clause that produced this series.
+ * @nullable
+ */
+ clause?: string | null;
+ }
+
+ export interface _MetricAnomalyReport {
+ /** Metric that was characterized. */
+ metric_name: string;
+ /** Aggregation used (auto-picked when not specified). */
+ aggregation: string;
+ /** Bucket size of the analysis grid. */
+ interval: string;
+ /** Baseline window start, ISO 8601. */
+ baseline_from: string;
+ /** Baseline window end, ISO 8601. */
+ baseline_to: string;
+ /** Anomaly window start, ISO 8601. */
+ anomaly_from: string;
+ /** Anomaly window end, ISO 8601. */
+ anomaly_to: string;
+ /** Mean over the baseline window. */
+ baseline_mean: number;
+ /** Population stddev over the baseline window. */
+ baseline_stddev: number;
+ /** Mean over the anomaly window. */
+ anomaly_mean: number;
+ /** Maximum bucket value in the anomaly window. */
+ anomaly_peak: number;
+ /** anomaly_mean / baseline_mean. A zero baseline yields anomaly_mean itself. */
+ change_ratio: number;
+ /** Which way the metric moved versus the baseline.
+ *
+ * * `up` - up
+ * * `down` - down
+ * * `flat` - flat */
+ direction: _MetricAnomalyReportDirectionEnum;
+ /**
+ * First bucket clearly outside the baseline range (3 stddevs or 50% relative change), or null if no clear onset.
+ * @nullable
+ */
+ onset_time: string | null;
+ /** Label values whose behavior changed the most between windows, largest change first. Empty when nothing moved or the metric has no labels. */
+ top_movers: _MetricAnomalyDimension[];
+ /** The metric across baseline + anomaly windows on one grid, for plotting or further inspection. */
+ series: _MetricSeries;
+ }
+
+ export interface _MetricAnomalyRequest {
+ /** The anomaly characterization to run. */
+ query: _MetricAnomalyBody;
+ }
+
export interface _MetricGroupBy {
/**
* Attribute name to split series by (e.g. 'k8s.pod.name', 'env').
@@ -48401,40 +48544,11 @@ export namespace Schemas {
dateTo?: string;
}
- export interface _MetricQueryPoint {
- /** Bucket start as ISO 8601 timestamp. */
- time: string;
- /** Aggregated value for the bucket. */
- value: number;
- }
-
export interface _MetricQueryRequest {
/** The metric query to execute. */
query: _MetricQueryBody;
}
- /**
- * Label values identifying this series. Empty for an ungrouped query.
- */
- export type _MetricSeriesLabels = {[key: string]: string};
-
- export interface _MetricSeries {
- /** Label values identifying this series. Empty for an ungrouped query. */
- labels: _MetricSeriesLabels;
- /** Time-bucketed points, ordered by time ascending. */
- points: _MetricQueryPoint[];
- /**
- * Metric the series was computed from. Null for formula results.
- * @nullable
- */
- metric_name?: string | null;
- /**
- * Name of the query clause that produced this series.
- * @nullable
- */
- clause?: string | null;
- }
-
export interface _MetricQueryResponse {
/** One series per (clause, label-set). A single ungrouped query returns exactly one series with empty labels. */
results: _MetricSeries[];
diff --git a/services/mcp/src/generated/metrics/api.ts b/services/mcp/src/generated/metrics/api.ts
index 0b3e75d1be6e..b99f58052cc7 100644
--- a/services/mcp/src/generated/metrics/api.ts
+++ b/services/mcp/src/generated/metrics/api.ts
@@ -3,11 +3,121 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 2 enabled ops
+ * PostHog API - MCP 3 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
+/**
+ * Characterize a metric anomaly: compare an anomaly window against a
+ * baseline, find the onset, and rank which label values moved.
+ */
+export const MetricsCharacterizeCreateParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const metricsCharacterizeCreateBodyQueryOneMetricNameMax = 255
+
+export const metricsCharacterizeCreateBodyQueryOneQuantileMin = 0
+export const metricsCharacterizeCreateBodyQueryOneQuantileMax = 1
+
+export const metricsCharacterizeCreateBodyQueryOneFiltersItemKeyMax = 255
+
+export const metricsCharacterizeCreateBodyQueryOneFiltersItemOpDefault = `eq`
+export const metricsCharacterizeCreateBodyQueryOneFiltersItemScopeDefault = `auto`
+export const metricsCharacterizeCreateBodyQueryOneCandidateKeysItemMax = 255
+
+export const MetricsCharacterizeCreateBody = /* @__PURE__ */ zod.object({
+ query: zod
+ .object({
+ metricName: zod
+ .string()
+ .max(metricsCharacterizeCreateBodyQueryOneMetricNameMax)
+ .describe("Exact metric name to characterize (e.g. 'metrics_rate_limiter_message_lag_seconds')."),
+ anomalyFrom: zod.iso
+ .datetime({ offset: true })
+ .describe(
+ 'Start of the suspicious window (inclusive). ISO 8601 — e.g. when the alert fired or the graph started looking wrong.'
+ ),
+ anomalyTo: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe('End of the suspicious window (exclusive). Defaults to now.'),
+ baselineFrom: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'Start of the healthy comparison window. Defaults to one anomaly-window-length before baselineTo.'
+ ),
+ baselineTo: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'End of the healthy comparison window. Defaults to anomalyFrom. Must not extend past anomalyFrom.'
+ ),
+ aggregation: zod
+ .union([
+ zod
+ .enum(['sum', 'avg', 'count', 'p95', 'rate', 'increase', 'histogram_quantile'])
+ .describe(
+ '* `sum` - sum\n* `avg` - avg\n* `count` - count\n* `p95` - p95\n* `rate` - rate\n* `increase` - increase\n* `histogram_quantile` - histogram_quantile'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Aggregation to characterize. Omit to auto-pick from the metric's OTel type (counter -> rate, gauge -> avg, histogram -> histogram_quantile 0.95).\n\n* `sum` - sum\n* `avg` - avg\n* `count` - count\n* `p95` - p95\n* `rate` - rate\n* `increase` - increase\n* `histogram_quantile` - histogram_quantile"
+ ),
+ quantile: zod
+ .number()
+ .min(metricsCharacterizeCreateBodyQueryOneQuantileMin)
+ .max(metricsCharacterizeCreateBodyQueryOneQuantileMax)
+ .nullish()
+ .describe('Quantile for histogram_quantile. Defaults to 0.95.'),
+ filters: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .max(metricsCharacterizeCreateBodyQueryOneFiltersItemKeyMax)
+ .describe(
+ "Attribute name to filter on, without any type-tag suffix (e.g. 'k8s.pod.name', 'env')."
+ ),
+ op: zod
+ .enum(['eq', 'neq', 'regex', 'not_regex'])
+ .describe('* `eq` - eq\n* `neq` - neq\n* `regex` - regex\n* `not_regex` - not_regex')
+ .default(metricsCharacterizeCreateBodyQueryOneFiltersItemOpDefault)
+ .describe(
+ "Comparison operator. 'regex'/'not_regex' use RE2 syntax. Negative operators also match rows that lack the key entirely, mirroring Prometheus negative matchers.\n\n* `eq` - eq\n* `neq` - neq\n* `regex` - regex\n* `not_regex` - not_regex"
+ ),
+ value: zod
+ .string()
+ .describe('Value to compare against. For regex operators this is the pattern.'),
+ scope: zod
+ .enum(['resource', 'attribute', 'auto'])
+ .describe('* `resource` - resource\n* `attribute` - attribute\n* `auto` - auto')
+ .default(metricsCharacterizeCreateBodyQueryOneFiltersItemScopeDefault)
+ .describe(
+ "Where the attribute lives: 'resource' = per-target resource attributes (k8s.pod.name, service.version), 'attribute' = per-datapoint attributes (http.method, path), 'auto' = resource first with per-datapoint fallback. Use 'auto' unless you know the exact scope.\n\n* `resource` - resource\n* `attribute` - attribute\n* `auto` - auto"
+ ),
+ })
+ )
+ .optional()
+ .describe('Label predicates narrowing which series are characterized.'),
+ candidateKeys: zod
+ .array(zod.string().max(metricsCharacterizeCreateBodyQueryOneCandidateKeysItemMax))
+ .optional()
+ .describe(
+ 'Label keys to drill into when finding which label values moved. Omit to auto-discover the most common keys on this metric (plus service_name). Max 4 are used.'
+ ),
+ })
+ .describe('The anomaly characterization to run.'),
+})
+
export const MetricsQueryCreateParams = /* @__PURE__ */ zod.object({
project_id: zod
.string()
diff --git a/services/mcp/src/tools/generated/metrics.ts b/services/mcp/src/tools/generated/metrics.ts
index 594d7111c249..72403997d411 100644
--- a/services/mcp/src/tools/generated/metrics.ts
+++ b/services/mcp/src/tools/generated/metrics.ts
@@ -2,10 +2,37 @@
import { z } from 'zod'
import type { Schemas } from '@/api/generated'
-import { MetricsQueryCreateBody, MetricsValuesRetrieveQueryParams } from '@/generated/metrics/api'
+import {
+ MetricsCharacterizeCreateBody,
+ MetricsQueryCreateBody,
+ MetricsValuesRetrieveQueryParams,
+} from '@/generated/metrics/api'
import { pickResponseFields } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+const CharacterizeMetricAnomalySchema = MetricsCharacterizeCreateBody
+
+const characterizeMetricAnomaly = (): ToolBase<
+ typeof CharacterizeMetricAnomalySchema,
+ Schemas._MetricAnomalyReport
+> => ({
+ name: 'characterize-metric-anomaly',
+ schema: CharacterizeMetricAnomalySchema,
+ handler: async (context: Context, params: z.infer<typeof CharacterizeMetricAnomalySchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.query !== undefined) {
+ body['query'] = params.query
+ }
+ const result = await context.api.request<Schemas._MetricAnomalyReport>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/metrics/characterize/`,
+ body,
+ })
+ return result
+ },
+})
+
const MetricNamesListSchema = MetricsValuesRetrieveQueryParams
const metricNamesList = (): ToolBase<typeof MetricNamesListSchema, Schemas._MetricNamesResponse> => ({
@@ -48,6 +75,7 @@ const queryMetrics = (): ToolBase<typeof QueryMetricsSchema, Schemas._MetricQuer
})
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'characterize-metric-anomaly': characterizeMetricAnomaly,
'metric-names-list': metricNamesList,
'query-metrics': queryMetrics,
}