: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): show the required query wrapper in domain tool inputs (#95477)
posthog[bot]d6188c7b60b0
diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yamlindex bd24160831c9..32986b80dcd7 100644--- a/products/data_warehouse/mcp/tools.yaml+++ b/products/data_warehouse/mcp/tools.yaml@@ -264,11 +264,17 @@ tools:idempotent: falseenrich_url: ?open_view={id}title: Create saved query- description: >+ description: |Create a new data warehouse saved query (view). If a view with the same name already exists, it will beupdated instead (upsert behavior). The query must be valid HogQL. After creation, the view can be referencedby name in other HogQL queries. Set `description` to record what the view represents (a semantic descriptionsurfaced to agents); per-column descriptions are set via the saved-query column annotation tools.++ Put the HogQL in `query`:++ ```json+ { "name": "example", "query": { "kind": "HogQLQuery", "query": "SELECT 1" } }+ ```exclude_params:- deleted- edited_history_id@@ -393,10 +399,16 @@ tools:idempotent: trueenrich_url: ?open_view={id}title: Revert materialization- description: >+ description: |Undo materialization for a saved query. Deletes the materialized table and removes the sync schedule,reverting the view back to a virtual query that runs on each access. The view definition itself ispreserved. Rate limited.++ Send the view ID, name, and query:++ ```json+ { "id": "<id>", "name": "example", "query": { "kind": "HogQLQuery", "query": "SELECT 1" } }+ ```view-update:operation: warehouse_saved_queries_partial_updateenabled: truediff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yamlindex 152e78806473..fb9838b1c176 100644--- a/products/logs/mcp/tools.yaml+++ b/products/logs/mcp/tools.yaml@@ -504,11 +504,17 @@ tools:destructive: falseidempotent: truetitle: List services with stats- description: >+ description: |Return the top-25 services by log volume in the window, each with log_count, error_count, and error_rate,plus a per-service sparkline. Use this as the entry point when triaging which services are worth alerting on— high volume × non-zero error_rate is the natural alert candidate. Far cheaper than walkingattribute-values + per-service counts.++ Put all parameters in `query`:++ ```json+ { "query": { "dateRange": { "date_from": "-24h" } } }+ ```response:include:- servicesdiff --git a/products/metrics/mcp/prompts/characterize-metric-anomaly.md b/products/metrics/mcp/prompts/characterize-metric-anomaly.mdindex 54a17b75c22a..53b1be690800 100644--- a/products/metrics/mcp/prompts/characterize-metric-anomaly.md+++ b/products/metrics/mcp/prompts/characterize-metric-anomaly.md@@ -1,5 +1,11 @@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`:++```json+{ "query": { "metricName": "m", "anomalyFrom": "2026-01-01T00:00:00Z" } }+```+Required: `metricName` (exact — discover via `metric-names-list` first) and `anomalyFrom` (when things started looking wrong; the alert fire time works). `anomalyTo` defaults to now. The baseline defaults to the equal-length window immediately before `anomalyFrom`; pass `baselineFrom`/`baselineTo` to compare against a known-good period instead (e.g. same time yesterday).The aggregation is auto-picked from the metric's OTel type (counter -> rate, gauge -> avg, histogram -> 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.@@ -11,4 +17,4 @@ Read the report in this order:3. `top_movers`: which label values changed. One label value moving alone (e.g. a single pod or shard) points at a localized culprit; everything moving together points at a shared cause upstream.4. `series`: the full baseline+anomaly time series if you need to eyeball the shape.-Then correlate: query logs (`query-logs` with the same service and a window around `onset_time`, severity error first) and traces (APM span tools, same service/window) to find what broke and its blast radius. All parameters are nested inside a `query` object.+Then correlate: query logs (`query-logs` with the same service and a window around `onset_time`, severity error first) and traces (APM span tools, same service/window) to find what broke and its blast radius.diff --git a/products/metrics/mcp/prompts/query-metrics.md b/products/metrics/mcp/prompts/query-metrics.mdindex de9922552294..c9e95c2c35cc 100644--- a/products/metrics/mcp/prompts/query-metrics.md+++ b/products/metrics/mcp/prompts/query-metrics.md@@ -1,6 +1,12 @@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 are nested inside a `query` object. Two request forms:+All parameters go inside `query`:++```json+{ "query": { "metricName": "m", "aggregation": "rate", "dateFrom": "2026-01-01T00:00:00Z" } }+```++Two request forms:- **Single metric (shorthand):** set `metricName` (+ `aggregation`, `filters`, `groupBy`).- **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.diff --git a/products/product_analytics/mcp/tools.yaml b/products/product_analytics/mcp/tools.yamlindex 6d9da2d26783..de77a99d085d 100644--- a/products/product_analytics/mcp/tools.yaml+++ b/products/product_analytics/mcp/tools.yaml@@ -82,9 +82,23 @@ tools:title: Create insightdescription: >Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel /+query-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save.+Returns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if+you want to see the computed results.+++ Put the insight definition in `query.source`:+++ ```json++ { "name": "Example", "query": { "kind": "InsightVizNode", "source": { "kind": "HogQLQuery", "query": "SELECT+ 1" } } }++ ```exclude_params:- queryinclude_params:diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 189aa152fddc..34c362d94f79 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1715,7 +1715,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\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. All parameters are nested inside a `query` object.",+ "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.","category": "Metrics","feature": "metrics","summary": "Characterize metric anomaly",@@ -5850,7 +5850,7 @@}},"insight-create": {- "description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel / query-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save. Returns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if you want to see the computed results.",+ "description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel /\nquery-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save.\nReturns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if\nyou want to see the computed results.\n\nPut the insight definition in `query.source`:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"InsightVizNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```","category": "Product analytics","feature": "product_analytics","summary": "Create insight",@@ -7392,7 +7392,7 @@}},"logs-services-create": {- "description": "Return the top-25 services by log volume in the window, each with log_count, error_count, and error_rate, plus a per-service sparkline. Use this as the entry point when triaging which services are worth alerting on — high volume × non-zero error_rate is the natural alert candidate. Far cheaper than walking attribute-values + per-service counts.",+ "description": "Return the top-25 services by log volume in the window, each with log_count, error_count, and error_rate,\nplus a per-service sparkline. Use this as the entry point when triaging which services are worth alerting on\n— high volume × non-zero error_rate is the natural alert candidate. Far cheaper than walking\nattribute-values + per-service counts.\n\nPut all parameters in `query`:\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-24h\" } } }\n```","category": "Logs","feature": "logs","summary": "List services with stats",@@ -8948,7 +8948,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 are nested inside a `query` object. Two 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`:\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",@@ -11402,7 +11402,7 @@}},"view-create": {- "description": "Create a new data warehouse saved query (view). If a view with the same name already exists, it will be updated instead (upsert behavior). The query must be valid HogQL. After creation, the view can be referenced by name in other HogQL queries. Set `description` to record what the view represents (a semantic description surfaced to agents); per-column descriptions are set via the saved-query column annotation tools.",+ "description": "Create a new data warehouse saved query (view). If a view with the same name already exists, it will be\nupdated instead (upsert behavior). The query must be valid HogQL. After creation, the view can be referenced\nby name in other HogQL queries. Set `description` to record what the view represents (a semantic description\nsurfaced to agents); per-column descriptions are set via the saved-query column annotation tools.\n\nPut the HogQL in `query`:\n\n```json\n{ \"name\": \"example\", \"query\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } }\n```","category": "Data warehouse","feature": "data_warehouse","summary": "Create saved query",@@ -11500,7 +11500,7 @@}},"view-unmaterialize": {- "description": "Undo materialization for a saved query. Deletes the materialized table and removes the sync schedule, reverting the view back to a virtual query that runs on each access. The view definition itself is preserved. Rate limited.",+ "description": "Undo materialization for a saved query. Deletes the materialized table and removes the sync schedule,\nreverting the view back to a virtual query that runs on each access. The view definition itself is\npreserved. Rate limited.\n\nSend the view ID, name, and query:\n\n```json\n{ \"id\": \"<id>\", \"name\": \"example\", \"query\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } }\n```","category": "Data warehouse","feature": "data_warehouse","summary": "Revert materialization",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 074af8570ab0..94fb5fb6e2b2 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1730,7 +1730,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\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. All parameters are nested inside a `query` object.",+ "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.","category": "Metrics","feature": "metrics","summary": "Characterize metric anomaly",@@ -6047,7 +6047,7 @@}},"insight-create": {- "description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel / query-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save. Returns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if you want to see the computed results.",+ "description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel /\nquery-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save.\nReturns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if\nyou want to see the computed results.\n\nPut the insight definition in `query.source`:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"InsightVizNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```","category": "Product analytics","feature": "product_analytics","summary": "Create insight",@@ -7771,7 +7771,7 @@}},"logs-services-create": {- "description": "Return the top-25 services by log volume in the window, each with log_count, error_count, and error_rate, plus a per-service sparkline. Use this as the entry point when triaging which services are worth alerting on — high volume × non-zero error_rate is the natural alert candidate. Far cheaper than walking attribute-values + per-service counts.",+ "description": "Return the top-25 services by log volume in the window, each with log_count, error_count, and error_rate,\nplus a per-service sparkline. Use this as the entry point when triaging which services are worth alerting on\n— high volume × non-zero error_rate is the natural alert candidate. Far cheaper than walking\nattribute-values + per-service counts.\n\nPut all parameters in `query`:\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-24h\" } } }\n```","category": "Logs","feature": "logs","summary": "List services with stats",@@ -9506,7 +9506,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 are nested inside a `query` object. Two 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`:\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",@@ -9702,7 +9702,7 @@"system_prompt_hint": "Core Web Vitals per page — LCP, INP, CLS, FCP bucketed into good / needs-improvement / poor"},"read-data-schema": {- "description": "Use this tool to explore the user's data schema. The user implements PostHog SDKs to collect events, properties, and property values. They are used by users to create insights with visualizations, SQL queries, watch session recordings, filter data, target particular users or groups by traits or behavior, etc. Each event, action, and entity has its own data schema. You must verify that specific combinations exist before using it anywhere else. Events or properties starting from \"$\" are system properties automatically captured by SDKs. Do not rely on your training data or PostHog defaults for events or properties. Always use this tool to confirm what actually exists in the user's project before referencing any event, property, or property value.",+ "description": "Use this tool to explore the user's data schema. The user implements PostHog SDKs to collect events, properties, and property values. They are used by users to create insights with visualizations, SQL queries, watch session recordings, filter data, target particular users or groups by traits or behavior, etc. Each event, action, and entity has its own data schema. You must verify that specific combinations exist before using it anywhere else. Events or properties starting from \"$\" are system properties automatically captured by SDKs. Do not rely on your training data or PostHog defaults for events or properties. Always use this tool to confirm what actually exists in the user's project before referencing any event, property, or property value.\n\nPut all parameters in `query`. Select the schema with `kind`:\n\n```json\n{ \"query\": { \"kind\": \"events\" } }\n```","category": "Data schema","feature": "data_schema","summary": "Explore the user's events, actions, properties, and property values.",@@ -12047,7 +12047,7 @@}},"view-create": {- "description": "Create a new data warehouse saved query (view). If a view with the same name already exists, it will be updated instead (upsert behavior). The query must be valid HogQL. After creation, the view can be referenced by name in other HogQL queries. Set `description` to record what the view represents (a semantic description surfaced to agents); per-column descriptions are set via the saved-query column annotation tools.",+ "description": "Create a new data warehouse saved query (view). If a view with the same name already exists, it will be\nupdated instead (upsert behavior). The query must be valid HogQL. After creation, the view can be referenced\nby name in other HogQL queries. Set `description` to record what the view represents (a semantic description\nsurfaced to agents); per-column descriptions are set via the saved-query column annotation tools.\n\nPut the HogQL in `query`:\n\n```json\n{ \"name\": \"example\", \"query\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } }\n```","category": "Data warehouse","feature": "data_warehouse","summary": "Create saved query",@@ -12145,7 +12145,7 @@}},"view-unmaterialize": {- "description": "Undo materialization for a saved query. Deletes the materialized table and removes the sync schedule, reverting the view back to a virtual query that runs on each access. The view definition itself is preserved. Rate limited.",+ "description": "Undo materialization for a saved query. Deletes the materialized table and removes the sync schedule,\nreverting the view back to a virtual query that runs on each access. The view definition itself is\npreserved. Rate limited.\n\nSend the view ID, name, and query:\n\n```json\n{ \"id\": \"<id>\", \"name\": \"example\", \"query\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } }\n```","category": "Data warehouse","feature": "data_warehouse","summary": "Revert materialization",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex a65ec37ddc07..80fb037640fc 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -729,7 +729,7 @@}},"read-data-schema": {- "description": "Use this tool to explore the user's data schema. The user implements PostHog SDKs to collect events, properties, and property values. They are used by users to create insights with visualizations, SQL queries, watch session recordings, filter data, target particular users or groups by traits or behavior, etc. Each event, action, and entity has its own data schema. You must verify that specific combinations exist before using it anywhere else. Events or properties starting from \"$\" are system properties automatically captured by SDKs. Do not rely on your training data or PostHog defaults for events or properties. Always use this tool to confirm what actually exists in the user's project before referencing any event, property, or property value.",+ "description": "Use this tool to explore the user's data schema. The user implements PostHog SDKs to collect events, properties, and property values. They are used by users to create insights with visualizations, SQL queries, watch session recordings, filter data, target particular users or groups by traits or behavior, etc. Each event, action, and entity has its own data schema. You must verify that specific combinations exist before using it anywhere else. Events or properties starting from \"$\" are system properties automatically captured by SDKs. Do not rely on your training data or PostHog defaults for events or properties. Always use this tool to confirm what actually exists in the user's project before referencing any event, property, or property value.\n\nPut all parameters in `query`. Select the schema with `kind`:\n\n```json\n{ \"query\": { \"kind\": \"events\" } }\n```","category": "Data schema","feature": "data_schema","summary": "Explore the user's events, actions, properties, and property values.",diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex a7c2a9c5becc..0914251aa45e 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -403,6 +403,68 @@ function looksLikeUnwrappedPayload(return wrapped.error.issues.every((issue) => issue.path.length > 1 && String(issue.path[0]) === key)}+/**+ * 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+ * a `kind` discriminator). Composition keywords are walked one level; nothing+ * deeper is collected, because only the caller's own top-level keys are matched+ * against this set.+ */+function wrapperFieldNames(schema: ZodObjectAny, key: string): ReadonlySet<string> {+ const root = inputJsonSchema(schema)+ const properties = isRecord(root) ? root['properties'] : undefined+ const wrapper = isRecord(properties) ? properties[key] : undefined+ const names = new Set<string>()+ if (!isRecord(wrapper)) {+ return names+ }+ for (const node of [wrapper, ...variantsOf(wrapper)]) {+ const fields = node['properties']+ if (isRecord(fields)) {+ for (const name of Object.keys(fields)) {+ names.add(name)+ }+ }+ }+ return names+}++function variantsOf(node: Record<string, unknown>): Record<string, unknown>[] {+ return ['anyOf', 'oneOf', 'allOf']+ .flatMap((keyword) => (Array.isArray(node[keyword]) ? (node[keyword] as unknown[]) : []))+ .filter(isRecord)+}++/**+ * Renders the shape the tool would have accepted, by nesting the caller's own+ * keys under the wrapper they omitted: `{"query": {"dateRange": ..., "limit": ...}}`.+ *+ * A caller told only to "resend them as {"query": {...}}" has to work out which+ * of its fields belong inside, and the reports behind this said so — they asked+ * for one valid input shape at the point of rejection. Echoing the keys back in+ * place answers that without a second `info` call.+ *+ * Only keys the wrapper itself declares are named, so the rendered shape is the+ * tool's own vocabulary rather than the caller's, and values are always elided.+ * The message is returned to the caller and recorded as the analytics error+ * message, so it must carry no input. Falls back to `{...}` when no key matches.+ */+function acceptedWrapperShape(key: string, input: unknown, schema: ZodObjectAny | undefined): string {+ if (!schema || !isRecord(input)) {+ return `{"${key}": {...}}`+ }+ const declared = wrapperFieldNames(schema, key)+ const named = Object.keys(input).filter((name) => declared.has(name))+ if (named.length === 0) {+ return `{"${key}": {...}}`+ }+ const shown = named.slice(0, MAX_WRAPPER_KEYS_NAMED).map((name) => `"${name}": ...`)+ if (named.length > MAX_WRAPPER_KEYS_NAMED) {+ shown.push('...')+ }+ return `{"${key}": {${shown.join(', ')}}}`+}+/*** Names the top-level keys a non-strict schema dropped, so a caller told `id` is* missing can see that the key it did send — `scanner_id` — was discarded rather@@ -432,6 +494,10 @@ function undeclaredKeys(input: unknown, schema: ZodObjectAny | undefined): strin* undeclared payload cannot inflate the analytics error message. */const MAX_DROPPED_KEYS_NAMED = 5+/** Same bound for the rendered wrapper shape: enough keys to recognize the+ * payload, not enough for a large one to inflate the message. */+const MAX_WRAPPER_KEYS_NAMED = 5+/** Bound on the parameter description echoed back with a missing-parameter* rejection, so a tool with a long field description cannot inflate the* analytics error message. */@@ -499,7 +565,8 @@ export function formatInputValidationError(if ('input' in issue && issue.input === undefined) {const hint = missingParameterHint(issue.path, schema)if (looksLikeUnwrappedPayload(issue.path, input, schema)) {- return `missing required parameter: ${path}${hint}; the fields you sent belong inside it, so resend them as {"${path}": {...}}`+ const shape = acceptedWrapperShape(path, input, schema)+ return `missing required parameter: ${path}${hint}; the fields you sent belong inside it, so resend them as ${shape}`}const dropped = keysWereRejected ? [] : undeclaredKeys(input, schema)if (dropped.length) {diff --git a/services/mcp/src/tools/schema-utils.ts b/services/mcp/src/tools/schema-utils.tsindex 9853eb4f6106..4bea283f4c90 100644--- a/services/mcp/src/tools/schema-utils.ts+++ b/services/mcp/src/tools/schema-utils.ts@@ -150,6 +150,55 @@ function describeItems(items: JSONSchema): string {// schemas are finite trees, but array/union unwrapping recurses — cap it anyway.const MAX_SUMMARY_DEPTH = 6+/** A tool-level control the executor strips before dispatch, so it doesn't count+ * as one of the tool's own parameters when deciding whether a field is the sole+ * wrapper. */+const TOOL_CONTROL_PROPERTIES = new Set(['output_format'])++/**+ * Whether a field is the wrapper a tool's whole payload sits under — the single+ * required top-level object on `query-logs`, `query-apm-spans`, `read-data-schema`+ * and their siblings.+ *+ * Callers flatten these: they send `{dateRange, limit}` where `{query: {dateRange,+ * limit}}` was wanted, because the fields they know about are the nested ones and+ * the drill-down hint alone never says the wrapper is mandatory. Naming it on the+ * field keeps the nesting in the summarized schema, which is all a caller sees once+ * the full schema overflows the token budget.+ *+ * Being the tool's ONLY parameter is what makes "everything goes inside it" true.+ * A required object sitting beside other top-level fields — `query-retention`'s+ * `retentionFilter`, `view-create`'s `query` next to `name` — is a component of the+ * payload, not the envelope, and saying otherwise would flatten calls that were+ * already correct.+ */+function isPayloadWrapper(+ name: string,+ prop: JSONSchema,+ schema: JSONSchema,+ requiredFields: readonly string[],+ fieldPath: string | undefined+): boolean {+ // Nested paths describe a field the caller already reached through the wrapper.+ if (fieldPath !== undefined || !requiredFields.includes(name)) {+ return false+ }+ const siblings = Object.keys((schema.properties || {}) as Record<string, unknown>).filter(+ (field) => field !== name && !TOOL_CONTROL_PROPERTIES.has(field)+ )+ if (siblings.length > 0) {+ return false+ }+ if (prop.type === 'object' && prop.properties) {+ return true+ }+ // A wrapper keyed by a discriminator (`read-data-schema`'s `query`) arrives as a+ // union of object variants, and gets flattened just as often.+ const variants = (prop.anyOf || prop.oneOf) as JSONSchema[] | undefined+ const nonNull = variants?.filter((variant) => variant.type !== 'null') ?? []+ return nonNull.length > 0 && nonNull.every((variant) => variant.type === 'object' && !!variant.properties)+}+/*** Summarize an object's top-level properties: field names, types, descriptions,* and drill-down hints for complex fields. Intentionally does NOT recurse into a@@ -197,6 +246,9 @@ function summarizeObject(schema: JSONSchema, toolName: string, fieldPath?: strin// the directive lives on the field the model is about to populate.if (isComplex(prop)) {entry.hint = `DO NOT GUESS — you MUST run \`schema ${toolName} ${pathPrefix}${name}\` before populating this field`+ if (isPayloadWrapper(name, prop, schema, requiredFields, fieldPath)) {+ entry.hint += `. Every parameter goes inside it — send {"${name}": {...}}, not the fields at the top level`+ }}result[name] = entrydiff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex c6f9ce644b32..e239f444c947 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -1669,11 +1669,11 @@ describe('exec tool', () => {return formatInputValidationError('query-logs', result.error!, input, wrapperSchema)}- it('tells the caller to nest the fields it sent at the top level', () => {+ it('shows the accepted shape, with the fields the caller sent nested inside it', () => {const message = formatFor({ dateRange: { date_from: '-1h' }, limit: 10 })expect(message).toBe(- 'Invalid input for "query-logs": missing required parameter: query; the fields you sent belong inside it, so resend them as {"query": {...}}'+ 'Invalid input for "query-logs": missing required parameter: query; the fields you sent belong inside it, so resend them as {"query": {"dateRange": ..., "limit": ...}}')})@@ -1682,7 +1682,49 @@ describe('exec tool', () => {// fails again on the same ambiguous message.const message = formatFor({ orderBy: 'newest', limit: 10 })- expect(message).toContain('resend them as {"query": {...}}')+ expect(message).toContain('resend them as {"query": {"orderBy": ..., "limit": ...}}')+ })++ it('names only wrapper fields, so an undeclared key cannot reach the message', () => {+ // The rendered shape is returned to the caller and recorded as the+ // analytics error message, so every key in it has to come from the+ // tool's own schema rather than the caller's payload.+ const message = formatFor({ limit: 10, sneaky_key: 'x' })++ expect(message).toContain('{"query": {"limit": ...}}')+ expect(message).not.toContain('sneaky_key')+ })++ it('caps the fields it names so a large payload cannot inflate the message', () => {+ const wide = z.object({+ query: z.object(+ Object.fromEntries(+ Array.from({ length: 8 }, (_unused, index) => [`field${index}`, z.string().optional()])+ )+ ),+ })+ const input = Object.fromEntries(Array.from({ length: 8 }, (_unused, index) => [`field${index}`, 'x']))+ const result = wide.safeParse(input, { reportInput: true })+ expect(result.success).toBe(false)++ const message = formatInputValidationError('query-logs', result.error!, input, wide)++ expect(message).toContain('{"query": {"field0": ..., "field1": ..., "field2": ..., "field3": ...')+ expect(message).toContain('...}}')+ expect(message).not.toContain('"field5"')+ })++ it('falls back to the bare shape when no key the caller sent belongs to the wrapper', () => {+ // A union-typed wrapper the caller half-guessed still gets a shape to+ // copy, rather than a message naming fields the wrapper never had.+ const looseWrapper = z.object({ query: z.looseObject({}).refine(() => true) })+ const input = { unknown_field: 1 }+ const result = looseWrapper.safeParse(input, { reportInput: true })+ expect(result.success).toBe(false)++ expect(formatInputValidationError('query-logs', result.error!, input, looseWrapper)).toContain(+ 'resend them as {"query": {...}}'+ )})it.each([@@ -1781,7 +1823,7 @@ describe('exec tool', () => {expect(result.success).toBe(false)expect(formatInputValidationError('query-logs', result.error!, input, tool.schema)).toContain(- 'resend them as {"query": {...}}'+ 'resend them as {"query": {"dateRange": ..., "limit": ...}}')})})diff --git a/services/mcp/tests/unit/nested-query-input-example.test.ts b/services/mcp/tests/unit/nested-query-input-example.test.tsnew file mode 100644index 000000000000..fd5ab369fe9b--- /dev/null+++ b/services/mcp/tests/unit/nested-query-input-example.test.ts@@ -0,0 +1,103 @@+import { describe, expect, it } from 'vitest'+import { z } from 'zod'++import { TOOL_MAP } from '@/tools'+import { GENERATED_TOOL_MAP } from '@/tools/generated'+import { getToolDefinitions } from '@/tools/toolDefinitions'+import type { ToolBase, ZodObjectAny } from '@/tools/types'++/**+ * A tool whose whole payload sits under a required `query` object is the shape+ * callers flatten: they send `{dateRange, limit}` where `{query: {dateRange,+ * limit}}` was wanted, and the call is rejected before it reaches the API.+ *+ * The guard is one valid example in the tool's own description. These tests keep+ * every such tool carrying one, and keep each example a payload the tool would+ * actually accept — a documented example that stopped parsing teaches the+ * flattening mistake it was written to prevent.+ */++type JsonSchema = Record<string, unknown>++function isRecord(value: unknown): value is JsonSchema {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++function inputJsonSchema(tool: ToolBase<ZodObjectAny>): JsonSchema | undefined {+ if (tool.rawInputSchema) {+ return tool.rawInputSchema+ }+ try {+ return z.toJSONSchema(tool.schema, { io: 'input' }) as JsonSchema+ } catch {+ return undefined+ }+}++/** Whether `query` is a required top-level object (or union of object variants). */+function requiresNestedQuery(schema: JsonSchema | undefined): boolean {+ const required = schema?.['required']+ if (!Array.isArray(required) || !required.includes('query')) {+ return false+ }+ const properties = schema?.['properties']+ const query = isRecord(properties) ? properties['query'] : undefined+ if (!isRecord(query)) {+ return false+ }+ if (query['type'] === 'object' && query['properties']) {+ return true+ }+ const variants = query['anyOf'] ?? query['oneOf']+ return (+ Array.isArray(variants) &&+ variants.length > 0 &&+ variants.every((variant) => isRecord(variant) && variant['type'] === 'object')+ )+}++/** Every fenced ```json block in a description, parsed; unparseable blocks are+ * skipped because a description may show a fragment rather than a whole call. */+function jsonExamples(description: string): unknown[] {+ const examples: unknown[] = []+ for (const match of description.matchAll(/```json\n([\s\S]*?)```/g)) {+ try {+ examples.push(JSON.parse(match[1]!))+ } catch {+ continue+ }+ }+ return examples+}++const allFactories: Record<string, () => ToolBase<ZodObjectAny>> = { ...TOOL_MAP, ...GENERATED_TOOL_MAP }+const definitions = getToolDefinitions()++const wrapperTools = Object.entries(allFactories).flatMap(([name, factory]) => {+ const tool = factory()+ return requiresNestedQuery(inputJsonSchema(tool)) ? [[name, tool] as const] : []+})++describe('tools that require a nested query object', () => {+ it('finds the wrapper tools to check', () => {+ // Guards the discovery itself: a refactor that stops matching any tool would+ // otherwise turn every case below into a silent no-op.+ expect(wrapperTools.length).toBeGreaterThan(15)+ expect(wrapperTools.map(([name]) => name)).toEqual(+ expect.arrayContaining(['query-logs', 'query-apm-spans', 'read-data-schema'])+ )+ })++ it.each(wrapperTools.map(([name]) => name))('%s documents an example its own schema accepts', (name) => {+ const tool = allFactories[name]!()+ const description = definitions[name]?.description ?? ''+ const accepted = jsonExamples(description).filter(+ (example) => isRecord(example) && 'query' in example && tool.schema.safeParse(example).success+ )++ expect(+ accepted.length,+ `${name} needs a \`\`\`json example wrapping its parameters in "query" that its schema accepts`+ ).toBeGreaterThan(0)+ })+})diff --git a/services/mcp/tests/unit/schema-utils.test.ts b/services/mcp/tests/unit/schema-utils.test.tsindex e51eb0b0b2fe..7c43b8f5cf64 100644--- a/services/mcp/tests/unit/schema-utils.test.ts+++ b/services/mcp/tests/unit/schema-utils.test.ts@@ -61,6 +61,84 @@ describe('schema-utils', () => {expect(result.properties.filter!.fields).toEqual(['key', 'value'])})+ // A tool whose whole payload sits under one required object is the shape+ // callers flatten. The summary is all they see once the full schema+ // overflows the token budget, so the nesting has to survive into it.+ describe('a sole required object parameter', () => {+ const wrapperSchema = (+ query: Record<string, unknown>,+ siblings: Record<string, unknown> = {}+ ): Record<string, unknown> => ({+ type: 'object',+ required: ['query'],+ properties: { query, ...siblings },+ })+ const objectQuery = { type: 'object', properties: { limit: { type: 'number' } } }++ it('says every parameter goes inside it', () => {+ const result = summarizeSchema(wrapperSchema(objectQuery), 'query-logs')++ expect(result.properties.query!.hint).toBe(+ 'DO NOT GUESS — you MUST run `schema query-logs query` before populating this field. Every parameter goes inside it — send {"query": {...}}, not the fields at the top level'+ )+ })++ it('says so for a wrapper that is a union of object variants', () => {+ // `read-data-schema` keys its shape off a `kind` discriminator.+ const unionQuery = {+ anyOf: [+ { type: 'object', properties: { kind: { const: 'events' } } },+ { type: 'object', properties: { kind: { const: 'event_properties' } } },+ ],+ }++ expect(summarizeSchema(wrapperSchema(unionQuery), 'read-data-schema').properties.query!.hint).toContain(+ 'Every parameter goes inside it'+ )+ })++ it('ignores the tool-level output_format control when counting parameters', () => {+ const withControl = wrapperSchema(objectQuery, { output_format: { type: 'string' } })++ expect(summarizeSchema(withControl, 'query-logs').properties.query!.hint).toContain(+ 'Every parameter goes inside it'+ )+ })++ it.each([+ [+ 'the object sits beside other top-level fields',+ wrapperSchema(objectQuery, { name: { type: 'string' } }),+ ],+ [+ 'the object is optional',+ { type: 'object', properties: { query: objectQuery } } as Record<string, unknown>,+ ],+ ])('stays with the bare drill-down hint when %s', (_label, schema) => {+ // Saying "everything goes inside it" here would flatten calls that+ // were already correct: the other top-level fields are real parameters.+ const result = summarizeSchema(schema as Record<string, unknown>, 'view-create')++ expect(result.properties.query!.hint).toBe(+ 'DO NOT GUESS — you MUST run `schema view-create query` before populating this field'+ )+ })++ it('does not repeat the wrapper note on fields inside the wrapper', () => {+ const nested = {+ type: 'object',+ required: ['dateRange'],+ properties: { dateRange: { type: 'object', properties: { date_from: { type: 'string' } } } },+ }++ const result = summarizeSchema(nested, 'query-logs', 'query')++ expect(result.properties.dateRange!.hint).toBe(+ 'DO NOT GUESS — you MUST run `schema query-logs query.dateRange` before populating this field'+ )+ })+ })+it('adds hints for arrays with complex items', () => {const schema = {type: 'object',