: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
fix(mcp): run the call a flattened query wrapper meant (#97235)
posthog[bot]cd49e4905234
diff --git a/products/logs/mcp/prompts/logs-count-ranges.md b/products/logs/mcp/prompts/logs-count-ranges.mdindex f940143910cb..ab14abe51ade 100644--- a/products/logs/mcp/prompts/logs-count-ranges.md+++ b/products/logs/mcp/prompts/logs-count-ranges.md@@ -1,5 +1,11 @@Get adaptive-interval bucket counts for a filtered log stream. Returns a flat list of `{date_from, date_to, count}` buckets covering the requested window. Modeled on Elasticsearch's `auto_date_histogram` — caller specifies a target bucket count, the engine picks the interval.+All parameters go inside `query` — top-level fields are rejected:++```json+{ "query": { "serviceNames": ["api"], "dateRange": { "date_from": "-1h" } } }+```+Use this to find **where the volume is concentrated** before pulling rows. Cheaper than `query-logs`, more agent-friendly than `logs-sparkline-query` (each bucket carries explicit `date_from`/`date_to` you can feed straight back as the next call's `dateRange` to drill in).# When to use this vs other tools@@ -22,8 +28,6 @@ This is the same pattern Elasticsearch users follow with `auto_date_histogram`.# Parameters-All parameters must be nested inside a `query` object.-## query.dateRangeWindow to bucket. Defaults to the last hour (`-1h`). Same format as `query-logs`.diff --git a/products/logs/mcp/prompts/logs-count.md b/products/logs/mcp/prompts/logs-count.mdindex ce1bb2f3a3d7..055303d62617 100644--- a/products/logs/mcp/prompts/logs-count.md+++ b/products/logs/mcp/prompts/logs-count.md@@ -1,6 +1,10 @@Return a scalar count of log entries matching a filter set. Use this as a cheap pre-flight before `query-logs` — if the count exceeds `query-logs`'s max `limit` of 1000, narrow the filters before pulling rows.-All parameters must be nested inside a `query` object.+All parameters go inside `query` — top-level fields are rejected:++```json+{ "query": { "serviceNames": ["api"], "dateRange": { "date_from": "-1h" } } }+```# When to usediff --git a/products/logs/mcp/prompts/logs-facet-values.md b/products/logs/mcp/prompts/logs-facet-values.mdindex debe3763ebe2..dca7f794373b 100644--- a/products/logs/mcp/prompts/logs-facet-values.md+++ b/products/logs/mcp/prompts/logs-facet-values.md@@ -1,8 +1,12 @@Return per-value counts for a single facet — the distribution of a log dimension across a filter set, ordered by count descending. This is the cheap way to see the _shape_ of a log stream (e.g. "which services produce the errors?") without pulling raw rows.-Counts are cross-filtered: every active filter is applied _except the faceted field's own filter_, so you see the full distribution rather than collapsing to your own selection. Faceting `service_name` with `serviceNames: ["api"]` still returns every service, not just `api`.+All parameters go inside `query` — top-level fields are rejected. Provide **exactly one** of `query.facetField` or `query.facetResourceAttribute` — not both, not neither:-All parameters must be nested inside a `query` object. You must provide **exactly one** of `query.facetField` or `query.facetResourceAttribute` — not both, not neither.+```json+{ "query": { "facetField": "service_name", "dateRange": { "date_from": "-1h" } } }+```++Counts are cross-filtered: every active filter is applied _except the faceted field's own filter_, so you see the full distribution rather than collapsing to your own selection. Faceting `service_name` with `serviceNames: ["api"]` still returns every service, not just `api`.# When to usediff --git a/products/logs/mcp/prompts/logs-patterns-diff.md b/products/logs/mcp/prompts/logs-patterns-diff.mdindex b46c5767acfb..68b0ad326933 100644--- a/products/logs/mcp/prompts/logs-patterns-diff.md+++ b/products/logs/mcp/prompts/logs-patterns-diff.md@@ -1,6 +1,10 @@Compare the log patterns of two time windows and return what changed: templates that are **new**, templates whose rate **shifted** (with magnitude, e.g. 4x), and templates that are **gone**. This is the single most useful call for incident triage — "what is different about now vs. before it broke" in one round trip, instead of mining two windows yourself and hand-matching templates.-All parameters must be nested inside a `query` object, with an optional sibling `baselineDateRange`.+All parameters go inside `query`, except the optional sibling `baselineDateRange`. Other top-level fields are rejected:++```json+{ "query": { "serviceNames": ["api"], "dateRange": { "date_from": "-1d" } } }+```# When to usediff --git a/products/logs/mcp/prompts/logs-patterns.md b/products/logs/mcp/prompts/logs-patterns.mdindex 9205b3a20293..8e6655281386 100644--- a/products/logs/mcp/prompts/logs-patterns.md+++ b/products/logs/mcp/prompts/logs-patterns.md@@ -1,8 +1,12 @@Mine recurring log templates ("patterns") from the logs matching a filter set, ordered by frequency. Each pattern is a message template with the variable parts masked — e.g. `Connected to <ip> in <num>ms` — plus occurrence estimates, severity mix, the services it appears in, and a ready-made predicate for fetching its matching lines.-This is the fastest way to understand what a log stream is _saying_ without reading raw rows: one call summarizes millions of lines into at most 200 templates.+All parameters go inside `query` — top-level fields are rejected:-All parameters must be nested inside a `query` object.+```json+{ "query": { "serviceNames": ["api"], "dateRange": { "date_from": "-1h" } } }+```++This is the fastest way to understand what a log stream is _saying_ without reading raw rows: one call summarizes millions of lines into at most 200 templates.# When to usediff --git a/products/logs/mcp/prompts/logs-sparkline.md b/products/logs/mcp/prompts/logs-sparkline.mdindex 83ee3c6989c2..751f322ad60c 100644--- a/products/logs/mcp/prompts/logs-sparkline.md+++ b/products/logs/mcp/prompts/logs-sparkline.md@@ -1,6 +1,10 @@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.-All parameters must be nested inside a `query` object.+All parameters go inside `query` — top-level fields are rejected:++```json+{ "query": { "serviceNames": ["api"], "dateRange": { "date_from": "-1h" } } }+```# Parametersdiff --git a/products/logs/mcp/prompts/query-logs.md b/products/logs/mcp/prompts/query-logs.mdindex 5b0dc486d878..fb35b6aba1ad 100644--- a/products/logs/mcp/prompts/query-logs.md+++ b/products/logs/mcp/prompts/query-logs.md@@ -1,5 +1,11 @@Query log entries with filtering by severity, service name, date range, search term, and structured attribute filters. Supports cursor-based pagination. The response schema (see the tool's typed output) lists every returned field — prefer `severity_text` over `severity_number` / `level`, and be aware that `trace_id` and `span_id` return zero-padded strings rather than null when unset.+All parameters go inside `query` — top-level fields are rejected:++```json+{ "query": { "serviceNames": ["api"], "dateRange": { "date_from": "-1h" } } }+```+Use `logs-attributes-list` and `logs-attribute-values-list` to discover available attributes before building filters.# Workflow — follow this order every time@@ -19,8 +25,6 @@ MANDATORY: Never call query-logs without setting `serviceNames` or at least oneMANDATORY: Always pass `query.dateRange` explicitly (e.g. `{ "date_from": "-1h" }`). Omitting it fails with a 400 `parse_error` ("Input should be a valid dictionary or instance of DateRange") — the server does not fall back to a default window.-All parameters must be nested inside a `query` object.-# Data narrowing## Property filters@@ -80,8 +84,6 @@ Use the `query.dateRange` field to control the time window — pass it on every# Parameters-All parameters go inside `query`.-## query.severityLevelsFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.diff --git a/products/metrics/mcp/prompts/characterize-metric-anomaly.md b/products/metrics/mcp/prompts/characterize-metric-anomaly.mdindex 53b1be690800..1be79d15b4ce 100644--- a/products/metrics/mcp/prompts/characterize-metric-anomaly.md+++ b/products/metrics/mcp/prompts/characterize-metric-anomaly.md@@ -1,6 +1,6 @@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.-All parameters go inside `query`:+All parameters go inside `query` — top-level fields are rejected:```json{ "query": { "metricName": "m", "anomalyFrom": "2026-01-01T00:00:00Z" } }diff --git a/products/metrics/mcp/prompts/query-metrics.md b/products/metrics/mcp/prompts/query-metrics.mdindex c9e95c2c35cc..ea4e59e2fef2 100644--- a/products/metrics/mcp/prompts/query-metrics.md+++ b/products/metrics/mcp/prompts/query-metrics.md@@ -1,6 +1,6 @@Query server/infrastructure metrics (OTel- or Prometheus-ingested) as bucketed time series. The response is a list of series — `{labels, points: [{time, value}], metric_name, clause}` — where every series shares one time grid (missing buckets are zero-filled). A single ungrouped query returns exactly one series with empty labels.-All parameters go inside `query`:+All parameters go inside `query` — top-level fields are rejected:```json{ "query": { "metricName": "m", "aggregation": "rate", "dateFrom": "2026-01-01T00:00:00Z" } }diff --git a/products/tracing/mcp/prompts/apm-attribute-breakdown.md b/products/tracing/mcp/prompts/apm-attribute-breakdown.mdindex d2412f98cff4..765d2a966869 100644--- a/products/tracing/mcp/prompts/apm-attribute-breakdown.md+++ b/products/tracing/mcp/prompts/apm-attribute-breakdown.md@@ -1,5 +1,11 @@Group spans by one attribute's value — the "what is different about the bad spans?" tool.+All parameters go inside `query` — top-level fields are rejected:++```json+{ "query": { "breakdownKey": "server.address", "breakdownType": "span_attribute" } }+```+Returns one row per distinct value of the chosen attribute, across the spans matching the filters:- `value` — the attribute's value (`''` for spans that don't carry the attribute)@@ -18,8 +24,6 @@ Use to answer:For aggregates grouped by operation, use `apm-spans-aggregate`. For trends over time, use `apm-spans-sparkline`.-All parameters must be nested inside a `query` object.-# "What's different" workflow1. Scope to the bad spans with `filterGroup` (e.g. `status_code = Error`) or `serviceNames`.@@ -29,8 +33,6 @@ All parameters must be nested inside a `query` object.# Parameters-All parameters go inside `query`.-## query.breakdownKey (required)The attribute key to group by (e.g. `server.address`, `http.response.status_code`, `k8s.pod.name`). Discover keys with `apm-attributes-list`.diff --git a/products/tracing/mcp/prompts/apm-spans-aggregate.md b/products/tracing/mcp/prompts/apm-spans-aggregate.mdindex 878f11fb898b..c90882d03493 100644--- a/products/tracing/mcp/prompts/apm-spans-aggregate.md+++ b/products/tracing/mcp/prompts/apm-spans-aggregate.md@@ -1,5 +1,11 @@Aggregate trace span statistics grouped by `(service_name, name)` over a date window.+All parameters go inside `query` — top-level fields are rejected:++```json+{ "query": { "serviceNames": ["api"], "dateRange": { "date_from": "-1h" } } }+```+Returns one row per `(service_name, name)` pair with the following metrics:- `count` — number of spans matched@@ -17,8 +23,6 @@ Use to answer:For per-call-tree breakdowns (parent → child relationships), use `apm-spans-tree` instead. For time-bucketed trends ("when did it change?"), use `apm-spans-sparkline` instead — `compareFilter` only contrasts two static windows.-All parameters must be nested inside a `query` object.-# Comparison windowSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.@@ -54,8 +58,6 @@ Use `query.dateRange` to control the time window. Default is the last hour (`-1h# Parameters-All parameters go inside `query`.-## query.dateRangeDate range for the primary window. Defaults to the last hour.diff --git a/products/tracing/mcp/prompts/apm-spans-count.md b/products/tracing/mcp/prompts/apm-spans-count.mdindex 88ea77bd75f4..1f39d0c385e0 100644--- a/products/tracing/mcp/prompts/apm-spans-count.md+++ b/products/tracing/mcp/prompts/apm-spans-count.md@@ -1,6 +1,10 @@Return a scalar count of trace spans matching a filter set. Use this as a cheap pre-flight before `query-apm-spans` — if the count is large, narrow the filters (or set `excludeAttributes`) before pulling rows.-All parameters must be nested inside a `query` object.+All parameters go inside `query` — top-level fields are rejected:++```json+{ "query": { "serviceNames": ["api"], "dateRange": { "date_from": "-1h" } } }+```# When to use@@ -14,8 +18,6 @@ If the count would scan too much data (a wide date range with no filters), the t# Parameters-All parameters go inside `query`.-## query.dateRangeDate range for the count. Defaults to the last hour (`-1h`).diff --git a/products/tracing/mcp/prompts/apm-spans-duration-histogram.md b/products/tracing/mcp/prompts/apm-spans-duration-histogram.mdindex 23fb0960691d..6a8db84da836 100644--- a/products/tracing/mcp/prompts/apm-spans-duration-histogram.md+++ b/products/tracing/mcp/prompts/apm-spans-duration-histogram.md@@ -1,5 +1,11 @@Trace counts per logarithmic duration bucket — the latency distribution of requests.+All parameters go inside `query` — top-level fields are rejected:++```json+{ "query": { "serviceNames": ["api"], "dateRange": { "date_from": "-1h" } } }+```+Returns one row per `(duration bucket, service)` pair:- `bucket_ns` — bucket floor in nanoseconds, on the 1-2-5 series (1ms, 2ms, 5ms, 10ms, 20ms, ...)@@ -17,12 +23,8 @@ Use to answer:For percentiles per operation (p50/p95), use `apm-spans-aggregate`. For counts over time, use `apm-spans-sparkline`.-All parameters must be nested inside a `query` object.-# Parameters-All parameters go inside `query`.-## query.dateRangeDate range. Defaults to the last hour.diff --git a/products/tracing/mcp/prompts/apm-spans-latency-heatmap.md b/products/tracing/mcp/prompts/apm-spans-latency-heatmap.mdindex d3794151edfb..5723264cc76b 100644--- a/products/tracing/mcp/prompts/apm-spans-latency-heatmap.md+++ b/products/tracing/mcp/prompts/apm-spans-latency-heatmap.md@@ -1,5 +1,11 @@Latency over time — trace counts per (time bucket, duration bucket) cell, combining `apm-spans-sparkline` and `apm-spans-duration-histogram` into one call: "when did latency change, and how".+All parameters go inside `query` — top-level fields are rejected:++```json+{ "query": { "serviceNames": ["api"], "dateRange": { "date_from": "-1h" } } }+```+Returns one row per non-empty `(time bucket, duration bucket)` cell:- `time` — ISO 8601 bucket start (UTC)@@ -17,8 +23,6 @@ Use to answer:For a single distribution with per-service breakdown, use `apm-spans-duration-histogram`; for counts over time, `apm-spans-sparkline`; for per-operation percentiles, `apm-spans-aggregate`.-All parameters must be nested inside a `query` object.-# Reading the gridGroup rows by `bucket_ns` and read each duration bucket as a horizontal band over time:@@ -29,8 +33,6 @@ Group rows by `bucket_ns` and read each duration bucket as a horizontal band ove# Parameters-All parameters go inside `query`.-## query.dateRangeDate range for the grid. Defaults to the last hour.diff --git a/products/tracing/mcp/prompts/apm-spans-sparkline.md b/products/tracing/mcp/prompts/apm-spans-sparkline.mdindex b4b655de1b62..07e816d9a8a3 100644--- a/products/tracing/mcp/prompts/apm-spans-sparkline.md+++ b/products/tracing/mcp/prompts/apm-spans-sparkline.md@@ -1,5 +1,11 @@Span counts over time — a zero-filled time series for trend and spike analysis.+All parameters go inside `query` — top-level fields are rejected:++```json+{ "query": { "serviceNames": ["api"], "dateRange": { "date_from": "-1h" } } }+```+Returns one row per `(time bucket, service)` pair:- `time` — ISO 8601 bucket start (UTC)@@ -17,8 +23,6 @@ Use to answer:For a single aggregate number per operation, use `apm-spans-aggregate` instead. For latency distribution, use `apm-spans-duration-histogram`.-All parameters must be nested inside a `query` object.-# Error-trend workflowTwo calls, then divide per bucket:@@ -30,8 +34,6 @@ Error rate per bucket = errors / total. The bucket where the ratio jumps is when# Parameters-All parameters go inside `query`.-## query.dateRangeDate range for the series. Defaults to the last hour.diff --git a/products/tracing/mcp/prompts/apm-spans-tree.md b/products/tracing/mcp/prompts/apm-spans-tree.mdindex 66719c5c4ffa..6804a13bb9ce 100644--- a/products/tracing/mcp/prompts/apm-spans-tree.md+++ b/products/tracing/mcp/prompts/apm-spans-tree.md@@ -1,5 +1,11 @@Aggregate trace span statistics as a call tree — one row per `(parent_service, parent_name) → (service_name, name)` edge.+All parameters go inside `query` — top-level fields are rejected:++```json+{ "query": { "spanName": "GET /checkout", "serviceName": "api", "dateRange": { "date_from": "-1h" } } }+```+Requires a `spanName` to bound the matched trace set (the `(trace_id, parent_span_id)` self-join is unsafe at high cardinality without it), and a `serviceName` to scope the returned tree to a single service. All traces that contain at least one span with the given name in the given service are included, and every span in those traces from that service is aggregated against its parent.Returns rows with:@@ -23,8 +29,6 @@ Use to answer:For a flat per-operation view (no parent linkage), use `apm-spans-aggregate` instead.-All parameters must be nested inside a `query` object.-# Comparison windowSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.@@ -50,8 +54,6 @@ Use `query.dateRange` to control the time window. Default is the last hour (`-1h# Parameters-All parameters go inside `query`.-## query.spanName (required)The span name that anchors the matched trace set. Every trace containing at least one span with this name (in the given `serviceName`) is included.diff --git a/products/tracing/mcp/prompts/query-apm-spans.md b/products/tracing/mcp/prompts/query-apm-spans.mdindex 9d015d9b9ad1..ba16dc933218 100644--- a/products/tracing/mcp/prompts/query-apm-spans.md+++ b/products/tracing/mcp/prompts/query-apm-spans.md@@ -1,5 +1,11 @@Query trace spans with filtering by service name, status code, date range, and structured attribute filters. Supports cursor-based pagination. Returns spans with uuid, trace_id, span_id, parent_span_id, name, kind, service_name, status_code, timestamp, end_time, duration_nano, is_root_span, matched_filter, and attributes (the span-level OTel attribute map, e.g. db.statement, http.url).+All parameters go inside `query` — top-level fields are rejected:++```json+{ "query": { "serviceNames": ["api"], "dateRange": { "date_from": "-1h" } } }+```+Use 'apm-attributes-list' and 'apm-attribute-values-list' to discover available attributes before building filters. Use 'apm-services-list' to discover available services.# Return shape@@ -13,8 +19,6 @@ To collapse each matching trace to a **single row — its root span**, set `rootCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.-All parameters must be nested inside a `query` object.-# Data narrowing## Property filters@@ -45,8 +49,6 @@ Use the `query.dateRange` field to control the time window. If the question does# Parameters-All parameters go inside `query`.-## query.serviceNamesFilter by service names. Use `apm-services-list` to discover available services.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 10df7d49833d..bb32558142a5 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -798,7 +798,7 @@"feature_flag": "customer-analytics-csp"},"apm-attribute-breakdown": {- "description": "Group spans by one attribute's value — the \"what is different about the bad spans?\" tool.\n\nReturns one row per distinct value of the chosen attribute, across the spans matching the filters:\n\n- `value` — the attribute's value (`''` for spans that don't carry the attribute)\n- `count` — spans with that value\n- `error_count` — of those, spans with OTel status `Error` (status_code = 2)\n- `p50_duration_nano`, `p95_duration_nano` — duration quantiles in nanoseconds\n\nRows are ordered by `count` DESC (or `error_count` DESC via `orderBy`) and capped at 5000.\n\nUse to answer:\n\n- \"Which attribute values are over-represented among the errored/slow spans?\"\n- \"Which downstream destination (`server.address`) is failing?\"\n- \"What `http.response.status_code` values are we getting back, and how often?\"\n- \"Which pod / version / region is the bad traffic concentrated on?\" (resource attributes)\n\nFor aggregates grouped by operation, use `apm-spans-aggregate`. For trends over time, use `apm-spans-sparkline`.\n\nAll parameters must be nested inside a `query` object.\n\n# \"What's different\" workflow\n\n1. Scope to the bad spans with `filterGroup` (e.g. `status_code = Error`) or `serviceNames`.\n2. Discover candidate keys with `apm-attributes-list` (don't guess — keys vary per project).\n3. Run `apm-attribute-breakdown` per candidate key. A value owning most of the `count` is your signature.\n4. To confirm over-representation, re-run without the bad-spans filter (or check `error_count / count` per row): a value at 95% of errors but 10% of all traffic is the smoking gun.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.breakdownKey (required)\n\nThe attribute key to group by (e.g. `server.address`, `http.response.status_code`, `k8s.pod.name`). Discover keys with `apm-attributes-list`.\n\n## query.breakdownType (required)\n\n- `span_attribute` — span-level attributes (e.g. `server.address`, `db.statement`)\n- `span_resource_attribute` — resource-level attributes (e.g. `k8s.pod.name`, `service.version`)\n\n## query.orderBy\n\n`count` (default) or `error_count` — rows are sorted by the chosen column, descending.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Set `compare: true` to also get the breakdown for a previous window under `compare` — useful for \"did this value's share change vs last week?\" (`compare_to: \"-7d\"`).\n\n## query.serviceNames\n\nList of service names to restrict the breakdown to. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters scoping the spans the breakdown runs over. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Which destinations do the errored spans hit?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"server.address\",\n \"breakdownType\": \"span_attribute\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": \"Error\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Which values drive the most errors overall?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"http.response.status_code\",\n \"breakdownType\": \"span_attribute\",\n \"orderBy\": \"error_count\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Is the bad pod's share new? (compare vs last week)\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"k8s.pod.name\",\n \"breakdownType\": \"span_resource_attribute\",\n \"serviceNames\": [\"cdp-worker\"],\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n# Reminders\n\n- `value: ''` groups the spans that don't carry the attribute at all — often itself a signal.\n- Duration values are in nanoseconds (1s = 1,000,000,000).\n- Use `apm-attributes-list` / `apm-attribute-values-list` to discover keys before guessing.\n- `error_count / count` per row is the error rate for that value — compute it when judging over-representation.",+ "description": "Group spans by one attribute's value — the \"what is different about the bad spans?\" tool.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"breakdownKey\": \"server.address\", \"breakdownType\": \"span_attribute\" } }\n```\n\nReturns one row per distinct value of the chosen attribute, across the spans matching the filters:\n\n- `value` — the attribute's value (`''` for spans that don't carry the attribute)\n- `count` — spans with that value\n- `error_count` — of those, spans with OTel status `Error` (status_code = 2)\n- `p50_duration_nano`, `p95_duration_nano` — duration quantiles in nanoseconds\n\nRows are ordered by `count` DESC (or `error_count` DESC via `orderBy`) and capped at 5000.\n\nUse to answer:\n\n- \"Which attribute values are over-represented among the errored/slow spans?\"\n- \"Which downstream destination (`server.address`) is failing?\"\n- \"What `http.response.status_code` values are we getting back, and how often?\"\n- \"Which pod / version / region is the bad traffic concentrated on?\" (resource attributes)\n\nFor aggregates grouped by operation, use `apm-spans-aggregate`. For trends over time, use `apm-spans-sparkline`.\n\n# \"What's different\" workflow\n\n1. Scope to the bad spans with `filterGroup` (e.g. `status_code = Error`) or `serviceNames`.\n2. Discover candidate keys with `apm-attributes-list` (don't guess — keys vary per project).\n3. Run `apm-attribute-breakdown` per candidate key. A value owning most of the `count` is your signature.\n4. To confirm over-representation, re-run without the bad-spans filter (or check `error_count / count` per row): a value at 95% of errors but 10% of all traffic is the smoking gun.\n\n# Parameters\n\n## query.breakdownKey (required)\n\nThe attribute key to group by (e.g. `server.address`, `http.response.status_code`, `k8s.pod.name`). Discover keys with `apm-attributes-list`.\n\n## query.breakdownType (required)\n\n- `span_attribute` — span-level attributes (e.g. `server.address`, `db.statement`)\n- `span_resource_attribute` — resource-level attributes (e.g. `k8s.pod.name`, `service.version`)\n\n## query.orderBy\n\n`count` (default) or `error_count` — rows are sorted by the chosen column, descending.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Set `compare: true` to also get the breakdown for a previous window under `compare` — useful for \"did this value's share change vs last week?\" (`compare_to: \"-7d\"`).\n\n## query.serviceNames\n\nList of service names to restrict the breakdown to. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters scoping the spans the breakdown runs over. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Which destinations do the errored spans hit?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"server.address\",\n \"breakdownType\": \"span_attribute\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": \"Error\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Which values drive the most errors overall?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"http.response.status_code\",\n \"breakdownType\": \"span_attribute\",\n \"orderBy\": \"error_count\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Is the bad pod's share new? (compare vs last week)\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"k8s.pod.name\",\n \"breakdownType\": \"span_resource_attribute\",\n \"serviceNames\": [\"cdp-worker\"],\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n# Reminders\n\n- `value: ''` groups the spans that don't carry the attribute at all — often itself a signal.\n- Duration values are in nanoseconds (1s = 1,000,000,000).\n- Use `apm-attributes-list` / `apm-attribute-values-list` to discover keys before guessing.\n- `error_count / count` per row is the error rate for that value — compute it when judging over-representation.","category": "Tracing","feature": "tracing","summary": "Break down spans by attribute value",@@ -858,7 +858,7 @@"feature_flag": "tracing"},"apm-spans-aggregate": {- "description": "Aggregate trace span statistics grouped by `(service_name, name)` over a date window.\n\nReturns one row per `(service_name, name)` pair with the following metrics:\n\n- `count` — number of spans matched\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (1 second = 1,000,000,000 ns). `p999_duration_nano` is the 99.9th percentile and is only meaningful for `(service, name)` groups with enough spans; on low-volume operations it collapses to the max\n- `error_count` — spans with OTel status code `Error` (status_code = 2)\n\nRows are ordered by `total_duration_nano` DESC. By default only the top 100 rows are returned — this keeps the response small, which matters because high span-name cardinality (e.g. untemplated URL paths) can otherwise produce an enormous payload. The top rows already surface the heaviest operations. When more rows genuinely exist the response sets `has_more: true` and `next_offset`; page through with `offset`, or raise `limit` (hard max 5000). Prefer narrowing with `serviceNames`/`filterGroup` over pulling a large page.\n\nUse to answer:\n\n- \"Which services/operations consume the most time?\"\n- \"What's the p95 or p99 latency of `GET /users`?\"\n- \"How many errors did the checkout service emit in the last day?\"\n- \"Did `POST /orders` get slower this week vs last week?\" (with `compareFilter`)\n\nFor per-call-tree breakdowns (parent → child relationships), use `apm-spans-tree` instead. For time-bucketed trends (\"when did it change?\"), use `apm-spans-sparkline` instead — `compareFilter` only contrasts two static windows.\n\nAll parameters must be nested inside a `query` object.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length (e.g. `dateRange: -1d` → compares vs the day before).\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\nWhen `compare` is true, `compare` is always an array — empty (`[]`) if the comparison window matched no spans (for example an operation that didn't exist yet), not null. `compare` is `null` only when no comparison was requested. So an empty array is a real answer (\"nothing in the prior window\"), not a failure.\n\n# Data narrowing\n\n## Property filters\n\nUse `query.filterGroup` to narrow results to spans matching specific attributes. Only include filters that are essential to the user's question.\n\nFilter `type` values:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes (e.g. \"http.method\", \"http.status_code\")\n- `span_resource_attribute` — resource-level attributes (e.g. k8s labels, deployment info)\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values before guessing.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`). Examples: `-1h`, `-6h`, `-1d`, `-7d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Omit when you only need the primary window.\n\n- `compare` (boolean): set to true to enable comparison.\n- `compare_to` (string, optional): relative offset for the comparison window (e.g. `-1d`, `-7d`). Defaults to the immediately previous period of equal length.\n\n## query.serviceNames\n\nList of service names to restrict the aggregation to. Use `apm-services-list` to discover available services.\n\n## query.filterGroup\n\nA flat list of property filters applied to both the primary and comparison windows. See the \"Property filters\" section.\n\n## query.limit\n\nMax rows to return, ordered by `total_duration_nano` DESC. Defaults to 100; hard max 5000. Keep this small — a high value on high-cardinality span names returns a very large response. Narrow with `serviceNames`/`filterGroup` instead of raising it when you can.\n\n## query.offset\n\nRow offset for pagination. Combine with `limit` and the `next_offset` from a previous response to page through results beyond the first page.\n\n# Examples\n\n## Top operations by total time in the last hour\n\n```json\n{\n \"query\": {}\n}\n```\n\n## p95 latency by operation in the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nInspect the `p95_duration_nano` field on each result.\n\n## Compare this hour vs the previous hour\n\n```json\n{\n \"query\": {\n \"compareFilter\": { \"compare\": true }\n }\n}\n```\n\nReturns `results` for the last hour and `compare` for the hour before. Diff `total_duration_nano`, `avg_duration_nano`, etc. to find regressions.\n\n## Compare today vs same time last week\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Aggregate only error spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Aggregate within one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Duration values are in nanoseconds. Divide by 1,000,000 for ms, 1,000,000,000 for seconds.\n- Results are ordered by `total_duration_nano` DESC and default to the top 100 rows. Check `has_more`/`next_offset` to page; raise `limit` (max 5000) only when you truly need the long tail.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attribute keys/values before filtering.\n- Use `apm-services-list` to discover services before filtering by service name.\n- For parent → child breakdowns, use `apm-spans-tree` instead.",+ "description": "Aggregate trace span statistics grouped by `(service_name, name)` over a date window.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nReturns one row per `(service_name, name)` pair with the following metrics:\n\n- `count` — number of spans matched\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (1 second = 1,000,000,000 ns). `p999_duration_nano` is the 99.9th percentile and is only meaningful for `(service, name)` groups with enough spans; on low-volume operations it collapses to the max\n- `error_count` — spans with OTel status code `Error` (status_code = 2)\n\nRows are ordered by `total_duration_nano` DESC. By default only the top 100 rows are returned — this keeps the response small, which matters because high span-name cardinality (e.g. untemplated URL paths) can otherwise produce an enormous payload. The top rows already surface the heaviest operations. When more rows genuinely exist the response sets `has_more: true` and `next_offset`; page through with `offset`, or raise `limit` (hard max 5000). Prefer narrowing with `serviceNames`/`filterGroup` over pulling a large page.\n\nUse to answer:\n\n- \"Which services/operations consume the most time?\"\n- \"What's the p95 or p99 latency of `GET /users`?\"\n- \"How many errors did the checkout service emit in the last day?\"\n- \"Did `POST /orders` get slower this week vs last week?\" (with `compareFilter`)\n\nFor per-call-tree breakdowns (parent → child relationships), use `apm-spans-tree` instead. For time-bucketed trends (\"when did it change?\"), use `apm-spans-sparkline` instead — `compareFilter` only contrasts two static windows.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length (e.g. `dateRange: -1d` → compares vs the day before).\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\nWhen `compare` is true, `compare` is always an array — empty (`[]`) if the comparison window matched no spans (for example an operation that didn't exist yet), not null. `compare` is `null` only when no comparison was requested. So an empty array is a real answer (\"nothing in the prior window\"), not a failure.\n\n# Data narrowing\n\n## Property filters\n\nUse `query.filterGroup` to narrow results to spans matching specific attributes. Only include filters that are essential to the user's question.\n\nFilter `type` values:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes (e.g. \"http.method\", \"http.status_code\")\n- `span_resource_attribute` — resource-level attributes (e.g. k8s labels, deployment info)\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values before guessing.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`). Examples: `-1h`, `-6h`, `-1d`, `-7d`.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Omit when you only need the primary window.\n\n- `compare` (boolean): set to true to enable comparison.\n- `compare_to` (string, optional): relative offset for the comparison window (e.g. `-1d`, `-7d`). Defaults to the immediately previous period of equal length.\n\n## query.serviceNames\n\nList of service names to restrict the aggregation to. Use `apm-services-list` to discover available services.\n\n## query.filterGroup\n\nA flat list of property filters applied to both the primary and comparison windows. See the \"Property filters\" section.\n\n## query.limit\n\nMax rows to return, ordered by `total_duration_nano` DESC. Defaults to 100; hard max 5000. Keep this small — a high value on high-cardinality span names returns a very large response. Narrow with `serviceNames`/`filterGroup` instead of raising it when you can.\n\n## query.offset\n\nRow offset for pagination. Combine with `limit` and the `next_offset` from a previous response to page through results beyond the first page.\n\n# Examples\n\n## Top operations by total time in the last hour\n\n```json\n{\n \"query\": {}\n}\n```\n\n## p95 latency by operation in the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nInspect the `p95_duration_nano` field on each result.\n\n## Compare this hour vs the previous hour\n\n```json\n{\n \"query\": {\n \"compareFilter\": { \"compare\": true }\n }\n}\n```\n\nReturns `results` for the last hour and `compare` for the hour before. Diff `total_duration_nano`, `avg_duration_nano`, etc. to find regressions.\n\n## Compare today vs same time last week\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Aggregate only error spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Aggregate within one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Duration values are in nanoseconds. Divide by 1,000,000 for ms, 1,000,000,000 for seconds.\n- Results are ordered by `total_duration_nano` DESC and default to the top 100 rows. Check `has_more`/`next_offset` to page; raise `limit` (max 5000) only when you truly need the long tail.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attribute keys/values before filtering.\n- Use `apm-services-list` to discover services before filtering by service name.\n- For parent → child breakdowns, use `apm-spans-tree` instead.","category": "Tracing","feature": "tracing","summary": "Aggregate span statistics",@@ -873,7 +873,7 @@"feature_flag": "tracing"},"apm-spans-count": {- "description": "Return a scalar count of trace spans matching a filter set. Use this as a cheap pre-flight before `query-apm-spans` — if the count is large, narrow the filters (or set `excludeAttributes`) before pulling rows.\n\nAll parameters must be nested inside a `query` object.\n\n# When to use\n\n- Before `query-apm-spans`, to confirm the filter set returns a tractable number of spans rather than pulling rows blind.\n- When the user asks \"how many X spans are there?\" and you don't need to see individual spans.\n- To check whether a filter combination matches anything at all before committing to a full query.\n\nThis counts **spans**, not traces. A single trace contains many spans, so a count of matching spans will exceed the number of matching traces.\n\nIf the count would scan too much data (a wide date range with no filters), the tool returns a 400 asking you to narrow the window or add filters — narrow the `dateRange` or add `serviceNames` / `statusCodes` / `filterGroup`, then retry.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range for the count. 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`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nFilter by service names. Unlike `query-apm-spans`, an unfiltered count is cheap and useful for sizing up a filter before narrowing. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.filterGroup\n\nProperty filters to narrow the count. Same format as `query-apm-spans` filters — each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`.\n\n# Examples\n\n## Count error spans in a service over the last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"statusCodes\": [2],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Count how many spans match a name before fetching them\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"name\", \"operator\": \"exact\", \"type\": \"span\", \"value\": \"redis_cluster.discovery\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```",+ "description": "Return a scalar count of trace spans matching a filter set. Use this as a cheap pre-flight before `query-apm-spans` — if the count is large, narrow the filters (or set `excludeAttributes`) before pulling rows.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\n# When to use\n\n- Before `query-apm-spans`, to confirm the filter set returns a tractable number of spans rather than pulling rows blind.\n- When the user asks \"how many X spans are there?\" and you don't need to see individual spans.\n- To check whether a filter combination matches anything at all before committing to a full query.\n\nThis counts **spans**, not traces. A single trace contains many spans, so a count of matching spans will exceed the number of matching traces.\n\nIf the count would scan too much data (a wide date range with no filters), the tool returns a 400 asking you to narrow the window or add filters — narrow the `dateRange` or add `serviceNames` / `statusCodes` / `filterGroup`, then retry.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the count. 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`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nFilter by service names. Unlike `query-apm-spans`, an unfiltered count is cheap and useful for sizing up a filter before narrowing. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.filterGroup\n\nProperty filters to narrow the count. Same format as `query-apm-spans` filters — each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`.\n\n# Examples\n\n## Count error spans in a service over the last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"statusCodes\": [2],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Count how many spans match a name before fetching them\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"name\", \"operator\": \"exact\", \"type\": \"span\", \"value\": \"redis_cluster.discovery\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```","category": "Tracing","feature": "tracing","summary": "Count spans",@@ -888,7 +888,7 @@"feature_flag": "tracing"},"apm-spans-duration-histogram": {- "description": "Trace counts per logarithmic duration bucket — the latency distribution of requests.\n\nReturns one row per `(duration bucket, service)` pair:\n\n- `bucket_ns` — bucket floor in nanoseconds, on the 1-2-5 series (1ms, 2ms, 5ms, 10ms, 20ms, ...)\n- `service` — service name (top 10 services per bucket)\n- `count` — traces whose ROOT span duration falls in the bucket\n\nBuckets count **traces by their root span's duration** (the request the user experienced), never child spans. Only non-empty buckets are returned.\n\nUse to answer:\n\n- \"What does the latency distribution look like — one population or bimodal?\"\n- \"How many requests took longer than 1 second?\"\n- \"Is the long tail a handful of outliers or a real second mode?\"\n- \"Which duration range should I filter on before pulling slow traces?\"\n\nFor percentiles per operation (p50/p95), use `apm-spans-aggregate`. For counts over time, use `apm-spans-sparkline`.\n\nAll parameters must be nested inside a `query` object.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nList of service names to restrict the histogram to. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.filterGroup\n\nProperty filters applied to the matched spans. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Latency distribution for one service over the last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Distribution of error traces only\n\n```json\n{\n \"query\": {\n \"statusCodes\": [2],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n# Reminders\n\n- `bucket_ns` is nanoseconds: 1ms = 1,000,000; 1s = 1,000,000,000.\n- Counts are **traces** (one per root span), so they line up with request counts — not with `apm-spans-count`, which counts every span.\n- Buckets follow the 1-2-5 series; a trace of 3.5ms lands in the 2ms bucket (bucket floor).\n- To fetch the actual slow traces after spotting a tail, use `query-apm-spans` with a `duration` filter (nanoseconds) and `orderBy: \"duration\"`.",+ "description": "Trace counts per logarithmic duration bucket — the latency distribution of requests.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nReturns one row per `(duration bucket, service)` pair:\n\n- `bucket_ns` — bucket floor in nanoseconds, on the 1-2-5 series (1ms, 2ms, 5ms, 10ms, 20ms, ...)\n- `service` — service name (top 10 services per bucket)\n- `count` — traces whose ROOT span duration falls in the bucket\n\nBuckets count **traces by their root span's duration** (the request the user experienced), never child spans. Only non-empty buckets are returned.\n\nUse to answer:\n\n- \"What does the latency distribution look like — one population or bimodal?\"\n- \"How many requests took longer than 1 second?\"\n- \"Is the long tail a handful of outliers or a real second mode?\"\n- \"Which duration range should I filter on before pulling slow traces?\"\n\nFor percentiles per operation (p50/p95), use `apm-spans-aggregate`. For counts over time, use `apm-spans-sparkline`.\n\n# Parameters\n\n## query.dateRange\n\nDate range. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nList of service names to restrict the histogram to. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.filterGroup\n\nProperty filters applied to the matched spans. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Latency distribution for one service over the last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Distribution of error traces only\n\n```json\n{\n \"query\": {\n \"statusCodes\": [2],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n# Reminders\n\n- `bucket_ns` is nanoseconds: 1ms = 1,000,000; 1s = 1,000,000,000.\n- Counts are **traces** (one per root span), so they line up with request counts — not with `apm-spans-count`, which counts every span.\n- Buckets follow the 1-2-5 series; a trace of 3.5ms lands in the 2ms bucket (bucket floor).\n- To fetch the actual slow traces after spotting a tail, use `query-apm-spans` with a `duration` filter (nanoseconds) and `orderBy: \"duration\"`.","category": "Tracing","feature": "tracing","summary": "Trace duration distribution (histogram)",@@ -903,7 +903,7 @@"feature_flag": "tracing"},"apm-spans-latency-heatmap": {- "description": "Latency over time — trace counts per (time bucket, duration bucket) cell, combining `apm-spans-sparkline` and `apm-spans-duration-histogram` into one call: \"when did latency change, and how\".\n\nReturns one row per non-empty `(time bucket, duration bucket)` cell:\n\n- `time` — ISO 8601 bucket start (UTC)\n- `bucket_ns` — duration bucket floor in nanoseconds, on the 1-2-5 series (1ms, 2ms, 5ms, 10ms, 20ms, ...)\n- `count` — traces whose ROOT span duration falls in that cell (or spans, when `rootSpans` is false)\n\nTime buckets are sized adaptively to the window (roughly 50 buckets regardless of range, e.g. `-1h` → ~minute buckets, `-7d` → ~4-hour buckets). A time bucket with no matching traces returns a single sentinel row `{time, bucket_ns: 0, count: 0}`, so the full time axis can be read off the response — ignore sentinel rows when reading densities.\n\nUse to answer:\n\n- \"When did this service get slow?\" — the slow band's first non-empty `time` is the onset.\n- \"Is the latency regression a shift (whole distribution moved) or a new mode (a second band appeared)?\"\n- \"Did the deploy at 14:00 change the latency profile, not just the p95?\"\n- \"Is the slow tail constant background or bursty?\"\n\nFor a single distribution with per-service breakdown, use `apm-spans-duration-histogram`; for counts over time, `apm-spans-sparkline`; for per-operation percentiles, `apm-spans-aggregate`.\n\nAll parameters must be nested inside a `query` object.\n\n# Reading the grid\n\nGroup rows by `bucket_ns` and read each duration bucket as a horizontal band over time:\n\n- A band that exists in every time bucket at similar counts = steady-state population.\n- A band that starts at a specific `time` = something changed then (deploy, dependency, cache).\n- The whole distribution stepping up one or two buckets at once = a uniform slowdown.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range for the grid. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nList of service names to restrict the grid to. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.rootSpans\n\nWhen true (default), cells count **traces by their root span's duration** — the request the user experienced, lining up with `apm-spans-duration-histogram`. Set false to count every matching span instead; combine with a `name` filter for one operation's latency over time.\n\n## query.filterGroup\n\nProperty filters applied to the counted spans. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## When did api-gateway get slow, over the last day?\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## One operation's latency over time (span-level, not per trace)\n\n```json\n{\n \"query\": {\n \"rootSpans\": false,\n \"filterGroup\": [{ \"key\": \"name\", \"operator\": \"exact\", \"type\": \"span\", \"value\": [\"SELECT orders\"] }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n# Reminders\n\n- `bucket_ns` is nanoseconds: 1ms = 1,000,000; 1s = 1,000,000,000. Buckets follow the 1-2-5 series; a 3.5ms trace lands in the 2ms bucket (bucket floor).\n- `{bucket_ns: 0, count: 0}` rows are the sentinel time-axis filler described above — skip them when reading densities.\n- Default counts are **traces** (one per root span); they line up with `apm-spans-duration-histogram`, not with `apm-spans-count`.\n- Cells carry no service breakdown — narrow with `serviceNames` instead.\n- After spotting when the slow band appeared, pull the actual traces with `query-apm-spans` filtered to that time window plus a `duration` filter (nanoseconds), `orderBy: \"duration\"`.",+ "description": "Latency over time — trace counts per (time bucket, duration bucket) cell, combining `apm-spans-sparkline` and `apm-spans-duration-histogram` into one call: \"when did latency change, and how\".\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nReturns one row per non-empty `(time bucket, duration bucket)` cell:\n\n- `time` — ISO 8601 bucket start (UTC)\n- `bucket_ns` — duration bucket floor in nanoseconds, on the 1-2-5 series (1ms, 2ms, 5ms, 10ms, 20ms, ...)\n- `count` — traces whose ROOT span duration falls in that cell (or spans, when `rootSpans` is false)\n\nTime buckets are sized adaptively to the window (roughly 50 buckets regardless of range, e.g. `-1h` → ~minute buckets, `-7d` → ~4-hour buckets). A time bucket with no matching traces returns a single sentinel row `{time, bucket_ns: 0, count: 0}`, so the full time axis can be read off the response — ignore sentinel rows when reading densities.\n\nUse to answer:\n\n- \"When did this service get slow?\" — the slow band's first non-empty `time` is the onset.\n- \"Is the latency regression a shift (whole distribution moved) or a new mode (a second band appeared)?\"\n- \"Did the deploy at 14:00 change the latency profile, not just the p95?\"\n- \"Is the slow tail constant background or bursty?\"\n\nFor a single distribution with per-service breakdown, use `apm-spans-duration-histogram`; for counts over time, `apm-spans-sparkline`; for per-operation percentiles, `apm-spans-aggregate`.\n\n# Reading the grid\n\nGroup rows by `bucket_ns` and read each duration bucket as a horizontal band over time:\n\n- A band that exists in every time bucket at similar counts = steady-state population.\n- A band that starts at a specific `time` = something changed then (deploy, dependency, cache).\n- The whole distribution stepping up one or two buckets at once = a uniform slowdown.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the grid. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nList of service names to restrict the grid to. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.rootSpans\n\nWhen true (default), cells count **traces by their root span's duration** — the request the user experienced, lining up with `apm-spans-duration-histogram`. Set false to count every matching span instead; combine with a `name` filter for one operation's latency over time.\n\n## query.filterGroup\n\nProperty filters applied to the counted spans. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## When did api-gateway get slow, over the last day?\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## One operation's latency over time (span-level, not per trace)\n\n```json\n{\n \"query\": {\n \"rootSpans\": false,\n \"filterGroup\": [{ \"key\": \"name\", \"operator\": \"exact\", \"type\": \"span\", \"value\": [\"SELECT orders\"] }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n# Reminders\n\n- `bucket_ns` is nanoseconds: 1ms = 1,000,000; 1s = 1,000,000,000. Buckets follow the 1-2-5 series; a 3.5ms trace lands in the 2ms bucket (bucket floor).\n- `{bucket_ns: 0, count: 0}` rows are the sentinel time-axis filler described above — skip them when reading densities.\n- Default counts are **traces** (one per root span); they line up with `apm-spans-duration-histogram`, not with `apm-spans-count`.\n- Cells carry no service breakdown — narrow with `serviceNames` instead.\n- After spotting when the slow band appeared, pull the actual traces with `query-apm-spans` filtered to that time window plus a `duration` filter (nanoseconds), `orderBy: \"duration\"`.","category": "Tracing","feature": "tracing","summary": "Latency over time (heatmap)",@@ -918,7 +918,7 @@"feature_flag": "tracing"},"apm-spans-sparkline": {- "description": "Span counts over time — a zero-filled time series for trend and spike analysis.\n\nReturns one row per `(time bucket, service)` pair:\n\n- `time` — ISO 8601 bucket start (UTC)\n- `service` — service name (top 10 services per bucket)\n- `count` — spans in that bucket matching the filters\n\nBuckets are sized adaptively to the window (roughly 50 buckets regardless of range, e.g. `-1h` → ~minute buckets, `-7d` → ~hour buckets). Quiet stretches return zero-count rows, so the series is continuous — read spike timing straight off the `time` values.\n\nUse to answer:\n\n- \"When did the error rate spike?\" (see the error-trend workflow below)\n- \"Is traffic to service X growing, flat, or bursty?\"\n- \"Did span volume change after the deploy at 14:00?\"\n- \"Which time window should I zoom into before pulling raw spans?\"\n\nFor a single aggregate number per operation, use `apm-spans-aggregate` instead. For latency distribution, use `apm-spans-duration-histogram`.\n\nAll parameters must be nested inside a `query` object.\n\n# Error-trend workflow\n\nTwo calls, then divide per bucket:\n\n1. `apm-spans-sparkline` with your filters → total counts per bucket.\n2. The same call with `statusCodes: [2]` added → error counts per bucket.\n\nError rate per bucket = errors / total. The bucket where the ratio jumps is when the spike started.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range for the series. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nList of service names to restrict the series to. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.filterGroup\n\nProperty filters applied to the counted spans. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Span volume per service over the last 6 hours\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Error spans only, one service, last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"statusCodes\": [2],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Request (root span) volume trend\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"is_root_span\", \"operator\": \"exact\", \"type\": \"span\", \"value\": true }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Counts are **spans**, not traces — filter `is_root_span = true` to count requests/traces.\n- Zero-count rows are bucket filler; read non-zero rows for activity and zero rows for gaps.\n- Only the top 10 services per bucket are returned — narrow with `serviceNames` when a busy project drowns out the service you care about.\n- Use `apm-services-list`, `apm-attributes-list`, `apm-attribute-values-list` to discover values before filtering.",+ "description": "Span counts over time — a zero-filled time series for trend and spike analysis.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nReturns one row per `(time bucket, service)` pair:\n\n- `time` — ISO 8601 bucket start (UTC)\n- `service` — service name (top 10 services per bucket)\n- `count` — spans in that bucket matching the filters\n\nBuckets are sized adaptively to the window (roughly 50 buckets regardless of range, e.g. `-1h` → ~minute buckets, `-7d` → ~hour buckets). Quiet stretches return zero-count rows, so the series is continuous — read spike timing straight off the `time` values.\n\nUse to answer:\n\n- \"When did the error rate spike?\" (see the error-trend workflow below)\n- \"Is traffic to service X growing, flat, or bursty?\"\n- \"Did span volume change after the deploy at 14:00?\"\n- \"Which time window should I zoom into before pulling raw spans?\"\n\nFor a single aggregate number per operation, use `apm-spans-aggregate` instead. For latency distribution, use `apm-spans-duration-histogram`.\n\n# Error-trend workflow\n\nTwo calls, then divide per bucket:\n\n1. `apm-spans-sparkline` with your filters → total counts per bucket.\n2. The same call with `statusCodes: [2]` added → error counts per bucket.\n\nError rate per bucket = errors / total. The bucket where the ratio jumps is when the spike started.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the series. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nList of service names to restrict the series to. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.filterGroup\n\nProperty filters applied to the counted spans. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Span volume per service over the last 6 hours\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Error spans only, one service, last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"statusCodes\": [2],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Request (root span) volume trend\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"is_root_span\", \"operator\": \"exact\", \"type\": \"span\", \"value\": true }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Counts are **spans**, not traces — filter `is_root_span = true` to count requests/traces.\n- Zero-count rows are bucket filler; read non-zero rows for activity and zero rows for gaps.\n- Only the top 10 services per bucket are returned — narrow with `serviceNames` when a busy project drowns out the service you care about.\n- Use `apm-services-list`, `apm-attributes-list`, `apm-attribute-values-list` to discover values before filtering.","category": "Tracing","feature": "tracing","summary": "Span counts over time (sparkline)",@@ -933,7 +933,7 @@"feature_flag": "tracing"},"apm-spans-tree": {- "description": "Aggregate trace span statistics as a call tree — one row per `(parent_service, parent_name) → (service_name, name)` edge.\n\nRequires a `spanName` to bound the matched trace set (the `(trace_id, parent_span_id)` self-join is unsafe at high cardinality without it), and a `serviceName` to scope the returned tree to a single service. All traces that contain at least one span with the given name in the given service are included, and every span in those traces from that service is aggregated against its parent.\n\nReturns rows with:\n\n- `parent_service`, `parent_name` — the parent span identity (`parent_name` is `\"<ROOT>\"` for root spans)\n- `service_name`, `name` — the child span identity\n- `count` — number of spans matched for this `(parent, child)` edge\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (`p999_duration_nano` is the 99.9th percentile; only meaningful for high-volume edges)\n- `error_count` — child spans with OTel status code `Error` (status_code = 2)\n- `avg_start_offset_nano` — average nanoseconds from the parent span's start to this child's start\n- `calls_per_parent_invocation` — how many times this child runs per parent invocation (null for root edges). A child can top `total_duration_nano` purely by fan-out volume; divide by this to compare per-call cost\n\nRows are ordered by `total_duration_nano` DESC and capped at 5000.\n\nUse to answer:\n\n- \"What does the `/checkout` flow actually call downstream?\"\n- \"Which child operation under `POST /orders` is the slowest?\"\n- \"Where is time spent inside `process_payment` — DB, external API, or something else?\"\n- \"Did the call tree under `/api/feed` change between last week and this week?\" (with `compareFilter`)\n\nFor a flat per-operation view (no parent linkage), use `apm-spans-aggregate` instead.\n\nAll parameters must be nested inside a `query` object.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length.\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\n# Data narrowing\n\n## Property filters\n\n`query.filterGroup` narrows the matched span set. Same filter shape and operators as `apm-spans-aggregate` / `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values.\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`).\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.spanName (required)\n\nThe span name that anchors the matched trace set. Every trace containing at least one span with this name (in the given `serviceName`) is included.\n\nPick a high-level entry-point span (e.g. an HTTP route or job name). Generic names (`HTTP`, `GET`) match too many traces and produce noisy aggregates. Use `query-apm-spans` first if you need to discover concrete span names.\n\n## query.serviceName (required)\n\nThe service the tree should be scoped to. Applied to the spans CTE so the returned rows only contain spans from this service, even when the matched traces also touch other services. Use `apm-services-list` to discover service names.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Same shape as in `apm-spans-aggregate`.\n\n## query.serviceNames\n\nList of service names to filter the matched span set. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters applied to both windows. See the \"Property filters\" section.\n\n# Examples\n\n## Call tree under a specific operation in the last hour\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\"\n }\n}\n```\n\n## Call tree over the last day\n\n```json\n{\n \"query\": {\n \"spanName\": \"checkout_flow\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Compare today's call tree vs last week\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Restrict to error-bearing traces\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }]\n }\n}\n```\n\n# Reminders\n\n- `spanName` and `serviceName` are both required. Bound `spanName` to a specific high-level span (avoid generic names like `HTTP`); set `serviceName` to the one service whose call-tree you want.\n- Root spans have `parent_name = \"<ROOT>\"` and `avg_start_offset_nano = 0`.\n- Duration values are in nanoseconds.\n- Results are ordered by `total_duration_nano` DESC and capped at 5000 rows.\n- `calls_per_parent_invocation` is derived from the returned rows. If results hit the 5000-row cap (only happens with very high span-name cardinality in one service), a parent's edges can be split across the cut and the ratio can read high — treat it as approximate when the row count is at the cap.\n- For a flat per-operation aggregate without parent linkage, use `apm-spans-aggregate`.\n- Use `apm-services-list`, `apm-attributes-list`, `apm-attribute-values-list` to discover values before filtering.",+ "description": "Aggregate trace span statistics as a call tree — one row per `(parent_service, parent_name) → (service_name, name)` edge.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"spanName\": \"GET /checkout\", \"serviceName\": \"api\", \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nRequires a `spanName` to bound the matched trace set (the `(trace_id, parent_span_id)` self-join is unsafe at high cardinality without it), and a `serviceName` to scope the returned tree to a single service. All traces that contain at least one span with the given name in the given service are included, and every span in those traces from that service is aggregated against its parent.\n\nReturns rows with:\n\n- `parent_service`, `parent_name` — the parent span identity (`parent_name` is `\"<ROOT>\"` for root spans)\n- `service_name`, `name` — the child span identity\n- `count` — number of spans matched for this `(parent, child)` edge\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (`p999_duration_nano` is the 99.9th percentile; only meaningful for high-volume edges)\n- `error_count` — child spans with OTel status code `Error` (status_code = 2)\n- `avg_start_offset_nano` — average nanoseconds from the parent span's start to this child's start\n- `calls_per_parent_invocation` — how many times this child runs per parent invocation (null for root edges). A child can top `total_duration_nano` purely by fan-out volume; divide by this to compare per-call cost\n\nRows are ordered by `total_duration_nano` DESC and capped at 5000.\n\nUse to answer:\n\n- \"What does the `/checkout` flow actually call downstream?\"\n- \"Which child operation under `POST /orders` is the slowest?\"\n- \"Where is time spent inside `process_payment` — DB, external API, or something else?\"\n- \"Did the call tree under `/api/feed` change between last week and this week?\" (with `compareFilter`)\n\nFor a flat per-operation view (no parent linkage), use `apm-spans-aggregate` instead.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length.\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\n# Data narrowing\n\n## Property filters\n\n`query.filterGroup` narrows the matched span set. Same filter shape and operators as `apm-spans-aggregate` / `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values.\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`).\n\n# Parameters\n\n## query.spanName (required)\n\nThe span name that anchors the matched trace set. Every trace containing at least one span with this name (in the given `serviceName`) is included.\n\nPick a high-level entry-point span (e.g. an HTTP route or job name). Generic names (`HTTP`, `GET`) match too many traces and produce noisy aggregates. Use `query-apm-spans` first if you need to discover concrete span names.\n\n## query.serviceName (required)\n\nThe service the tree should be scoped to. Applied to the spans CTE so the returned rows only contain spans from this service, even when the matched traces also touch other services. Use `apm-services-list` to discover service names.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Same shape as in `apm-spans-aggregate`.\n\n## query.serviceNames\n\nList of service names to filter the matched span set. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters applied to both windows. See the \"Property filters\" section.\n\n# Examples\n\n## Call tree under a specific operation in the last hour\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\"\n }\n}\n```\n\n## Call tree over the last day\n\n```json\n{\n \"query\": {\n \"spanName\": \"checkout_flow\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Compare today's call tree vs last week\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Restrict to error-bearing traces\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }]\n }\n}\n```\n\n# Reminders\n\n- `spanName` and `serviceName` are both required. Bound `spanName` to a specific high-level span (avoid generic names like `HTTP`); set `serviceName` to the one service whose call-tree you want.\n- Root spans have `parent_name = \"<ROOT>\"` and `avg_start_offset_nano = 0`.\n- Duration values are in nanoseconds.\n- Results are ordered by `total_duration_nano` DESC and capped at 5000 rows.\n- `calls_per_parent_invocation` is derived from the returned rows. If results hit the 5000-row cap (only happens with very high span-name cardinality in one service), a parent's edges can be split across the cut and the ratio can read high — treat it as approximate when the row count is at the cap.\n- For a flat per-operation aggregate without parent linkage, use `apm-spans-aggregate`.\n- Use `apm-services-list`, `apm-attributes-list`, `apm-attribute-values-list` to discover values before filtering.","category": "Tracing","feature": "tracing","summary": "Aggregate span call tree",@@ -1883,7 +1883,7 @@}},"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\nAll parameters go inside `query`:\n\n```json\n{ \"query\": { \"metricName\": \"m\", \"anomalyFrom\": \"2026-01-01T00:00:00Z\" } }\n```\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 -> histogram_quantile 0.95); 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.",+ "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\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"metricName\": \"m\", \"anomalyFrom\": \"2026-01-01T00:00:00Z\" } }\n```\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 -> histogram_quantile 0.95); 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.","category": "Metrics","feature": "metrics","summary": "Characterize metric anomaly",@@ -7505,7 +7505,7 @@}},"logs-count": {- "description": "Return a scalar count of log entries matching a filter set. Use this as a cheap pre-flight before `query-logs` — if the count exceeds `query-logs`'s max `limit` of 1000, narrow the filters before pulling rows.\n\nAll parameters must be nested inside a `query` object.\n\n# When to use\n\n- Before `query-logs`, to confirm the filter set returns a tractable number of rows. If the count is above `query-logs`'s max `limit` of 1000, narrow the filters.\n- When the user asks \"how many X logs are there?\" and you don't need to see individual rows.\n- To check whether a filter combination matches anything at all before committing to a full query.\n\nTo find **when** the volume is concentrated within the window (rather than just the total), follow up with `logs-count-ranges` — it returns time-bucketed counts with explicit `date_from`/`date_to` per bucket so you can drill into a sub-range without reasoning about interval width.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the count. 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. Unlike `query-logs`, this tool does NOT require `serviceNames` — an unfiltered count is cheap and often useful for sizing up a filter before narrowing.\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# Examples\n\n## Count errors in a service 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## Confirm a k8s namespace is producing logs at all\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1h\" },\n \"filterGroup\": [\n { \"key\": \"k8s.namespace.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"payments\" }\n ]\n }\n}\n```",+ "description": "Return a scalar count of log entries matching a filter set. Use this as a cheap pre-flight before `query-logs` — if the count exceeds `query-logs`'s max `limit` of 1000, narrow the filters before pulling rows.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\n# When to use\n\n- Before `query-logs`, to confirm the filter set returns a tractable number of rows. If the count is above `query-logs`'s max `limit` of 1000, narrow the filters.\n- When the user asks \"how many X logs are there?\" and you don't need to see individual rows.\n- To check whether a filter combination matches anything at all before committing to a full query.\n\nTo find **when** the volume is concentrated within the window (rather than just the total), follow up with `logs-count-ranges` — it returns time-bucketed counts with explicit `date_from`/`date_to` per bucket so you can drill into a sub-range without reasoning about interval width.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the count. 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. Unlike `query-logs`, this tool does NOT require `serviceNames` — an unfiltered count is cheap and often useful for sizing up a filter before narrowing.\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# Examples\n\n## Count errors in a service 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## Confirm a k8s namespace is producing logs at all\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1h\" },\n \"filterGroup\": [\n { \"key\": \"k8s.namespace.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"payments\" }\n ]\n }\n}\n```","category": "Logs","feature": "logs","summary": "Count logs",@@ -7519,7 +7519,7 @@}},"logs-count-ranges": {- "description": "Get adaptive-interval bucket counts for a filtered log stream. Returns a flat list of `{date_from, date_to, count}` buckets covering the requested window. Modeled on Elasticsearch's `auto_date_histogram` — caller specifies a target bucket count, the engine picks the interval.\n\nUse this to find **where the volume is concentrated** before pulling rows. Cheaper than `query-logs`, more agent-friendly than `logs-sparkline-query` (each bucket carries explicit `date_from`/`date_to` you can feed straight back as the next call's `dateRange` to drill in).\n\n# When to use this vs other tools\n\n- **`logs-count`** — total volume in a window. Scalar.\n- **`logs-count-ranges`** (this tool) — _when_ in the window the volume sits. Time-bucketed.\n- **`query-logs`** — pull individual log rows. Most expensive; only call after counts confirm the window is right-sized.\n\n# Recursion pattern (the main reason this tool exists)\n\nUse the response to narrow into a sub-range without reasoning about interval width:\n\n1. Call `logs-count-ranges` with the user's window (e.g. last 24h).\n2. Pick the bucket(s) of interest (densest, an obvious spike, an unexpectedly empty stretch).\n3. Call `logs-count-ranges` again with that bucket's `date_from` and `date_to` as the next `dateRange`.\n4. Repeat up to ~3–4 levels — stop when buckets are shorter than your precision goal (e.g. 1 minute).\n5. Once narrowed, call `query-logs` for the actual rows.\n\nThis is the same pattern Elasticsearch users follow with `auto_date_histogram`. Keep recursion shallow — every call is cheap individually but they multiply quickly.\n\n# Parameters\n\nAll parameters must be nested inside a `query` object.\n\n## query.dateRange\n\nWindow to bucket. Defaults to the last hour (`-1h`). Same format as `query-logs`.\n\n## query.targetBuckets\n\nApproximate bucket count. Defaults to **10**, max 100. The engine picks the interval adaptively from a fixed list (1/5/10s, 1/2/5/10/15/30/60/120/240/360/720/1440m) to land near this target — actual count may differ slightly. Empty buckets are dropped, so the response can have fewer rows than `targetBuckets`.\n\nPick a value based on what you're doing:\n\n- **10** (default) — overview, finding spikes, \"is this concentrated or spread out?\"\n- **20–30** — characterising a known busy window\n- **50+** — high-resolution drill-down, only when you know the window is small\n\n## query.severityLevels, query.serviceNames, query.searchTerm, query.filterGroup\n\nSame shape as `query-logs`. Applied **before** bucketing.\n\n# Response\n\n```json\n{\n \"ranges\": [\n { \"date_from\": \"2026-04-26T00:00:00Z\", \"date_to\": \"2026-04-26T02:24:00Z\", \"count\": 1024 },\n { \"date_from\": \"2026-04-26T02:24:00Z\", \"date_to\": \"2026-04-26T04:48:00Z\", \"count\": 47 }\n ],\n \"interval\": \"2h\"\n}\n```\n\n- `ranges` — buckets ordered by `date_from` ascending. **Empty buckets are omitted** — infer gaps by comparing each bucket's `date_to` to the next bucket's `date_from`.\n- `interval` — short-form duration of the chosen bucket width (`1s` / `5m` / `1h` / `1d`). Informational only — for follow-up queries, use the per-bucket `date_from`/`date_to`.\n\n# Examples\n\n## Find when errors spiked over the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"targetBuckets\": 24,\n \"serviceNames\": [\"api-gateway\"],\n \"severityLevels\": [\"error\", \"fatal\"]\n }\n}\n```\n\n## Drill into the densest hour from a previous call\n\nAfter picking the densest bucket from the response above (say `{date_from: \"2026-04-26T15:00:00Z\", date_to: \"2026-04-26T16:00:00Z\", count: 894}`):\n\n```json\n{\n \"query\": {\n \"dateRange\": {\n \"date_from\": \"2026-04-26T15:00:00Z\",\n \"date_to\": \"2026-04-26T16:00:00Z\"\n },\n \"targetBuckets\": 12,\n \"serviceNames\": [\"api-gateway\"],\n \"severityLevels\": [\"error\", \"fatal\"]\n }\n}\n```\n\n# Reminders\n\n- Cap recursion at ~3–4 levels. If your bucket width drops below your precision goal (e.g. 1 minute), stop and call `query-logs`.\n- Empty windows return `{\"ranges\": [], \"interval\": \"...\"}` — that's not an error, it's \"I asked, nothing matched.\"\n- Always include `serviceNames` or a resource attribute filter, just like `query-logs`. Don't bucket the entire team's log stream.",+ "description": "Get adaptive-interval bucket counts for a filtered log stream. Returns a flat list of `{date_from, date_to, count}` buckets covering the requested window. Modeled on Elasticsearch's `auto_date_histogram` — caller specifies a target bucket count, the engine picks the interval.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nUse this to find **where the volume is concentrated** before pulling rows. Cheaper than `query-logs`, more agent-friendly than `logs-sparkline-query` (each bucket carries explicit `date_from`/`date_to` you can feed straight back as the next call's `dateRange` to drill in).\n\n# When to use this vs other tools\n\n- **`logs-count`** — total volume in a window. Scalar.\n- **`logs-count-ranges`** (this tool) — _when_ in the window the volume sits. Time-bucketed.\n- **`query-logs`** — pull individual log rows. Most expensive; only call after counts confirm the window is right-sized.\n\n# Recursion pattern (the main reason this tool exists)\n\nUse the response to narrow into a sub-range without reasoning about interval width:\n\n1. Call `logs-count-ranges` with the user's window (e.g. last 24h).\n2. Pick the bucket(s) of interest (densest, an obvious spike, an unexpectedly empty stretch).\n3. Call `logs-count-ranges` again with that bucket's `date_from` and `date_to` as the next `dateRange`.\n4. Repeat up to ~3–4 levels — stop when buckets are shorter than your precision goal (e.g. 1 minute).\n5. Once narrowed, call `query-logs` for the actual rows.\n\nThis is the same pattern Elasticsearch users follow with `auto_date_histogram`. Keep recursion shallow — every call is cheap individually but they multiply quickly.\n\n# Parameters\n\n## query.dateRange\n\nWindow to bucket. Defaults to the last hour (`-1h`). Same format as `query-logs`.\n\n## query.targetBuckets\n\nApproximate bucket count. Defaults to **10**, max 100. The engine picks the interval adaptively from a fixed list (1/5/10s, 1/2/5/10/15/30/60/120/240/360/720/1440m) to land near this target — actual count may differ slightly. Empty buckets are dropped, so the response can have fewer rows than `targetBuckets`.\n\nPick a value based on what you're doing:\n\n- **10** (default) — overview, finding spikes, \"is this concentrated or spread out?\"\n- **20–30** — characterising a known busy window\n- **50+** — high-resolution drill-down, only when you know the window is small\n\n## query.severityLevels, query.serviceNames, query.searchTerm, query.filterGroup\n\nSame shape as `query-logs`. Applied **before** bucketing.\n\n# Response\n\n```json\n{\n \"ranges\": [\n { \"date_from\": \"2026-04-26T00:00:00Z\", \"date_to\": \"2026-04-26T02:24:00Z\", \"count\": 1024 },\n { \"date_from\": \"2026-04-26T02:24:00Z\", \"date_to\": \"2026-04-26T04:48:00Z\", \"count\": 47 }\n ],\n \"interval\": \"2h\"\n}\n```\n\n- `ranges` — buckets ordered by `date_from` ascending. **Empty buckets are omitted** — infer gaps by comparing each bucket's `date_to` to the next bucket's `date_from`.\n- `interval` — short-form duration of the chosen bucket width (`1s` / `5m` / `1h` / `1d`). Informational only — for follow-up queries, use the per-bucket `date_from`/`date_to`.\n\n# Examples\n\n## Find when errors spiked over the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"targetBuckets\": 24,\n \"serviceNames\": [\"api-gateway\"],\n \"severityLevels\": [\"error\", \"fatal\"]\n }\n}\n```\n\n## Drill into the densest hour from a previous call\n\nAfter picking the densest bucket from the response above (say `{date_from: \"2026-04-26T15:00:00Z\", date_to: \"2026-04-26T16:00:00Z\", count: 894}`):\n\n```json\n{\n \"query\": {\n \"dateRange\": {\n \"date_from\": \"2026-04-26T15:00:00Z\",\n \"date_to\": \"2026-04-26T16:00:00Z\"\n },\n \"targetBuckets\": 12,\n \"serviceNames\": [\"api-gateway\"],\n \"severityLevels\": [\"error\", \"fatal\"]\n }\n}\n```\n\n# Reminders\n\n- Cap recursion at ~3–4 levels. If your bucket width drops below your precision goal (e.g. 1 minute), stop and call `query-logs`.\n- Empty windows return `{\"ranges\": [], \"interval\": \"...\"}` — that's not an error, it's \"I asked, nothing matched.\"\n- Always include `serviceNames` or a resource attribute filter, just like `query-logs`. Don't bucket the entire team's log stream.","category": "Logs","feature": "logs","summary": "Count logs by time bucket",@@ -7533,7 +7533,7 @@}},"logs-facet-values-create": {- "description": "Return per-value counts for a single facet — the distribution of a log dimension across a filter set, ordered by count descending. This is the cheap way to see the _shape_ of a log stream (e.g. \"which services produce the errors?\") without pulling raw rows.\n\nCounts are cross-filtered: every active filter is applied _except the faceted field's own filter_, so you see the full distribution rather than collapsing to your own selection. Faceting `service_name` with `serviceNames: [\"api\"]` still returns every service, not just `api`.\n\nAll parameters must be nested inside a `query` object. You must provide **exactly one** of `query.facetField` or `query.facetResourceAttribute` — not both, not neither.\n\n# When to use\n\n- To find how log volume is distributed across severity or service under a filter — e.g. \"of the logs matching 'timeout', which services emit them?\" Facet `service_name` with `searchTerm: \"timeout\"`.\n- As the drill-down loop for an investigation: facet `service_name` filtered to `severity=error` → find the hot service → add it to `serviceNames` → facet a resource attribute like `k8s.pod.name` → find the bad pod. Each call is one cheap aggregation that narrows the search space before you pull raw rows with `query-logs`.\n- To confirm the severity mix in a window before committing to a query: facet `severity_text`.\n\n## Pick the right tool\n\n- Counts for an arbitrary **attribute** value (any log or resource attribute key) → use `logs-attribute-values-list`. It returns `{value, count}` for any key and is the general-purpose choice for attributes.\n- Per-service log/error counts and error rates with a sparkline → use `logs-services-create`.\n- Use **this** tool for `severity_text` / `service_name` distribution cross-filtered by the full query (severity + body `searchTerm` + `filterGroup`) — the one thing the tools above can't do.\n\n# Parameters\n\n## query.facetField\n\nTop-level column to facet on: `severity_text` or `service_name`. Provide this OR `facetResourceAttribute`, not both. Counts are grouped on the raw logs table with all _other_ filters applied — so this path honors `severityLevels`, `serviceNames`, `searchTerm`, and `filterGroup`.\n\n## query.facetResourceAttribute\n\nResource attribute key to facet on, e.g. `k8s.namespace.name`, `k8s.pod.name`, `host.name`. Provide this OR `facetField`, not both.\n\n**Limitation:** this path is served from a pre-aggregated rollup that has no severity or body dimension. It honors only `serviceNames` and other resource-attribute filters — `severityLevels`, `searchTerm`, and log-attribute filters are **ignored**. If you need those applied, facet a column instead, or narrow with `logs-attribute-values-list`.\n\n## query.facetSearch\n\nCase-insensitive substring match over the faceted field's _own_ values (e.g. return only service names containing `kafka`). Distinct from `searchTerm`, which searches log bodies. Use it to search past the 100-value result cap.\n\n## query.dateRange\n\nDate range for the counts. Defaults to the last hour (`-1h`).\n\n- `date_from`: Start of the range. 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.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels. Ignored when faceting on `severity_text` (that field's own filter is excluded) and when faceting a resource attribute (rollup has no severity dimension).\n\n## query.serviceNames\n\nFilter by service names. Ignored when faceting on `service_name` (that field's own filter is excluded).\n\n## query.searchTerm\n\nFull-text search across log bodies. Ignored when faceting a resource attribute.\n\n## query.filterGroup\n\nProperty filters to narrow results. Same format as `query-logs` filters.\n\n# Examples\n\n## Severity distribution in the last hour\n\n```json\n{\n \"query\": {\n \"facetField\": \"severity_text\",\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Which services produce errors over the last day\n\n```json\n{\n \"query\": {\n \"facetField\": \"service_name\",\n \"severityLevels\": [\"error\", \"fatal\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Which pods a service's logs come from\n\n```json\n{\n \"query\": {\n \"facetResourceAttribute\": \"k8s.pod.name\",\n \"serviceNames\": [\"checkout\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Which services emit a specific error message\n\n```json\n{\n \"query\": {\n \"facetField\": \"service_name\",\n \"searchTerm\": \"connection reset\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```",+ "description": "Return per-value counts for a single facet — the distribution of a log dimension across a filter set, ordered by count descending. This is the cheap way to see the _shape_ of a log stream (e.g. \"which services produce the errors?\") without pulling raw rows.\n\nAll parameters go inside `query` — top-level fields are rejected. Provide **exactly one** of `query.facetField` or `query.facetResourceAttribute` — not both, not neither:\n\n```json\n{ \"query\": { \"facetField\": \"service_name\", \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nCounts are cross-filtered: every active filter is applied _except the faceted field's own filter_, so you see the full distribution rather than collapsing to your own selection. Faceting `service_name` with `serviceNames: [\"api\"]` still returns every service, not just `api`.\n\n# When to use\n\n- To find how log volume is distributed across severity or service under a filter — e.g. \"of the logs matching 'timeout', which services emit them?\" Facet `service_name` with `searchTerm: \"timeout\"`.\n- As the drill-down loop for an investigation: facet `service_name` filtered to `severity=error` → find the hot service → add it to `serviceNames` → facet a resource attribute like `k8s.pod.name` → find the bad pod. Each call is one cheap aggregation that narrows the search space before you pull raw rows with `query-logs`.\n- To confirm the severity mix in a window before committing to a query: facet `severity_text`.\n\n## Pick the right tool\n\n- Counts for an arbitrary **attribute** value (any log or resource attribute key) → use `logs-attribute-values-list`. It returns `{value, count}` for any key and is the general-purpose choice for attributes.\n- Per-service log/error counts and error rates with a sparkline → use `logs-services-create`.\n- Use **this** tool for `severity_text` / `service_name` distribution cross-filtered by the full query (severity + body `searchTerm` + `filterGroup`) — the one thing the tools above can't do.\n\n# Parameters\n\n## query.facetField\n\nTop-level column to facet on: `severity_text` or `service_name`. Provide this OR `facetResourceAttribute`, not both. Counts are grouped on the raw logs table with all _other_ filters applied — so this path honors `severityLevels`, `serviceNames`, `searchTerm`, and `filterGroup`.\n\n## query.facetResourceAttribute\n\nResource attribute key to facet on, e.g. `k8s.namespace.name`, `k8s.pod.name`, `host.name`. Provide this OR `facetField`, not both.\n\n**Limitation:** this path is served from a pre-aggregated rollup that has no severity or body dimension. It honors only `serviceNames` and other resource-attribute filters — `severityLevels`, `searchTerm`, and log-attribute filters are **ignored**. If you need those applied, facet a column instead, or narrow with `logs-attribute-values-list`.\n\n## query.facetSearch\n\nCase-insensitive substring match over the faceted field's _own_ values (e.g. return only service names containing `kafka`). Distinct from `searchTerm`, which searches log bodies. Use it to search past the 100-value result cap.\n\n## query.dateRange\n\nDate range for the counts. Defaults to the last hour (`-1h`).\n\n- `date_from`: Start of the range. 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.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels. Ignored when faceting on `severity_text` (that field's own filter is excluded) and when faceting a resource attribute (rollup has no severity dimension).\n\n## query.serviceNames\n\nFilter by service names. Ignored when faceting on `service_name` (that field's own filter is excluded).\n\n## query.searchTerm\n\nFull-text search across log bodies. Ignored when faceting a resource attribute.\n\n## query.filterGroup\n\nProperty filters to narrow results. Same format as `query-logs` filters.\n\n# Examples\n\n## Severity distribution in the last hour\n\n```json\n{\n \"query\": {\n \"facetField\": \"severity_text\",\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Which services produce errors over the last day\n\n```json\n{\n \"query\": {\n \"facetField\": \"service_name\",\n \"severityLevels\": [\"error\", \"fatal\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Which pods a service's logs come from\n\n```json\n{\n \"query\": {\n \"facetResourceAttribute\": \"k8s.pod.name\",\n \"serviceNames\": [\"checkout\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Which services emit a specific error message\n\n```json\n{\n \"query\": {\n \"facetField\": \"service_name\",\n \"searchTerm\": \"connection reset\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```","category": "Logs","feature": "logs","summary": "Facet log counts",@@ -7547,7 +7547,7 @@}},"logs-patterns": {- "description": "Mine recurring log templates (\"patterns\") from the logs matching a filter set, ordered by frequency. Each pattern is a message template with the variable parts masked — e.g. `Connected to <ip> in <num>ms` — plus occurrence estimates, severity mix, the services it appears in, and a ready-made predicate for fetching its matching lines.\n\nThis is the fastest way to understand what a log stream is _saying_ without reading raw rows: one call summarizes millions of lines into at most 200 templates.\n\nAll parameters must be nested inside a `query` object.\n\n# When to use\n\n- To triage an unfamiliar or noisy stream: mine the last hour, scan the top templates by `estimated_count`, and look for anything with a non-zero error share in `severity_counts`.\n- To find what's new or dominant during an incident window: mine with `severityLevels: [\"error\", \"fatal\"]` and a `dateRange` covering the incident.\n- As the entry point of a drill-down loop: mine → pick a suspicious pattern → filter logs to exactly its lines using `match_regex` (see below) → read the raw rows with `query-logs`.\n- To quantify repetition before proposing log sampling or cleanup: `volume_share_pct` tells you how much of the stream one template accounts for.\n\n## Pick the right tool\n\n- Raw log lines matching a filter → `query-logs`.\n- A single number (how many logs match) → `logs-count`; per-time-bucket counts → `logs-count-ranges`.\n- Distribution of a dimension (which services emit the errors?) → `logs-facet-values-create`.\n- Use **this** tool to summarize message _content_ — what distinct things the logs say and how often.\n\n# Reading the response\n\n- `pattern` — the mined template. Masked tokens: `<uuid>`, `<ip>`, `<hex>`, `<num>`, and `<*>` for any word position that varied.\n- `estimated_count` / `estimated_error_count` — occurrences extrapolated to the full window. When `sampled` is false these are exact.\n- `severity_counts` — sampled occurrences per severity. A template split across `info` and `error` often means the same code path logging both outcomes.\n- `services` — up to 4 service names the pattern was seen in.\n- `match_regex` — a regex over raw log bodies that matches this pattern's lines, pre-validated against the raw bodies of the pattern's own sampled rows. Null when no trustworthy regex could be compiled. For JSON logs the pattern is mined from the extracted message field, so the regex may be unanchored, because the message is a substring of the raw line. It still targets the raw stored body.\n- `match_literal` — longest literal run of the template, a plain-text fallback when `match_regex` is null.\n\nMining samples the window (`sampled: true` when it did): counts are estimates, and rare patterns (below roughly 1 in `scanned_count` of the volume) may be missing entirely. Narrow the `dateRange` or filters to mine a finer-grained sample.\n\n## Pivoting to a pattern's raw lines\n\nTo fetch the lines behind a pattern, call `query-logs` with a message filter in `filterGroup`:\n\n- If `match_regex` is set: `{ \"key\": \"message\", \"value\": \"<match_regex>\", \"operator\": \"regex\", \"type\": \"log\" }`\n- Else if `match_literal` is set: `{ \"key\": \"message\", \"value\": \"<match_literal>\", \"operator\": \"icontains\", \"type\": \"log\" }`\n\nAlso pass the pattern's `services` as `serviceNames` and (when every entry is one of trace/debug/info/warn/error/fatal) the keys of `severity_counts` as `severityLevels` — both make the query dramatically cheaper.\n\n# Parameters\n\n## query.dateRange\n\nDate range to mine. Defaults to the last hour (`-1h`).\n\n- `date_from`: ISO 8601 timestamp or relative format: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: Same format. Omit or null for \"now\".\n\n## query.severityLevels\n\nMine only these severities: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\n## query.serviceNames\n\nRestrict mining to these services. Recommended once you know the target service — it prunes the scan and spends the whole sample budget on one service's templates.\n\n## query.searchTerm\n\nFull-text search over log bodies applied before mining. Useful to mine only the sub-stream around a keyword (e.g. `timeout`).\n\n## query.filterGroup\n\nProperty filters applied before mining. Same format as `query-logs` filters.\n\n# Examples\n\n## What is this stream saying? (last hour, everything)\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\n## Dominant error templates during an incident\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"dateRange\": { \"date_from\": \"2024-01-15T09:00:00Z\", \"date_to\": \"2024-01-15T11:00:00Z\" }\n }\n}\n```\n\n## Mine one service's logs around a keyword\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"checkout\"],\n \"searchTerm\": \"payment\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```",+ "description": "Mine recurring log templates (\"patterns\") from the logs matching a filter set, ordered by frequency. Each pattern is a message template with the variable parts masked — e.g. `Connected to <ip> in <num>ms` — plus occurrence estimates, severity mix, the services it appears in, and a ready-made predicate for fetching its matching lines.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nThis is the fastest way to understand what a log stream is _saying_ without reading raw rows: one call summarizes millions of lines into at most 200 templates.\n\n# When to use\n\n- To triage an unfamiliar or noisy stream: mine the last hour, scan the top templates by `estimated_count`, and look for anything with a non-zero error share in `severity_counts`.\n- To find what's new or dominant during an incident window: mine with `severityLevels: [\"error\", \"fatal\"]` and a `dateRange` covering the incident.\n- As the entry point of a drill-down loop: mine → pick a suspicious pattern → filter logs to exactly its lines using `match_regex` (see below) → read the raw rows with `query-logs`.\n- To quantify repetition before proposing log sampling or cleanup: `volume_share_pct` tells you how much of the stream one template accounts for.\n\n## Pick the right tool\n\n- Raw log lines matching a filter → `query-logs`.\n- A single number (how many logs match) → `logs-count`; per-time-bucket counts → `logs-count-ranges`.\n- Distribution of a dimension (which services emit the errors?) → `logs-facet-values-create`.\n- Use **this** tool to summarize message _content_ — what distinct things the logs say and how often.\n\n# Reading the response\n\n- `pattern` — the mined template. Masked tokens: `<uuid>`, `<ip>`, `<hex>`, `<num>`, and `<*>` for any word position that varied.\n- `estimated_count` / `estimated_error_count` — occurrences extrapolated to the full window. When `sampled` is false these are exact.\n- `severity_counts` — sampled occurrences per severity. A template split across `info` and `error` often means the same code path logging both outcomes.\n- `services` — up to 4 service names the pattern was seen in.\n- `match_regex` — a regex over raw log bodies that matches this pattern's lines, pre-validated against the raw bodies of the pattern's own sampled rows. Null when no trustworthy regex could be compiled. For JSON logs the pattern is mined from the extracted message field, so the regex may be unanchored, because the message is a substring of the raw line. It still targets the raw stored body.\n- `match_literal` — longest literal run of the template, a plain-text fallback when `match_regex` is null.\n\nMining samples the window (`sampled: true` when it did): counts are estimates, and rare patterns (below roughly 1 in `scanned_count` of the volume) may be missing entirely. Narrow the `dateRange` or filters to mine a finer-grained sample.\n\n## Pivoting to a pattern's raw lines\n\nTo fetch the lines behind a pattern, call `query-logs` with a message filter in `filterGroup`:\n\n- If `match_regex` is set: `{ \"key\": \"message\", \"value\": \"<match_regex>\", \"operator\": \"regex\", \"type\": \"log\" }`\n- Else if `match_literal` is set: `{ \"key\": \"message\", \"value\": \"<match_literal>\", \"operator\": \"icontains\", \"type\": \"log\" }`\n\nAlso pass the pattern's `services` as `serviceNames` and (when every entry is one of trace/debug/info/warn/error/fatal) the keys of `severity_counts` as `severityLevels` — both make the query dramatically cheaper.\n\n# Parameters\n\n## query.dateRange\n\nDate range to mine. Defaults to the last hour (`-1h`).\n\n- `date_from`: ISO 8601 timestamp or relative format: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: Same format. Omit or null for \"now\".\n\n## query.severityLevels\n\nMine only these severities: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\n## query.serviceNames\n\nRestrict mining to these services. Recommended once you know the target service — it prunes the scan and spends the whole sample budget on one service's templates.\n\n## query.searchTerm\n\nFull-text search over log bodies applied before mining. Useful to mine only the sub-stream around a keyword (e.g. `timeout`).\n\n## query.filterGroup\n\nProperty filters applied before mining. Same format as `query-logs` filters.\n\n# Examples\n\n## What is this stream saying? (last hour, everything)\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\n## Dominant error templates during an incident\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"dateRange\": { \"date_from\": \"2024-01-15T09:00:00Z\", \"date_to\": \"2024-01-15T11:00:00Z\" }\n }\n}\n```\n\n## Mine one service's logs around a keyword\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"checkout\"],\n \"searchTerm\": \"payment\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```","category": "Logs","feature": "logs","summary": "Mine log patterns",@@ -7561,7 +7561,7 @@}},"logs-patterns-diff": {- "description": "Compare the log patterns of two time windows and return what changed: templates that are **new**, templates whose rate **shifted** (with magnitude, e.g. 4x), and templates that are **gone**. This is the single most useful call for incident triage — \"what is different about now vs. before it broke\" in one round trip, instead of mining two windows yourself and hand-matching templates.\n\nAll parameters must be nested inside a `query` object, with an optional sibling `baselineDateRange`.\n\n# When to use\n\n- **Incident triage (the primary loop):** set `query.dateRange` to the incident window. Omit `baselineDateRange` (defaults to the same window one week earlier) or set it to a known-good window just before the incident. The `new` and biggest `rate_shift` entries are your suspects; pivot to their raw lines with `query-logs`.\n- **Explain a spike:** when a count or sparkline shows a spike (e.g. from `logs-count-ranges`), set `query.dateRange` to the spike window and `baselineDateRange` to the window just before it — the top `new` and `rate_shift` entries are the explanation. This is one call; do not mine the two windows separately and diff them yourself.\n- **Post-deploy check:** current window = since the deploy; `baselineDateRange` = the same-length window just before it. New error-severity templates right after a deploy are the classic regression signature.\n- **\"What changed this week?\"** — current = `-1d`, baseline auto. Good periodic sweep for a service you own.\n\n## Pick the right tool\n\n- Just summarize one window's content → `logs-patterns`.\n- Explain a _count_ change without needing message content → `logs-count-ranges` (cheaper).\n- Use **this** tool when you need to know _which messages_ are new or behaving differently between two periods.\n\n# Reading the response\n\nEntries come sorted most-interesting-first: `new` (by volume), then `rate_shift` (by magnitude), then `gone`, then `unchanged`.\n\n- `classification` — trust the labels; the thresholds already handle sampling honesty:\n - `new` requires clearing a novelty floor (~1% volume share, or any error/fatal lines). Below the floor, absence from the baseline sample is not evidence of novelty.\n - `rate_shift` requires ≥2x change in per-second rate (windows of different lengths are normalized) _and_ enough raw samples on both sides.\n - `unchanged` means \"no confident claim\", not \"provably identical\".\n- `rate_ratio` — current rate / baseline rate. 4.0 = 4x faster now, 0.25 = quartered.\n- `pattern` — full pattern stats including `match_regex` / `match_literal`, so you can pivot straight to the matching lines (same recipe as `logs-patterns`: message regex filter + the pattern's services/severities).\n- **Check `baseline.total_count` before trusting a wall of `new` entries** — an empty or tiny baseline (logging only started recently, service didn't exist last week) makes everything look new.\n- Both windows are mined from samples (`sampled: true`), so counts are estimates and templates rarer than ~1 in 10,000 rows may be invisible in either window.\n\nTemplate identity across the two windows is fingerprint-based (literal content), so the miner rendering `User <*> not found` in one window and `User <num> not found` in the other still compares as one pattern rather than a false new+gone pair.\n\n# Parameters\n\n## query.dateRange\n\nThe current (foreground) window — the period you are investigating. Same format as `logs-patterns`.\n\n## baselineDateRange\n\nOptional, sibling of `query` (not inside it). The comparison window. Omit for the default: the current window shifted back exactly one week, which absorbs daily/weekly volume cycles. Provide explicitly to compare against a pre-deploy or pre-incident period. It does not need to be the same length as the current window — rates are normalized per second.\n\n## query.severityLevels / query.serviceNames / query.searchTerm / query.filterGroup\n\nSame as `logs-patterns`; applied to **both** windows. Scoping by service is recommended — it prunes both scans and focuses the sample budget.\n\n# Examples\n\n## What changed during the incident vs. just before it\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"2026-07-07T09:30:00Z\", \"date_to\": \"2026-07-07T10:30:00Z\" },\n \"serviceNames\": [\"checkout\"]\n },\n \"baselineDateRange\": { \"date_from\": \"2026-07-07T08:00:00Z\", \"date_to\": \"2026-07-07T09:00:00Z\" }\n}\n```\n\n## What is new or different today vs. the same time last week\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-1d\" } } }\n```\n\n## Did the deploy change what the service logs?\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"2026-07-07T14:00:00Z\" },\n \"serviceNames\": [\"api\"]\n },\n \"baselineDateRange\": { \"date_from\": \"2026-07-07T10:00:00Z\", \"date_to\": \"2026-07-07T14:00:00Z\" }\n}\n```",+ "description": "Compare the log patterns of two time windows and return what changed: templates that are **new**, templates whose rate **shifted** (with magnitude, e.g. 4x), and templates that are **gone**. This is the single most useful call for incident triage — \"what is different about now vs. before it broke\" in one round trip, instead of mining two windows yourself and hand-matching templates.\n\nAll parameters go inside `query`, except the optional sibling `baselineDateRange`. Other top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1d\" } } }\n```\n\n# When to use\n\n- **Incident triage (the primary loop):** set `query.dateRange` to the incident window. Omit `baselineDateRange` (defaults to the same window one week earlier) or set it to a known-good window just before the incident. The `new` and biggest `rate_shift` entries are your suspects; pivot to their raw lines with `query-logs`.\n- **Explain a spike:** when a count or sparkline shows a spike (e.g. from `logs-count-ranges`), set `query.dateRange` to the spike window and `baselineDateRange` to the window just before it — the top `new` and `rate_shift` entries are the explanation. This is one call; do not mine the two windows separately and diff them yourself.\n- **Post-deploy check:** current window = since the deploy; `baselineDateRange` = the same-length window just before it. New error-severity templates right after a deploy are the classic regression signature.\n- **\"What changed this week?\"** — current = `-1d`, baseline auto. Good periodic sweep for a service you own.\n\n## Pick the right tool\n\n- Just summarize one window's content → `logs-patterns`.\n- Explain a _count_ change without needing message content → `logs-count-ranges` (cheaper).\n- Use **this** tool when you need to know _which messages_ are new or behaving differently between two periods.\n\n# Reading the response\n\nEntries come sorted most-interesting-first: `new` (by volume), then `rate_shift` (by magnitude), then `gone`, then `unchanged`.\n\n- `classification` — trust the labels; the thresholds already handle sampling honesty:\n - `new` requires clearing a novelty floor (~1% volume share, or any error/fatal lines). Below the floor, absence from the baseline sample is not evidence of novelty.\n - `rate_shift` requires ≥2x change in per-second rate (windows of different lengths are normalized) _and_ enough raw samples on both sides.\n - `unchanged` means \"no confident claim\", not \"provably identical\".\n- `rate_ratio` — current rate / baseline rate. 4.0 = 4x faster now, 0.25 = quartered.\n- `pattern` — full pattern stats including `match_regex` / `match_literal`, so you can pivot straight to the matching lines (same recipe as `logs-patterns`: message regex filter + the pattern's services/severities).\n- **Check `baseline.total_count` before trusting a wall of `new` entries** — an empty or tiny baseline (logging only started recently, service didn't exist last week) makes everything look new.\n- Both windows are mined from samples (`sampled: true`), so counts are estimates and templates rarer than ~1 in 10,000 rows may be invisible in either window.\n\nTemplate identity across the two windows is fingerprint-based (literal content), so the miner rendering `User <*> not found` in one window and `User <num> not found` in the other still compares as one pattern rather than a false new+gone pair.\n\n# Parameters\n\n## query.dateRange\n\nThe current (foreground) window — the period you are investigating. Same format as `logs-patterns`.\n\n## baselineDateRange\n\nOptional, sibling of `query` (not inside it). The comparison window. Omit for the default: the current window shifted back exactly one week, which absorbs daily/weekly volume cycles. Provide explicitly to compare against a pre-deploy or pre-incident period. It does not need to be the same length as the current window — rates are normalized per second.\n\n## query.severityLevels / query.serviceNames / query.searchTerm / query.filterGroup\n\nSame as `logs-patterns`; applied to **both** windows. Scoping by service is recommended — it prunes both scans and focuses the sample budget.\n\n# Examples\n\n## What changed during the incident vs. just before it\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"2026-07-07T09:30:00Z\", \"date_to\": \"2026-07-07T10:30:00Z\" },\n \"serviceNames\": [\"checkout\"]\n },\n \"baselineDateRange\": { \"date_from\": \"2026-07-07T08:00:00Z\", \"date_to\": \"2026-07-07T09:00:00Z\" }\n}\n```\n\n## What is new or different today vs. the same time last week\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-1d\" } } }\n```\n\n## Did the deploy change what the service logs?\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"2026-07-07T14:00:00Z\" },\n \"serviceNames\": [\"api\"]\n },\n \"baselineDateRange\": { \"date_from\": \"2026-07-07T10:00:00Z\", \"date_to\": \"2026-07-07T14:00:00Z\" }\n}\n```","category": "Logs","feature": "logs","summary": "Diff log patterns between two windows",@@ -7589,7 +7589,7 @@}},"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```",+ "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 go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\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","feature": "logs","summary": "Query logs sparkline",@@ -8852,7 +8852,7 @@"feature_flag": "engineering-analytics"},"query-apm-spans": {- "description": "Query trace spans with filtering by service name, status code, date range, and structured attribute filters. Supports cursor-based pagination. Returns spans with uuid, trace_id, span_id, parent_span_id, name, kind, service_name, status_code, timestamp, end_time, duration_nano, is_root_span, matched_filter, and attributes (the span-level OTel attribute map, e.g. db.statement, http.url).\n\nUse 'apm-attributes-list' and 'apm-attribute-values-list' to discover available attributes before building filters. Use 'apm-services-list' to discover available services.\n\n# Return shape\n\nResults are **grouped by trace**, not a flat list of matching spans. For each trace that contains at least one span matching your filters, the response includes spans from that trace (up to `prefetchSpans` per trace, root span first). Two fields tell you which spans actually matched:\n\n- `matched_filter` — `1` if **this span** satisfies your `filterGroup`/`serviceNames`/`statusCodes`, `0` if it's only included because it shares a trace with a match (e.g. a prefetched sibling or the trace's root). When you filter by a child span's name, the matching child has `matched_filter: 1` and its root/siblings have `matched_filter: 0`.\n- `is_root_span` — `true` for the trace's entry span.\n\nTo collapse each matching trace to a **single row — its root span**, set `rootSpans: true` — see below. (The row is the trace's entry span, which may itself carry `matched_filter: 0` when the match was on a child.) To inspect a single trace's full tree, take a `trace_id` from the results and call `apm-trace-get`.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nAll parameters must be nested inside a `query` object.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Span property types are:\n - `span` — filters built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span).\n - `span_attribute` — filters span-level attributes (e.g. \"http.method\", \"http.status_code\").\n - `span_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `apm-attributes-list` to discover available attribute keys** before building filters.\n- **Use `apm-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window. If the question doesn't mention time, the default is the last hour (`-1h`). Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.serviceNames\n\nFilter by service names. Use `apm-services-list` to discover available services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. 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`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.traceId\n\nFilter to a specific trace ID (hex string). Use this when you already know the trace ID.\n\n## query.rootSpans\n\nSet `true` to return **only root spans** — one entry span per matching trace, which collapses each trace to a single row. Useful for \"list the traces matching X\" without sifting through `matched_filter`. Leave unset (or `false`) to get all spans of matching traces, where you read `matched_filter` to find the ones that matched. The frontend leaves this unset.\n\n## query.flatSpans\n\nSet `true` to return **the matching spans themselves, one row per span** (root and child), rather than collapsing to traces. This is the way to search by a child-span attribute (e.g. `code.filepath`) — the result is the matching child spans directly, not the traces that contain them. Streams under `ORDER BY … LIMIT`, so it stays bounded on hot child attributes where the whole-trace grouping would not. Distinct from `rootSpans` (which scopes whole-trace selection); `prefetchSpans` is ignored. Defaults to false.\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.prefetchSpans\n\nNumber of spans to return per matching trace (1-100), root span first. Useful to preview trace structure without a separate `apm-trace-get`. With the default (1) you get one span per trace (the root); raise it to also pull the matching children and their siblings (check `matched_filter` to tell them apart). Ignored when `rootSpans: true`, which always returns just the root.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-span `attributes` map from results (the map stays present but empty). The attribute map holds multi-KB values like `db.statement`, so excluding it keeps large result sets compact — set it when you only need span structure/timing (`name`, `service_name`, `duration_nano`, `parent_span_id`) and not the OTel attributes. Defaults to false.\n\n# Examples\n\n## List recent error spans\n\n```json\n{\n \"query\": {\n \"statusCodes\": [2]\n }\n}\n```\n\n## Search spans from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a span attribute\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"http.method\", \"operator\": \"exact\", \"type\": \"span_attribute\", \"value\": \"POST\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Find slow spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"duration\", \"operator\": \"gt\", \"type\": \"span\", \"value\": \"1000000000\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine service and attribute filters\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"web-server\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"gt\", \"type\": \"span_attribute\", \"value\": \"399\" }],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Check if a resource attribute exists\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"k8s.pod.name\", \"operator\": \"is_set\", \"type\": \"span_resource_attribute\" }]\n }\n}\n```\n\n# Reminders\n\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Use `apm-services-list` to discover available services before filtering by service name.\n- Duration values are in nanoseconds (1 second = 1,000,000,000 nanoseconds).",+ "description": "Query trace spans with filtering by service name, status code, date range, and structured attribute filters. Supports cursor-based pagination. Returns spans with uuid, trace_id, span_id, parent_span_id, name, kind, service_name, status_code, timestamp, end_time, duration_nano, is_root_span, matched_filter, and attributes (the span-level OTel attribute map, e.g. db.statement, http.url).\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nUse 'apm-attributes-list' and 'apm-attribute-values-list' to discover available attributes before building filters. Use 'apm-services-list' to discover available services.\n\n# Return shape\n\nResults are **grouped by trace**, not a flat list of matching spans. For each trace that contains at least one span matching your filters, the response includes spans from that trace (up to `prefetchSpans` per trace, root span first). Two fields tell you which spans actually matched:\n\n- `matched_filter` — `1` if **this span** satisfies your `filterGroup`/`serviceNames`/`statusCodes`, `0` if it's only included because it shares a trace with a match (e.g. a prefetched sibling or the trace's root). When you filter by a child span's name, the matching child has `matched_filter: 1` and its root/siblings have `matched_filter: 0`.\n- `is_root_span` — `true` for the trace's entry span.\n\nTo collapse each matching trace to a **single row — its root span**, set `rootSpans: true` — see below. (The row is the trace's entry span, which may itself carry `matched_filter: 0` when the match was on a child.) To inspect a single trace's full tree, take a `trace_id` from the results and call `apm-trace-get`.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Span property types are:\n - `span` — filters built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span).\n - `span_attribute` — filters span-level attributes (e.g. \"http.method\", \"http.status_code\").\n - `span_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `apm-attributes-list` to discover available attribute keys** before building filters.\n- **Use `apm-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window. If the question doesn't mention time, the default is the last hour (`-1h`). Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\n## query.serviceNames\n\nFilter by service names. Use `apm-services-list` to discover available services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. 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`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.traceId\n\nFilter to a specific trace ID (hex string). Use this when you already know the trace ID.\n\n## query.rootSpans\n\nSet `true` to return **only root spans** — one entry span per matching trace, which collapses each trace to a single row. Useful for \"list the traces matching X\" without sifting through `matched_filter`. Leave unset (or `false`) to get all spans of matching traces, where you read `matched_filter` to find the ones that matched. The frontend leaves this unset.\n\n## query.flatSpans\n\nSet `true` to return **the matching spans themselves, one row per span** (root and child), rather than collapsing to traces. This is the way to search by a child-span attribute (e.g. `code.filepath`) — the result is the matching child spans directly, not the traces that contain them. Streams under `ORDER BY … LIMIT`, so it stays bounded on hot child attributes where the whole-trace grouping would not. Distinct from `rootSpans` (which scopes whole-trace selection); `prefetchSpans` is ignored. Defaults to false.\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.prefetchSpans\n\nNumber of spans to return per matching trace (1-100), root span first. Useful to preview trace structure without a separate `apm-trace-get`. With the default (1) you get one span per trace (the root); raise it to also pull the matching children and their siblings (check `matched_filter` to tell them apart). Ignored when `rootSpans: true`, which always returns just the root.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-span `attributes` map from results (the map stays present but empty). The attribute map holds multi-KB values like `db.statement`, so excluding it keeps large result sets compact — set it when you only need span structure/timing (`name`, `service_name`, `duration_nano`, `parent_span_id`) and not the OTel attributes. Defaults to false.\n\n# Examples\n\n## List recent error spans\n\n```json\n{\n \"query\": {\n \"statusCodes\": [2]\n }\n}\n```\n\n## Search spans from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a span attribute\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"http.method\", \"operator\": \"exact\", \"type\": \"span_attribute\", \"value\": \"POST\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Find slow spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"duration\", \"operator\": \"gt\", \"type\": \"span\", \"value\": \"1000000000\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine service and attribute filters\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"web-server\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"gt\", \"type\": \"span_attribute\", \"value\": \"399\" }],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Check if a resource attribute exists\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"k8s.pod.name\", \"operator\": \"is_set\", \"type\": \"span_resource_attribute\" }]\n }\n}\n```\n\n# Reminders\n\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Use `apm-services-list` to discover available services before filtering by service name.\n- Duration values are in nanoseconds (1 second = 1,000,000,000 nanoseconds).","category": "Tracing","feature": "tracing","summary": "Query tracing spans",@@ -9002,7 +9002,7 @@"system_prompt_hint": "LLM/AI trace listing and inspection"},"query-logs": {- "description": "Query log entries with filtering by severity, service name, date range, search term, and structured attribute filters. Supports cursor-based pagination. The response schema (see the tool's typed output) lists every returned field — prefer `severity_text` over `severity_number` / `level`, and be aware that `trace_id` and `span_id` return zero-padded strings rather than null when unset.\n\nUse `logs-attributes-list` and `logs-attribute-values-list` to discover available attributes before building filters.\n\n# Workflow — follow this order every time\n\n1. **Discover services first.** Call `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to see available services.\n2. **Explore resource attributes.** Call `logs-attributes-list` with `attribute_type: \"resource\"` to discover resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`). Then call `logs-attribute-values-list` with `attribute_type: \"resource\"` for relevant attributes to validate what data exists.\n3. **Explore log attributes if needed.** Call `logs-attributes-list` (defaults to log attributes) and `logs-attribute-values-list` to discover log-level attributes.\n4. **Size the total volume with `logs-count`.** Call `logs-count` with the discovered `serviceNames` and filters. If it exceeds `query-logs`'s max `limit` of 1000 — or if the user's question is about _when_ something happened — continue to step 5.\n5. **Find where the volume sits with `logs-count-ranges`.** Call `logs-count-ranges` to get time-bucketed counts. Each bucket carries explicit `date_from`/`date_to` you can pass straight back as the next call's `dateRange` to drill into a sub-range. Recurse up to 3–4 levels to narrow onto a spike or a specific window. Stop when the bucket width drops below your precision goal (e.g. 1 minute).\n6. **Only then query logs.** Once the count is in range and the window is right-sized, call `query-logs` with `serviceNames` and any additional filters.\n\nMany cheap calls (attribute/value queries, counts, count-ranges) beat one expensive `query-logs`. Prefer thorough exploration over speculative log searches.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nMANDATORY: Never call query-logs without setting `serviceNames` or at least one `log_resource_attribute` filter. Unfiltered log queries are too broad, expensive, and noisy. If the user hasn't specified a service, use the workflow above to discover services first, then ask or infer.\n\nMANDATORY: Always pass `query.dateRange` explicitly (e.g. `{ \"date_from\": \"-1h\" }`). Omitting it fails with a 400 `parse_error` (\"Input should be a valid dictionary or instance of DateRange\") — the server does not fall back to a default window.\n\nAll parameters must be nested inside a `query` object.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Log property types are:\n - `log` — filters the log body/message. Use key \"message\" for this type.\n - `log_attribute` — filters log-level attributes (e.g. \"k8s.container.name\", \"http.method\").\n - `log_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `logs-attributes-list` to discover available attribute keys** before building filters.\n- **Use `logs-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\n**Important:** The `logs-attributes-list` and `logs-attribute-values-list` tools default to `attribute_type: \"log\"` (log-level attributes). To search resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`), you must explicitly pass `attribute_type: \"resource\"`. Forgetting this will return log-level attributes when you intended resource-level ones.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Date: `is_date_exact`, `is_date_before`, `is_date_after`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Filtering logs by a PostHog person\n\nWhen the user references a person — by `distinct_id`, name, email, or via a prior `persons-retrieve` call — filter logs to that person via `log_attribute` filters. The attribute keys are configurable per project (they default to `[\"posthogDistinctId\"]`); read `logs_distinct_id_attribute_keys` from the `/api/projects/:id/logs_config/` endpoint and use those as the filter `key`s.\n\nIf a person has multiple `distinct_ids`, pass the array as the filter `value` with operator `exact` (matches any of them):\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [\n {\n \"key\": \"posthogDistinctId\",\n \"operator\": \"exact\",\n \"type\": \"log_attribute\",\n \"value\": [\"<distinct_id_1>\", \"<distinct_id_2>\"]\n }\n ]\n }\n}\n```\n\nEntries in the `filterGroup` array are combined with AND, so never put two distinct-id keys in one call — a log only carries one of them. When the team has multiple keys configured, run one query per key and merge the results.\n\nDo not invent a different attribute key based on what looks plausible — use the configured keys. If the configured keys return zero results, the customer's logs pipeline may not stamp person identity at all; tell the user rather than guessing.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window — pass it on every call. If the question doesn't mention time, use the last hour: `{ \"date_from\": \"-1h\" }`. Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\nThis filter is an **exact match against the response's `severity_text` field** using these six lowercase buckets — it is _not_ a numeric range and _not_ case-insensitive. If a service ingests non-canonical severity strings (e.g. `\"ERROR\"`, `\"Warning\"`, `\"err\"`), `severityLevels: [\"error\"]` will not match them and you will get zero rows. When a severity filter returns nothing unexpectedly, discover the actual stored values with `logs-attribute-values-list { key: \"severity_text\" }` and either filter on the value you find or fall back to a `searchTerm`. See \"Severity fields in the response\" below for the `severity_text` / `severity_number` / `level` mapping.\n\n## query.serviceNames\n\nFilter by service names. Use `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to discover available services.\n\n## query.searchTerm\n\nFull-text search across log bodies. Use this when the user is looking for specific text in log messages.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (log/log_attribute/log_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Required in practice: omitting it fails with a 400 `parse_error`, so always pass it (use `{ \"date_from\": \"-1h\" }` when the question doesn't mention time).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-log `attributes` and `resource_attributes` maps from results (the maps stay present but empty). These maps can hold large values, so excluding them keeps big result sets compact — set it when you only need `body`, `severity_text`, `timestamp`, and `service`-level fields and not the full attribute maps. Defaults to false.\n\n# Examples\n\n## List recent error logs\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Search for a specific log message\n\n```json\n{\n \"query\": {\n \"searchTerm\": \"connection refused\",\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Filter logs from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a log attribute\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"exact\", \"type\": \"log_attribute\", \"value\": \"500\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine severity and attribute filters\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\"],\n \"filterGroup\": [\n { \"key\": \"k8s.container.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"web\" }\n ],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Filter by log body content using property filter\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"message\", \"operator\": \"icontains\", \"type\": \"log\", \"value\": \"timeout\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Check if an attribute exists\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"trace_id\", \"operator\": \"is_set\", \"type\": \"log_attribute\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n# Severity fields in the response\n\nEach returned log row carries three overlapping severity fields. Read and report `severity_text`; treat the other two as redundant:\n\n| Field | What it is | Use it for |\n| ----------------- | --------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `severity_text` | Canonical severity string. **Prefer this.** | Filtering (`severityLevels`), grouping, and anything you show a user. |\n| `severity_number` | OpenTelemetry numeric severity (1–24). Redundant with the text. | Sorting by exact severity, or interop with OTel tooling. |\n| `level` | ClickHouse alias for `severity_text`. Redundant. | Ignore — prefer `severity_text`. |\n\n`severity_number` maps to the `severityLevels` buckets by OTel range. Use this when you only have a number and need the bucket, or vice-versa:\n\n| Bucket | `severity_number` range | Canonical `severity_text` |\n| ------- | ----------------------- | ------------------------- |\n| `trace` | 1–4 | `trace` |\n| `debug` | 5–8 | `debug` |\n| `info` | 9–12 | `info` |\n| `warn` | 13–16 | `warn` |\n| `error` | 17–20 | `error` |\n| `fatal` | 21–24 | `fatal` |\n\nWhen the user asks for \"warnings and above\", that is `severityLevels: [\"warn\", \"error\", \"fatal\"]` — there is no numeric `>=` operator on the top-level severity filter.\n\n# If the query fails (500 / timeout)\n\nA `query-logs` call that returns a 500 almost always means the query scanned too much data and timed out server-side — it is rarely a bug in your filters. Do not retry the same call. Instead, narrow and re-size:\n\n1. Shorten `dateRange` (e.g. `-1h` instead of `-1d`).\n2. Add `serviceNames` or a `log_resource_attribute` filter to reduce the scan.\n3. Size the volume with `logs-count`, then locate the busy window with `logs-count-ranges`, before pulling rows again.\n\n# Reminders\n\n- Always set `serviceNames` or a resource attribute filter. Never run a broad unfiltered log query.\n- Limit `dateRange` to at most `-1d` (24 hours) unless the user explicitly requests a longer range.\n- When using `logs-attributes-list` or `logs-attribute-values-list`, remember they default to `attribute_type: \"log\"`. Pass `attribute_type: \"resource\"` to search resource-level attributes.\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `logs-attributes-list` and `logs-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Prefer `searchTerm` for simple text matching; use `filterGroup` with type `log` and key `message` for regex or exact matching.",+ "description": "Query log entries with filtering by severity, service name, date range, search term, and structured attribute filters. Supports cursor-based pagination. The response schema (see the tool's typed output) lists every returned field — prefer `severity_text` over `severity_number` / `level`, and be aware that `trace_id` and `span_id` return zero-padded strings rather than null when unset.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nUse `logs-attributes-list` and `logs-attribute-values-list` to discover available attributes before building filters.\n\n# Workflow — follow this order every time\n\n1. **Discover services first.** Call `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to see available services.\n2. **Explore resource attributes.** Call `logs-attributes-list` with `attribute_type: \"resource\"` to discover resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`). Then call `logs-attribute-values-list` with `attribute_type: \"resource\"` for relevant attributes to validate what data exists.\n3. **Explore log attributes if needed.** Call `logs-attributes-list` (defaults to log attributes) and `logs-attribute-values-list` to discover log-level attributes.\n4. **Size the total volume with `logs-count`.** Call `logs-count` with the discovered `serviceNames` and filters. If it exceeds `query-logs`'s max `limit` of 1000 — or if the user's question is about _when_ something happened — continue to step 5.\n5. **Find where the volume sits with `logs-count-ranges`.** Call `logs-count-ranges` to get time-bucketed counts. Each bucket carries explicit `date_from`/`date_to` you can pass straight back as the next call's `dateRange` to drill into a sub-range. Recurse up to 3–4 levels to narrow onto a spike or a specific window. Stop when the bucket width drops below your precision goal (e.g. 1 minute).\n6. **Only then query logs.** Once the count is in range and the window is right-sized, call `query-logs` with `serviceNames` and any additional filters.\n\nMany cheap calls (attribute/value queries, counts, count-ranges) beat one expensive `query-logs`. Prefer thorough exploration over speculative log searches.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nMANDATORY: Never call query-logs without setting `serviceNames` or at least one `log_resource_attribute` filter. Unfiltered log queries are too broad, expensive, and noisy. If the user hasn't specified a service, use the workflow above to discover services first, then ask or infer.\n\nMANDATORY: Always pass `query.dateRange` explicitly (e.g. `{ \"date_from\": \"-1h\" }`). Omitting it fails with a 400 `parse_error` (\"Input should be a valid dictionary or instance of DateRange\") — the server does not fall back to a default window.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Log property types are:\n - `log` — filters the log body/message. Use key \"message\" for this type.\n - `log_attribute` — filters log-level attributes (e.g. \"k8s.container.name\", \"http.method\").\n - `log_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `logs-attributes-list` to discover available attribute keys** before building filters.\n- **Use `logs-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\n**Important:** The `logs-attributes-list` and `logs-attribute-values-list` tools default to `attribute_type: \"log\"` (log-level attributes). To search resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`), you must explicitly pass `attribute_type: \"resource\"`. Forgetting this will return log-level attributes when you intended resource-level ones.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Date: `is_date_exact`, `is_date_before`, `is_date_after`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Filtering logs by a PostHog person\n\nWhen the user references a person — by `distinct_id`, name, email, or via a prior `persons-retrieve` call — filter logs to that person via `log_attribute` filters. The attribute keys are configurable per project (they default to `[\"posthogDistinctId\"]`); read `logs_distinct_id_attribute_keys` from the `/api/projects/:id/logs_config/` endpoint and use those as the filter `key`s.\n\nIf a person has multiple `distinct_ids`, pass the array as the filter `value` with operator `exact` (matches any of them):\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [\n {\n \"key\": \"posthogDistinctId\",\n \"operator\": \"exact\",\n \"type\": \"log_attribute\",\n \"value\": [\"<distinct_id_1>\", \"<distinct_id_2>\"]\n }\n ]\n }\n}\n```\n\nEntries in the `filterGroup` array are combined with AND, so never put two distinct-id keys in one call — a log only carries one of them. When the team has multiple keys configured, run one query per key and merge the results.\n\nDo not invent a different attribute key based on what looks plausible — use the configured keys. If the configured keys return zero results, the customer's logs pipeline may not stamp person identity at all; tell the user rather than guessing.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window — pass it on every call. If the question doesn't mention time, use the last hour: `{ \"date_from\": \"-1h\" }`. Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\nThis filter is an **exact match against the response's `severity_text` field** using these six lowercase buckets — it is _not_ a numeric range and _not_ case-insensitive. If a service ingests non-canonical severity strings (e.g. `\"ERROR\"`, `\"Warning\"`, `\"err\"`), `severityLevels: [\"error\"]` will not match them and you will get zero rows. When a severity filter returns nothing unexpectedly, discover the actual stored values with `logs-attribute-values-list { key: \"severity_text\" }` and either filter on the value you find or fall back to a `searchTerm`. See \"Severity fields in the response\" below for the `severity_text` / `severity_number` / `level` mapping.\n\n## query.serviceNames\n\nFilter by service names. Use `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to discover available services.\n\n## query.searchTerm\n\nFull-text search across log bodies. Use this when the user is looking for specific text in log messages.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (log/log_attribute/log_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Required in practice: omitting it fails with a 400 `parse_error`, so always pass it (use `{ \"date_from\": \"-1h\" }` when the question doesn't mention time).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-log `attributes` and `resource_attributes` maps from results (the maps stay present but empty). These maps can hold large values, so excluding them keeps big result sets compact — set it when you only need `body`, `severity_text`, `timestamp`, and `service`-level fields and not the full attribute maps. Defaults to false.\n\n# Examples\n\n## List recent error logs\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Search for a specific log message\n\n```json\n{\n \"query\": {\n \"searchTerm\": \"connection refused\",\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Filter logs from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a log attribute\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"exact\", \"type\": \"log_attribute\", \"value\": \"500\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine severity and attribute filters\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\"],\n \"filterGroup\": [\n { \"key\": \"k8s.container.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"web\" }\n ],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Filter by log body content using property filter\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"message\", \"operator\": \"icontains\", \"type\": \"log\", \"value\": \"timeout\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Check if an attribute exists\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"trace_id\", \"operator\": \"is_set\", \"type\": \"log_attribute\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n# Severity fields in the response\n\nEach returned log row carries three overlapping severity fields. Read and report `severity_text`; treat the other two as redundant:\n\n| Field | What it is | Use it for |\n| ----------------- | --------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `severity_text` | Canonical severity string. **Prefer this.** | Filtering (`severityLevels`), grouping, and anything you show a user. |\n| `severity_number` | OpenTelemetry numeric severity (1–24). Redundant with the text. | Sorting by exact severity, or interop with OTel tooling. |\n| `level` | ClickHouse alias for `severity_text`. Redundant. | Ignore — prefer `severity_text`. |\n\n`severity_number` maps to the `severityLevels` buckets by OTel range. Use this when you only have a number and need the bucket, or vice-versa:\n\n| Bucket | `severity_number` range | Canonical `severity_text` |\n| ------- | ----------------------- | ------------------------- |\n| `trace` | 1–4 | `trace` |\n| `debug` | 5–8 | `debug` |\n| `info` | 9–12 | `info` |\n| `warn` | 13–16 | `warn` |\n| `error` | 17–20 | `error` |\n| `fatal` | 21–24 | `fatal` |\n\nWhen the user asks for \"warnings and above\", that is `severityLevels: [\"warn\", \"error\", \"fatal\"]` — there is no numeric `>=` operator on the top-level severity filter.\n\n# If the query fails (500 / timeout)\n\nA `query-logs` call that returns a 500 almost always means the query scanned too much data and timed out server-side — it is rarely a bug in your filters. Do not retry the same call. Instead, narrow and re-size:\n\n1. Shorten `dateRange` (e.g. `-1h` instead of `-1d`).\n2. Add `serviceNames` or a `log_resource_attribute` filter to reduce the scan.\n3. Size the volume with `logs-count`, then locate the busy window with `logs-count-ranges`, before pulling rows again.\n\n# Reminders\n\n- Always set `serviceNames` or a resource attribute filter. Never run a broad unfiltered log query.\n- Limit `dateRange` to at most `-1d` (24 hours) unless the user explicitly requests a longer range.\n- When using `logs-attributes-list` or `logs-attribute-values-list`, remember they default to `attribute_type: \"log\"`. Pass `attribute_type: \"resource\"` to search resource-level attributes.\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `logs-attributes-list` and `logs-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Prefer `searchTerm` for simple text matching; use `filterGroup` with type `log` and key `message` for regex or exact matching.","category": "Logs","feature": "logs","summary": "Query logs",@@ -9177,7 +9177,7 @@"system_prompt_hint": "One MCP tool's top callers — calls, error rate, harnesses, person email/name"},"query-metrics": {- "description": "Query server/infrastructure metrics (OTel- or Prometheus-ingested) as bucketed time series. The response is a list of series — `{labels, points: [{time, value}], metric_name, clause}` — where every series shares one time grid (missing buckets are zero-filled). A single ungrouped query returns exactly one series with empty labels.\n\nAll parameters go inside `query`:\n\n```json\n{ \"query\": { \"metricName\": \"m\", \"aggregation\": \"rate\", \"dateFrom\": \"2026-01-01T00:00:00Z\" } }\n```\n\nTwo request forms:\n\n- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).\n- **Multi-clause / formula:** set `clauses: [{name, metricName, aggregation, quantile?, filters?, groupBy?}, ...]` and optionally `formula` (e.g. `\"(a - b) / a\"` over clause names; `+ - * /` and parentheses; division by zero yields 0). With a formula set, only the formula result series are returned.\n\n# Workflow — follow this order every time\n\n1. **Discover names first.** Call `metric-names-list` with a substring (`value`) before querying — metric names must match exactly, and the returned `metric_type` tells you the right aggregation.\n2. **Pick the aggregation by metric type:**\n - `sum` counters (usually `_total`): use `rate` (per-second) or `increase` — both are counter-reset safe and temporality-aware. Do NOT use `sum`/`avg` on cumulative counters; absolute counter values are meaningless.\n - `gauge`: `avg` (typical), `p95`, `sum`.\n - Every aggregation combines across series, never across raw samples, so a result never scales with the scrape rate: `sum`/`avg`/`p95` reduce each series to its latest value in the bucket and combine those, and `count` is the number of series that reported.\n - `histogram`: `histogram_quantile` with `quantile` (e.g. 0.95). All selected series must share one bucket layout — narrow with `filters` if you get a bounds-mismatch error.\n3. **Narrow with filters.** `filters: [{key, op, value, scope?}]`, ANDed. Ops: `eq`, `neq`, `regex`, `not_regex` (RE2). Leave `scope` at its default `auto` unless you know whether the attribute is per-target (`resource`) or per-datapoint (`attribute`). Negative ops also match rows lacking the key, like Prometheus negative matchers.\n4. **Split with groupBy.** `groupBy: [{key}]` returns one series per label value (capped at the 100 largest). The service name is always available — `service_name` and `service.name` both resolve to it in metrics (logs only accept the dotted `service.name`); discover other keys from a sample query's labels or ask the user.\n5. **Control the grid with `interval`.** One of `second, minute, minute_5, minute_15, hour, hour_6, day, week`. Omit to auto-pick (~60 buckets across the range). Use the same interval when comparing windows.\n\n# Investigating an anomaly (\"metric X is rising — why?\")\n\n1. Query the metric over a window that includes the anomaly AND an equal-length healthy baseline before it (one call, auto interval).\n2. Find the onset: the first bucket where the value clearly departs from the baseline range.\n3. Re-query grouped by `service_name` (then by other candidate keys) over the same window to see WHICH series moved — a single label value moving points at the culprit; all moving together points at something shared (upstream dependency, infra).\n4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.\n5. Correlate the onset window across signals: query logs (`query-logs`, filtered to the same `service.name` and time window, severity error) and traces (APM span tools, same service/window) to find the cause and its blast radius.\n\nCRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now. `dateFrom` snaps down to its bucket boundary, so the first point can be labelled up to one interval earlier than requested but always covers a whole bucket.",+ "description": "Query server/infrastructure metrics (OTel- or Prometheus-ingested) as bucketed time series. The response is a list of series — `{labels, points: [{time, value}], metric_name, clause}` — where every series shares one time grid (missing buckets are zero-filled). A single ungrouped query returns exactly one series with empty labels.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"metricName\": \"m\", \"aggregation\": \"rate\", \"dateFrom\": \"2026-01-01T00:00:00Z\" } }\n```\n\nTwo request forms:\n\n- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).\n- **Multi-clause / formula:** set `clauses: [{name, metricName, aggregation, quantile?, filters?, groupBy?}, ...]` and optionally `formula` (e.g. `\"(a - b) / a\"` over clause names; `+ - * /` and parentheses; division by zero yields 0). With a formula set, only the formula result series are returned.\n\n# Workflow — follow this order every time\n\n1. **Discover names first.** Call `metric-names-list` with a substring (`value`) before querying — metric names must match exactly, and the returned `metric_type` tells you the right aggregation.\n2. **Pick the aggregation by metric type:**\n - `sum` counters (usually `_total`): use `rate` (per-second) or `increase` — both are counter-reset safe and temporality-aware. Do NOT use `sum`/`avg` on cumulative counters; absolute counter values are meaningless.\n - `gauge`: `avg` (typical), `p95`, `sum`.\n - Every aggregation combines across series, never across raw samples, so a result never scales with the scrape rate: `sum`/`avg`/`p95` reduce each series to its latest value in the bucket and combine those, and `count` is the number of series that reported.\n - `histogram`: `histogram_quantile` with `quantile` (e.g. 0.95). All selected series must share one bucket layout — narrow with `filters` if you get a bounds-mismatch error.\n3. **Narrow with filters.** `filters: [{key, op, value, scope?}]`, ANDed. Ops: `eq`, `neq`, `regex`, `not_regex` (RE2). Leave `scope` at its default `auto` unless you know whether the attribute is per-target (`resource`) or per-datapoint (`attribute`). Negative ops also match rows lacking the key, like Prometheus negative matchers.\n4. **Split with groupBy.** `groupBy: [{key}]` returns one series per label value (capped at the 100 largest). The service name is always available — `service_name` and `service.name` both resolve to it in metrics (logs only accept the dotted `service.name`); discover other keys from a sample query's labels or ask the user.\n5. **Control the grid with `interval`.** One of `second, minute, minute_5, minute_15, hour, hour_6, day, week`. Omit to auto-pick (~60 buckets across the range). Use the same interval when comparing windows.\n\n# Investigating an anomaly (\"metric X is rising — why?\")\n\n1. Query the metric over a window that includes the anomaly AND an equal-length healthy baseline before it (one call, auto interval).\n2. Find the onset: the first bucket where the value clearly departs from the baseline range.\n3. Re-query grouped by `service_name` (then by other candidate keys) over the same window to see WHICH series moved — a single label value moving points at the culprit; all moving together points at something shared (upstream dependency, infra).\n4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.\n5. Correlate the onset window across signals: query logs (`query-logs`, filtered to the same `service.name` and time window, severity error) and traces (APM span tools, same service/window) to find the cause and its blast radius.\n\nCRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now. `dateFrom` snaps down to its bucket boundary, so the first point can be labelled up to one interval earlier than requested but always covers a whole bucket.","category": "Metrics","feature": "metrics","summary": "Query metrics",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex a4aba32e7db9..beb1cb41b3cb 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -813,7 +813,7 @@"feature_flag": "customer-analytics-csp"},"apm-attribute-breakdown": {- "description": "Group spans by one attribute's value — the \"what is different about the bad spans?\" tool.\n\nReturns one row per distinct value of the chosen attribute, across the spans matching the filters:\n\n- `value` — the attribute's value (`''` for spans that don't carry the attribute)\n- `count` — spans with that value\n- `error_count` — of those, spans with OTel status `Error` (status_code = 2)\n- `p50_duration_nano`, `p95_duration_nano` — duration quantiles in nanoseconds\n\nRows are ordered by `count` DESC (or `error_count` DESC via `orderBy`) and capped at 5000.\n\nUse to answer:\n\n- \"Which attribute values are over-represented among the errored/slow spans?\"\n- \"Which downstream destination (`server.address`) is failing?\"\n- \"What `http.response.status_code` values are we getting back, and how often?\"\n- \"Which pod / version / region is the bad traffic concentrated on?\" (resource attributes)\n\nFor aggregates grouped by operation, use `apm-spans-aggregate`. For trends over time, use `apm-spans-sparkline`.\n\nAll parameters must be nested inside a `query` object.\n\n# \"What's different\" workflow\n\n1. Scope to the bad spans with `filterGroup` (e.g. `status_code = Error`) or `serviceNames`.\n2. Discover candidate keys with `apm-attributes-list` (don't guess — keys vary per project).\n3. Run `apm-attribute-breakdown` per candidate key. A value owning most of the `count` is your signature.\n4. To confirm over-representation, re-run without the bad-spans filter (or check `error_count / count` per row): a value at 95% of errors but 10% of all traffic is the smoking gun.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.breakdownKey (required)\n\nThe attribute key to group by (e.g. `server.address`, `http.response.status_code`, `k8s.pod.name`). Discover keys with `apm-attributes-list`.\n\n## query.breakdownType (required)\n\n- `span_attribute` — span-level attributes (e.g. `server.address`, `db.statement`)\n- `span_resource_attribute` — resource-level attributes (e.g. `k8s.pod.name`, `service.version`)\n\n## query.orderBy\n\n`count` (default) or `error_count` — rows are sorted by the chosen column, descending.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Set `compare: true` to also get the breakdown for a previous window under `compare` — useful for \"did this value's share change vs last week?\" (`compare_to: \"-7d\"`).\n\n## query.serviceNames\n\nList of service names to restrict the breakdown to. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters scoping the spans the breakdown runs over. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Which destinations do the errored spans hit?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"server.address\",\n \"breakdownType\": \"span_attribute\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": \"Error\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Which values drive the most errors overall?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"http.response.status_code\",\n \"breakdownType\": \"span_attribute\",\n \"orderBy\": \"error_count\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Is the bad pod's share new? (compare vs last week)\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"k8s.pod.name\",\n \"breakdownType\": \"span_resource_attribute\",\n \"serviceNames\": [\"cdp-worker\"],\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n# Reminders\n\n- `value: ''` groups the spans that don't carry the attribute at all — often itself a signal.\n- Duration values are in nanoseconds (1s = 1,000,000,000).\n- Use `apm-attributes-list` / `apm-attribute-values-list` to discover keys before guessing.\n- `error_count / count` per row is the error rate for that value — compute it when judging over-representation.",+ "description": "Group spans by one attribute's value — the \"what is different about the bad spans?\" tool.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"breakdownKey\": \"server.address\", \"breakdownType\": \"span_attribute\" } }\n```\n\nReturns one row per distinct value of the chosen attribute, across the spans matching the filters:\n\n- `value` — the attribute's value (`''` for spans that don't carry the attribute)\n- `count` — spans with that value\n- `error_count` — of those, spans with OTel status `Error` (status_code = 2)\n- `p50_duration_nano`, `p95_duration_nano` — duration quantiles in nanoseconds\n\nRows are ordered by `count` DESC (or `error_count` DESC via `orderBy`) and capped at 5000.\n\nUse to answer:\n\n- \"Which attribute values are over-represented among the errored/slow spans?\"\n- \"Which downstream destination (`server.address`) is failing?\"\n- \"What `http.response.status_code` values are we getting back, and how often?\"\n- \"Which pod / version / region is the bad traffic concentrated on?\" (resource attributes)\n\nFor aggregates grouped by operation, use `apm-spans-aggregate`. For trends over time, use `apm-spans-sparkline`.\n\n# \"What's different\" workflow\n\n1. Scope to the bad spans with `filterGroup` (e.g. `status_code = Error`) or `serviceNames`.\n2. Discover candidate keys with `apm-attributes-list` (don't guess — keys vary per project).\n3. Run `apm-attribute-breakdown` per candidate key. A value owning most of the `count` is your signature.\n4. To confirm over-representation, re-run without the bad-spans filter (or check `error_count / count` per row): a value at 95% of errors but 10% of all traffic is the smoking gun.\n\n# Parameters\n\n## query.breakdownKey (required)\n\nThe attribute key to group by (e.g. `server.address`, `http.response.status_code`, `k8s.pod.name`). Discover keys with `apm-attributes-list`.\n\n## query.breakdownType (required)\n\n- `span_attribute` — span-level attributes (e.g. `server.address`, `db.statement`)\n- `span_resource_attribute` — resource-level attributes (e.g. `k8s.pod.name`, `service.version`)\n\n## query.orderBy\n\n`count` (default) or `error_count` — rows are sorted by the chosen column, descending.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Set `compare: true` to also get the breakdown for a previous window under `compare` — useful for \"did this value's share change vs last week?\" (`compare_to: \"-7d\"`).\n\n## query.serviceNames\n\nList of service names to restrict the breakdown to. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters scoping the spans the breakdown runs over. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Which destinations do the errored spans hit?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"server.address\",\n \"breakdownType\": \"span_attribute\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": \"Error\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Which values drive the most errors overall?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"http.response.status_code\",\n \"breakdownType\": \"span_attribute\",\n \"orderBy\": \"error_count\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Is the bad pod's share new? (compare vs last week)\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"k8s.pod.name\",\n \"breakdownType\": \"span_resource_attribute\",\n \"serviceNames\": [\"cdp-worker\"],\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n# Reminders\n\n- `value: ''` groups the spans that don't carry the attribute at all — often itself a signal.\n- Duration values are in nanoseconds (1s = 1,000,000,000).\n- Use `apm-attributes-list` / `apm-attribute-values-list` to discover keys before guessing.\n- `error_count / count` per row is the error rate for that value — compute it when judging over-representation.","category": "Tracing","feature": "tracing","summary": "Break down spans by attribute value",@@ -873,7 +873,7 @@"feature_flag": "tracing"},"apm-spans-aggregate": {- "description": "Aggregate trace span statistics grouped by `(service_name, name)` over a date window.\n\nReturns one row per `(service_name, name)` pair with the following metrics:\n\n- `count` — number of spans matched\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (1 second = 1,000,000,000 ns). `p999_duration_nano` is the 99.9th percentile and is only meaningful for `(service, name)` groups with enough spans; on low-volume operations it collapses to the max\n- `error_count` — spans with OTel status code `Error` (status_code = 2)\n\nRows are ordered by `total_duration_nano` DESC. By default only the top 100 rows are returned — this keeps the response small, which matters because high span-name cardinality (e.g. untemplated URL paths) can otherwise produce an enormous payload. The top rows already surface the heaviest operations. When more rows genuinely exist the response sets `has_more: true` and `next_offset`; page through with `offset`, or raise `limit` (hard max 5000). Prefer narrowing with `serviceNames`/`filterGroup` over pulling a large page.\n\nUse to answer:\n\n- \"Which services/operations consume the most time?\"\n- \"What's the p95 or p99 latency of `GET /users`?\"\n- \"How many errors did the checkout service emit in the last day?\"\n- \"Did `POST /orders` get slower this week vs last week?\" (with `compareFilter`)\n\nFor per-call-tree breakdowns (parent → child relationships), use `apm-spans-tree` instead. For time-bucketed trends (\"when did it change?\"), use `apm-spans-sparkline` instead — `compareFilter` only contrasts two static windows.\n\nAll parameters must be nested inside a `query` object.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length (e.g. `dateRange: -1d` → compares vs the day before).\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\nWhen `compare` is true, `compare` is always an array — empty (`[]`) if the comparison window matched no spans (for example an operation that didn't exist yet), not null. `compare` is `null` only when no comparison was requested. So an empty array is a real answer (\"nothing in the prior window\"), not a failure.\n\n# Data narrowing\n\n## Property filters\n\nUse `query.filterGroup` to narrow results to spans matching specific attributes. Only include filters that are essential to the user's question.\n\nFilter `type` values:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes (e.g. \"http.method\", \"http.status_code\")\n- `span_resource_attribute` — resource-level attributes (e.g. k8s labels, deployment info)\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values before guessing.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`). Examples: `-1h`, `-6h`, `-1d`, `-7d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Omit when you only need the primary window.\n\n- `compare` (boolean): set to true to enable comparison.\n- `compare_to` (string, optional): relative offset for the comparison window (e.g. `-1d`, `-7d`). Defaults to the immediately previous period of equal length.\n\n## query.serviceNames\n\nList of service names to restrict the aggregation to. Use `apm-services-list` to discover available services.\n\n## query.filterGroup\n\nA flat list of property filters applied to both the primary and comparison windows. See the \"Property filters\" section.\n\n## query.limit\n\nMax rows to return, ordered by `total_duration_nano` DESC. Defaults to 100; hard max 5000. Keep this small — a high value on high-cardinality span names returns a very large response. Narrow with `serviceNames`/`filterGroup` instead of raising it when you can.\n\n## query.offset\n\nRow offset for pagination. Combine with `limit` and the `next_offset` from a previous response to page through results beyond the first page.\n\n# Examples\n\n## Top operations by total time in the last hour\n\n```json\n{\n \"query\": {}\n}\n```\n\n## p95 latency by operation in the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nInspect the `p95_duration_nano` field on each result.\n\n## Compare this hour vs the previous hour\n\n```json\n{\n \"query\": {\n \"compareFilter\": { \"compare\": true }\n }\n}\n```\n\nReturns `results` for the last hour and `compare` for the hour before. Diff `total_duration_nano`, `avg_duration_nano`, etc. to find regressions.\n\n## Compare today vs same time last week\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Aggregate only error spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Aggregate within one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Duration values are in nanoseconds. Divide by 1,000,000 for ms, 1,000,000,000 for seconds.\n- Results are ordered by `total_duration_nano` DESC and default to the top 100 rows. Check `has_more`/`next_offset` to page; raise `limit` (max 5000) only when you truly need the long tail.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attribute keys/values before filtering.\n- Use `apm-services-list` to discover services before filtering by service name.\n- For parent → child breakdowns, use `apm-spans-tree` instead.",+ "description": "Aggregate trace span statistics grouped by `(service_name, name)` over a date window.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nReturns one row per `(service_name, name)` pair with the following metrics:\n\n- `count` — number of spans matched\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (1 second = 1,000,000,000 ns). `p999_duration_nano` is the 99.9th percentile and is only meaningful for `(service, name)` groups with enough spans; on low-volume operations it collapses to the max\n- `error_count` — spans with OTel status code `Error` (status_code = 2)\n\nRows are ordered by `total_duration_nano` DESC. By default only the top 100 rows are returned — this keeps the response small, which matters because high span-name cardinality (e.g. untemplated URL paths) can otherwise produce an enormous payload. The top rows already surface the heaviest operations. When more rows genuinely exist the response sets `has_more: true` and `next_offset`; page through with `offset`, or raise `limit` (hard max 5000). Prefer narrowing with `serviceNames`/`filterGroup` over pulling a large page.\n\nUse to answer:\n\n- \"Which services/operations consume the most time?\"\n- \"What's the p95 or p99 latency of `GET /users`?\"\n- \"How many errors did the checkout service emit in the last day?\"\n- \"Did `POST /orders` get slower this week vs last week?\" (with `compareFilter`)\n\nFor per-call-tree breakdowns (parent → child relationships), use `apm-spans-tree` instead. For time-bucketed trends (\"when did it change?\"), use `apm-spans-sparkline` instead — `compareFilter` only contrasts two static windows.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length (e.g. `dateRange: -1d` → compares vs the day before).\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\nWhen `compare` is true, `compare` is always an array — empty (`[]`) if the comparison window matched no spans (for example an operation that didn't exist yet), not null. `compare` is `null` only when no comparison was requested. So an empty array is a real answer (\"nothing in the prior window\"), not a failure.\n\n# Data narrowing\n\n## Property filters\n\nUse `query.filterGroup` to narrow results to spans matching specific attributes. Only include filters that are essential to the user's question.\n\nFilter `type` values:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes (e.g. \"http.method\", \"http.status_code\")\n- `span_resource_attribute` — resource-level attributes (e.g. k8s labels, deployment info)\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values before guessing.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`). Examples: `-1h`, `-6h`, `-1d`, `-7d`.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Omit when you only need the primary window.\n\n- `compare` (boolean): set to true to enable comparison.\n- `compare_to` (string, optional): relative offset for the comparison window (e.g. `-1d`, `-7d`). Defaults to the immediately previous period of equal length.\n\n## query.serviceNames\n\nList of service names to restrict the aggregation to. Use `apm-services-list` to discover available services.\n\n## query.filterGroup\n\nA flat list of property filters applied to both the primary and comparison windows. See the \"Property filters\" section.\n\n## query.limit\n\nMax rows to return, ordered by `total_duration_nano` DESC. Defaults to 100; hard max 5000. Keep this small — a high value on high-cardinality span names returns a very large response. Narrow with `serviceNames`/`filterGroup` instead of raising it when you can.\n\n## query.offset\n\nRow offset for pagination. Combine with `limit` and the `next_offset` from a previous response to page through results beyond the first page.\n\n# Examples\n\n## Top operations by total time in the last hour\n\n```json\n{\n \"query\": {}\n}\n```\n\n## p95 latency by operation in the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nInspect the `p95_duration_nano` field on each result.\n\n## Compare this hour vs the previous hour\n\n```json\n{\n \"query\": {\n \"compareFilter\": { \"compare\": true }\n }\n}\n```\n\nReturns `results` for the last hour and `compare` for the hour before. Diff `total_duration_nano`, `avg_duration_nano`, etc. to find regressions.\n\n## Compare today vs same time last week\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Aggregate only error spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Aggregate within one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Duration values are in nanoseconds. Divide by 1,000,000 for ms, 1,000,000,000 for seconds.\n- Results are ordered by `total_duration_nano` DESC and default to the top 100 rows. Check `has_more`/`next_offset` to page; raise `limit` (max 5000) only when you truly need the long tail.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attribute keys/values before filtering.\n- Use `apm-services-list` to discover services before filtering by service name.\n- For parent → child breakdowns, use `apm-spans-tree` instead.","category": "Tracing","feature": "tracing","summary": "Aggregate span statistics",@@ -888,7 +888,7 @@"feature_flag": "tracing"},"apm-spans-count": {- "description": "Return a scalar count of trace spans matching a filter set. Use this as a cheap pre-flight before `query-apm-spans` — if the count is large, narrow the filters (or set `excludeAttributes`) before pulling rows.\n\nAll parameters must be nested inside a `query` object.\n\n# When to use\n\n- Before `query-apm-spans`, to confirm the filter set returns a tractable number of spans rather than pulling rows blind.\n- When the user asks \"how many X spans are there?\" and you don't need to see individual spans.\n- To check whether a filter combination matches anything at all before committing to a full query.\n\nThis counts **spans**, not traces. A single trace contains many spans, so a count of matching spans will exceed the number of matching traces.\n\nIf the count would scan too much data (a wide date range with no filters), the tool returns a 400 asking you to narrow the window or add filters — narrow the `dateRange` or add `serviceNames` / `statusCodes` / `filterGroup`, then retry.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range for the count. 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`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nFilter by service names. Unlike `query-apm-spans`, an unfiltered count is cheap and useful for sizing up a filter before narrowing. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.filterGroup\n\nProperty filters to narrow the count. Same format as `query-apm-spans` filters — each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`.\n\n# Examples\n\n## Count error spans in a service over the last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"statusCodes\": [2],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Count how many spans match a name before fetching them\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"name\", \"operator\": \"exact\", \"type\": \"span\", \"value\": \"redis_cluster.discovery\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```",+ "description": "Return a scalar count of trace spans matching a filter set. Use this as a cheap pre-flight before `query-apm-spans` — if the count is large, narrow the filters (or set `excludeAttributes`) before pulling rows.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\n# When to use\n\n- Before `query-apm-spans`, to confirm the filter set returns a tractable number of spans rather than pulling rows blind.\n- When the user asks \"how many X spans are there?\" and you don't need to see individual spans.\n- To check whether a filter combination matches anything at all before committing to a full query.\n\nThis counts **spans**, not traces. A single trace contains many spans, so a count of matching spans will exceed the number of matching traces.\n\nIf the count would scan too much data (a wide date range with no filters), the tool returns a 400 asking you to narrow the window or add filters — narrow the `dateRange` or add `serviceNames` / `statusCodes` / `filterGroup`, then retry.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the count. 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`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nFilter by service names. Unlike `query-apm-spans`, an unfiltered count is cheap and useful for sizing up a filter before narrowing. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.filterGroup\n\nProperty filters to narrow the count. Same format as `query-apm-spans` filters — each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`.\n\n# Examples\n\n## Count error spans in a service over the last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"statusCodes\": [2],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Count how many spans match a name before fetching them\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"name\", \"operator\": \"exact\", \"type\": \"span\", \"value\": \"redis_cluster.discovery\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```","category": "Tracing","feature": "tracing","summary": "Count spans",@@ -903,7 +903,7 @@"feature_flag": "tracing"},"apm-spans-duration-histogram": {- "description": "Trace counts per logarithmic duration bucket — the latency distribution of requests.\n\nReturns one row per `(duration bucket, service)` pair:\n\n- `bucket_ns` — bucket floor in nanoseconds, on the 1-2-5 series (1ms, 2ms, 5ms, 10ms, 20ms, ...)\n- `service` — service name (top 10 services per bucket)\n- `count` — traces whose ROOT span duration falls in the bucket\n\nBuckets count **traces by their root span's duration** (the request the user experienced), never child spans. Only non-empty buckets are returned.\n\nUse to answer:\n\n- \"What does the latency distribution look like — one population or bimodal?\"\n- \"How many requests took longer than 1 second?\"\n- \"Is the long tail a handful of outliers or a real second mode?\"\n- \"Which duration range should I filter on before pulling slow traces?\"\n\nFor percentiles per operation (p50/p95), use `apm-spans-aggregate`. For counts over time, use `apm-spans-sparkline`.\n\nAll parameters must be nested inside a `query` object.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nList of service names to restrict the histogram to. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.filterGroup\n\nProperty filters applied to the matched spans. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Latency distribution for one service over the last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Distribution of error traces only\n\n```json\n{\n \"query\": {\n \"statusCodes\": [2],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n# Reminders\n\n- `bucket_ns` is nanoseconds: 1ms = 1,000,000; 1s = 1,000,000,000.\n- Counts are **traces** (one per root span), so they line up with request counts — not with `apm-spans-count`, which counts every span.\n- Buckets follow the 1-2-5 series; a trace of 3.5ms lands in the 2ms bucket (bucket floor).\n- To fetch the actual slow traces after spotting a tail, use `query-apm-spans` with a `duration` filter (nanoseconds) and `orderBy: \"duration\"`.",+ "description": "Trace counts per logarithmic duration bucket — the latency distribution of requests.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nReturns one row per `(duration bucket, service)` pair:\n\n- `bucket_ns` — bucket floor in nanoseconds, on the 1-2-5 series (1ms, 2ms, 5ms, 10ms, 20ms, ...)\n- `service` — service name (top 10 services per bucket)\n- `count` — traces whose ROOT span duration falls in the bucket\n\nBuckets count **traces by their root span's duration** (the request the user experienced), never child spans. Only non-empty buckets are returned.\n\nUse to answer:\n\n- \"What does the latency distribution look like — one population or bimodal?\"\n- \"How many requests took longer than 1 second?\"\n- \"Is the long tail a handful of outliers or a real second mode?\"\n- \"Which duration range should I filter on before pulling slow traces?\"\n\nFor percentiles per operation (p50/p95), use `apm-spans-aggregate`. For counts over time, use `apm-spans-sparkline`.\n\n# Parameters\n\n## query.dateRange\n\nDate range. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nList of service names to restrict the histogram to. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.filterGroup\n\nProperty filters applied to the matched spans. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Latency distribution for one service over the last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Distribution of error traces only\n\n```json\n{\n \"query\": {\n \"statusCodes\": [2],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n# Reminders\n\n- `bucket_ns` is nanoseconds: 1ms = 1,000,000; 1s = 1,000,000,000.\n- Counts are **traces** (one per root span), so they line up with request counts — not with `apm-spans-count`, which counts every span.\n- Buckets follow the 1-2-5 series; a trace of 3.5ms lands in the 2ms bucket (bucket floor).\n- To fetch the actual slow traces after spotting a tail, use `query-apm-spans` with a `duration` filter (nanoseconds) and `orderBy: \"duration\"`.","category": "Tracing","feature": "tracing","summary": "Trace duration distribution (histogram)",@@ -918,7 +918,7 @@"feature_flag": "tracing"},"apm-spans-latency-heatmap": {- "description": "Latency over time — trace counts per (time bucket, duration bucket) cell, combining `apm-spans-sparkline` and `apm-spans-duration-histogram` into one call: \"when did latency change, and how\".\n\nReturns one row per non-empty `(time bucket, duration bucket)` cell:\n\n- `time` — ISO 8601 bucket start (UTC)\n- `bucket_ns` — duration bucket floor in nanoseconds, on the 1-2-5 series (1ms, 2ms, 5ms, 10ms, 20ms, ...)\n- `count` — traces whose ROOT span duration falls in that cell (or spans, when `rootSpans` is false)\n\nTime buckets are sized adaptively to the window (roughly 50 buckets regardless of range, e.g. `-1h` → ~minute buckets, `-7d` → ~4-hour buckets). A time bucket with no matching traces returns a single sentinel row `{time, bucket_ns: 0, count: 0}`, so the full time axis can be read off the response — ignore sentinel rows when reading densities.\n\nUse to answer:\n\n- \"When did this service get slow?\" — the slow band's first non-empty `time` is the onset.\n- \"Is the latency regression a shift (whole distribution moved) or a new mode (a second band appeared)?\"\n- \"Did the deploy at 14:00 change the latency profile, not just the p95?\"\n- \"Is the slow tail constant background or bursty?\"\n\nFor a single distribution with per-service breakdown, use `apm-spans-duration-histogram`; for counts over time, `apm-spans-sparkline`; for per-operation percentiles, `apm-spans-aggregate`.\n\nAll parameters must be nested inside a `query` object.\n\n# Reading the grid\n\nGroup rows by `bucket_ns` and read each duration bucket as a horizontal band over time:\n\n- A band that exists in every time bucket at similar counts = steady-state population.\n- A band that starts at a specific `time` = something changed then (deploy, dependency, cache).\n- The whole distribution stepping up one or two buckets at once = a uniform slowdown.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range for the grid. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nList of service names to restrict the grid to. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.rootSpans\n\nWhen true (default), cells count **traces by their root span's duration** — the request the user experienced, lining up with `apm-spans-duration-histogram`. Set false to count every matching span instead; combine with a `name` filter for one operation's latency over time.\n\n## query.filterGroup\n\nProperty filters applied to the counted spans. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## When did api-gateway get slow, over the last day?\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## One operation's latency over time (span-level, not per trace)\n\n```json\n{\n \"query\": {\n \"rootSpans\": false,\n \"filterGroup\": [{ \"key\": \"name\", \"operator\": \"exact\", \"type\": \"span\", \"value\": [\"SELECT orders\"] }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n# Reminders\n\n- `bucket_ns` is nanoseconds: 1ms = 1,000,000; 1s = 1,000,000,000. Buckets follow the 1-2-5 series; a 3.5ms trace lands in the 2ms bucket (bucket floor).\n- `{bucket_ns: 0, count: 0}` rows are the sentinel time-axis filler described above — skip them when reading densities.\n- Default counts are **traces** (one per root span); they line up with `apm-spans-duration-histogram`, not with `apm-spans-count`.\n- Cells carry no service breakdown — narrow with `serviceNames` instead.\n- After spotting when the slow band appeared, pull the actual traces with `query-apm-spans` filtered to that time window plus a `duration` filter (nanoseconds), `orderBy: \"duration\"`.",+ "description": "Latency over time — trace counts per (time bucket, duration bucket) cell, combining `apm-spans-sparkline` and `apm-spans-duration-histogram` into one call: \"when did latency change, and how\".\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nReturns one row per non-empty `(time bucket, duration bucket)` cell:\n\n- `time` — ISO 8601 bucket start (UTC)\n- `bucket_ns` — duration bucket floor in nanoseconds, on the 1-2-5 series (1ms, 2ms, 5ms, 10ms, 20ms, ...)\n- `count` — traces whose ROOT span duration falls in that cell (or spans, when `rootSpans` is false)\n\nTime buckets are sized adaptively to the window (roughly 50 buckets regardless of range, e.g. `-1h` → ~minute buckets, `-7d` → ~4-hour buckets). A time bucket with no matching traces returns a single sentinel row `{time, bucket_ns: 0, count: 0}`, so the full time axis can be read off the response — ignore sentinel rows when reading densities.\n\nUse to answer:\n\n- \"When did this service get slow?\" — the slow band's first non-empty `time` is the onset.\n- \"Is the latency regression a shift (whole distribution moved) or a new mode (a second band appeared)?\"\n- \"Did the deploy at 14:00 change the latency profile, not just the p95?\"\n- \"Is the slow tail constant background or bursty?\"\n\nFor a single distribution with per-service breakdown, use `apm-spans-duration-histogram`; for counts over time, `apm-spans-sparkline`; for per-operation percentiles, `apm-spans-aggregate`.\n\n# Reading the grid\n\nGroup rows by `bucket_ns` and read each duration bucket as a horizontal band over time:\n\n- A band that exists in every time bucket at similar counts = steady-state population.\n- A band that starts at a specific `time` = something changed then (deploy, dependency, cache).\n- The whole distribution stepping up one or two buckets at once = a uniform slowdown.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the grid. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nList of service names to restrict the grid to. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.rootSpans\n\nWhen true (default), cells count **traces by their root span's duration** — the request the user experienced, lining up with `apm-spans-duration-histogram`. Set false to count every matching span instead; combine with a `name` filter for one operation's latency over time.\n\n## query.filterGroup\n\nProperty filters applied to the counted spans. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## When did api-gateway get slow, over the last day?\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## One operation's latency over time (span-level, not per trace)\n\n```json\n{\n \"query\": {\n \"rootSpans\": false,\n \"filterGroup\": [{ \"key\": \"name\", \"operator\": \"exact\", \"type\": \"span\", \"value\": [\"SELECT orders\"] }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n# Reminders\n\n- `bucket_ns` is nanoseconds: 1ms = 1,000,000; 1s = 1,000,000,000. Buckets follow the 1-2-5 series; a 3.5ms trace lands in the 2ms bucket (bucket floor).\n- `{bucket_ns: 0, count: 0}` rows are the sentinel time-axis filler described above — skip them when reading densities.\n- Default counts are **traces** (one per root span); they line up with `apm-spans-duration-histogram`, not with `apm-spans-count`.\n- Cells carry no service breakdown — narrow with `serviceNames` instead.\n- After spotting when the slow band appeared, pull the actual traces with `query-apm-spans` filtered to that time window plus a `duration` filter (nanoseconds), `orderBy: \"duration\"`.","category": "Tracing","feature": "tracing","summary": "Latency over time (heatmap)",@@ -933,7 +933,7 @@"feature_flag": "tracing"},"apm-spans-sparkline": {- "description": "Span counts over time — a zero-filled time series for trend and spike analysis.\n\nReturns one row per `(time bucket, service)` pair:\n\n- `time` — ISO 8601 bucket start (UTC)\n- `service` — service name (top 10 services per bucket)\n- `count` — spans in that bucket matching the filters\n\nBuckets are sized adaptively to the window (roughly 50 buckets regardless of range, e.g. `-1h` → ~minute buckets, `-7d` → ~hour buckets). Quiet stretches return zero-count rows, so the series is continuous — read spike timing straight off the `time` values.\n\nUse to answer:\n\n- \"When did the error rate spike?\" (see the error-trend workflow below)\n- \"Is traffic to service X growing, flat, or bursty?\"\n- \"Did span volume change after the deploy at 14:00?\"\n- \"Which time window should I zoom into before pulling raw spans?\"\n\nFor a single aggregate number per operation, use `apm-spans-aggregate` instead. For latency distribution, use `apm-spans-duration-histogram`.\n\nAll parameters must be nested inside a `query` object.\n\n# Error-trend workflow\n\nTwo calls, then divide per bucket:\n\n1. `apm-spans-sparkline` with your filters → total counts per bucket.\n2. The same call with `statusCodes: [2]` added → error counts per bucket.\n\nError rate per bucket = errors / total. The bucket where the ratio jumps is when the spike started.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.dateRange\n\nDate range for the series. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nList of service names to restrict the series to. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.filterGroup\n\nProperty filters applied to the counted spans. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Span volume per service over the last 6 hours\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Error spans only, one service, last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"statusCodes\": [2],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Request (root span) volume trend\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"is_root_span\", \"operator\": \"exact\", \"type\": \"span\", \"value\": true }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Counts are **spans**, not traces — filter `is_root_span = true` to count requests/traces.\n- Zero-count rows are bucket filler; read non-zero rows for activity and zero rows for gaps.\n- Only the top 10 services per bucket are returned — narrow with `serviceNames` when a busy project drowns out the service you care about.\n- Use `apm-services-list`, `apm-attributes-list`, `apm-attribute-values-list` to discover values before filtering.",+ "description": "Span counts over time — a zero-filled time series for trend and spike analysis.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nReturns one row per `(time bucket, service)` pair:\n\n- `time` — ISO 8601 bucket start (UTC)\n- `service` — service name (top 10 services per bucket)\n- `count` — spans in that bucket matching the filters\n\nBuckets are sized adaptively to the window (roughly 50 buckets regardless of range, e.g. `-1h` → ~minute buckets, `-7d` → ~hour buckets). Quiet stretches return zero-count rows, so the series is continuous — read spike timing straight off the `time` values.\n\nUse to answer:\n\n- \"When did the error rate spike?\" (see the error-trend workflow below)\n- \"Is traffic to service X growing, flat, or bursty?\"\n- \"Did span volume change after the deploy at 14:00?\"\n- \"Which time window should I zoom into before pulling raw spans?\"\n\nFor a single aggregate number per operation, use `apm-spans-aggregate` instead. For latency distribution, use `apm-spans-duration-histogram`.\n\n# Error-trend workflow\n\nTwo calls, then divide per bucket:\n\n1. `apm-spans-sparkline` with your filters → total counts per bucket.\n2. The same call with `statusCodes: [2]` added → error counts per bucket.\n\nError rate per bucket = errors / total. The bucket where the ratio jumps is when the spike started.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the series. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.serviceNames\n\nList of service names to restrict the series to. Use `apm-services-list` to discover services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.filterGroup\n\nProperty filters applied to the counted spans. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Span volume per service over the last 6 hours\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Error spans only, one service, last day\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"statusCodes\": [2],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Request (root span) volume trend\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"is_root_span\", \"operator\": \"exact\", \"type\": \"span\", \"value\": true }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Counts are **spans**, not traces — filter `is_root_span = true` to count requests/traces.\n- Zero-count rows are bucket filler; read non-zero rows for activity and zero rows for gaps.\n- Only the top 10 services per bucket are returned — narrow with `serviceNames` when a busy project drowns out the service you care about.\n- Use `apm-services-list`, `apm-attributes-list`, `apm-attribute-values-list` to discover values before filtering.","category": "Tracing","feature": "tracing","summary": "Span counts over time (sparkline)",@@ -948,7 +948,7 @@"feature_flag": "tracing"},"apm-spans-tree": {- "description": "Aggregate trace span statistics as a call tree — one row per `(parent_service, parent_name) → (service_name, name)` edge.\n\nRequires a `spanName` to bound the matched trace set (the `(trace_id, parent_span_id)` self-join is unsafe at high cardinality without it), and a `serviceName` to scope the returned tree to a single service. All traces that contain at least one span with the given name in the given service are included, and every span in those traces from that service is aggregated against its parent.\n\nReturns rows with:\n\n- `parent_service`, `parent_name` — the parent span identity (`parent_name` is `\"<ROOT>\"` for root spans)\n- `service_name`, `name` — the child span identity\n- `count` — number of spans matched for this `(parent, child)` edge\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (`p999_duration_nano` is the 99.9th percentile; only meaningful for high-volume edges)\n- `error_count` — child spans with OTel status code `Error` (status_code = 2)\n- `avg_start_offset_nano` — average nanoseconds from the parent span's start to this child's start\n- `calls_per_parent_invocation` — how many times this child runs per parent invocation (null for root edges). A child can top `total_duration_nano` purely by fan-out volume; divide by this to compare per-call cost\n\nRows are ordered by `total_duration_nano` DESC and capped at 5000.\n\nUse to answer:\n\n- \"What does the `/checkout` flow actually call downstream?\"\n- \"Which child operation under `POST /orders` is the slowest?\"\n- \"Where is time spent inside `process_payment` — DB, external API, or something else?\"\n- \"Did the call tree under `/api/feed` change between last week and this week?\" (with `compareFilter`)\n\nFor a flat per-operation view (no parent linkage), use `apm-spans-aggregate` instead.\n\nAll parameters must be nested inside a `query` object.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length.\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\n# Data narrowing\n\n## Property filters\n\n`query.filterGroup` narrows the matched span set. Same filter shape and operators as `apm-spans-aggregate` / `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values.\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`).\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.spanName (required)\n\nThe span name that anchors the matched trace set. Every trace containing at least one span with this name (in the given `serviceName`) is included.\n\nPick a high-level entry-point span (e.g. an HTTP route or job name). Generic names (`HTTP`, `GET`) match too many traces and produce noisy aggregates. Use `query-apm-spans` first if you need to discover concrete span names.\n\n## query.serviceName (required)\n\nThe service the tree should be scoped to. Applied to the spans CTE so the returned rows only contain spans from this service, even when the matched traces also touch other services. Use `apm-services-list` to discover service names.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Same shape as in `apm-spans-aggregate`.\n\n## query.serviceNames\n\nList of service names to filter the matched span set. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters applied to both windows. See the \"Property filters\" section.\n\n# Examples\n\n## Call tree under a specific operation in the last hour\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\"\n }\n}\n```\n\n## Call tree over the last day\n\n```json\n{\n \"query\": {\n \"spanName\": \"checkout_flow\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Compare today's call tree vs last week\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Restrict to error-bearing traces\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }]\n }\n}\n```\n\n# Reminders\n\n- `spanName` and `serviceName` are both required. Bound `spanName` to a specific high-level span (avoid generic names like `HTTP`); set `serviceName` to the one service whose call-tree you want.\n- Root spans have `parent_name = \"<ROOT>\"` and `avg_start_offset_nano = 0`.\n- Duration values are in nanoseconds.\n- Results are ordered by `total_duration_nano` DESC and capped at 5000 rows.\n- `calls_per_parent_invocation` is derived from the returned rows. If results hit the 5000-row cap (only happens with very high span-name cardinality in one service), a parent's edges can be split across the cut and the ratio can read high — treat it as approximate when the row count is at the cap.\n- For a flat per-operation aggregate without parent linkage, use `apm-spans-aggregate`.\n- Use `apm-services-list`, `apm-attributes-list`, `apm-attribute-values-list` to discover values before filtering.",+ "description": "Aggregate trace span statistics as a call tree — one row per `(parent_service, parent_name) → (service_name, name)` edge.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"spanName\": \"GET /checkout\", \"serviceName\": \"api\", \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nRequires a `spanName` to bound the matched trace set (the `(trace_id, parent_span_id)` self-join is unsafe at high cardinality without it), and a `serviceName` to scope the returned tree to a single service. All traces that contain at least one span with the given name in the given service are included, and every span in those traces from that service is aggregated against its parent.\n\nReturns rows with:\n\n- `parent_service`, `parent_name` — the parent span identity (`parent_name` is `\"<ROOT>\"` for root spans)\n- `service_name`, `name` — the child span identity\n- `count` — number of spans matched for this `(parent, child)` edge\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (`p999_duration_nano` is the 99.9th percentile; only meaningful for high-volume edges)\n- `error_count` — child spans with OTel status code `Error` (status_code = 2)\n- `avg_start_offset_nano` — average nanoseconds from the parent span's start to this child's start\n- `calls_per_parent_invocation` — how many times this child runs per parent invocation (null for root edges). A child can top `total_duration_nano` purely by fan-out volume; divide by this to compare per-call cost\n\nRows are ordered by `total_duration_nano` DESC and capped at 5000.\n\nUse to answer:\n\n- \"What does the `/checkout` flow actually call downstream?\"\n- \"Which child operation under `POST /orders` is the slowest?\"\n- \"Where is time spent inside `process_payment` — DB, external API, or something else?\"\n- \"Did the call tree under `/api/feed` change between last week and this week?\" (with `compareFilter`)\n\nFor a flat per-operation view (no parent linkage), use `apm-spans-aggregate` instead.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length.\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\n# Data narrowing\n\n## Property filters\n\n`query.filterGroup` narrows the matched span set. Same filter shape and operators as `apm-spans-aggregate` / `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values.\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`).\n\n# Parameters\n\n## query.spanName (required)\n\nThe span name that anchors the matched trace set. Every trace containing at least one span with this name (in the given `serviceName`) is included.\n\nPick a high-level entry-point span (e.g. an HTTP route or job name). Generic names (`HTTP`, `GET`) match too many traces and produce noisy aggregates. Use `query-apm-spans` first if you need to discover concrete span names.\n\n## query.serviceName (required)\n\nThe service the tree should be scoped to. Applied to the spans CTE so the returned rows only contain spans from this service, even when the matched traces also touch other services. Use `apm-services-list` to discover service names.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Same shape as in `apm-spans-aggregate`.\n\n## query.serviceNames\n\nList of service names to filter the matched span set. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters applied to both windows. See the \"Property filters\" section.\n\n# Examples\n\n## Call tree under a specific operation in the last hour\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\"\n }\n}\n```\n\n## Call tree over the last day\n\n```json\n{\n \"query\": {\n \"spanName\": \"checkout_flow\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Compare today's call tree vs last week\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Restrict to error-bearing traces\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }]\n }\n}\n```\n\n# Reminders\n\n- `spanName` and `serviceName` are both required. Bound `spanName` to a specific high-level span (avoid generic names like `HTTP`); set `serviceName` to the one service whose call-tree you want.\n- Root spans have `parent_name = \"<ROOT>\"` and `avg_start_offset_nano = 0`.\n- Duration values are in nanoseconds.\n- Results are ordered by `total_duration_nano` DESC and capped at 5000 rows.\n- `calls_per_parent_invocation` is derived from the returned rows. If results hit the 5000-row cap (only happens with very high span-name cardinality in one service), a parent's edges can be split across the cut and the ratio can read high — treat it as approximate when the row count is at the cap.\n- For a flat per-operation aggregate without parent linkage, use `apm-spans-aggregate`.\n- Use `apm-services-list`, `apm-attributes-list`, `apm-attribute-values-list` to discover values before filtering.","category": "Tracing","feature": "tracing","summary": "Aggregate span call tree",@@ -1898,7 +1898,7 @@}},"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\nAll parameters go inside `query`:\n\n```json\n{ \"query\": { \"metricName\": \"m\", \"anomalyFrom\": \"2026-01-01T00:00:00Z\" } }\n```\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 -> histogram_quantile 0.95); 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.",+ "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\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"metricName\": \"m\", \"anomalyFrom\": \"2026-01-01T00:00:00Z\" } }\n```\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 -> histogram_quantile 0.95); 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.","category": "Metrics","feature": "metrics","summary": "Characterize metric anomaly",@@ -7884,7 +7884,7 @@}},"logs-count": {- "description": "Return a scalar count of log entries matching a filter set. Use this as a cheap pre-flight before `query-logs` — if the count exceeds `query-logs`'s max `limit` of 1000, narrow the filters before pulling rows.\n\nAll parameters must be nested inside a `query` object.\n\n# When to use\n\n- Before `query-logs`, to confirm the filter set returns a tractable number of rows. If the count is above `query-logs`'s max `limit` of 1000, narrow the filters.\n- When the user asks \"how many X logs are there?\" and you don't need to see individual rows.\n- To check whether a filter combination matches anything at all before committing to a full query.\n\nTo find **when** the volume is concentrated within the window (rather than just the total), follow up with `logs-count-ranges` — it returns time-bucketed counts with explicit `date_from`/`date_to` per bucket so you can drill into a sub-range without reasoning about interval width.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the count. 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. Unlike `query-logs`, this tool does NOT require `serviceNames` — an unfiltered count is cheap and often useful for sizing up a filter before narrowing.\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# Examples\n\n## Count errors in a service 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## Confirm a k8s namespace is producing logs at all\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1h\" },\n \"filterGroup\": [\n { \"key\": \"k8s.namespace.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"payments\" }\n ]\n }\n}\n```",+ "description": "Return a scalar count of log entries matching a filter set. Use this as a cheap pre-flight before `query-logs` — if the count exceeds `query-logs`'s max `limit` of 1000, narrow the filters before pulling rows.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\n# When to use\n\n- Before `query-logs`, to confirm the filter set returns a tractable number of rows. If the count is above `query-logs`'s max `limit` of 1000, narrow the filters.\n- When the user asks \"how many X logs are there?\" and you don't need to see individual rows.\n- To check whether a filter combination matches anything at all before committing to a full query.\n\nTo find **when** the volume is concentrated within the window (rather than just the total), follow up with `logs-count-ranges` — it returns time-bucketed counts with explicit `date_from`/`date_to` per bucket so you can drill into a sub-range without reasoning about interval width.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the count. 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. Unlike `query-logs`, this tool does NOT require `serviceNames` — an unfiltered count is cheap and often useful for sizing up a filter before narrowing.\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# Examples\n\n## Count errors in a service 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## Confirm a k8s namespace is producing logs at all\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1h\" },\n \"filterGroup\": [\n { \"key\": \"k8s.namespace.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"payments\" }\n ]\n }\n}\n```","category": "Logs","feature": "logs","summary": "Count logs",@@ -7898,7 +7898,7 @@}},"logs-count-ranges": {- "description": "Get adaptive-interval bucket counts for a filtered log stream. Returns a flat list of `{date_from, date_to, count}` buckets covering the requested window. Modeled on Elasticsearch's `auto_date_histogram` — caller specifies a target bucket count, the engine picks the interval.\n\nUse this to find **where the volume is concentrated** before pulling rows. Cheaper than `query-logs`, more agent-friendly than `logs-sparkline-query` (each bucket carries explicit `date_from`/`date_to` you can feed straight back as the next call's `dateRange` to drill in).\n\n# When to use this vs other tools\n\n- **`logs-count`** — total volume in a window. Scalar.\n- **`logs-count-ranges`** (this tool) — _when_ in the window the volume sits. Time-bucketed.\n- **`query-logs`** — pull individual log rows. Most expensive; only call after counts confirm the window is right-sized.\n\n# Recursion pattern (the main reason this tool exists)\n\nUse the response to narrow into a sub-range without reasoning about interval width:\n\n1. Call `logs-count-ranges` with the user's window (e.g. last 24h).\n2. Pick the bucket(s) of interest (densest, an obvious spike, an unexpectedly empty stretch).\n3. Call `logs-count-ranges` again with that bucket's `date_from` and `date_to` as the next `dateRange`.\n4. Repeat up to ~3–4 levels — stop when buckets are shorter than your precision goal (e.g. 1 minute).\n5. Once narrowed, call `query-logs` for the actual rows.\n\nThis is the same pattern Elasticsearch users follow with `auto_date_histogram`. Keep recursion shallow — every call is cheap individually but they multiply quickly.\n\n# Parameters\n\nAll parameters must be nested inside a `query` object.\n\n## query.dateRange\n\nWindow to bucket. Defaults to the last hour (`-1h`). Same format as `query-logs`.\n\n## query.targetBuckets\n\nApproximate bucket count. Defaults to **10**, max 100. The engine picks the interval adaptively from a fixed list (1/5/10s, 1/2/5/10/15/30/60/120/240/360/720/1440m) to land near this target — actual count may differ slightly. Empty buckets are dropped, so the response can have fewer rows than `targetBuckets`.\n\nPick a value based on what you're doing:\n\n- **10** (default) — overview, finding spikes, \"is this concentrated or spread out?\"\n- **20–30** — characterising a known busy window\n- **50+** — high-resolution drill-down, only when you know the window is small\n\n## query.severityLevels, query.serviceNames, query.searchTerm, query.filterGroup\n\nSame shape as `query-logs`. Applied **before** bucketing.\n\n# Response\n\n```json\n{\n \"ranges\": [\n { \"date_from\": \"2026-04-26T00:00:00Z\", \"date_to\": \"2026-04-26T02:24:00Z\", \"count\": 1024 },\n { \"date_from\": \"2026-04-26T02:24:00Z\", \"date_to\": \"2026-04-26T04:48:00Z\", \"count\": 47 }\n ],\n \"interval\": \"2h\"\n}\n```\n\n- `ranges` — buckets ordered by `date_from` ascending. **Empty buckets are omitted** — infer gaps by comparing each bucket's `date_to` to the next bucket's `date_from`.\n- `interval` — short-form duration of the chosen bucket width (`1s` / `5m` / `1h` / `1d`). Informational only — for follow-up queries, use the per-bucket `date_from`/`date_to`.\n\n# Examples\n\n## Find when errors spiked over the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"targetBuckets\": 24,\n \"serviceNames\": [\"api-gateway\"],\n \"severityLevels\": [\"error\", \"fatal\"]\n }\n}\n```\n\n## Drill into the densest hour from a previous call\n\nAfter picking the densest bucket from the response above (say `{date_from: \"2026-04-26T15:00:00Z\", date_to: \"2026-04-26T16:00:00Z\", count: 894}`):\n\n```json\n{\n \"query\": {\n \"dateRange\": {\n \"date_from\": \"2026-04-26T15:00:00Z\",\n \"date_to\": \"2026-04-26T16:00:00Z\"\n },\n \"targetBuckets\": 12,\n \"serviceNames\": [\"api-gateway\"],\n \"severityLevels\": [\"error\", \"fatal\"]\n }\n}\n```\n\n# Reminders\n\n- Cap recursion at ~3–4 levels. If your bucket width drops below your precision goal (e.g. 1 minute), stop and call `query-logs`.\n- Empty windows return `{\"ranges\": [], \"interval\": \"...\"}` — that's not an error, it's \"I asked, nothing matched.\"\n- Always include `serviceNames` or a resource attribute filter, just like `query-logs`. Don't bucket the entire team's log stream.",+ "description": "Get adaptive-interval bucket counts for a filtered log stream. Returns a flat list of `{date_from, date_to, count}` buckets covering the requested window. Modeled on Elasticsearch's `auto_date_histogram` — caller specifies a target bucket count, the engine picks the interval.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nUse this to find **where the volume is concentrated** before pulling rows. Cheaper than `query-logs`, more agent-friendly than `logs-sparkline-query` (each bucket carries explicit `date_from`/`date_to` you can feed straight back as the next call's `dateRange` to drill in).\n\n# When to use this vs other tools\n\n- **`logs-count`** — total volume in a window. Scalar.\n- **`logs-count-ranges`** (this tool) — _when_ in the window the volume sits. Time-bucketed.\n- **`query-logs`** — pull individual log rows. Most expensive; only call after counts confirm the window is right-sized.\n\n# Recursion pattern (the main reason this tool exists)\n\nUse the response to narrow into a sub-range without reasoning about interval width:\n\n1. Call `logs-count-ranges` with the user's window (e.g. last 24h).\n2. Pick the bucket(s) of interest (densest, an obvious spike, an unexpectedly empty stretch).\n3. Call `logs-count-ranges` again with that bucket's `date_from` and `date_to` as the next `dateRange`.\n4. Repeat up to ~3–4 levels — stop when buckets are shorter than your precision goal (e.g. 1 minute).\n5. Once narrowed, call `query-logs` for the actual rows.\n\nThis is the same pattern Elasticsearch users follow with `auto_date_histogram`. Keep recursion shallow — every call is cheap individually but they multiply quickly.\n\n# Parameters\n\n## query.dateRange\n\nWindow to bucket. Defaults to the last hour (`-1h`). Same format as `query-logs`.\n\n## query.targetBuckets\n\nApproximate bucket count. Defaults to **10**, max 100. The engine picks the interval adaptively from a fixed list (1/5/10s, 1/2/5/10/15/30/60/120/240/360/720/1440m) to land near this target — actual count may differ slightly. Empty buckets are dropped, so the response can have fewer rows than `targetBuckets`.\n\nPick a value based on what you're doing:\n\n- **10** (default) — overview, finding spikes, \"is this concentrated or spread out?\"\n- **20–30** — characterising a known busy window\n- **50+** — high-resolution drill-down, only when you know the window is small\n\n## query.severityLevels, query.serviceNames, query.searchTerm, query.filterGroup\n\nSame shape as `query-logs`. Applied **before** bucketing.\n\n# Response\n\n```json\n{\n \"ranges\": [\n { \"date_from\": \"2026-04-26T00:00:00Z\", \"date_to\": \"2026-04-26T02:24:00Z\", \"count\": 1024 },\n { \"date_from\": \"2026-04-26T02:24:00Z\", \"date_to\": \"2026-04-26T04:48:00Z\", \"count\": 47 }\n ],\n \"interval\": \"2h\"\n}\n```\n\n- `ranges` — buckets ordered by `date_from` ascending. **Empty buckets are omitted** — infer gaps by comparing each bucket's `date_to` to the next bucket's `date_from`.\n- `interval` — short-form duration of the chosen bucket width (`1s` / `5m` / `1h` / `1d`). Informational only — for follow-up queries, use the per-bucket `date_from`/`date_to`.\n\n# Examples\n\n## Find when errors spiked over the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"targetBuckets\": 24,\n \"serviceNames\": [\"api-gateway\"],\n \"severityLevels\": [\"error\", \"fatal\"]\n }\n}\n```\n\n## Drill into the densest hour from a previous call\n\nAfter picking the densest bucket from the response above (say `{date_from: \"2026-04-26T15:00:00Z\", date_to: \"2026-04-26T16:00:00Z\", count: 894}`):\n\n```json\n{\n \"query\": {\n \"dateRange\": {\n \"date_from\": \"2026-04-26T15:00:00Z\",\n \"date_to\": \"2026-04-26T16:00:00Z\"\n },\n \"targetBuckets\": 12,\n \"serviceNames\": [\"api-gateway\"],\n \"severityLevels\": [\"error\", \"fatal\"]\n }\n}\n```\n\n# Reminders\n\n- Cap recursion at ~3–4 levels. If your bucket width drops below your precision goal (e.g. 1 minute), stop and call `query-logs`.\n- Empty windows return `{\"ranges\": [], \"interval\": \"...\"}` — that's not an error, it's \"I asked, nothing matched.\"\n- Always include `serviceNames` or a resource attribute filter, just like `query-logs`. Don't bucket the entire team's log stream.","category": "Logs","feature": "logs","summary": "Count logs by time bucket",@@ -7912,7 +7912,7 @@}},"logs-facet-values-create": {- "description": "Return per-value counts for a single facet — the distribution of a log dimension across a filter set, ordered by count descending. This is the cheap way to see the _shape_ of a log stream (e.g. \"which services produce the errors?\") without pulling raw rows.\n\nCounts are cross-filtered: every active filter is applied _except the faceted field's own filter_, so you see the full distribution rather than collapsing to your own selection. Faceting `service_name` with `serviceNames: [\"api\"]` still returns every service, not just `api`.\n\nAll parameters must be nested inside a `query` object. You must provide **exactly one** of `query.facetField` or `query.facetResourceAttribute` — not both, not neither.\n\n# When to use\n\n- To find how log volume is distributed across severity or service under a filter — e.g. \"of the logs matching 'timeout', which services emit them?\" Facet `service_name` with `searchTerm: \"timeout\"`.\n- As the drill-down loop for an investigation: facet `service_name` filtered to `severity=error` → find the hot service → add it to `serviceNames` → facet a resource attribute like `k8s.pod.name` → find the bad pod. Each call is one cheap aggregation that narrows the search space before you pull raw rows with `query-logs`.\n- To confirm the severity mix in a window before committing to a query: facet `severity_text`.\n\n## Pick the right tool\n\n- Counts for an arbitrary **attribute** value (any log or resource attribute key) → use `logs-attribute-values-list`. It returns `{value, count}` for any key and is the general-purpose choice for attributes.\n- Per-service log/error counts and error rates with a sparkline → use `logs-services-create`.\n- Use **this** tool for `severity_text` / `service_name` distribution cross-filtered by the full query (severity + body `searchTerm` + `filterGroup`) — the one thing the tools above can't do.\n\n# Parameters\n\n## query.facetField\n\nTop-level column to facet on: `severity_text` or `service_name`. Provide this OR `facetResourceAttribute`, not both. Counts are grouped on the raw logs table with all _other_ filters applied — so this path honors `severityLevels`, `serviceNames`, `searchTerm`, and `filterGroup`.\n\n## query.facetResourceAttribute\n\nResource attribute key to facet on, e.g. `k8s.namespace.name`, `k8s.pod.name`, `host.name`. Provide this OR `facetField`, not both.\n\n**Limitation:** this path is served from a pre-aggregated rollup that has no severity or body dimension. It honors only `serviceNames` and other resource-attribute filters — `severityLevels`, `searchTerm`, and log-attribute filters are **ignored**. If you need those applied, facet a column instead, or narrow with `logs-attribute-values-list`.\n\n## query.facetSearch\n\nCase-insensitive substring match over the faceted field's _own_ values (e.g. return only service names containing `kafka`). Distinct from `searchTerm`, which searches log bodies. Use it to search past the 100-value result cap.\n\n## query.dateRange\n\nDate range for the counts. Defaults to the last hour (`-1h`).\n\n- `date_from`: Start of the range. 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.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels. Ignored when faceting on `severity_text` (that field's own filter is excluded) and when faceting a resource attribute (rollup has no severity dimension).\n\n## query.serviceNames\n\nFilter by service names. Ignored when faceting on `service_name` (that field's own filter is excluded).\n\n## query.searchTerm\n\nFull-text search across log bodies. Ignored when faceting a resource attribute.\n\n## query.filterGroup\n\nProperty filters to narrow results. Same format as `query-logs` filters.\n\n# Examples\n\n## Severity distribution in the last hour\n\n```json\n{\n \"query\": {\n \"facetField\": \"severity_text\",\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Which services produce errors over the last day\n\n```json\n{\n \"query\": {\n \"facetField\": \"service_name\",\n \"severityLevels\": [\"error\", \"fatal\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Which pods a service's logs come from\n\n```json\n{\n \"query\": {\n \"facetResourceAttribute\": \"k8s.pod.name\",\n \"serviceNames\": [\"checkout\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Which services emit a specific error message\n\n```json\n{\n \"query\": {\n \"facetField\": \"service_name\",\n \"searchTerm\": \"connection reset\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```",+ "description": "Return per-value counts for a single facet — the distribution of a log dimension across a filter set, ordered by count descending. This is the cheap way to see the _shape_ of a log stream (e.g. \"which services produce the errors?\") without pulling raw rows.\n\nAll parameters go inside `query` — top-level fields are rejected. Provide **exactly one** of `query.facetField` or `query.facetResourceAttribute` — not both, not neither:\n\n```json\n{ \"query\": { \"facetField\": \"service_name\", \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nCounts are cross-filtered: every active filter is applied _except the faceted field's own filter_, so you see the full distribution rather than collapsing to your own selection. Faceting `service_name` with `serviceNames: [\"api\"]` still returns every service, not just `api`.\n\n# When to use\n\n- To find how log volume is distributed across severity or service under a filter — e.g. \"of the logs matching 'timeout', which services emit them?\" Facet `service_name` with `searchTerm: \"timeout\"`.\n- As the drill-down loop for an investigation: facet `service_name` filtered to `severity=error` → find the hot service → add it to `serviceNames` → facet a resource attribute like `k8s.pod.name` → find the bad pod. Each call is one cheap aggregation that narrows the search space before you pull raw rows with `query-logs`.\n- To confirm the severity mix in a window before committing to a query: facet `severity_text`.\n\n## Pick the right tool\n\n- Counts for an arbitrary **attribute** value (any log or resource attribute key) → use `logs-attribute-values-list`. It returns `{value, count}` for any key and is the general-purpose choice for attributes.\n- Per-service log/error counts and error rates with a sparkline → use `logs-services-create`.\n- Use **this** tool for `severity_text` / `service_name` distribution cross-filtered by the full query (severity + body `searchTerm` + `filterGroup`) — the one thing the tools above can't do.\n\n# Parameters\n\n## query.facetField\n\nTop-level column to facet on: `severity_text` or `service_name`. Provide this OR `facetResourceAttribute`, not both. Counts are grouped on the raw logs table with all _other_ filters applied — so this path honors `severityLevels`, `serviceNames`, `searchTerm`, and `filterGroup`.\n\n## query.facetResourceAttribute\n\nResource attribute key to facet on, e.g. `k8s.namespace.name`, `k8s.pod.name`, `host.name`. Provide this OR `facetField`, not both.\n\n**Limitation:** this path is served from a pre-aggregated rollup that has no severity or body dimension. It honors only `serviceNames` and other resource-attribute filters — `severityLevels`, `searchTerm`, and log-attribute filters are **ignored**. If you need those applied, facet a column instead, or narrow with `logs-attribute-values-list`.\n\n## query.facetSearch\n\nCase-insensitive substring match over the faceted field's _own_ values (e.g. return only service names containing `kafka`). Distinct from `searchTerm`, which searches log bodies. Use it to search past the 100-value result cap.\n\n## query.dateRange\n\nDate range for the counts. Defaults to the last hour (`-1h`).\n\n- `date_from`: Start of the range. 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.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels. Ignored when faceting on `severity_text` (that field's own filter is excluded) and when faceting a resource attribute (rollup has no severity dimension).\n\n## query.serviceNames\n\nFilter by service names. Ignored when faceting on `service_name` (that field's own filter is excluded).\n\n## query.searchTerm\n\nFull-text search across log bodies. Ignored when faceting a resource attribute.\n\n## query.filterGroup\n\nProperty filters to narrow results. Same format as `query-logs` filters.\n\n# Examples\n\n## Severity distribution in the last hour\n\n```json\n{\n \"query\": {\n \"facetField\": \"severity_text\",\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Which services produce errors over the last day\n\n```json\n{\n \"query\": {\n \"facetField\": \"service_name\",\n \"severityLevels\": [\"error\", \"fatal\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Which pods a service's logs come from\n\n```json\n{\n \"query\": {\n \"facetResourceAttribute\": \"k8s.pod.name\",\n \"serviceNames\": [\"checkout\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Which services emit a specific error message\n\n```json\n{\n \"query\": {\n \"facetField\": \"service_name\",\n \"searchTerm\": \"connection reset\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```","category": "Logs","feature": "logs","summary": "Facet log counts",@@ -7926,7 +7926,7 @@}},"logs-patterns": {- "description": "Mine recurring log templates (\"patterns\") from the logs matching a filter set, ordered by frequency. Each pattern is a message template with the variable parts masked — e.g. `Connected to <ip> in <num>ms` — plus occurrence estimates, severity mix, the services it appears in, and a ready-made predicate for fetching its matching lines.\n\nThis is the fastest way to understand what a log stream is _saying_ without reading raw rows: one call summarizes millions of lines into at most 200 templates.\n\nAll parameters must be nested inside a `query` object.\n\n# When to use\n\n- To triage an unfamiliar or noisy stream: mine the last hour, scan the top templates by `estimated_count`, and look for anything with a non-zero error share in `severity_counts`.\n- To find what's new or dominant during an incident window: mine with `severityLevels: [\"error\", \"fatal\"]` and a `dateRange` covering the incident.\n- As the entry point of a drill-down loop: mine → pick a suspicious pattern → filter logs to exactly its lines using `match_regex` (see below) → read the raw rows with `query-logs`.\n- To quantify repetition before proposing log sampling or cleanup: `volume_share_pct` tells you how much of the stream one template accounts for.\n\n## Pick the right tool\n\n- Raw log lines matching a filter → `query-logs`.\n- A single number (how many logs match) → `logs-count`; per-time-bucket counts → `logs-count-ranges`.\n- Distribution of a dimension (which services emit the errors?) → `logs-facet-values-create`.\n- Use **this** tool to summarize message _content_ — what distinct things the logs say and how often.\n\n# Reading the response\n\n- `pattern` — the mined template. Masked tokens: `<uuid>`, `<ip>`, `<hex>`, `<num>`, and `<*>` for any word position that varied.\n- `estimated_count` / `estimated_error_count` — occurrences extrapolated to the full window. When `sampled` is false these are exact.\n- `severity_counts` — sampled occurrences per severity. A template split across `info` and `error` often means the same code path logging both outcomes.\n- `services` — up to 4 service names the pattern was seen in.\n- `match_regex` — a regex over raw log bodies that matches this pattern's lines, pre-validated against the raw bodies of the pattern's own sampled rows. Null when no trustworthy regex could be compiled. For JSON logs the pattern is mined from the extracted message field, so the regex may be unanchored, because the message is a substring of the raw line. It still targets the raw stored body.\n- `match_literal` — longest literal run of the template, a plain-text fallback when `match_regex` is null.\n\nMining samples the window (`sampled: true` when it did): counts are estimates, and rare patterns (below roughly 1 in `scanned_count` of the volume) may be missing entirely. Narrow the `dateRange` or filters to mine a finer-grained sample.\n\n## Pivoting to a pattern's raw lines\n\nTo fetch the lines behind a pattern, call `query-logs` with a message filter in `filterGroup`:\n\n- If `match_regex` is set: `{ \"key\": \"message\", \"value\": \"<match_regex>\", \"operator\": \"regex\", \"type\": \"log\" }`\n- Else if `match_literal` is set: `{ \"key\": \"message\", \"value\": \"<match_literal>\", \"operator\": \"icontains\", \"type\": \"log\" }`\n\nAlso pass the pattern's `services` as `serviceNames` and (when every entry is one of trace/debug/info/warn/error/fatal) the keys of `severity_counts` as `severityLevels` — both make the query dramatically cheaper.\n\n# Parameters\n\n## query.dateRange\n\nDate range to mine. Defaults to the last hour (`-1h`).\n\n- `date_from`: ISO 8601 timestamp or relative format: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: Same format. Omit or null for \"now\".\n\n## query.severityLevels\n\nMine only these severities: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\n## query.serviceNames\n\nRestrict mining to these services. Recommended once you know the target service — it prunes the scan and spends the whole sample budget on one service's templates.\n\n## query.searchTerm\n\nFull-text search over log bodies applied before mining. Useful to mine only the sub-stream around a keyword (e.g. `timeout`).\n\n## query.filterGroup\n\nProperty filters applied before mining. Same format as `query-logs` filters.\n\n# Examples\n\n## What is this stream saying? (last hour, everything)\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\n## Dominant error templates during an incident\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"dateRange\": { \"date_from\": \"2024-01-15T09:00:00Z\", \"date_to\": \"2024-01-15T11:00:00Z\" }\n }\n}\n```\n\n## Mine one service's logs around a keyword\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"checkout\"],\n \"searchTerm\": \"payment\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```",+ "description": "Mine recurring log templates (\"patterns\") from the logs matching a filter set, ordered by frequency. Each pattern is a message template with the variable parts masked — e.g. `Connected to <ip> in <num>ms` — plus occurrence estimates, severity mix, the services it appears in, and a ready-made predicate for fetching its matching lines.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nThis is the fastest way to understand what a log stream is _saying_ without reading raw rows: one call summarizes millions of lines into at most 200 templates.\n\n# When to use\n\n- To triage an unfamiliar or noisy stream: mine the last hour, scan the top templates by `estimated_count`, and look for anything with a non-zero error share in `severity_counts`.\n- To find what's new or dominant during an incident window: mine with `severityLevels: [\"error\", \"fatal\"]` and a `dateRange` covering the incident.\n- As the entry point of a drill-down loop: mine → pick a suspicious pattern → filter logs to exactly its lines using `match_regex` (see below) → read the raw rows with `query-logs`.\n- To quantify repetition before proposing log sampling or cleanup: `volume_share_pct` tells you how much of the stream one template accounts for.\n\n## Pick the right tool\n\n- Raw log lines matching a filter → `query-logs`.\n- A single number (how many logs match) → `logs-count`; per-time-bucket counts → `logs-count-ranges`.\n- Distribution of a dimension (which services emit the errors?) → `logs-facet-values-create`.\n- Use **this** tool to summarize message _content_ — what distinct things the logs say and how often.\n\n# Reading the response\n\n- `pattern` — the mined template. Masked tokens: `<uuid>`, `<ip>`, `<hex>`, `<num>`, and `<*>` for any word position that varied.\n- `estimated_count` / `estimated_error_count` — occurrences extrapolated to the full window. When `sampled` is false these are exact.\n- `severity_counts` — sampled occurrences per severity. A template split across `info` and `error` often means the same code path logging both outcomes.\n- `services` — up to 4 service names the pattern was seen in.\n- `match_regex` — a regex over raw log bodies that matches this pattern's lines, pre-validated against the raw bodies of the pattern's own sampled rows. Null when no trustworthy regex could be compiled. For JSON logs the pattern is mined from the extracted message field, so the regex may be unanchored, because the message is a substring of the raw line. It still targets the raw stored body.\n- `match_literal` — longest literal run of the template, a plain-text fallback when `match_regex` is null.\n\nMining samples the window (`sampled: true` when it did): counts are estimates, and rare patterns (below roughly 1 in `scanned_count` of the volume) may be missing entirely. Narrow the `dateRange` or filters to mine a finer-grained sample.\n\n## Pivoting to a pattern's raw lines\n\nTo fetch the lines behind a pattern, call `query-logs` with a message filter in `filterGroup`:\n\n- If `match_regex` is set: `{ \"key\": \"message\", \"value\": \"<match_regex>\", \"operator\": \"regex\", \"type\": \"log\" }`\n- Else if `match_literal` is set: `{ \"key\": \"message\", \"value\": \"<match_literal>\", \"operator\": \"icontains\", \"type\": \"log\" }`\n\nAlso pass the pattern's `services` as `serviceNames` and (when every entry is one of trace/debug/info/warn/error/fatal) the keys of `severity_counts` as `severityLevels` — both make the query dramatically cheaper.\n\n# Parameters\n\n## query.dateRange\n\nDate range to mine. Defaults to the last hour (`-1h`).\n\n- `date_from`: ISO 8601 timestamp or relative format: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: Same format. Omit or null for \"now\".\n\n## query.severityLevels\n\nMine only these severities: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\n## query.serviceNames\n\nRestrict mining to these services. Recommended once you know the target service — it prunes the scan and spends the whole sample budget on one service's templates.\n\n## query.searchTerm\n\nFull-text search over log bodies applied before mining. Useful to mine only the sub-stream around a keyword (e.g. `timeout`).\n\n## query.filterGroup\n\nProperty filters applied before mining. Same format as `query-logs` filters.\n\n# Examples\n\n## What is this stream saying? (last hour, everything)\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\n## Dominant error templates during an incident\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"dateRange\": { \"date_from\": \"2024-01-15T09:00:00Z\", \"date_to\": \"2024-01-15T11:00:00Z\" }\n }\n}\n```\n\n## Mine one service's logs around a keyword\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"checkout\"],\n \"searchTerm\": \"payment\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```","category": "Logs","feature": "logs","summary": "Mine log patterns",@@ -7940,7 +7940,7 @@}},"logs-patterns-diff": {- "description": "Compare the log patterns of two time windows and return what changed: templates that are **new**, templates whose rate **shifted** (with magnitude, e.g. 4x), and templates that are **gone**. This is the single most useful call for incident triage — \"what is different about now vs. before it broke\" in one round trip, instead of mining two windows yourself and hand-matching templates.\n\nAll parameters must be nested inside a `query` object, with an optional sibling `baselineDateRange`.\n\n# When to use\n\n- **Incident triage (the primary loop):** set `query.dateRange` to the incident window. Omit `baselineDateRange` (defaults to the same window one week earlier) or set it to a known-good window just before the incident. The `new` and biggest `rate_shift` entries are your suspects; pivot to their raw lines with `query-logs`.\n- **Explain a spike:** when a count or sparkline shows a spike (e.g. from `logs-count-ranges`), set `query.dateRange` to the spike window and `baselineDateRange` to the window just before it — the top `new` and `rate_shift` entries are the explanation. This is one call; do not mine the two windows separately and diff them yourself.\n- **Post-deploy check:** current window = since the deploy; `baselineDateRange` = the same-length window just before it. New error-severity templates right after a deploy are the classic regression signature.\n- **\"What changed this week?\"** — current = `-1d`, baseline auto. Good periodic sweep for a service you own.\n\n## Pick the right tool\n\n- Just summarize one window's content → `logs-patterns`.\n- Explain a _count_ change without needing message content → `logs-count-ranges` (cheaper).\n- Use **this** tool when you need to know _which messages_ are new or behaving differently between two periods.\n\n# Reading the response\n\nEntries come sorted most-interesting-first: `new` (by volume), then `rate_shift` (by magnitude), then `gone`, then `unchanged`.\n\n- `classification` — trust the labels; the thresholds already handle sampling honesty:\n - `new` requires clearing a novelty floor (~1% volume share, or any error/fatal lines). Below the floor, absence from the baseline sample is not evidence of novelty.\n - `rate_shift` requires ≥2x change in per-second rate (windows of different lengths are normalized) _and_ enough raw samples on both sides.\n - `unchanged` means \"no confident claim\", not \"provably identical\".\n- `rate_ratio` — current rate / baseline rate. 4.0 = 4x faster now, 0.25 = quartered.\n- `pattern` — full pattern stats including `match_regex` / `match_literal`, so you can pivot straight to the matching lines (same recipe as `logs-patterns`: message regex filter + the pattern's services/severities).\n- **Check `baseline.total_count` before trusting a wall of `new` entries** — an empty or tiny baseline (logging only started recently, service didn't exist last week) makes everything look new.\n- Both windows are mined from samples (`sampled: true`), so counts are estimates and templates rarer than ~1 in 10,000 rows may be invisible in either window.\n\nTemplate identity across the two windows is fingerprint-based (literal content), so the miner rendering `User <*> not found` in one window and `User <num> not found` in the other still compares as one pattern rather than a false new+gone pair.\n\n# Parameters\n\n## query.dateRange\n\nThe current (foreground) window — the period you are investigating. Same format as `logs-patterns`.\n\n## baselineDateRange\n\nOptional, sibling of `query` (not inside it). The comparison window. Omit for the default: the current window shifted back exactly one week, which absorbs daily/weekly volume cycles. Provide explicitly to compare against a pre-deploy or pre-incident period. It does not need to be the same length as the current window — rates are normalized per second.\n\n## query.severityLevels / query.serviceNames / query.searchTerm / query.filterGroup\n\nSame as `logs-patterns`; applied to **both** windows. Scoping by service is recommended — it prunes both scans and focuses the sample budget.\n\n# Examples\n\n## What changed during the incident vs. just before it\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"2026-07-07T09:30:00Z\", \"date_to\": \"2026-07-07T10:30:00Z\" },\n \"serviceNames\": [\"checkout\"]\n },\n \"baselineDateRange\": { \"date_from\": \"2026-07-07T08:00:00Z\", \"date_to\": \"2026-07-07T09:00:00Z\" }\n}\n```\n\n## What is new or different today vs. the same time last week\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-1d\" } } }\n```\n\n## Did the deploy change what the service logs?\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"2026-07-07T14:00:00Z\" },\n \"serviceNames\": [\"api\"]\n },\n \"baselineDateRange\": { \"date_from\": \"2026-07-07T10:00:00Z\", \"date_to\": \"2026-07-07T14:00:00Z\" }\n}\n```",+ "description": "Compare the log patterns of two time windows and return what changed: templates that are **new**, templates whose rate **shifted** (with magnitude, e.g. 4x), and templates that are **gone**. This is the single most useful call for incident triage — \"what is different about now vs. before it broke\" in one round trip, instead of mining two windows yourself and hand-matching templates.\n\nAll parameters go inside `query`, except the optional sibling `baselineDateRange`. Other top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1d\" } } }\n```\n\n# When to use\n\n- **Incident triage (the primary loop):** set `query.dateRange` to the incident window. Omit `baselineDateRange` (defaults to the same window one week earlier) or set it to a known-good window just before the incident. The `new` and biggest `rate_shift` entries are your suspects; pivot to their raw lines with `query-logs`.\n- **Explain a spike:** when a count or sparkline shows a spike (e.g. from `logs-count-ranges`), set `query.dateRange` to the spike window and `baselineDateRange` to the window just before it — the top `new` and `rate_shift` entries are the explanation. This is one call; do not mine the two windows separately and diff them yourself.\n- **Post-deploy check:** current window = since the deploy; `baselineDateRange` = the same-length window just before it. New error-severity templates right after a deploy are the classic regression signature.\n- **\"What changed this week?\"** — current = `-1d`, baseline auto. Good periodic sweep for a service you own.\n\n## Pick the right tool\n\n- Just summarize one window's content → `logs-patterns`.\n- Explain a _count_ change without needing message content → `logs-count-ranges` (cheaper).\n- Use **this** tool when you need to know _which messages_ are new or behaving differently between two periods.\n\n# Reading the response\n\nEntries come sorted most-interesting-first: `new` (by volume), then `rate_shift` (by magnitude), then `gone`, then `unchanged`.\n\n- `classification` — trust the labels; the thresholds already handle sampling honesty:\n - `new` requires clearing a novelty floor (~1% volume share, or any error/fatal lines). Below the floor, absence from the baseline sample is not evidence of novelty.\n - `rate_shift` requires ≥2x change in per-second rate (windows of different lengths are normalized) _and_ enough raw samples on both sides.\n - `unchanged` means \"no confident claim\", not \"provably identical\".\n- `rate_ratio` — current rate / baseline rate. 4.0 = 4x faster now, 0.25 = quartered.\n- `pattern` — full pattern stats including `match_regex` / `match_literal`, so you can pivot straight to the matching lines (same recipe as `logs-patterns`: message regex filter + the pattern's services/severities).\n- **Check `baseline.total_count` before trusting a wall of `new` entries** — an empty or tiny baseline (logging only started recently, service didn't exist last week) makes everything look new.\n- Both windows are mined from samples (`sampled: true`), so counts are estimates and templates rarer than ~1 in 10,000 rows may be invisible in either window.\n\nTemplate identity across the two windows is fingerprint-based (literal content), so the miner rendering `User <*> not found` in one window and `User <num> not found` in the other still compares as one pattern rather than a false new+gone pair.\n\n# Parameters\n\n## query.dateRange\n\nThe current (foreground) window — the period you are investigating. Same format as `logs-patterns`.\n\n## baselineDateRange\n\nOptional, sibling of `query` (not inside it). The comparison window. Omit for the default: the current window shifted back exactly one week, which absorbs daily/weekly volume cycles. Provide explicitly to compare against a pre-deploy or pre-incident period. It does not need to be the same length as the current window — rates are normalized per second.\n\n## query.severityLevels / query.serviceNames / query.searchTerm / query.filterGroup\n\nSame as `logs-patterns`; applied to **both** windows. Scoping by service is recommended — it prunes both scans and focuses the sample budget.\n\n# Examples\n\n## What changed during the incident vs. just before it\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"2026-07-07T09:30:00Z\", \"date_to\": \"2026-07-07T10:30:00Z\" },\n \"serviceNames\": [\"checkout\"]\n },\n \"baselineDateRange\": { \"date_from\": \"2026-07-07T08:00:00Z\", \"date_to\": \"2026-07-07T09:00:00Z\" }\n}\n```\n\n## What is new or different today vs. the same time last week\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-1d\" } } }\n```\n\n## Did the deploy change what the service logs?\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"2026-07-07T14:00:00Z\" },\n \"serviceNames\": [\"api\"]\n },\n \"baselineDateRange\": { \"date_from\": \"2026-07-07T10:00:00Z\", \"date_to\": \"2026-07-07T14:00:00Z\" }\n}\n```","category": "Logs","feature": "logs","summary": "Diff log patterns between two windows",@@ -7968,7 +7968,7 @@}},"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```",+ "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 go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\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","feature": "logs","summary": "Query logs sparkline",@@ -9410,7 +9410,7 @@"feature_flag": "engineering-analytics"},"query-apm-spans": {- "description": "Query trace spans with filtering by service name, status code, date range, and structured attribute filters. Supports cursor-based pagination. Returns spans with uuid, trace_id, span_id, parent_span_id, name, kind, service_name, status_code, timestamp, end_time, duration_nano, is_root_span, matched_filter, and attributes (the span-level OTel attribute map, e.g. db.statement, http.url).\n\nUse 'apm-attributes-list' and 'apm-attribute-values-list' to discover available attributes before building filters. Use 'apm-services-list' to discover available services.\n\n# Return shape\n\nResults are **grouped by trace**, not a flat list of matching spans. For each trace that contains at least one span matching your filters, the response includes spans from that trace (up to `prefetchSpans` per trace, root span first). Two fields tell you which spans actually matched:\n\n- `matched_filter` — `1` if **this span** satisfies your `filterGroup`/`serviceNames`/`statusCodes`, `0` if it's only included because it shares a trace with a match (e.g. a prefetched sibling or the trace's root). When you filter by a child span's name, the matching child has `matched_filter: 1` and its root/siblings have `matched_filter: 0`.\n- `is_root_span` — `true` for the trace's entry span.\n\nTo collapse each matching trace to a **single row — its root span**, set `rootSpans: true` — see below. (The row is the trace's entry span, which may itself carry `matched_filter: 0` when the match was on a child.) To inspect a single trace's full tree, take a `trace_id` from the results and call `apm-trace-get`.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nAll parameters must be nested inside a `query` object.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Span property types are:\n - `span` — filters built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span).\n - `span_attribute` — filters span-level attributes (e.g. \"http.method\", \"http.status_code\").\n - `span_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `apm-attributes-list` to discover available attribute keys** before building filters.\n- **Use `apm-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window. If the question doesn't mention time, the default is the last hour (`-1h`). Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.serviceNames\n\nFilter by service names. Use `apm-services-list` to discover available services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. 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`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.traceId\n\nFilter to a specific trace ID (hex string). Use this when you already know the trace ID.\n\n## query.rootSpans\n\nSet `true` to return **only root spans** — one entry span per matching trace, which collapses each trace to a single row. Useful for \"list the traces matching X\" without sifting through `matched_filter`. Leave unset (or `false`) to get all spans of matching traces, where you read `matched_filter` to find the ones that matched. The frontend leaves this unset.\n\n## query.flatSpans\n\nSet `true` to return **the matching spans themselves, one row per span** (root and child), rather than collapsing to traces. This is the way to search by a child-span attribute (e.g. `code.filepath`) — the result is the matching child spans directly, not the traces that contain them. Streams under `ORDER BY … LIMIT`, so it stays bounded on hot child attributes where the whole-trace grouping would not. Distinct from `rootSpans` (which scopes whole-trace selection); `prefetchSpans` is ignored. Defaults to false.\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.prefetchSpans\n\nNumber of spans to return per matching trace (1-100), root span first. Useful to preview trace structure without a separate `apm-trace-get`. With the default (1) you get one span per trace (the root); raise it to also pull the matching children and their siblings (check `matched_filter` to tell them apart). Ignored when `rootSpans: true`, which always returns just the root.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-span `attributes` map from results (the map stays present but empty). The attribute map holds multi-KB values like `db.statement`, so excluding it keeps large result sets compact — set it when you only need span structure/timing (`name`, `service_name`, `duration_nano`, `parent_span_id`) and not the OTel attributes. Defaults to false.\n\n# Examples\n\n## List recent error spans\n\n```json\n{\n \"query\": {\n \"statusCodes\": [2]\n }\n}\n```\n\n## Search spans from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a span attribute\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"http.method\", \"operator\": \"exact\", \"type\": \"span_attribute\", \"value\": \"POST\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Find slow spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"duration\", \"operator\": \"gt\", \"type\": \"span\", \"value\": \"1000000000\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine service and attribute filters\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"web-server\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"gt\", \"type\": \"span_attribute\", \"value\": \"399\" }],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Check if a resource attribute exists\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"k8s.pod.name\", \"operator\": \"is_set\", \"type\": \"span_resource_attribute\" }]\n }\n}\n```\n\n# Reminders\n\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Use `apm-services-list` to discover available services before filtering by service name.\n- Duration values are in nanoseconds (1 second = 1,000,000,000 nanoseconds).",+ "description": "Query trace spans with filtering by service name, status code, date range, and structured attribute filters. Supports cursor-based pagination. Returns spans with uuid, trace_id, span_id, parent_span_id, name, kind, service_name, status_code, timestamp, end_time, duration_nano, is_root_span, matched_filter, and attributes (the span-level OTel attribute map, e.g. db.statement, http.url).\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nUse 'apm-attributes-list' and 'apm-attribute-values-list' to discover available attributes before building filters. Use 'apm-services-list' to discover available services.\n\n# Return shape\n\nResults are **grouped by trace**, not a flat list of matching spans. For each trace that contains at least one span matching your filters, the response includes spans from that trace (up to `prefetchSpans` per trace, root span first). Two fields tell you which spans actually matched:\n\n- `matched_filter` — `1` if **this span** satisfies your `filterGroup`/`serviceNames`/`statusCodes`, `0` if it's only included because it shares a trace with a match (e.g. a prefetched sibling or the trace's root). When you filter by a child span's name, the matching child has `matched_filter: 1` and its root/siblings have `matched_filter: 0`.\n- `is_root_span` — `true` for the trace's entry span.\n\nTo collapse each matching trace to a **single row — its root span**, set `rootSpans: true` — see below. (The row is the trace's entry span, which may itself carry `matched_filter: 0` when the match was on a child.) To inspect a single trace's full tree, take a `trace_id` from the results and call `apm-trace-get`.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Span property types are:\n - `span` — filters built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span).\n - `span_attribute` — filters span-level attributes (e.g. \"http.method\", \"http.status_code\").\n - `span_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `apm-attributes-list` to discover available attribute keys** before building filters.\n- **Use `apm-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window. If the question doesn't mention time, the default is the last hour (`-1h`). Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\n## query.serviceNames\n\nFilter by service names. Use `apm-services-list` to discover available services.\n\n## query.statusCodes\n\nFilter by OTel span status codes (list of integers: `0` Unset, `1` OK, `2` Error) — **not** HTTP status codes. Use `[2]` to select error spans.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (span/span_attribute/span_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. 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`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.traceId\n\nFilter to a specific trace ID (hex string). Use this when you already know the trace ID.\n\n## query.rootSpans\n\nSet `true` to return **only root spans** — one entry span per matching trace, which collapses each trace to a single row. Useful for \"list the traces matching X\" without sifting through `matched_filter`. Leave unset (or `false`) to get all spans of matching traces, where you read `matched_filter` to find the ones that matched. The frontend leaves this unset.\n\n## query.flatSpans\n\nSet `true` to return **the matching spans themselves, one row per span** (root and child), rather than collapsing to traces. This is the way to search by a child-span attribute (e.g. `code.filepath`) — the result is the matching child spans directly, not the traces that contain them. Streams under `ORDER BY … LIMIT`, so it stays bounded on hot child attributes where the whole-trace grouping would not. Distinct from `rootSpans` (which scopes whole-trace selection); `prefetchSpans` is ignored. Defaults to false.\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.prefetchSpans\n\nNumber of spans to return per matching trace (1-100), root span first. Useful to preview trace structure without a separate `apm-trace-get`. With the default (1) you get one span per trace (the root); raise it to also pull the matching children and their siblings (check `matched_filter` to tell them apart). Ignored when `rootSpans: true`, which always returns just the root.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-span `attributes` map from results (the map stays present but empty). The attribute map holds multi-KB values like `db.statement`, so excluding it keeps large result sets compact — set it when you only need span structure/timing (`name`, `service_name`, `duration_nano`, `parent_span_id`) and not the OTel attributes. Defaults to false.\n\n# Examples\n\n## List recent error spans\n\n```json\n{\n \"query\": {\n \"statusCodes\": [2]\n }\n}\n```\n\n## Search spans from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a span attribute\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"http.method\", \"operator\": \"exact\", \"type\": \"span_attribute\", \"value\": \"POST\" }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Find slow spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"duration\", \"operator\": \"gt\", \"type\": \"span\", \"value\": \"1000000000\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine service and attribute filters\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"web-server\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"gt\", \"type\": \"span_attribute\", \"value\": \"399\" }],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Check if a resource attribute exists\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"k8s.pod.name\", \"operator\": \"is_set\", \"type\": \"span_resource_attribute\" }]\n }\n}\n```\n\n# Reminders\n\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Use `apm-services-list` to discover available services before filtering by service name.\n- Duration values are in nanoseconds (1 second = 1,000,000,000 nanoseconds).","category": "Tracing","feature": "tracing","summary": "Query tracing spans",@@ -9560,7 +9560,7 @@"system_prompt_hint": "LLM/AI trace listing and inspection"},"query-logs": {- "description": "Query log entries with filtering by severity, service name, date range, search term, and structured attribute filters. Supports cursor-based pagination. The response schema (see the tool's typed output) lists every returned field — prefer `severity_text` over `severity_number` / `level`, and be aware that `trace_id` and `span_id` return zero-padded strings rather than null when unset.\n\nUse `logs-attributes-list` and `logs-attribute-values-list` to discover available attributes before building filters.\n\n# Workflow — follow this order every time\n\n1. **Discover services first.** Call `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to see available services.\n2. **Explore resource attributes.** Call `logs-attributes-list` with `attribute_type: \"resource\"` to discover resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`). Then call `logs-attribute-values-list` with `attribute_type: \"resource\"` for relevant attributes to validate what data exists.\n3. **Explore log attributes if needed.** Call `logs-attributes-list` (defaults to log attributes) and `logs-attribute-values-list` to discover log-level attributes.\n4. **Size the total volume with `logs-count`.** Call `logs-count` with the discovered `serviceNames` and filters. If it exceeds `query-logs`'s max `limit` of 1000 — or if the user's question is about _when_ something happened — continue to step 5.\n5. **Find where the volume sits with `logs-count-ranges`.** Call `logs-count-ranges` to get time-bucketed counts. Each bucket carries explicit `date_from`/`date_to` you can pass straight back as the next call's `dateRange` to drill into a sub-range. Recurse up to 3–4 levels to narrow onto a spike or a specific window. Stop when the bucket width drops below your precision goal (e.g. 1 minute).\n6. **Only then query logs.** Once the count is in range and the window is right-sized, call `query-logs` with `serviceNames` and any additional filters.\n\nMany cheap calls (attribute/value queries, counts, count-ranges) beat one expensive `query-logs`. Prefer thorough exploration over speculative log searches.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nMANDATORY: Never call query-logs without setting `serviceNames` or at least one `log_resource_attribute` filter. Unfiltered log queries are too broad, expensive, and noisy. If the user hasn't specified a service, use the workflow above to discover services first, then ask or infer.\n\nMANDATORY: Always pass `query.dateRange` explicitly (e.g. `{ \"date_from\": \"-1h\" }`). Omitting it fails with a 400 `parse_error` (\"Input should be a valid dictionary or instance of DateRange\") — the server does not fall back to a default window.\n\nAll parameters must be nested inside a `query` object.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Log property types are:\n - `log` — filters the log body/message. Use key \"message\" for this type.\n - `log_attribute` — filters log-level attributes (e.g. \"k8s.container.name\", \"http.method\").\n - `log_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `logs-attributes-list` to discover available attribute keys** before building filters.\n- **Use `logs-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\n**Important:** The `logs-attributes-list` and `logs-attribute-values-list` tools default to `attribute_type: \"log\"` (log-level attributes). To search resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`), you must explicitly pass `attribute_type: \"resource\"`. Forgetting this will return log-level attributes when you intended resource-level ones.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Date: `is_date_exact`, `is_date_before`, `is_date_after`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Filtering logs by a PostHog person\n\nWhen the user references a person — by `distinct_id`, name, email, or via a prior `persons-retrieve` call — filter logs to that person via `log_attribute` filters. The attribute keys are configurable per project (they default to `[\"posthogDistinctId\"]`); read `logs_distinct_id_attribute_keys` from the `/api/projects/:id/logs_config/` endpoint and use those as the filter `key`s.\n\nIf a person has multiple `distinct_ids`, pass the array as the filter `value` with operator `exact` (matches any of them):\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [\n {\n \"key\": \"posthogDistinctId\",\n \"operator\": \"exact\",\n \"type\": \"log_attribute\",\n \"value\": [\"<distinct_id_1>\", \"<distinct_id_2>\"]\n }\n ]\n }\n}\n```\n\nEntries in the `filterGroup` array are combined with AND, so never put two distinct-id keys in one call — a log only carries one of them. When the team has multiple keys configured, run one query per key and merge the results.\n\nDo not invent a different attribute key based on what looks plausible — use the configured keys. If the configured keys return zero results, the customer's logs pipeline may not stamp person identity at all; tell the user rather than guessing.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window — pass it on every call. If the question doesn't mention time, use the last hour: `{ \"date_from\": \"-1h\" }`. Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\nThis filter is an **exact match against the response's `severity_text` field** using these six lowercase buckets — it is _not_ a numeric range and _not_ case-insensitive. If a service ingests non-canonical severity strings (e.g. `\"ERROR\"`, `\"Warning\"`, `\"err\"`), `severityLevels: [\"error\"]` will not match them and you will get zero rows. When a severity filter returns nothing unexpectedly, discover the actual stored values with `logs-attribute-values-list { key: \"severity_text\" }` and either filter on the value you find or fall back to a `searchTerm`. See \"Severity fields in the response\" below for the `severity_text` / `severity_number` / `level` mapping.\n\n## query.serviceNames\n\nFilter by service names. Use `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to discover available services.\n\n## query.searchTerm\n\nFull-text search across log bodies. Use this when the user is looking for specific text in log messages.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (log/log_attribute/log_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Required in practice: omitting it fails with a 400 `parse_error`, so always pass it (use `{ \"date_from\": \"-1h\" }` when the question doesn't mention time).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-log `attributes` and `resource_attributes` maps from results (the maps stay present but empty). These maps can hold large values, so excluding them keeps big result sets compact — set it when you only need `body`, `severity_text`, `timestamp`, and `service`-level fields and not the full attribute maps. Defaults to false.\n\n# Examples\n\n## List recent error logs\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Search for a specific log message\n\n```json\n{\n \"query\": {\n \"searchTerm\": \"connection refused\",\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Filter logs from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a log attribute\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"exact\", \"type\": \"log_attribute\", \"value\": \"500\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine severity and attribute filters\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\"],\n \"filterGroup\": [\n { \"key\": \"k8s.container.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"web\" }\n ],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Filter by log body content using property filter\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"message\", \"operator\": \"icontains\", \"type\": \"log\", \"value\": \"timeout\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Check if an attribute exists\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"trace_id\", \"operator\": \"is_set\", \"type\": \"log_attribute\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n# Severity fields in the response\n\nEach returned log row carries three overlapping severity fields. Read and report `severity_text`; treat the other two as redundant:\n\n| Field | What it is | Use it for |\n| ----------------- | --------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `severity_text` | Canonical severity string. **Prefer this.** | Filtering (`severityLevels`), grouping, and anything you show a user. |\n| `severity_number` | OpenTelemetry numeric severity (1–24). Redundant with the text. | Sorting by exact severity, or interop with OTel tooling. |\n| `level` | ClickHouse alias for `severity_text`. Redundant. | Ignore — prefer `severity_text`. |\n\n`severity_number` maps to the `severityLevels` buckets by OTel range. Use this when you only have a number and need the bucket, or vice-versa:\n\n| Bucket | `severity_number` range | Canonical `severity_text` |\n| ------- | ----------------------- | ------------------------- |\n| `trace` | 1–4 | `trace` |\n| `debug` | 5–8 | `debug` |\n| `info` | 9–12 | `info` |\n| `warn` | 13–16 | `warn` |\n| `error` | 17–20 | `error` |\n| `fatal` | 21–24 | `fatal` |\n\nWhen the user asks for \"warnings and above\", that is `severityLevels: [\"warn\", \"error\", \"fatal\"]` — there is no numeric `>=` operator on the top-level severity filter.\n\n# If the query fails (500 / timeout)\n\nA `query-logs` call that returns a 500 almost always means the query scanned too much data and timed out server-side — it is rarely a bug in your filters. Do not retry the same call. Instead, narrow and re-size:\n\n1. Shorten `dateRange` (e.g. `-1h` instead of `-1d`).\n2. Add `serviceNames` or a `log_resource_attribute` filter to reduce the scan.\n3. Size the volume with `logs-count`, then locate the busy window with `logs-count-ranges`, before pulling rows again.\n\n# Reminders\n\n- Always set `serviceNames` or a resource attribute filter. Never run a broad unfiltered log query.\n- Limit `dateRange` to at most `-1d` (24 hours) unless the user explicitly requests a longer range.\n- When using `logs-attributes-list` or `logs-attribute-values-list`, remember they default to `attribute_type: \"log\"`. Pass `attribute_type: \"resource\"` to search resource-level attributes.\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `logs-attributes-list` and `logs-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Prefer `searchTerm` for simple text matching; use `filterGroup` with type `log` and key `message` for regex or exact matching.",+ "description": "Query log entries with filtering by severity, service name, date range, search term, and structured attribute filters. Supports cursor-based pagination. The response schema (see the tool's typed output) lists every returned field — prefer `severity_text` over `severity_number` / `level`, and be aware that `trace_id` and `span_id` return zero-padded strings rather than null when unset.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nUse `logs-attributes-list` and `logs-attribute-values-list` to discover available attributes before building filters.\n\n# Workflow — follow this order every time\n\n1. **Discover services first.** Call `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to see available services.\n2. **Explore resource attributes.** Call `logs-attributes-list` with `attribute_type: \"resource\"` to discover resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`). Then call `logs-attribute-values-list` with `attribute_type: \"resource\"` for relevant attributes to validate what data exists.\n3. **Explore log attributes if needed.** Call `logs-attributes-list` (defaults to log attributes) and `logs-attribute-values-list` to discover log-level attributes.\n4. **Size the total volume with `logs-count`.** Call `logs-count` with the discovered `serviceNames` and filters. If it exceeds `query-logs`'s max `limit` of 1000 — or if the user's question is about _when_ something happened — continue to step 5.\n5. **Find where the volume sits with `logs-count-ranges`.** Call `logs-count-ranges` to get time-bucketed counts. Each bucket carries explicit `date_from`/`date_to` you can pass straight back as the next call's `dateRange` to drill into a sub-range. Recurse up to 3–4 levels to narrow onto a spike or a specific window. Stop when the bucket width drops below your precision goal (e.g. 1 minute).\n6. **Only then query logs.** Once the count is in range and the window is right-sized, call `query-logs` with `serviceNames` and any additional filters.\n\nMany cheap calls (attribute/value queries, counts, count-ranges) beat one expensive `query-logs`. Prefer thorough exploration over speculative log searches.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nMANDATORY: Never call query-logs without setting `serviceNames` or at least one `log_resource_attribute` filter. Unfiltered log queries are too broad, expensive, and noisy. If the user hasn't specified a service, use the workflow above to discover services first, then ask or infer.\n\nMANDATORY: Always pass `query.dateRange` explicitly (e.g. `{ \"date_from\": \"-1h\" }`). Omitting it fails with a 400 `parse_error` (\"Input should be a valid dictionary or instance of DateRange\") — the server does not fall back to a default window.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Log property types are:\n - `log` — filters the log body/message. Use key \"message\" for this type.\n - `log_attribute` — filters log-level attributes (e.g. \"k8s.container.name\", \"http.method\").\n - `log_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `logs-attributes-list` to discover available attribute keys** before building filters.\n- **Use `logs-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\n**Important:** The `logs-attributes-list` and `logs-attribute-values-list` tools default to `attribute_type: \"log\"` (log-level attributes). To search resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`), you must explicitly pass `attribute_type: \"resource\"`. Forgetting this will return log-level attributes when you intended resource-level ones.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Date: `is_date_exact`, `is_date_before`, `is_date_after`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Filtering logs by a PostHog person\n\nWhen the user references a person — by `distinct_id`, name, email, or via a prior `persons-retrieve` call — filter logs to that person via `log_attribute` filters. The attribute keys are configurable per project (they default to `[\"posthogDistinctId\"]`); read `logs_distinct_id_attribute_keys` from the `/api/projects/:id/logs_config/` endpoint and use those as the filter `key`s.\n\nIf a person has multiple `distinct_ids`, pass the array as the filter `value` with operator `exact` (matches any of them):\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [\n {\n \"key\": \"posthogDistinctId\",\n \"operator\": \"exact\",\n \"type\": \"log_attribute\",\n \"value\": [\"<distinct_id_1>\", \"<distinct_id_2>\"]\n }\n ]\n }\n}\n```\n\nEntries in the `filterGroup` array are combined with AND, so never put two distinct-id keys in one call — a log only carries one of them. When the team has multiple keys configured, run one query per key and merge the results.\n\nDo not invent a different attribute key based on what looks plausible — use the configured keys. If the configured keys return zero results, the customer's logs pipeline may not stamp person identity at all; tell the user rather than guessing.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window — pass it on every call. If the question doesn't mention time, use the last hour: `{ \"date_from\": \"-1h\" }`. Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\nThis filter is an **exact match against the response's `severity_text` field** using these six lowercase buckets — it is _not_ a numeric range and _not_ case-insensitive. If a service ingests non-canonical severity strings (e.g. `\"ERROR\"`, `\"Warning\"`, `\"err\"`), `severityLevels: [\"error\"]` will not match them and you will get zero rows. When a severity filter returns nothing unexpectedly, discover the actual stored values with `logs-attribute-values-list { key: \"severity_text\" }` and either filter on the value you find or fall back to a `searchTerm`. See \"Severity fields in the response\" below for the `severity_text` / `severity_number` / `level` mapping.\n\n## query.serviceNames\n\nFilter by service names. Use `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to discover available services.\n\n## query.searchTerm\n\nFull-text search across log bodies. Use this when the user is looking for specific text in log messages.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (log/log_attribute/log_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Required in practice: omitting it fails with a 400 `parse_error`, so always pass it (use `{ \"date_from\": \"-1h\" }` when the question doesn't mention time).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-log `attributes` and `resource_attributes` maps from results (the maps stay present but empty). These maps can hold large values, so excluding them keeps big result sets compact — set it when you only need `body`, `severity_text`, `timestamp`, and `service`-level fields and not the full attribute maps. Defaults to false.\n\n# Examples\n\n## List recent error logs\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Search for a specific log message\n\n```json\n{\n \"query\": {\n \"searchTerm\": \"connection refused\",\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Filter logs from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a log attribute\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"exact\", \"type\": \"log_attribute\", \"value\": \"500\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine severity and attribute filters\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\"],\n \"filterGroup\": [\n { \"key\": \"k8s.container.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"web\" }\n ],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Filter by log body content using property filter\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"message\", \"operator\": \"icontains\", \"type\": \"log\", \"value\": \"timeout\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Check if an attribute exists\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"trace_id\", \"operator\": \"is_set\", \"type\": \"log_attribute\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n# Severity fields in the response\n\nEach returned log row carries three overlapping severity fields. Read and report `severity_text`; treat the other two as redundant:\n\n| Field | What it is | Use it for |\n| ----------------- | --------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `severity_text` | Canonical severity string. **Prefer this.** | Filtering (`severityLevels`), grouping, and anything you show a user. |\n| `severity_number` | OpenTelemetry numeric severity (1–24). Redundant with the text. | Sorting by exact severity, or interop with OTel tooling. |\n| `level` | ClickHouse alias for `severity_text`. Redundant. | Ignore — prefer `severity_text`. |\n\n`severity_number` maps to the `severityLevels` buckets by OTel range. Use this when you only have a number and need the bucket, or vice-versa:\n\n| Bucket | `severity_number` range | Canonical `severity_text` |\n| ------- | ----------------------- | ------------------------- |\n| `trace` | 1–4 | `trace` |\n| `debug` | 5–8 | `debug` |\n| `info` | 9–12 | `info` |\n| `warn` | 13–16 | `warn` |\n| `error` | 17–20 | `error` |\n| `fatal` | 21–24 | `fatal` |\n\nWhen the user asks for \"warnings and above\", that is `severityLevels: [\"warn\", \"error\", \"fatal\"]` — there is no numeric `>=` operator on the top-level severity filter.\n\n# If the query fails (500 / timeout)\n\nA `query-logs` call that returns a 500 almost always means the query scanned too much data and timed out server-side — it is rarely a bug in your filters. Do not retry the same call. Instead, narrow and re-size:\n\n1. Shorten `dateRange` (e.g. `-1h` instead of `-1d`).\n2. Add `serviceNames` or a `log_resource_attribute` filter to reduce the scan.\n3. Size the volume with `logs-count`, then locate the busy window with `logs-count-ranges`, before pulling rows again.\n\n# Reminders\n\n- Always set `serviceNames` or a resource attribute filter. Never run a broad unfiltered log query.\n- Limit `dateRange` to at most `-1d` (24 hours) unless the user explicitly requests a longer range.\n- When using `logs-attributes-list` or `logs-attribute-values-list`, remember they default to `attribute_type: \"log\"`. Pass `attribute_type: \"resource\"` to search resource-level attributes.\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `logs-attributes-list` and `logs-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Prefer `searchTerm` for simple text matching; use `filterGroup` with type `log` and key `message` for regex or exact matching.","category": "Logs","feature": "logs","summary": "Query logs",@@ -9735,7 +9735,7 @@"system_prompt_hint": "One MCP tool's top callers — calls, error rate, harnesses, person email/name"},"query-metrics": {- "description": "Query server/infrastructure metrics (OTel- or Prometheus-ingested) as bucketed time series. The response is a list of series — `{labels, points: [{time, value}], metric_name, clause}` — where every series shares one time grid (missing buckets are zero-filled). A single ungrouped query returns exactly one series with empty labels.\n\nAll parameters go inside `query`:\n\n```json\n{ \"query\": { \"metricName\": \"m\", \"aggregation\": \"rate\", \"dateFrom\": \"2026-01-01T00:00:00Z\" } }\n```\n\nTwo request forms:\n\n- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).\n- **Multi-clause / formula:** set `clauses: [{name, metricName, aggregation, quantile?, filters?, groupBy?}, ...]` and optionally `formula` (e.g. `\"(a - b) / a\"` over clause names; `+ - * /` and parentheses; division by zero yields 0). With a formula set, only the formula result series are returned.\n\n# Workflow — follow this order every time\n\n1. **Discover names first.** Call `metric-names-list` with a substring (`value`) before querying — metric names must match exactly, and the returned `metric_type` tells you the right aggregation.\n2. **Pick the aggregation by metric type:**\n - `sum` counters (usually `_total`): use `rate` (per-second) or `increase` — both are counter-reset safe and temporality-aware. Do NOT use `sum`/`avg` on cumulative counters; absolute counter values are meaningless.\n - `gauge`: `avg` (typical), `p95`, `sum`.\n - Every aggregation combines across series, never across raw samples, so a result never scales with the scrape rate: `sum`/`avg`/`p95` reduce each series to its latest value in the bucket and combine those, and `count` is the number of series that reported.\n - `histogram`: `histogram_quantile` with `quantile` (e.g. 0.95). All selected series must share one bucket layout — narrow with `filters` if you get a bounds-mismatch error.\n3. **Narrow with filters.** `filters: [{key, op, value, scope?}]`, ANDed. Ops: `eq`, `neq`, `regex`, `not_regex` (RE2). Leave `scope` at its default `auto` unless you know whether the attribute is per-target (`resource`) or per-datapoint (`attribute`). Negative ops also match rows lacking the key, like Prometheus negative matchers.\n4. **Split with groupBy.** `groupBy: [{key}]` returns one series per label value (capped at the 100 largest). The service name is always available — `service_name` and `service.name` both resolve to it in metrics (logs only accept the dotted `service.name`); discover other keys from a sample query's labels or ask the user.\n5. **Control the grid with `interval`.** One of `second, minute, minute_5, minute_15, hour, hour_6, day, week`. Omit to auto-pick (~60 buckets across the range). Use the same interval when comparing windows.\n\n# Investigating an anomaly (\"metric X is rising — why?\")\n\n1. Query the metric over a window that includes the anomaly AND an equal-length healthy baseline before it (one call, auto interval).\n2. Find the onset: the first bucket where the value clearly departs from the baseline range.\n3. Re-query grouped by `service_name` (then by other candidate keys) over the same window to see WHICH series moved — a single label value moving points at the culprit; all moving together points at something shared (upstream dependency, infra).\n4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.\n5. Correlate the onset window across signals: query logs (`query-logs`, filtered to the same `service.name` and time window, severity error) and traces (APM span tools, same service/window) to find the cause and its blast radius.\n\nCRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now. `dateFrom` snaps down to its bucket boundary, so the first point can be labelled up to one interval earlier than requested but always covers a whole bucket.",+ "description": "Query server/infrastructure metrics (OTel- or Prometheus-ingested) as bucketed time series. The response is a list of series — `{labels, points: [{time, value}], metric_name, clause}` — where every series shares one time grid (missing buckets are zero-filled). A single ungrouped query returns exactly one series with empty labels.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"metricName\": \"m\", \"aggregation\": \"rate\", \"dateFrom\": \"2026-01-01T00:00:00Z\" } }\n```\n\nTwo request forms:\n\n- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).\n- **Multi-clause / formula:** set `clauses: [{name, metricName, aggregation, quantile?, filters?, groupBy?}, ...]` and optionally `formula` (e.g. `\"(a - b) / a\"` over clause names; `+ - * /` and parentheses; division by zero yields 0). With a formula set, only the formula result series are returned.\n\n# Workflow — follow this order every time\n\n1. **Discover names first.** Call `metric-names-list` with a substring (`value`) before querying — metric names must match exactly, and the returned `metric_type` tells you the right aggregation.\n2. **Pick the aggregation by metric type:**\n - `sum` counters (usually `_total`): use `rate` (per-second) or `increase` — both are counter-reset safe and temporality-aware. Do NOT use `sum`/`avg` on cumulative counters; absolute counter values are meaningless.\n - `gauge`: `avg` (typical), `p95`, `sum`.\n - Every aggregation combines across series, never across raw samples, so a result never scales with the scrape rate: `sum`/`avg`/`p95` reduce each series to its latest value in the bucket and combine those, and `count` is the number of series that reported.\n - `histogram`: `histogram_quantile` with `quantile` (e.g. 0.95). All selected series must share one bucket layout — narrow with `filters` if you get a bounds-mismatch error.\n3. **Narrow with filters.** `filters: [{key, op, value, scope?}]`, ANDed. Ops: `eq`, `neq`, `regex`, `not_regex` (RE2). Leave `scope` at its default `auto` unless you know whether the attribute is per-target (`resource`) or per-datapoint (`attribute`). Negative ops also match rows lacking the key, like Prometheus negative matchers.\n4. **Split with groupBy.** `groupBy: [{key}]` returns one series per label value (capped at the 100 largest). The service name is always available — `service_name` and `service.name` both resolve to it in metrics (logs only accept the dotted `service.name`); discover other keys from a sample query's labels or ask the user.\n5. **Control the grid with `interval`.** One of `second, minute, minute_5, minute_15, hour, hour_6, day, week`. Omit to auto-pick (~60 buckets across the range). Use the same interval when comparing windows.\n\n# Investigating an anomaly (\"metric X is rising — why?\")\n\n1. Query the metric over a window that includes the anomaly AND an equal-length healthy baseline before it (one call, auto interval).\n2. Find the onset: the first bucket where the value clearly departs from the baseline range.\n3. Re-query grouped by `service_name` (then by other candidate keys) over the same window to see WHICH series moved — a single label value moving points at the culprit; all moving together points at something shared (upstream dependency, infra).\n4. Use `formula` for normalized comparisons, e.g. error ratio `errors / requests` instead of raw error counts.\n5. Correlate the onset window across signals: query logs (`query-logs`, filtered to the same `service.name` and time window, severity error) and traces (APM span tools, same service/window) to find the cause and its blast radius.\n\nCRITICAL: be minimalist — only include filters/settings essential to the question. Time ranges: `dateFrom` is required, ISO 8601; `dateTo` defaults to now. `dateFrom` snaps down to its bucket boundary, so the first point can be labelled up to one interval earlier than requested but always covers a whole bucket.","category": "Metrics","feature": "metrics","summary": "Query metrics",diff --git a/services/mcp/src/cli/index.ts b/services/mcp/src/cli/index.tsindex bd8d6d6eeb2b..77eedb0d981a 100644--- a/services/mcp/src/cli/index.ts+++ b/services/mcp/src/cli/index.ts@@ -1,6 +1,6 @@#!/usr/bin/env nodeimport { AnalyticsEvent } from '@/lib/posthog/analytics'-import { createExecTool } from '@/tools/exec'+import { createExecTool, formatInputValidationError, rewrapFlattenedArguments } from '@/tools/exec'import type { Context, Tool, ZodObjectAny } from '@/tools/types'import { buildAgentHelp } from './agent-help'@@ -145,7 +145,10 @@ async function runDryCall(args: string[]): Promise<void> {throw new Error(`Invalid JSON input: ${detail}`)}- const validation = tool.schema.safeParse(parsed)+ // The same rewrap the MCP paths apply, so a dry run reports what a real call would do.+ const firstPass = tool.schema.safeParse(parsed, { reportInput: true })+ const rewrapped = firstPass.success ? undefined : rewrapFlattenedArguments(firstPass.error, parsed, tool.schema)+ const validation = rewrapped ? tool.schema.safeParse(rewrapped, { reportInput: true }) : firstPassprintResult({dryRun: true,tool: tool.name,@@ -154,7 +157,9 @@ async function runDryCall(args: string[]): Promise<void> {outputFormat: forceJson ? 'json' : 'text',destructiveConfirmationRequired: tool.annotations.destructiveHint && !confirmed,valid: validation.success,- ...(validation.success ? { input: validation.data } : { error: validation.error.message }),+ ...(validation.success+ ? { input: validation.data }+ : { error: formatInputValidationError(tool.name, validation.error, parsed, tool.schema) }),})}diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex ed29e5ef76d7..a1dfb8599967 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -28,6 +28,7 @@ import {formatInputValidationError,parseExecCallInnerArgs,parseExecCallInnerToolName,+ rewrapFlattenedArguments,type ExecCommandMeta,type ExecInnerCallTracker,} from '@/tools/exec'@@ -237,8 +238,13 @@ export class ToolExecutor {state: ResolvedState,intentMeta?: ToolCallIntentMeta): Promise<unknown> {- const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>- const validation = tool.schema.safeParse(toolArgs, { reportInput: true })+ const rawToolArgs = (params?.arguments ?? {}) as Record<string, unknown>+ const firstPass = tool.schema.safeParse(rawToolArgs, { reportInput: true })+ const rewrapped = firstPass.success+ ? undefined+ : rewrapFlattenedArguments(firstPass.error, rawToolArgs, tool.schema)+ const toolArgs = rewrapped ?? rawToolArgs+ const validation = rewrapped ? tool.schema.safeParse(toolArgs, { reportInput: true }) : firstPassif (!validation.success) {toolCallsTotal.inc({ tool: tool.name, status: 'validation_error' })const message = formatInputValidationError(tool.name, validation.error, toolArgs, tool.schema)diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex f45adbd85eb3..abeec631aec6 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -509,6 +509,66 @@ function looksLikeUnwrappedPayload(return wrapped.error.issues.every((issue) => issue.path.length > 1 && String(issue.path[0]) === key)}+/**+ * Rebuilds a flattened payload under the wrapper the schema wanted, so the call the caller meant runs.+ *+ * Naming the mistake in the rejection still costs a round trip, and the flattened shape is the most+ * common rejection on the tools built this way.+ *+ * Keys the outer schema declares beside the wrapper stay at the top level. Folding a sibling such as+ * `baselineDateRange` into `query` would have the nested schema strip it, and the caller would get a+ * different query than it asked for without being told.+ *+ * Every key that moves inside must be one the wrapper declares. A wrapper that defaults its own+ * fields parses `{"dateRagne": ...}` into a full set of defaults, so accepting that rebuild would run+ * an unfiltered query and return plausible but wrong rows instead of reporting the typo.+ *+ * Returns undefined unless the rebuilt payload parses, so a payload malformed for some other reason+ * keeps its own rejection.+ */+export function rewrapFlattenedArguments(+ error: z.ZodError,+ input: unknown,+ schema: ZodObjectAny | undefined+): Record<string, unknown> | undefined {+ if (!schema || !isRecord(input) || error.issues.length !== 1) {+ return undefined+ }+ const issue = error.issues[0]!+ if (issue.code !== 'invalid_type' || !('input' in issue) || issue.input !== undefined) {+ return undefined+ }+ if (!looksLikeUnwrappedPayload(issue.path, input, schema)) {+ return undefined+ }++ const key = String(issue.path[0])+ const siblings = topLevelFieldNames(schema)+ const rebuilt: Record<string, unknown> = {}+ const nested: Record<string, unknown> = {}+ for (const [name, value] of Object.entries(input)) {+ if (name !== key && siblings.has(name)) {+ rebuilt[name] = value+ } else {+ nested[name] = value+ }+ }+ const declared = wrapperFieldNames(schema, key)+ const nestedNames = Object.keys(nested)+ if (nestedNames.length === 0 || !nestedNames.every((name) => declared.has(name))) {+ return undefined+ }+ rebuilt[key] = nested++ return schema.safeParse(rebuilt).success ? rebuilt : undefined+}++function topLevelFieldNames(schema: ZodObjectAny): ReadonlySet<string> {+ const root = inputJsonSchema(schema)+ const properties = isRecord(root) ? root['properties'] : undefined+ return new Set(isRecord(properties) ? Object.keys(properties) : [])+}+/*** The field names a wrapper parameter declares directly, including the fields of* each variant when the wrapper is a union (`read-data-schema` keys its shape off@@ -1325,7 +1385,14 @@ export function createExecTool(// otherwise bad input reaches the HTTP layer and builds URLs like// `.../actions/undefined/`, a misleading 404 that hides the offending// field. Dispatch the parsed output so coerced values and defaults apply.- const validation = toolSchema.safeParse(input, { reportInput: true })+ let validation = toolSchema.safeParse(input, { reportInput: true })+ if (!validation.success) {+ const rewrapped = rewrapFlattenedArguments(validation.error, input, toolSchema)+ if (rewrapped) {+ input = rewrapped+ validation = toolSchema.safeParse(input, { reportInput: true })+ }+ }if (!validation.success) {const message = formatInputValidationError(tool.name, validation.error, input, tool.schema)trackInnerCall?.(tool.name, {diff --git a/services/mcp/src/tools/posthogConnections/call.ts b/services/mcp/src/tools/posthogConnections/call.tsindex 77d2c383e9d1..5c912aa94e2b 100644--- a/services/mcp/src/tools/posthogConnections/call.ts+++ b/services/mcp/src/tools/posthogConnections/call.ts@@ -2,6 +2,7 @@ import { z } from 'zod'import { buildForwardedContext, resolveConnectionTarget, seedForwardedContext } from '@/lib/connection-forwarding'import { ExecCommandError } from '@/lib/errors'+import { formatInputValidationError, rewrapFlattenedArguments } from '@/tools/exec'import { getToolDefinition } from '@/tools/toolDefinitions'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'@@ -96,12 +97,15 @@ export function createConnectionCallTool(// Check the arguments before touching the connection, so a malformed call fails here// rather than after a cross-region round trip, as an opaque 400 from the other project.- const parsedArguments = target.schema.safeParse(params.arguments ?? {})+ const rawArguments = params.arguments ?? {}+ const firstPass = target.schema.safeParse(rawArguments, { reportInput: true })+ const rewrapped = firstPass.success+ ? undefined+ : rewrapFlattenedArguments(firstPass.error, rawArguments, target.schema)+ const parsedArguments = rewrapped ? target.schema.safeParse(rewrapped, { reportInput: true }) : firstPassif (!parsedArguments.success) {throw new ExecCommandError(- `Arguments for \`${params.tool}\` are invalid: ${parsedArguments.error.issues- .map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`)- .join('; ')}`,+ formatInputValidationError(target.name, parsedArguments.error, rawArguments, target.schema),'usage')}diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex ef3c0b74785c..a88541879742 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -19,6 +19,7 @@ import {type ExecInnerCallProperties,type ExecToolOptions,formatInputValidationError,+ rewrapFlattenedArguments,parseExecCallInnerToolName,} from '@/tools/exec'import { ExecLearnCatalog } from '@/tools/exec-learn'@@ -1982,6 +1983,71 @@ describe('exec tool', () => {'resend them as {"query": {"dateRange": ..., "limit": ...}}')})++ describe('rewrapping it into the call the caller meant', () => {+ const rewrapFor = (schema: ZodObjectAny, input: unknown): Record<string, unknown> | undefined => {+ const result = schema.safeParse(input, { reportInput: true })+ expect(result.success).toBe(false)+ return rewrapFlattenedArguments(result.error!, input, schema)+ }++ it('nests the flattened fields under the wrapper', () => {+ expect(rewrapFor(wrapperSchema, { dateRange: { date_from: '-1h' }, limit: 10 })).toEqual({+ query: { dateRange: { date_from: '-1h' }, limit: 10 },+ })+ })++ it('leaves a sibling the outer schema declares at the top level', () => {+ // Folding `baselineDateRange` inside `query` would have the nested schema strip it,+ // and the caller would get a diff against the default baseline without being told.+ const tool = GENERATED_TOOL_MAP['logs-patterns-diff']!()+ const input = {+ serviceNames: ['api'],+ dateRange: { date_from: '-1d' },+ baselineDateRange: { date_from: '-2d', date_to: '-1d' },+ }++ expect(rewrapFor(tool.schema, input)).toEqual({+ query: { serviceNames: ['api'], dateRange: { date_from: '-1d' } },+ baselineDateRange: { date_from: '-2d', date_to: '-1d' },+ })+ })++ it.each([+ ['an empty input, which is a caller that sent nothing', {}],+ ['keys the nested schema does not declare', { nonsense: 1, alsoNonsense: 2 }],+ ['a nested field the wrapper still rejects', { orderBy: 'newest' }],+ ])('leaves %s to its own rejection', (_label, input) => {+ expect(rewrapFor(wrapperSchema, input)).toBeUndefined()+ })++ it('leaves a typo alone rather than running a query the caller did not ask for', () => {+ // `query-logs` defaults most of its query fields, so wrapping `dateRagne` parses+ // into a full set of defaults and would run an unfiltered query over the default+ // window. The caller has to see the typo instead of plausible but wrong rows.+ const tool = GENERATED_TOOL_MAP['query-logs']!()++ expect(rewrapFor(tool.schema, { dateRagne: { date_from: '-7d' } })).toBeUndefined()+ })++ it('leaves a payload alone when only some of its keys belong inside the wrapper', () => {+ const tool = GENERATED_TOOL_MAP['query-logs']!()+ const input = { serviceNames: ['api'], dateRagne: { date_from: '-7d' } }++ expect(rewrapFor(tool.schema, input)).toBeUndefined()+ })++ it('leaves a rejection that names more than the missing wrapper alone', () => {+ // Two complaints mean the payload is wrong in a way nesting cannot fix,+ // so guessing at one of them would hide the other.+ const strictWrapper = z.object({+ query: z.object({ limit: z.number().optional() }),+ mode: z.enum(['fast', 'full']),+ })++ expect(rewrapFor(strictWrapper, { limit: 10, mode: 'quick' })).toBeUndefined()+ })+ })})// A caller that omits an identifier usually never held one, so a rejectiondiff --git a/services/mcp/tests/unit/query-wrapper-contract.test.ts b/services/mcp/tests/unit/query-wrapper-contract.test.tsnew file mode 100644index 000000000000..507f7ae6c59a--- /dev/null+++ b/services/mcp/tests/unit/query-wrapper-contract.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it } from 'vitest'+import { z } from 'zod'++import { formatInputValidationError, rewrapFlattenedArguments } from '@/tools/exec'+import { GENERATED_TOOL_MAP } from '@/tools/generated'+import { getToolDefinition } from '@/tools/toolDefinitions'+import type { ToolBase, ZodObjectAny } from '@/tools/types'++/** Read from the schemas rather than listed, so a new tool with this shape has to satisfy the contract too. */+function queryWrapperTools(): [string, ToolBase<ZodObjectAny>][] {+ const tools: [string, ToolBase<ZodObjectAny>][] = []+ for (const [name, factory] of Object.entries(GENERATED_TOOL_MAP)) {+ const tool = factory()+ let jsonSchema: Record<string, unknown>+ try {+ jsonSchema = z.toJSONSchema(tool.schema, { io: 'input' }) as Record<string, unknown>+ } catch {+ continue+ }+ const required = jsonSchema['required']+ const properties = jsonSchema['properties'] as Record<string, { type?: string }> | undefined+ if (Array.isArray(required) && required.length === 1 && required[0] === 'query') {+ if (properties?.['query']?.type === 'object') {+ tools.push([name, tool])+ }+ }+ }+ return tools+}++function leadExample(+ description: string+): { json: Record<string, unknown>; source: string; offset: number } | undefined {+ const match = /```json\n([\s\S]*?)\n```/.exec(description)+ if (!match) {+ return undefined+ }+ const source = match[1]!+ try {+ return { json: JSON.parse(source) as Record<string, unknown>, source, offset: match.index }+ } catch {+ return undefined+ }+}++/** An example below this offset sits under a workflow section, which a caller reaches after it composed the call. */+const LEAD_EXAMPLE_MAX_OFFSET = 700++/** Every description ships on every tools/list, and a longer example also wraps under `oxfmt`. */+const LEAD_EXAMPLE_MAX_LENGTH = 110++describe('tools whose payload sits under a required `query` object', () => {+ const tools = queryWrapperTools()++ it('finds the wrapper tools to check', () => {+ expect(tools.length).toBeGreaterThan(10)+ })++ describe.each(tools)('%s', (name, tool) => {+ const description = getToolDefinition(name).description+ const example = leadExample(description)++ it('leads with a wrapped example the caller can copy', () => {+ expect(example).not.toBeUndefined()+ expect(Object.keys(example!.json)).toContain('query')+ expect(example!.offset).toBeLessThan(LEAD_EXAMPLE_MAX_OFFSET)+ expect(example!.source).not.toContain('\n')+ expect(example!.source.length).toBeLessThanOrEqual(LEAD_EXAMPLE_MAX_LENGTH)+ })++ it('accepts that example', () => {+ const parsed = tool.schema.safeParse(example!.json)+ expect(parsed.error?.issues ?? []).toEqual([])+ })++ it('names the nesting mistake when that example is sent flattened', () => {+ const flattened = example!.json['query'] as Record<string, unknown>+ const rejected = tool.schema.safeParse(flattened, { reportInput: true })+ expect(rejected.success).toBe(false)++ const message = formatInputValidationError(name, rejected.error!, flattened, tool.schema)++ expect(message).toContain('missing required parameter: query')+ expect(message).toContain('the fields you sent belong inside it')+ expect(message).toContain('resend them as {"query": {')+ })++ it('rewraps that flattened example back into the call the caller meant', () => {+ const flattened = example!.json['query'] as Record<string, unknown>+ const rejected = tool.schema.safeParse(flattened, { reportInput: true })++ const rewrapped = rewrapFlattenedArguments(rejected.error!, flattened, tool.schema)++ expect(rewrapped).toEqual(example!.json)+ })+ })+})