: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): enable alert authoring tools and ship authoring-log-alerts skill (#56894)
Jon McCallum495ad978f810
diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yamlindex 86e3d39a10ff..55728c10837d 100644--- a/products/logs/mcp/tools.yaml+++ b/products/logs/mcp/tools.yaml@@ -76,10 +76,37 @@ tools:- updated_atlogs-alerts-destinations-create:operation: logs_alerts_destinations_create- enabled: false+ enabled: true+ scopes:+ - logs:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Attach alert destination+ description: >+ Attach a notification destination (Slack channel or webhook) to a log alert. Without a destination an alert+ evaluates silently and never notifies. One HogFunction is created per event kind (firing, resolved, broken,+ errored) atomically — the returned hog_function_ids identify the destination group.+ feature_flag: logs-alerting+ response:+ include:+ - hog_function_idslogs-alerts-destinations-delete-create:operation: logs_alerts_destinations_delete_create- enabled: false+ enabled: true+ scopes:+ - logs:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Detach alert destination+ description: >+ Remove a notification destination from a log alert by passing the hog_function_ids returned from+ logs-alerts-destinations-create. Destinations are deleted as one atomic group — partial deletion fails the+ call.+ feature_flag: logs-alertinglogs-alerts-destroy:operation: logs_alerts_destroyenabled: true@@ -95,7 +122,32 @@ tools:feature_flag: logs-alertinglogs-alerts-events-list:operation: logs_alerts_events_list- enabled: false+ enabled: true+ scopes:+ - logs:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List alert events+ description: >+ List historical events for a log alert — fires, resolves, errors, enable/disable toggles, threshold changes.+ Use to evaluate how an existing alert has behaved (firing cadence, error rate, flap pattern) before tuning+ thresholds. Quiet no-op check rows are filtered out server-side. Optional `kind` query param narrows to a+ single event kind.+ feature_flag: logs-alerting+ response:+ include:+ - id+ - created_at+ - kind+ - state_before+ - state_after+ - threshold_breached+ - result_count+ - error_message+ - query_duration_mslogs-alerts-list:operation: logs_alerts_listenabled: true@@ -210,7 +262,28 @@ tools:- updated_atlogs-alerts-simulate-create:operation: logs_alerts_simulate_create- enabled: false+ enabled: true+ scopes:+ - logs:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Simulate log alert+ description: >+ Run a draft alert configuration against historical logs and return per-bucket results from the full state+ machine — count, threshold_breached, state, notification (none/fire/resolve), reason. Use to validate+ threshold + N-of-M settings before creating an alert. Read-only; no alert records are written. Aim for+ fire_count between 0 and 3 over a `-7d` lookback for a healthy threshold.+ feature_flag: logs-alerting+ response:+ include:+ - buckets+ - fire_count+ - resolve_count+ - total_buckets+ - threshold_count+ - threshold_operatorlogs-alerts-update:operation: logs_alerts_updateenabled: false@@ -315,7 +388,23 @@ tools:enabled: falselogs-services-create:operation: logs_services_create- enabled: false+ enabled: true+ scopes:+ - logs:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: List services with stats+ description: >+ Return the top-25 services by log volume in the window, each with log_count, error_count, and error_rate,+ plus a per-service sparkline. Use this as the entry point when triaging which services are worth alerting on+ — high volume × non-zero error_rate is the natural alert candidate. Far cheaper than walking+ attribute-values + per-service counts.+ response:+ include:+ - services+ - sparklinelogs-sparkline-query:operation: logs_sparkline_createenabled: truediff --git a/products/logs/skills/authoring-log-alerts/SKILL.md b/products/logs/skills/authoring-log-alerts/SKILL.mdnew file mode 100644index 000000000000..bc3d7d5c07e4--- /dev/null+++ b/products/logs/skills/authoring-log-alerts/SKILL.md@@ -0,0 +1,190 @@+---+name: authoring-log-alerts+description: >+ Author useful, low-noise log alerts on services in a PostHog project. Use when the user asks to set up+ alerts for their logs, suggest alerts they should add, or evaluate whether a service is worth monitoring.+ Covers service triage, baseline characterisation, threshold drafting, back-testing via simulate, and+ shipping with a notification destination.+---++# Authoring log alerts++Authoring an alert is a _measurement_ problem, not a guessing problem. You are not trying to be exhaustive — you+are trying to land thresholds that fire 0–3 times per week on real production patterns, on services that matter.++## When to use this skill++- The user asks to "set up alerts" / "suggest alerts" for their project.+- The user wants to evaluate whether a service is producing alertable signal.+- The user has just enabled log alerting and wants a starter set.++## When _not_ to use this skill++- Tuning an alert that already exists — that's a different job (use `posthog:logs-alerts-events-list` to inspect+ fire/resolve cadence and `posthog:logs-alerts-partial-update` to adjust).+- Investigating an active incident — pull rows with `posthog:query-logs`, don't author an alert mid-incident.++## Tools++| Tool | Job | Where it fits |+| --------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ------------------ |+| `posthog:logs-services` | Top-25 services in window with log_count, error_count, error_rate, sparkline. | Step 1 — triage. |+| `posthog:logs-attributes-list` / `posthog:logs-attribute-values-list` | Discover keys/values for narrower filters. | Step 2, optional. |+| `posthog:logs-count-ranges` | Adaptive time-bucketed counts for a filter. | Step 3 — baseline. |+| `posthog:logs-alerts-simulate-create` | Replay a draft config against `-7d` history with full state machine. | Step 4 — validate. |+| `posthog:logs-alerts-create` | Persist the alert. | Step 5 — ship. |+| `posthog:logs-alerts-destinations-create` | Wire the alert to Slack or webhook. | Step 5 — ship. |++Do **not** call `posthog:query-logs` during authoring. You need distributions, not rows. Reserve `posthog:query-logs` for+the very end if the user asks "show me a sample of what would have fired" — `limit: 10` is plenty.++## Workflow++### 1. Triage — pick candidate services++Call `posthog:logs-services` for the last 24h with no filters. The response is capped at 25 services and includes a+sparkline, so it is small and bounded.++A service is a candidate when **both** are true:++- `log_count` is non-trivial (≥ ~1k in 24h — quieter services produce too little signal to alert on).+- `error_rate` is non-zero, **or** the user has named the service explicitly.++Skip services with high volume but `error_rate == 0` unless the user wants a volume-shape alert (e.g. "warn me+if api-gateway suddenly stops producing logs"). Volume-floor alerts use `threshold_operator: below` and need+different reasoning — see [references/volume-floor-alerts.md](./references/volume-floor-alerts.md).++If the user names a service, treat it as a candidate even without error signal.++### 2. (Optional) Narrow the filter++If a service has many error sub-types, an alert on "all errors" is usually too broad. Use+`posthog:logs-attributes-list` (try `attribute_type: log`) and `posthog:logs-attribute-values-list` to find a discriminator —+common ones are `http.status_code`, `error.type`, `k8s.container.name`. Add the narrowing filter to your draft.++Keep it simple: one severity filter + one or two attribute filters is plenty. Multi-clause filters are+harder to reason about and rarely improve precision.++### 3. Baseline — characterise the candidate over 7 days++Call `posthog:logs-count-ranges` with the candidate's filters, `dateRange: { date_from: "-7d" }`, and+`targetBuckets: 24` (one bucket ≈ 7h). The response gives you bucket counts.++**Do not eyeball the percentiles or scale the threshold to the alert window manually.** Pipe the+count-ranges response into the helper script:++```bash+echo '<count-ranges JSON>' | python3 scripts/baseline_stats.py --window-minutes 5+```++The script returns:++```json+{+ "n_buckets": 12,+ "bucket_minutes": 420.0,+ "alert_window_minutes": 5,+ "stats": { "p50": 12.0, "p95": 71.25, "p99": 126.25, "max": 140 },+ "suggested_threshold_count": 5,+ "rationale": "max(p99=126.25, median*3=36.0, floor=5) scaled from 420m bucket to 5m window",+ "health": []+}+```++Use `suggested_threshold_count` as your starting threshold. Read `health`:++| `health` flag | What it means | What to do |+| ----------------------- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |+| `sparse:N_of_M_buckets` | Too few non-empty buckets for a 7d baseline. | Widen filter, extend to `-30d`, or skip. |+| `empty` | All buckets are zero. | Skip — no signal. |+| `spiky` | `max` is 10×+ `p95`. | Count-threshold alerts work well. Proceed. |+| `flat` | `p95` ≈ `p50`. | Be cautious — either no incidents in lookback, or the metric is too smooth. Try a longer lookback or skip. |+| `[]` (empty) | Healthy distribution. | Proceed. |++### 4. Draft and simulate++Pick a starter draft from these defaults — see [references/threshold-defaults.md](./references/threshold-defaults.md)+for the reasoning:++| Setting | Default | Notes |+| --------------------- | ------------------------------------------- | --------------------------------------------------------------------- |+| `threshold_count` | `suggested_threshold_count` from the script | Already scaled to the alert window. |+| `threshold_operator` | `above` | Use `below` only for volume-floor alerts. |+| `window_minutes` | `5` | Allowed: 5, 10, 15, 30, 60. Must match what you passed to the script. |+| `evaluation_periods` | `3` | M in N-of-M. |+| `datapoints_to_alarm` | `2` | N in N-of-M. 2-of-3 reduces flap from a single noisy bucket. |+| `cooldown_minutes` | `30` | Minimum time between repeat fires. |++Call `posthog:logs-alerts-simulate-create` with these settings and `date_from: "-7d"`. The response gives you `fire_count`+and `resolve_count`.++### 5. Iterate — three rounds, then ship or skip++Target: `fire_count` between 0 and ~3 over `-7d`. If outside the band:++| Outcome | Adjustment |+| --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |+| `fire_count` = 0 over 7d _and_ the baseline was spiky | Lower `threshold_count` toward `stats.p95` from the script, or drop to 1-of-2. |+| `fire_count` = 0 _and_ the baseline was flat | The service has no alertable signal. Skip it; log why. |+| `fire_count` > 5 | Raise `threshold_count` toward `stats.max` from the script, or move to 3-of-5 for a smoother window. |+| `fire_count` is fine but resolve_count never matches fire_count | Cooldown is too long, or the underlying state is genuinely sticky. Acceptable for now. |++When adjusting the threshold, **read values from the script's `stats` block — never recompute percentiles+by hand.**++Cap iteration at **3 simulate calls per candidate**. If you can't land in the band in 3 rounds, the metric+is wrong — either the filter is too broad, the window is wrong, or the service genuinely doesn't have a+threshold-shape signal. Note it and move on.++### 6. Ship — create + attach destination++Once a draft simulates cleanly:++1. Call `posthog:logs-alerts-create` with the validated config. Use a name like `<service> error rate (auto)` so the+ user can see at a glance which alerts came from this skill.+2. Call `posthog:logs-alerts-destinations-create` to wire it to a notification target. **An alert with no destination+ is silent.** Always confirm the channel name or webhook URL with the user before attaching — never wire+ an auto-generated alert to a production channel without explicit confirmation. If the user is unsure,+ suggest a low-traffic testing channel for the first few alerts.++If the user wants alerts created in `enabled: false` state for review-then-flip, pass `enabled: false` to+`-create` and tell them how many drafts you produced.++## Filter shape — required++The `filters` field on `posthog:logs-alerts-create` takes a subset of `LogsViewerFilters` and **must contain at+least one of**:++- `severityLevels` — list of `["trace","debug","info","warn","error","fatal"]`+- `serviceNames` — list of service name strings+- `filterGroup` — property filter group++The same shape goes into `posthog:logs-alerts-simulate-create`'s `filters` field. Match the simulate filters to the alert filters+exactly — otherwise the simulation is testing a different alert than the one you ship.++Example minimum:++```json+{+ "severityLevels": ["error", "fatal"],+ "serviceNames": ["api-gateway"]+}+```++## Token-economy rules++- One `posthog:logs-services` call at the start, not per-candidate.+- One `posthog:logs-count-ranges` call per candidate at `targetBuckets: 24`. Don't go above 30 during authoring.+- ≤ 3 `posthog:logs-alerts-simulate-create` calls per candidate.+- Zero `posthog:query-logs` calls during the authoring loop.+- Prefer reporting a small set of well-validated alerts over a long list of unvalidated drafts.++## Output++Report what you did, in this shape:++- For each shipped alert: name, filters, threshold, simulated fire_count over 7d, destination.+- For each skipped candidate: service name + why (flat baseline, can't land threshold, low volume).+- Total simulate calls made, total alerts created.++The user should be able to read this and decide whether to disable any drafts before they go live.diff --git a/products/logs/skills/authoring-log-alerts/references/threshold-defaults.md b/products/logs/skills/authoring-log-alerts/references/threshold-defaults.mdnew file mode 100644index 000000000000..4389df41663d--- /dev/null+++ b/products/logs/skills/authoring-log-alerts/references/threshold-defaults.md@@ -0,0 +1,65 @@+# Threshold defaults — reasoning++The math here is implemented in [`../scripts/baseline_stats.py`](../scripts/baseline_stats.py). The agent+should not reproduce these calculations inline — pipe the `posthog:logs-count-ranges` response into the script and+read `suggested_threshold_count`. This section explains _what the script computes and why_, so you can+sanity-check its output and reason about edge cases.++## `threshold_count = max(p99, median × 3, floor) × (window_minutes / bucket_minutes)`++The bucket-level threshold takes the max of three terms:++1. **p99 of bucket counts.** The 99th percentile of recent buckets is a data-driven "above normal" line.+ Works when the baseline has enough non-empty buckets to compute a percentile.+2. **median × 3.** Catches services where p99 is misleadingly close to the median (flat baselines), or where+ the lookback didn't include any spikes.+3. **floor (default 5).** Alerting on counts of 1 or 2 produces too much noise on small services. Below 5+ matches/window, prefer a different alert shape (e.g. existence-based) or skip.++The bucket-level threshold is then **rate-scaled to the alert window** — a 7h bucket with a threshold of+1000 errors equals ~12 errors per 5-minute window. The script does this scaling; the rationale field shows+the math.++The scaling assumes errors arrive uniformly within a bucket, which is rarely true — a real spike can pack+the entire bucket's count into a single 5-minute window. That's exactly why `posthog:logs-alerts-simulate-create` is the+final arbiter: it replays the alert state machine against actual per-minute history, not the rate-scaled+average.++## `window_minutes = 5`++The default minimum. Reasons to go higher:++- The service is bursty in 5-minute chunks but the _trend_ over 30 minutes is what matters → use 30.+- Notifications at 5-minute resolution would be too noisy for the user (e.g. expected periodic spikes during+ cron) → smooth with a 30 or 60 minute window.++Allowed: `5`, `10`, `15`, `30`, `60`. Don't pick a value not on this list — the API rejects it.++## `evaluation_periods = 3`, `datapoints_to_alarm = 2` (2-of-3)++N-of-M is the cheap, high-signal way to dampen flap. 2-of-3 means: out of the last 3 check intervals, at+least 2 must breach to fire. A single noisy interval doesn't trip the alert. A sustained problem still does.++When to deviate:++- **1-of-1** — fire instantly on a single bucket breach. Use only for incidents you cannot afford to delay+ (e.g. payments service erroring at all).+- **3-of-5** — smoother, slower. Use when the service has known short bursts that are not real incidents.+- Higher than 5 — diminishing returns; if 5 buckets aren't enough signal, the threshold is wrong.++## `cooldown_minutes = 30`++After a fire, suppress repeat fires for 30 minutes. This avoids paging the same channel every check interval+during an ongoing incident — once the alert is firing, the user already knows.++Use 0 for snapshot-style alerts where every breach is independently interesting (rare).++## Avoid these footguns++- **`threshold_operator: below` without justification.** Below-threshold alerts measure absence — useful for+ "service stopped logging" but easy to misuse. If the service has any quiet hours (overnight, weekends),+ a below-threshold alert will fire at 3am every night. See [volume-floor-alerts.md](./volume-floor-alerts.md).+- **Filtering by message text alone (`searchTerm` or `message icontains`).** Brittle to log format changes.+ Prefer a structured attribute (`http.status_code`, `error.type`) when one exists.+- **Filtering by `trace_id`/`span_id`.** Not useful in alerts — these are per-request and never repeat at a+ rate that crosses a meaningful threshold.diff --git a/products/logs/skills/authoring-log-alerts/references/volume-floor-alerts.md b/products/logs/skills/authoring-log-alerts/references/volume-floor-alerts.mdnew file mode 100644index 000000000000..ed591cb36c86--- /dev/null+++ b/products/logs/skills/authoring-log-alerts/references/volume-floor-alerts.md@@ -0,0 +1,46 @@+# Volume-floor alerts (`threshold_operator: below`)++Use to alert when a service _stops_ producing logs — a strong signal that the service is down, the logging+pipeline is broken, or something upstream stopped sending traffic.++## When to use++- The user says "tell me if X stops logging."+- A service has dependably constant volume across all hours (no nightly drop, no weekend drop) and the user+ cares about availability.++## When NOT to use++- The service has any quiet hours (overnight, weekends, batch-only). Below-threshold alerts will fire every+ quiet period.+- The service is bursty by design — a 5-minute "no logs" window is normal.+- You don't have at least 7 days of stable baseline. With less data, "below normal" is unknowable.++## How to size the threshold++The `baseline_stats.py` script doesn't suggest below-thresholds directly — derive it manually from the+script's output. Don't compute by hand; use Python:++```bash+python3 -c "import sys, json; d=json.load(sys.stdin); print(max(1, round(d['stats']['p50'] * (5/d['bucket_minutes']) * 0.25)))" < stats.json+```++The reasoning:++1. Take `p50` from the script (the typical bucket count).+2. Rate-scale to the alert window (`window_minutes / bucket_minutes`).+3. Multiply by 0.25 — fire when volume drops to 25% of the typical bucket. Buffer absorbs normal variance.+4. Set `threshold_operator: below`.++## Recommended N-of-M for floors++- `evaluation_periods: 3`, `datapoints_to_alarm: 3` (3-of-3) — require 3 consecutive quiet windows. A single+ blip won't fire.+- `window_minutes: 15` minimum — 5-minute floor alerts on noisy services are unreliable.+- `cooldown_minutes: 60` — once you know the service is quiet, no point re-paging every check.++## Simulate is essential here++Floor alerts are easy to misconfigure into "fires every night." Always run `posthog:logs-alerts-simulate-create` over `-7d`+before shipping. If `fire_count > 0` and the user has not had outages in the last 7 days, the threshold is+too aggressive.diff --git a/products/logs/skills/authoring-log-alerts/scripts/baseline_stats.py b/products/logs/skills/authoring-log-alerts/scripts/baseline_stats.pynew file mode 100755index 000000000000..f3ee7b4db669--- /dev/null+++ b/products/logs/skills/authoring-log-alerts/scripts/baseline_stats.py@@ -0,0 +1,164 @@+#!/usr/bin/env python3+"""+Compute baseline statistics from `logs-count-ranges` output and suggest an alert+threshold scaled to a target alert window. Pure stdlib — no install needed.++Usage:+ cat count_ranges_output.json | baseline_stats.py --window-minutes 5+ baseline_stats.py --window-minutes 30 --floor 10 < count_ranges_output.json++Input (stdin): the JSON body returned by the `logs-count-ranges` tool, e.g.+ {+ "ranges": [+ {"date_from": "2026-04-22T00:00:00", "date_to": "2026-04-22T07:00:00", "count": 47},+ ...+ ],+ "interval": "7h"+ }++Output (stdout): JSON with `stats` (p50/p95/p99/max), `suggested_threshold_count`+scaled to the alert window, and a `health` field flagging baselines that are too+sparse, too flat, or too spiky to alert on usefully.++Exit codes:+ 0 — stats produced+ 1 — invalid input (no ranges, malformed JSON, etc.)+"""++from __future__ import annotations++import argparse+import json+import sys+from datetime import datetime+from typing import Any+++def parse_args() -> argparse.Namespace:+ p = argparse.ArgumentParser(+ description=__doc__,+ formatter_class=argparse.RawDescriptionHelpFormatter,+ )+ p.add_argument(+ "--window-minutes",+ type=int,+ required=True,+ choices=[5, 10, 15, 30, 60],+ help="Alert window in minutes (must match logs-alerts-create.window_minutes).",+ )+ p.add_argument(+ "--floor",+ type=int,+ default=5,+ help="Minimum threshold (default: 5). Stops the suggestion collapsing on tiny services.",+ )+ p.add_argument(+ "--min-buckets",+ type=int,+ default=12,+ help="Minimum non-empty buckets for a useful baseline (default: 12).",+ )+ return p.parse_args()+++def parse_iso(s: str) -> datetime:+ # logs-count-ranges currently returns naive ISO; some clients add Z.+ cleaned = s.replace("Z", "+00:00")+ return datetime.fromisoformat(cleaned)+++def percentile(sorted_counts: list[int], q: float) -> float:+ # Matches numpy default (linear interpolation between nearest ranks).+ if not sorted_counts:+ return 0.0+ if len(sorted_counts) == 1:+ return float(sorted_counts[0])+ rank = q * (len(sorted_counts) - 1)+ lo = int(rank)+ hi = min(lo + 1, len(sorted_counts) - 1)+ frac = rank - lo+ return sorted_counts[lo] * (1 - frac) + sorted_counts[hi] * frac+++def main() -> int:+ args = parse_args()++ try:+ data = json.load(sys.stdin)+ except json.JSONDecodeError as e:+ print(f"Could not parse stdin as JSON: {e}", file=sys.stderr)+ return 1++ ranges = data.get("ranges") if isinstance(data, dict) else None+ if not ranges:+ print(+ "No buckets in input — `ranges` is empty or missing. "+ "Either the filter matched nothing, or you piped the wrong response.",+ file=sys.stderr,+ )+ return 1++ counts = [r["count"] for r in ranges if isinstance(r, dict) and "count" in r]+ if not counts:+ print("Bucket entries are missing `count` fields.", file=sys.stderr)+ return 1++ try:+ first = ranges[0]+ bucket_minutes = (parse_iso(first["date_to"]) - parse_iso(first["date_from"])).total_seconds() / 60+ except (KeyError, ValueError) as e:+ print(f"Could not derive bucket width from first range: {e}", file=sys.stderr)+ return 1++ if bucket_minutes <= 0:+ print("Bucket width is non-positive — input looks corrupt.", file=sys.stderr)+ return 1++ sorted_counts = sorted(counts)+ n = len(counts)++ mid = n // 2+ p50 = float(sorted_counts[mid]) if n % 2 else (sorted_counts[mid - 1] + sorted_counts[mid]) / 2+ p95 = percentile(sorted_counts, 0.95)+ p99 = percentile(sorted_counts, 0.99)+ bucket_max = sorted_counts[-1]++ bucket_threshold = max(p99, p50 * 3, args.floor)+ scale = args.window_minutes / bucket_minutes+ suggested = max(args.floor, round(bucket_threshold * scale))++ health: list[str] = []+ if n < args.min_buckets:+ health.append(f"sparse:{n}_of_{args.min_buckets}_buckets")+ if bucket_max == 0:+ health.append("empty")+ elif p95 > 0 and bucket_max / p95 >= 10:+ health.append("spiky")+ elif p50 > 0 and (p95 / p50) <= 1.5:+ health.append("flat")++ output: dict[str, Any] = {+ "n_buckets": n,+ "bucket_minutes": round(bucket_minutes, 2),+ "alert_window_minutes": args.window_minutes,+ "stats": {+ "p50": round(p50, 2),+ "p95": round(p95, 2),+ "p99": round(p99, 2),+ "max": bucket_max,+ },+ "suggested_threshold_count": suggested,+ "rationale": (+ f"max(p99={round(p99, 2)}, median*3={round(p50 * 3, 2)}, floor={args.floor}) "+ f"scaled from {bucket_minutes:.0f}m bucket to {args.window_minutes}m window"+ ),+ "health": health,+ }++ json.dump(output, sys.stdout, indent=2)+ sys.stdout.write("\n")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/products/logs/skills/authoring-log-alerts/tests/test_baseline_stats.py b/products/logs/skills/authoring-log-alerts/tests/test_baseline_stats.pynew file mode 100644index 000000000000..76c216fc09f6--- /dev/null+++ b/products/logs/skills/authoring-log-alerts/tests/test_baseline_stats.py@@ -0,0 +1,230 @@+"""End-to-end tests for the alert authoring baseline_stats helper script."""++from __future__ import annotations++import sys+import json+import subprocess+from datetime import datetime, timedelta+from pathlib import Path++import pytest++SCRIPT = Path(__file__).resolve().parent.parent / "scripts" / "baseline_stats.py"+++def _bucket(date_from: str, date_to: str, count: int) -> dict:+ return {"date_from": date_from, "date_to": date_to, "count": count}+++def _run(payload: dict | str, *args: str) -> tuple[int, dict | None, str]:+ """Run the script with a JSON payload on stdin and return (exit_code, parsed_stdout, stderr)."""+ body = payload if isinstance(payload, str) else json.dumps(payload)+ result = subprocess.run(+ [sys.executable, str(SCRIPT), *args],+ input=body,+ capture_output=True,+ text=True,+ timeout=10,+ )+ parsed: dict | None = None+ if result.returncode == 0 and result.stdout.strip():+ parsed = json.loads(result.stdout)+ return result.returncode, parsed, result.stderr+++_BUCKETS_BASE = datetime(2026, 4, 22)+++def _seven_hour_buckets(counts: list[int]) -> list[dict]:+ """Build 7h buckets starting 2026-04-22T00:00:00."""+ return [+ _bucket(+ (_BUCKETS_BASE + timedelta(hours=i * 7)).isoformat(),+ (_BUCKETS_BASE + timedelta(hours=(i + 1) * 7)).isoformat(),+ c,+ )+ for i, c in enumerate(counts)+ ]+++class TestHealthyBaseline:+ def test_spiky_baseline_returns_threshold_and_no_critical_health_flags(self) -> None:+ counts = [10, 12, 15, 11, 140, 13, 9, 11, 14, 10, 13, 12]+ code, out, err = _run({"ranges": _seven_hour_buckets(counts), "interval": "7h"}, "--window-minutes", "5")++ assert code == 0, err+ assert out is not None+ assert out["n_buckets"] == 12+ assert out["bucket_minutes"] == 420.0+ assert out["alert_window_minutes"] == 5+ assert out["stats"]["max"] == 140+ assert out["stats"]["p50"] == 12.0+ assert out["stats"]["p95"] > out["stats"]["p50"]+ assert out["suggested_threshold_count"] >= 5 # floor enforced+ assert "empty" not in out["health"]+ assert "sparse:" not in " ".join(out["health"])++ def test_rationale_includes_terms(self) -> None:+ counts = [10, 12, 15, 11, 140, 13, 9, 11, 14, 10, 13, 12]+ code, out, _ = _run({"ranges": _seven_hour_buckets(counts), "interval": "7h"}, "--window-minutes", "5")++ assert code == 0+ assert out is not None+ assert "p99" in out["rationale"]+ assert "median*3" in out["rationale"]+ assert "floor" in out["rationale"]+++class TestHealthFlags:+ def test_sparse_flag_when_fewer_than_min_buckets(self) -> None:+ code, out, _ = _run({"ranges": _seven_hour_buckets([10, 12]), "interval": "7h"}, "--window-minutes", "5")++ assert code == 0+ assert out is not None+ assert any(flag.startswith("sparse:2_of_12_buckets") for flag in out["health"])++ def test_sparse_flag_respects_min_buckets_override(self) -> None:+ code, out, _ = _run(+ {"ranges": _seven_hour_buckets([10, 12, 11]), "interval": "7h"},+ "--window-minutes",+ "5",+ "--min-buckets",+ "2",+ )++ assert code == 0+ assert out is not None+ assert not any(flag.startswith("sparse:") for flag in out["health"])++ def test_empty_flag_when_all_buckets_zero(self) -> None:+ code, out, _ = _run({"ranges": _seven_hour_buckets([0] * 24), "interval": "7h"}, "--window-minutes", "5")++ assert code == 0+ assert out is not None+ assert "empty" in out["health"]++ def test_flat_flag_when_p95_close_to_median(self) -> None:+ counts = [10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11]+ code, out, _ = _run({"ranges": _seven_hour_buckets(counts), "interval": "7h"}, "--window-minutes", "5")++ assert code == 0+ assert out is not None+ assert "flat" in out["health"]+ assert "spiky" not in out["health"]++ def test_spiky_flag_when_max_dwarfs_p95(self) -> None:+ # 23 quiet buckets at ~10, one massive spike — pushes max/p95 over 10×.+ counts = [10] * 23 + [500]+ code, out, _ = _run({"ranges": _seven_hour_buckets(counts), "interval": "7h"}, "--window-minutes", "5")++ assert code == 0+ assert out is not None+ assert "spiky" in out["health"]+ assert "flat" not in out["health"]+++class TestWindowScaling:+ def test_thirty_minute_window_yields_six_times_the_five_minute_threshold(self) -> None:+ # Same data, different window. With a 7h bucket and rate-uniform scaling,+ # a 30m window should be 6× the 5m suggestion (modulo floor and rounding).+ counts = [100] * 12 + [10000] # one big spike — ensures the suggestion is well above floor+ ranges = _seven_hour_buckets(counts)++ code_5, out_5, _ = _run({"ranges": ranges}, "--window-minutes", "5")+ code_30, out_30, _ = _run({"ranges": ranges}, "--window-minutes", "30")++ assert code_5 == 0 and code_30 == 0+ assert out_5 is not None and out_30 is not None+ # Allow a few units of rounding noise — ratio should be ~6.+ ratio = out_30["suggested_threshold_count"] / out_5["suggested_threshold_count"]+ assert 5.5 <= ratio <= 6.5, f"expected ~6× scaling, got {ratio}"++ def test_floor_dominates_when_data_is_tiny(self) -> None:+ code, out, _ = _run(+ {"ranges": _seven_hour_buckets([1, 2, 1, 2] * 3), "interval": "7h"},+ "--window-minutes",+ "5",+ )++ assert code == 0+ assert out is not None+ assert out["suggested_threshold_count"] == 5 # floor wins on tiny-count data++ def test_custom_floor_is_respected(self) -> None:+ code, out, _ = _run(+ {"ranges": _seven_hour_buckets([1] * 12), "interval": "7h"},+ "--window-minutes",+ "5",+ "--floor",+ "20",+ )++ assert code == 0+ assert out is not None+ assert out["suggested_threshold_count"] == 20+++class TestErrorPaths:+ def test_empty_ranges_returns_error(self) -> None:+ code, out, err = _run({"ranges": [], "interval": "7h"}, "--window-minutes", "5")++ assert code == 1+ assert out is None+ assert "no buckets" in err.lower()++ def test_missing_ranges_key_returns_error(self) -> None:+ code, _, err = _run({"interval": "7h"}, "--window-minutes", "5")++ assert code == 1+ assert "no buckets" in err.lower()++ def test_malformed_json_returns_error(self) -> None:+ code, _, err = _run("not json at all", "--window-minutes", "5")++ assert code == 1+ assert "json" in err.lower()++ def test_invalid_window_minutes_rejected_by_argparse(self) -> None:+ result = subprocess.run(+ [sys.executable, str(SCRIPT), "--window-minutes", "7"],+ input="{}",+ capture_output=True,+ text=True,+ timeout=10,+ )+ assert result.returncode == 2+ assert "invalid choice" in result.stderr.lower()++ def test_missing_count_field_in_buckets(self) -> None:+ code, _, err = _run({"ranges": [{"date_from": "x", "date_to": "y"}]}, "--window-minutes", "5")++ assert code == 1+ assert "count" in err.lower()++ def test_iso_timestamp_with_z_suffix(self) -> None:+ # Some clients format ISO with trailing Z; the script should tolerate it.+ ranges = [+ _bucket("2026-04-22T00:00:00Z", "2026-04-22T07:00:00Z", 50),+ _bucket("2026-04-22T07:00:00Z", "2026-04-22T14:00:00Z", 60),+ ]+ code, out, err = _run({"ranges": ranges}, "--window-minutes", "5", "--min-buckets", "2")++ assert code == 0, err+ assert out is not None+ assert out["bucket_minutes"] == 420.0+++ "window_minutes",+ [5, 10, 15, 30, 60],+)+def test_all_allowed_windows_accepted(window_minutes: int) -> None:+ counts = [10, 12, 15, 11, 13, 9, 11, 14, 10, 13, 12, 11]+ code, out, _ = _run(+ {"ranges": _seven_hour_buckets(counts), "interval": "7h"}, "--window-minutes", str(window_minutes)+ )++ assert code == 0+ assert out is not None+ assert out["alert_window_minutes"] == window_minutesdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 5f5a0e37b97f..9280c6793c1e 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3036,6 +3036,38 @@},"feature_flag": "logs-alerting"},+ "logs-alerts-destinations-create": {+ "description": "Attach a notification destination (Slack channel or webhook) to a log alert. Without a destination an alert evaluates silently and never notifies. One HogFunction is created per event kind (firing, resolved, broken, errored) atomically — the returned hog_function_ids identify the destination group.",+ "category": "Logs",+ "feature": "logs",+ "summary": "Attach alert destination",+ "title": "Attach alert destination",+ "required_scopes": ["logs:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "logs-alerting"+ },+ "logs-alerts-destinations-delete-create": {+ "description": "Remove a notification destination from a log alert by passing the hog_function_ids returned from logs-alerts-destinations-create. Destinations are deleted as one atomic group — partial deletion fails the call.",+ "category": "Logs",+ "feature": "logs",+ "summary": "Detach alert destination",+ "title": "Detach alert destination",+ "required_scopes": ["logs:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "logs-alerting"+ },"logs-alerts-destroy": {"description": "Permanently delete a log alert configuration by ID.","category": "Logs",@@ -3052,6 +3084,22 @@},"feature_flag": "logs-alerting"},+ "logs-alerts-events-list": {+ "description": "List historical events for a log alert — fires, resolves, errors, enable/disable toggles, threshold changes. Use to evaluate how an existing alert has behaved (firing cadence, error rate, flap pattern) before tuning thresholds. Quiet no-op check rows are filtered out server-side. Optional `kind` query param narrows to a single event kind.",+ "category": "Logs",+ "feature": "logs",+ "summary": "List alert events",+ "title": "List alert events",+ "required_scopes": ["logs:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "logs-alerting"+ },"logs-alerts-list": {"description": "List log alert configurations in the current project, newest first. Returns alert name, state, threshold, filters, and scheduling details. Use this to review existing alerts before creating or modifying them.","category": "Logs",@@ -3100,6 +3148,22 @@},"feature_flag": "logs-alerting"},+ "logs-alerts-simulate-create": {+ "description": "Run a draft alert configuration against historical logs and return per-bucket results from the full state machine — count, threshold_breached, state, notification (none/fire/resolve), reason. Use to validate threshold + N-of-M settings before creating an alert. Read-only; no alert records are written. Aim for fire_count between 0 and 3 over a `-7d` lookback for a healthy threshold.",+ "category": "Logs",+ "feature": "logs",+ "summary": "Simulate log alert",+ "title": "Simulate log alert",+ "required_scopes": ["logs:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "logs-alerting"+ },"logs-attribute-values-list": {"description": "List values for a specific log attribute key. Use to discover what values exist before building filters. Defaults to attribute_type \"log\" (log-level attributes). To get values for resource-level attributes (e.g. service.name, k8s.pod.name), you MUST explicitly pass attribute_type: \"resource\". Accepts optional serviceNames, dateRange, and filterGroup to narrow which logs are scanned.","category": "Logs",@@ -3160,6 +3224,21 @@"readOnlyHint": true}},+ "logs-services-create": {+ "description": "Return the top-25 services by log volume in the window, each with log_count, error_count, and error_rate, plus a per-service sparkline. Use this as the entry point when triaging which services are worth alerting on — high volume × non-zero error_rate is the natural alert candidate. Far cheaper than walking attribute-values + per-service counts.",+ "category": "Logs",+ "feature": "logs",+ "summary": "List services with stats",+ "title": "List services with stats",+ "required_scopes": ["logs:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"logs-sparkline-query": {"description": "Get a time-bucketed sparkline of log volume, broken down by severity or service. Use this to understand log volume patterns before querying individual log entries — it is much cheaper than a full log query.\n\nAll parameters must be nested inside a `query` object.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the sparkline. Defaults to the last hour (`-1h`).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nFilter by service names.\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\n## query.searchTerm\n\nFull-text search across log bodies.\n\n## query.filterGroup\n\nProperty filters to narrow results. Same format as `query-logs` filters.\n\n## query.sparklineBreakdownBy\n\nBreak down the sparkline by `\"severity\"` (default) or `\"service\"`. Use `\"service\"` to see which services are producing the most logs.\n\n# Examples\n\n## Error volume over the last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"severityLevels\": [\"error\", \"fatal\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Log volume by service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"sparklineBreakdownBy\": \"service\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Log volume by severity\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"sparklineBreakdownBy\": \"severity\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```","category": "Logs",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex fc385895fe1b..3671111fd129 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -3349,6 +3349,38 @@},"feature_flag": "logs-alerting"},+ "logs-alerts-destinations-create": {+ "description": "Attach a notification destination (Slack channel or webhook) to a log alert. Without a destination an alert evaluates silently and never notifies. One HogFunction is created per event kind (firing, resolved, broken, errored) atomically — the returned hog_function_ids identify the destination group.",+ "category": "Logs",+ "feature": "logs",+ "summary": "Attach alert destination",+ "title": "Attach alert destination",+ "required_scopes": ["logs:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "logs-alerting"+ },+ "logs-alerts-destinations-delete-create": {+ "description": "Remove a notification destination from a log alert by passing the hog_function_ids returned from logs-alerts-destinations-create. Destinations are deleted as one atomic group — partial deletion fails the call.",+ "category": "Logs",+ "feature": "logs",+ "summary": "Detach alert destination",+ "title": "Detach alert destination",+ "required_scopes": ["logs:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "logs-alerting"+ },"logs-alerts-destroy": {"description": "Permanently delete a log alert configuration by ID.","category": "Logs",@@ -3365,6 +3397,22 @@},"feature_flag": "logs-alerting"},+ "logs-alerts-events-list": {+ "description": "List historical events for a log alert — fires, resolves, errors, enable/disable toggles, threshold changes. Use to evaluate how an existing alert has behaved (firing cadence, error rate, flap pattern) before tuning thresholds. Quiet no-op check rows are filtered out server-side. Optional `kind` query param narrows to a single event kind.",+ "category": "Logs",+ "feature": "logs",+ "summary": "List alert events",+ "title": "List alert events",+ "required_scopes": ["logs:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "logs-alerting"+ },"logs-alerts-list": {"description": "List log alert configurations in the current project, newest first. Returns alert name, state, threshold, filters, and scheduling details. Use this to review existing alerts before creating or modifying them.","category": "Logs",@@ -3413,6 +3461,22 @@},"feature_flag": "logs-alerting"},+ "logs-alerts-simulate-create": {+ "description": "Run a draft alert configuration against historical logs and return per-bucket results from the full state machine — count, threshold_breached, state, notification (none/fire/resolve), reason. Use to validate threshold + N-of-M settings before creating an alert. Read-only; no alert records are written. Aim for fire_count between 0 and 3 over a `-7d` lookback for a healthy threshold.",+ "category": "Logs",+ "feature": "logs",+ "summary": "Simulate log alert",+ "title": "Simulate log alert",+ "required_scopes": ["logs:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "logs-alerting"+ },"logs-attribute-values-list": {"description": "List values for a specific log attribute key. Use to discover what values exist before building filters. Defaults to attribute_type \"log\" (log-level attributes). To get values for resource-level attributes (e.g. service.name, k8s.pod.name), you MUST explicitly pass attribute_type: \"resource\". Accepts optional serviceNames, dateRange, and filterGroup to narrow which logs are scanned.","category": "Logs",@@ -3473,6 +3537,21 @@"readOnlyHint": true}},+ "logs-services-create": {+ "description": "Return the top-25 services by log volume in the window, each with log_count, error_count, and error_rate, plus a per-service sparkline. Use this as the entry point when triaging which services are worth alerting on — high volume × non-zero error_rate is the natural alert candidate. Far cheaper than walking attribute-values + per-service counts.",+ "category": "Logs",+ "feature": "logs",+ "summary": "List services with stats",+ "title": "List services with stats",+ "required_scopes": ["logs:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"logs-sparkline-query": {"description": "Get a time-bucketed sparkline of log volume, broken down by severity or service. Use this to understand log volume patterns before querying individual log entries — it is much cheaper than a full log query.\n\nAll parameters must be nested inside a `query` object.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the sparkline. Defaults to the last hour (`-1h`).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nFilter by service names.\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\n## query.searchTerm\n\nFull-text search across log bodies.\n\n## query.filterGroup\n\nProperty filters to narrow results. Same format as `query-logs` filters.\n\n## query.sparklineBreakdownBy\n\nBreak down the sparkline by `\"severity\"` (default) or `\"service\"`. Use `\"service\"` to see which services are producing the most logs.\n\n# Examples\n\n## Error volume over the last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"severityLevels\": [\"error\", \"fatal\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Log volume by service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"sparklineBreakdownBy\": \"service\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Log volume by severity\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"sparklineBreakdownBy\": \"severity\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```","category": "Logs",diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.tsindex e06544a6dc60..9627bcb5a55a 100644--- a/services/mcp/src/generated/logs/api.ts+++ b/services/mcp/src/generated/logs/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 11 enabled ops+ * PostHog API - MCP 16 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -194,6 +194,127 @@ export const LogsAlertsDestroyParams = /* @__PURE__ */ zod.object({),})+/**+ * Create a notification destination for this alert. One HogFunction is created per alert event kind (firing, resolved, ...) atomically.+ */+export const LogsAlertsDestinationsCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this logs alert configuration.'),+ 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 LogsAlertsDestinationsCreateBody = /* @__PURE__ */ zod.object({+ type: zod+ .enum(['slack', 'webhook'])+ .describe('* `slack` - slack\n* `webhook` - webhook')+ .describe('Destination type — slack or webhook.\n\n* `slack` - slack\n* `webhook` - webhook'),+ slack_workspace_id: zod+ .number()+ .optional()+ .describe('Integration ID for the Slack workspace. Required when type=slack.'),+ slack_channel_id: zod.string().optional().describe('Slack channel ID. Required when type=slack.'),+ slack_channel_name: zod.string().optional().describe('Human-readable channel name for display.'),+ webhook_url: zod.url().optional().describe('HTTPS endpoint to POST to. Required when type=webhook.'),+})++/**+ * Delete a notification destination by deleting its HogFunction group atomically.+ */+export const LogsAlertsDestinationsDeleteCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this logs alert configuration.'),+ 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 LogsAlertsDestinationsDeleteCreateBody = /* @__PURE__ */ zod.object({+ hog_function_ids: zod+ .array(zod.string())+ .min(1)+ .describe('HogFunction IDs to delete as one atomic destination group.'),+})++/**+ * Paginated event history for this alert, newest first. Returns state transitions, errored checks, and user-initiated control-plane rows (reset, enable/disable, snooze/unsnooze, threshold change) — quiet no-op check rows (where state didn't change and there was no error) are filtered out since only the last 10 are kept and they carry no forensic value. Optional `?kind=...` narrows to a single kind.+ */+export const LogsAlertsEventsListParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this logs alert configuration.'),+ 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 LogsAlertsEventsListQueryParams = /* @__PURE__ */ zod.object({+ limit: zod.number().optional().describe('Number of results to return per page.'),+ offset: zod.number().optional().describe('The initial index from which to return the results.'),+})++/**+ * Simulate a logs alert on historical data using the full state machine. Read-only — no alert check records are created.+ */+export const LogsAlertsSimulateCreateParams = /* @__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 logsAlertsSimulateCreateBodyCheckIntervalMinutesDefault = 5+export const logsAlertsSimulateCreateBodyCheckIntervalMinutesMax = 60++export const logsAlertsSimulateCreateBodyEvaluationPeriodsDefault = 1+export const logsAlertsSimulateCreateBodyEvaluationPeriodsMax = 10++export const logsAlertsSimulateCreateBodyDatapointsToAlarmDefault = 1+export const logsAlertsSimulateCreateBodyDatapointsToAlarmMax = 10++export const logsAlertsSimulateCreateBodyCooldownMinutesDefault = 0+export const logsAlertsSimulateCreateBodyCooldownMinutesMin = 0++export const LogsAlertsSimulateCreateBody = /* @__PURE__ */ zod.object({+ filters: zod.unknown().describe('Filter criteria — same format as LogsAlertConfiguration.filters.'),+ threshold_count: zod.number().min(1).describe('Threshold count to evaluate against.'),+ threshold_operator: zod+ .enum(['above', 'below'])+ .describe('* `above` - Above\n* `below` - Below')+ .describe(+ 'Whether the alert fires when the count is above or below the threshold.\n\n* `above` - Above\n* `below` - Below'+ ),+ window_minutes: zod.number().describe('Window size in minutes — determines bucket interval.'),+ check_interval_minutes: zod+ .number()+ .min(1)+ .max(logsAlertsSimulateCreateBodyCheckIntervalMinutesMax)+ .default(logsAlertsSimulateCreateBodyCheckIntervalMinutesDefault)+ .describe('How often the alert is evaluated, in minutes.'),+ evaluation_periods: zod+ .number()+ .min(1)+ .max(logsAlertsSimulateCreateBodyEvaluationPeriodsMax)+ .default(logsAlertsSimulateCreateBodyEvaluationPeriodsDefault)+ .describe('Total check periods in the N-of-M evaluation window (M).'),+ datapoints_to_alarm: zod+ .number()+ .min(1)+ .max(logsAlertsSimulateCreateBodyDatapointsToAlarmMax)+ .default(logsAlertsSimulateCreateBodyDatapointsToAlarmDefault)+ .describe('How many periods must breach to fire (N in N-of-M).'),+ cooldown_minutes: zod+ .number()+ .min(logsAlertsSimulateCreateBodyCooldownMinutesMin)+ .default(logsAlertsSimulateCreateBodyCooldownMinutesDefault)+ .describe('Minutes to wait after firing before sending another notification.'),+ date_from: zod.string().describe("Relative date string for how far back to simulate (e.g. '-24h', '-7d', '-30d')."),+})+export const LogsAttributesRetrieveParams = /* @__PURE__ */ zod.object({project_id: zod.string()@@ -608,6 +729,99 @@ export const LogsQueryCreateBody = /* @__PURE__ */ zod.object({.describe('The logs query to execute.'),})+export const LogsServicesCreateParams = /* @__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 LogsServicesCreateBody = /* @__PURE__ */ zod.object({+ query: zod+ .object({+ dateRange: zod+ .object({+ date_from: zod+ .string()+ .nullish()+ .describe(+ 'Start of the date range. Accepts ISO 8601 timestamps or relative formats: -7d, -1h, -1mStart, etc.'+ ),+ date_to: zod+ .string()+ .nullish()+ .describe('End of the date range. Same format as date_from. Omit or null for "now".'),+ })+ .optional()+ .describe('Date range for the services aggregation. Defaults to last hour.'),+ severityLevels: zod+ .array(+ zod+ .enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal'])+ .describe(+ '* `trace` - trace\n* `debug` - debug\n* `info` - info\n* `warn` - warn\n* `error` - error\n* `fatal` - fatal'+ )+ )+ .optional()+ .describe('Filter by log severity levels.'),+ serviceNames: zod+ .array(zod.string())+ .optional()+ .describe('Restrict the aggregation to these service names.'),+ searchTerm: zod.string().optional().describe('Full-text search term to filter log bodies.'),+ filterGroup: zod+ .array(+ zod.object({+ key: zod+ .string()+ .describe(+ 'Attribute key. For type "log", use "message". For "log_attribute"/"log_resource_attribute", use the attribute key (e.g. "k8s.container.name").'+ ),+ type: zod+ .enum(['log', 'log_attribute', 'log_resource_attribute'])+ .describe(+ '* `log` - log\n* `log_attribute` - log_attribute\n* `log_resource_attribute` - log_resource_attribute'+ )+ .describe(+ '"log" filters the log body/message. "log_attribute" filters log-level attributes. "log_resource_attribute" filters resource-level attributes.\n\n* `log` - log\n* `log_attribute` - log_attribute\n* `log_resource_attribute` - log_resource_attribute'+ ),+ operator: zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'regex',+ 'not_regex',+ 'gt',+ 'lt',+ 'is_date_exact',+ 'is_date_before',+ 'is_date_after',+ 'is_set',+ 'is_not_set',+ ])+ .describe(+ '* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `is_date_exact` - is_date_exact\n* `is_date_before` - is_date_before\n* `is_date_after` - is_date_after\n* `is_set` - is_set\n* `is_not_set` - is_not_set'+ )+ .describe(+ 'Comparison operator.\n\n* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `is_date_exact` - is_date_exact\n* `is_date_before` - is_date_before\n* `is_date_after` - is_date_after\n* `is_set` - is_set\n* `is_not_set` - is_not_set'+ ),+ value: zod+ .unknown()+ .nullish()+ .describe(+ 'Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators.'+ ),+ })+ )+ .optional()+ .describe('Property filters for the query.'),+ })+ .describe('The services aggregation query to execute.'),+})+export const LogsSparklineCreateParams = /* @__PURE__ */ zod.object({project_id: zod.string()diff --git a/services/mcp/src/tools/generated/logs.ts b/services/mcp/src/tools/generated/logs.tsindex 18fdbd69ec3d..427fd0115965 100644--- a/services/mcp/src/tools/generated/logs.ts+++ b/services/mcp/src/tools/generated/logs.ts@@ -4,15 +4,23 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import {LogsAlertsCreateBody,+ LogsAlertsDestinationsCreateBody,+ LogsAlertsDestinationsCreateParams,+ LogsAlertsDestinationsDeleteCreateBody,+ LogsAlertsDestinationsDeleteCreateParams,LogsAlertsDestroyParams,+ LogsAlertsEventsListParams,+ LogsAlertsEventsListQueryParams,LogsAlertsListQueryParams,LogsAlertsPartialUpdateBody,LogsAlertsPartialUpdateParams,LogsAlertsRetrieveParams,+ LogsAlertsSimulateCreateBody,LogsAttributesRetrieveQueryParams,LogsCountCreateBody,LogsCountRangesCreateBody,LogsQueryCreateBody,+ LogsServicesCreateBody,LogsSparklineCreateBody,LogsValuesRetrieveQueryParams,} from '@/generated/logs/api'@@ -88,6 +96,66 @@ const logsAlertsCreate = (): ToolBase<typeof LogsAlertsCreateSchema, Schemas.Log},})+const LogsAlertsDestinationsCreateSchema = LogsAlertsDestinationsCreateParams.omit({ project_id: true }).extend(+ LogsAlertsDestinationsCreateBody.shape+)++const logsAlertsDestinationsCreate = (): ToolBase<+ typeof LogsAlertsDestinationsCreateSchema,+ Schemas.LogsAlertDestinationResponse+> => ({+ name: 'logs-alerts-destinations-create',+ schema: LogsAlertsDestinationsCreateSchema,+ handler: async (context: Context, params: z.infer<typeof LogsAlertsDestinationsCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.type !== undefined) {+ body['type'] = params.type+ }+ if (params.slack_workspace_id !== undefined) {+ body['slack_workspace_id'] = params.slack_workspace_id+ }+ if (params.slack_channel_id !== undefined) {+ body['slack_channel_id'] = params.slack_channel_id+ }+ if (params.slack_channel_name !== undefined) {+ body['slack_channel_name'] = params.slack_channel_name+ }+ if (params.webhook_url !== undefined) {+ body['webhook_url'] = params.webhook_url+ }+ const result = await context.api.request<Schemas.LogsAlertDestinationResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/alerts/${encodeURIComponent(String(params.id))}/destinations/`,+ body,+ })+ const filtered = pickResponseFields(result, ['hog_function_ids']) as typeof result+ return filtered+ },+})++const LogsAlertsDestinationsDeleteCreateSchema = LogsAlertsDestinationsDeleteCreateParams.omit({+ project_id: true,+}).extend(LogsAlertsDestinationsDeleteCreateBody.shape)++const logsAlertsDestinationsDeleteCreate = (): ToolBase<typeof LogsAlertsDestinationsDeleteCreateSchema, unknown> => ({+ name: 'logs-alerts-destinations-delete-create',+ schema: LogsAlertsDestinationsDeleteCreateSchema,+ handler: async (context: Context, params: z.infer<typeof LogsAlertsDestinationsDeleteCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.hog_function_ids !== undefined) {+ body['hog_function_ids'] = params.hog_function_ids+ }+ const result = await context.api.request<unknown>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/alerts/${encodeURIComponent(String(params.id))}/destinations/delete/`,+ body,+ })+ return result+ },+})+const LogsAlertsDestroySchema = LogsAlertsDestroyParams.omit({ project_id: true })const logsAlertsDestroy = (): ToolBase<typeof LogsAlertsDestroySchema, unknown> => ({@@ -103,6 +171,46 @@ const logsAlertsDestroy = (): ToolBase<typeof LogsAlertsDestroySchema, unknown>},})+const LogsAlertsEventsListSchema = LogsAlertsEventsListParams.omit({ project_id: true }).extend(+ LogsAlertsEventsListQueryParams.shape+)++const logsAlertsEventsList = (): ToolBase<+ typeof LogsAlertsEventsListSchema,+ WithPostHogUrl<Schemas.PaginatedLogsAlertEventList>+> => ({+ name: 'logs-alerts-events-list',+ schema: LogsAlertsEventsListSchema,+ handler: async (context: Context, params: z.infer<typeof LogsAlertsEventsListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedLogsAlertEventList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/alerts/${encodeURIComponent(String(params.id))}/events/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ },+ })+ const filtered = {+ ...result,+ results: (result.results ?? []).map((item: any) =>+ pickResponseFields(item, [+ 'id',+ 'created_at',+ 'kind',+ 'state_before',+ 'state_after',+ 'threshold_breached',+ 'result_count',+ 'error_message',+ 'query_duration_ms',+ ])+ ),+ } as typeof result+ return await withPostHogUrl(context, filtered, '/logs')+ },+})+const LogsAlertsListSchema = LogsAlertsListQueryParamsconst logsAlertsList = (): ToolBase<@@ -249,6 +357,61 @@ const logsAlertsRetrieve = (): ToolBase<typeof LogsAlertsRetrieveSchema, Schemas},})+const LogsAlertsSimulateCreateSchema = LogsAlertsSimulateCreateBody++const logsAlertsSimulateCreate = (): ToolBase<+ typeof LogsAlertsSimulateCreateSchema,+ Schemas.LogsAlertSimulateResponse+> => ({+ name: 'logs-alerts-simulate-create',+ schema: LogsAlertsSimulateCreateSchema,+ handler: async (context: Context, params: z.infer<typeof LogsAlertsSimulateCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.filters !== undefined) {+ body['filters'] = params.filters+ }+ if (params.threshold_count !== undefined) {+ body['threshold_count'] = params.threshold_count+ }+ if (params.threshold_operator !== undefined) {+ body['threshold_operator'] = params.threshold_operator+ }+ if (params.window_minutes !== undefined) {+ body['window_minutes'] = params.window_minutes+ }+ if (params.check_interval_minutes !== undefined) {+ body['check_interval_minutes'] = params.check_interval_minutes+ }+ if (params.evaluation_periods !== undefined) {+ body['evaluation_periods'] = params.evaluation_periods+ }+ if (params.datapoints_to_alarm !== undefined) {+ body['datapoints_to_alarm'] = params.datapoints_to_alarm+ }+ if (params.cooldown_minutes !== undefined) {+ body['cooldown_minutes'] = params.cooldown_minutes+ }+ if (params.date_from !== undefined) {+ body['date_from'] = params.date_from+ }+ const result = await context.api.request<Schemas.LogsAlertSimulateResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/alerts/simulate/`,+ body,+ })+ const filtered = pickResponseFields(result, [+ 'buckets',+ 'fire_count',+ 'resolve_count',+ 'total_buckets',+ 'threshold_count',+ 'threshold_operator',+ ]) as typeof result+ return filtered+ },+})+const LogsAttributeValuesListSchema = LogsValuesRetrieveQueryParamsconst logsAttributeValuesList = (): ToolBase<typeof LogsAttributeValuesListSchema, Schemas._LogsValuesResponse> => ({@@ -341,6 +504,27 @@ const logsCountRanges = (): ToolBase<typeof LogsCountRangesSchema, Schemas._Logs},})+const LogsServicesCreateSchema = LogsServicesCreateBody++const logsServicesCreate = (): ToolBase<typeof LogsServicesCreateSchema, Schemas._LogsServicesResponse> => ({+ name: 'logs-services-create',+ schema: LogsServicesCreateSchema,+ handler: async (context: Context, params: z.infer<typeof LogsServicesCreateSchema>) => {+ 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._LogsServicesResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/services/`,+ body,+ })+ const filtered = pickResponseFields(result, ['services', 'sparkline']) as typeof result+ return filtered+ },+})+const LogsSparklineQuerySchema = LogsSparklineCreateBodyconst logsSparklineQuery = (): ToolBase<typeof LogsSparklineQuerySchema, Schemas._LogsSparklineResponse> => ({@@ -385,14 +569,19 @@ const queryLogs = (): ToolBase<typeof QueryLogsSchema, Schemas._LogsQueryResponsexport const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'logs-alerts-create': logsAlertsCreate,+ 'logs-alerts-destinations-create': logsAlertsDestinationsCreate,+ 'logs-alerts-destinations-delete-create': logsAlertsDestinationsDeleteCreate,'logs-alerts-destroy': logsAlertsDestroy,+ 'logs-alerts-events-list': logsAlertsEventsList,'logs-alerts-list': logsAlertsList,'logs-alerts-partial-update': logsAlertsPartialUpdate,'logs-alerts-retrieve': logsAlertsRetrieve,+ 'logs-alerts-simulate-create': logsAlertsSimulateCreate,'logs-attribute-values-list': logsAttributeValuesList,'logs-attributes-list': logsAttributesList,'logs-count': logsCount,'logs-count-ranges': logsCountRanges,+ 'logs-services-create': logsServicesCreate,'logs-sparkline-query': logsSparklineQuery,'query-logs': queryLogs,}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/logs-services-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/logs-services-create.jsonnew file mode 100644index 000000000000..dddef9fdf98e--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/logs-services-create.json@@ -0,0 +1,108 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "query": {+ "description": "The services aggregation query to execute.",+ "properties": {+ "dateRange": {+ "description": "Date range for the services aggregation. Defaults to last hour.",+ "properties": {+ "date_from": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Start of the date range. Accepts ISO 8601 timestamps or relative formats: -7d, -1h, -1mStart, etc."+ },+ "date_to": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "End of the date range. Same format as date_from. Omit or null for \"now\"."+ }+ },+ "type": "object"+ },+ "filterGroup": {+ "description": "Property filters for the query.",+ "items": {+ "properties": {+ "key": {+ "description": "Attribute key. For type \"log\", use \"message\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").",+ "type": "string"+ },+ "operator": {+ "description": "Comparison operator.\n\n* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `is_date_exact` - is_date_exact\n* `is_date_before` - is_date_before\n* `is_date_after` - is_date_after\n* `is_set` - is_set\n* `is_not_set` - is_not_set",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "regex",+ "not_regex",+ "gt",+ "lt",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ "is_set",+ "is_not_set"+ ],+ "type": "string"+ },+ "type": {+ "description": "\"log\" filters the log body/message. \"log_attribute\" filters log-level attributes. \"log_resource_attribute\" filters resource-level attributes.\n\n* `log` - log\n* `log_attribute` - log_attribute\n* `log_resource_attribute` - log_resource_attribute",+ "enum": ["log", "log_attribute", "log_resource_attribute"],+ "type": "string"+ },+ "value": {+ "anyOf": [+ {},+ {+ "type": "null"+ }+ ],+ "description": "Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators."+ }+ },+ "required": ["key", "type", "operator"],+ "type": "object"+ },+ "type": "array"+ },+ "searchTerm": {+ "description": "Full-text search term to filter log bodies.",+ "type": "string"+ },+ "serviceNames": {+ "description": "Restrict the aggregation to these service names.",+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "severityLevels": {+ "description": "Filter by log severity levels.",+ "items": {+ "description": "* `trace` - trace\n* `debug` - debug\n* `info` - info\n* `warn` - warn\n* `error` - error\n* `fatal` - fatal",+ "enum": ["trace", "debug", "info", "warn", "error", "fatal"],+ "type": "string"+ },+ "type": "array"+ }+ },+ "type": "object"+ }+ },+ "required": ["query"],+ "type": "object"+}