: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(web_analytics): group MCP web query tools under Web analytics (#73559)
Lucas Ricoy953cac222599
diff --git a/services/mcp/definitions/prompts/query-web-overview.md b/products/web_analytics/mcp/prompts/query-web-overview.mdsimilarity index 100%rename from services/mcp/definitions/prompts/query-web-overview.mdrename to products/web_analytics/mcp/prompts/query-web-overview.mddiff --git a/services/mcp/definitions/prompts/query-web-stats.md b/products/web_analytics/mcp/prompts/query-web-stats.mdsimilarity index 100%rename from services/mcp/definitions/prompts/query-web-stats.mdrename to products/web_analytics/mcp/prompts/query-web-stats.mddiff --git a/services/mcp/definitions/prompts/query-web-vitals.md b/products/web_analytics/mcp/prompts/query-web-vitals.mdsimilarity index 100%rename from services/mcp/definitions/prompts/query-web-vitals.mdrename to products/web_analytics/mcp/prompts/query-web-vitals.mddiff --git a/products/web_analytics/mcp/tools.yaml b/products/web_analytics/mcp/tools.yamlindex 3e899160dd49..d8911f70feb2 100644--- a/products/web_analytics/mcp/tools.yaml+++ b/products/web_analytics/mcp/tools.yaml@@ -200,3 +200,58 @@ tools:(bool, default true) query params — pass `days=30` to summarize the last month, or `compare=false` to skipthe period-over-period comparison for a faster response. Use this to answer questions like "how are my webanalytics?", "how did the site do last week?", or "what's my traffic looking like this month?".+wrappers:+ query-web-overview:+ schema_ref: AssistantWebOverviewQuery+ enabled: true+ scopes:+ - query:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Run a web analytics overview query+ description_file: ./prompts/query-web-overview.md+ system_prompt_hint: Web analytics KPIs — visitors, sessions, bounce rate, session duration+ ui_resource_uri: ui://posthog/query-results.html+ exclude_properties:+ - response+ - modifiers+ - samplingFactor+ use_optimized_output: false+ query-web-stats:+ schema_ref: AssistantWebStatsTableQuery+ enabled: true+ scopes:+ - query:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Run a web analytics breakdown table query+ description_file: ./prompts/query-web-stats.md+ system_prompt_hint: Web analytics breakdowns — top pages, UTMs, devices, countries, with bounce rate+ ui_resource_uri: ui://posthog/query-results.html+ exclude_properties:+ - response+ - modifiers+ - samplingFactor+ use_optimized_output: false+ query-web-vitals:+ schema_ref: AssistantWebVitalsPathBreakdownQuery+ enabled: true+ scopes:+ - query:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Run a web vitals path breakdown query+ description_file: ./prompts/query-web-vitals.md+ system_prompt_hint: Core Web Vitals per page — LCP, INP, CLS, FCP bucketed into good / needs-improvement / poor+ ui_resource_uri: ui://posthog/query-results.html+ exclude_properties:+ - response+ - modifiers+ - samplingFactor+ use_optimized_output: falsediff --git a/services/mcp/definitions/query-wrappers.yaml b/services/mcp/definitions/query-wrappers.yamlindex d6348e9ee21b..8d5b84d8b086 100644--- a/services/mcp/definitions/query-wrappers.yaml+++ b/services/mcp/definitions/query-wrappers.yaml@@ -122,60 +122,6 @@ wrappers:- modifiers- samplingFactor- query-web-overview:- schema_ref: AssistantWebOverviewQuery- enabled: true- scopes:- - query:read- annotations:- readOnly: true- destructive: false- idempotent: true- title: Run a web analytics overview query- description_file: ./prompts/query-web-overview.md- system_prompt_hint: Web analytics KPIs — visitors, sessions, bounce rate, session duration- ui_resource_uri: ui://posthog/query-results.html- exclude_properties:- - response- - modifiers- - samplingFactor-- query-web-stats:- schema_ref: AssistantWebStatsTableQuery- enabled: true- scopes:- - query:read- annotations:- readOnly: true- destructive: false- idempotent: true- title: Run a web analytics breakdown table query- description_file: ./prompts/query-web-stats.md- system_prompt_hint: Web analytics breakdowns — top pages, UTMs, devices, countries, with bounce rate- ui_resource_uri: ui://posthog/query-results.html- exclude_properties:- - response- - modifiers- - samplingFactor-- query-web-vitals:- schema_ref: AssistantWebVitalsPathBreakdownQuery- enabled: true- scopes:- - query:read- annotations:- readOnly: true- destructive: false- idempotent: true- title: Run a web vitals path breakdown query- description_file: ./prompts/query-web-vitals.md- system_prompt_hint: Core Web Vitals per page — LCP, INP, CLS, FCP bucketed into good / needs-improvement / poor- ui_resource_uri: ui://posthog/query-results.html- exclude_properties:- - response- - modifiers- - samplingFactor-query-llm-traces-list:schema_ref: AssistantTracesQueryenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 5679a3ebc6d4..1f370abb83aa 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -7725,8 +7725,8 @@},"query-web-overview": {"description": "Run a web analytics overview query — high-level KPIs over a period: visitors, pageviews, sessions, average session duration, and bounce rate. Returns a small list of metric tuples with optional period-over-period comparison. Mirrors the in-product **Web analytics** scene.\n\n# When to use this vs `query-trends`\n\nPick this tool only when the answer needs **session-level math**. Session aggregation is more expensive than per-event queries — only pay for it when needed.\n\nUse `query-web-overview` when the question references just the aggregate values across the period instead of time series for those session-level values: bounce rate, session duration, sessions as a count, or entry/initial values (entry page, initial channel, initial UTM).\n\nUse `query-trends` instead for per-event counts — pageviews, sign-ups, button clicks. Faster.\n\n# Inputs\n\n- `dateRange` — defaults to last 7 days when omitted. Keep ranges short — there is no enforced upper bound and large windows on the slow path can be expensive.\n- `compareFilter: { compare: true }` — return prior-period values for change %. **Roughly doubles query cost** because it runs the same aggregation over the previous period — leave it off unless the user explicitly asks for a comparison.\n- `properties` — event/person/session/cohort filters. Same operator semantics as `query-trends` — see that prompt. Defaults to `[]`.\n- `filterTestAccounts` — exclude internal/test users.\n- `doPathCleaning` — apply team's path-cleaning rules.\n- `conversionGoal` — pass an `actionId` (must belong to the current project) or a `customEventName`. Only set when the user asks about a conversion.\n\nUse `read-data-schema` to validate property names/values when needed.\n\n# Example\n\n```json\n{\n \"kind\": \"WebOverviewQuery\",\n \"dateRange\": { \"date_from\": \"-7d\" }\n}\n```\n\n# Out of scope\n\n`conversionGoal` is supported as an input on this tool. Goal-funnel breakdowns (`WebGoalsQuery`), web vitals, and external clicks aren't exposed as separate query modes — fall back to `execute-sql` for those.",- "category": "Query wrappers",- "feature": "insights",+ "category": "Web analytics",+ "feature": "web_analytics","summary": "Run a web analytics overview query","title": "Run a web analytics overview query","required_scopes": ["query:read"],@@ -7740,8 +7740,8 @@},"query-web-stats": {"description": "Run a web analytics breakdown table query — top pages, UTMs, devices, browsers, countries, etc. — with visitors and pageviews per row, plus optional bounce rate / average time on page. Mirrors the in-product **Web analytics** scene's table tiles.\n\n# When to use this vs `query-trends` / `query-paths`\n\nPick this tool only when the answer needs **session-level math**. Session aggregation is more expensive than per-event queries — only pay for it when needed.\n\nUse `query-web-stats` when the breakdown or metric is session-derived:\n\n- `includeBounceRate=true` or `includeAvgTimeOnPage=true` (per-session metrics)\n- Initial / first-touch breakdowns: `InitialPage`, `InitialChannelType`, `InitialReferringDomain`, `InitialUTMSource`/`Medium`/`Campaign`/`Term`/`Content`\n- `ExitPage` (last event in a session)\n\nUse `query-trends` (with a breakdown) for per-event counts by an event property — no session boundaries needed. Faster.\n\nUse `query-paths` for navigation between arbitrary events when you don't need bounce rate or session-level metrics.\n\n# `breakdownBy` cheat-sheet\n\n- **Path-style** (pair with `includeBounceRate`/`includeAvgTimeOnPage`): `Page`, `InitialPage`, `ExitPage`, `PreviousPage`\n- **Marketing**: `InitialChannelType`, `InitialReferringDomain`, `InitialReferringURL`, `InitialUTMSource`, `InitialUTMMedium`, `InitialUTMCampaign`, `InitialUTMTerm`, `InitialUTMContent`, `InitialUTMSourceMediumCampaign`\n- **Audience / device**: `Browser`, `OS`, `Viewport`, `DeviceType`, `Country`, `Region`, `City`, `Timezone`, `Language`\n- **Other**: `ScreenName`, `ExitClick`, `FrustrationMetrics` (these don't combine with `includeBounceRate` / `includeAvgTimeOnPage`)\n\n# Inputs\n\nSame filter set as `query-web-overview` (`dateRange`, `compareFilter`, `properties`, `filterTestAccounts`, `doPathCleaning`, `conversionGoal`). Plus `breakdownBy` (required), `includeBounceRate`, `includeAvgTimeOnPage`, `includeHost`, `limit`, `offset`. Default `dateRange` is last 7 days.\n\nPerformance hints:\n\n- Leave `compareFilter` off unless the user asks for period-over-period — enabling it roughly doubles query cost.\n- `limit` is capped at 200 by the wrapper. Prefer 10–25 unless the user explicitly asks for more.\n\nUse `read-data-schema` to validate property names/values when needed.\n\n# Example\n\nTop 20 pages by bounce rate, last 7 days:\n\n```json\n{\n \"kind\": \"WebStatsTableQuery\",\n \"breakdownBy\": \"Page\",\n \"includeBounceRate\": true,\n \"limit\": 20,\n \"dateRange\": { \"date_from\": \"-7d\" }\n}\n```\n\n# Out of scope\n\n`conversionGoal` is supported as an input on this tool. Goal-funnel breakdowns (`WebGoalsQuery`), web vitals, and external clicks aren't exposed as separate query modes — fall back to `execute-sql` for those.",- "category": "Query wrappers",- "feature": "insights",+ "category": "Web analytics",+ "feature": "web_analytics","summary": "Run a web analytics breakdown table query","title": "Run a web analytics breakdown table query","required_scopes": ["query:read"],@@ -7755,8 +7755,8 @@},"query-web-vitals": {"description": "Per-page Core Web Vitals breakdown — one metric at one percentile, with pages bucketed into `good` / `needs_improvements` / `poor` bands. Mirrors the in-product **Web analytics → Web vitals** tab.\n\n# When to use this vs `query-trends` / `execute-sql`\n\nUse `query-web-vitals` for **page-level** vitals questions: \"which pages are slow?\", \"where is LCP bad?\", \"audit our Core Web Vitals\". One call replaces a hand-written percentile query over `$web_vitals` and classifies each page against the band thresholds for you.\n\nUse `query-trends` on the `$web_vitals` event (property math on `$web_vitals_LCP_value` etc.) for a **site-wide trend over time** — this tool has no time axis; it aggregates the whole window.\n\nReach for `execute-sql` only for shapes neither covers (e.g. per-page sample counts, device splits per page, or custom baselines).\n\nRequires the project to capture the `$web_vitals` event (`capture_performance` in posthog-js). If results come back empty, check capture with `read-data-schema` before concluding pages are fine.\n\n# Inputs\n\n- `metric` (required): `LCP` (load, ms), `INP` (interactivity, ms), `CLS` (layout stability, unitless), or `FCP` (first paint, ms). One metric per call — run up to four calls for a full audit.\n- `percentile` (required): use `p75` unless the user asks otherwise — the Google bands are defined at p75. `p90`/`p99` show the slow tail.\n- `thresholds` (required): `[good, poor]` boundaries for the chosen metric. Standard Google values:\n\n| Metric | thresholds |\n| ------ | -------------- |\n| LCP | `[2500, 4000]` |\n| INP | `[200, 500]` |\n| CLS | `[0.1, 0.25]` |\n| FCP | `[1800, 3000]` |\n\n- `dateRange`: defaults to the last 7 days — a good window for a stable percentile; shorter windows get noisy on low-traffic pages.\n- `properties`: event and person filters only (the runner ignores session and cohort filters) — e.g. an event filter on `$host` to scope one domain of a multi-domain project, or on `$device_type` (`Mobile`/`Desktop`) to isolate a population.\n- `filterTestAccounts`, `doPathCleaning`: same semantics as the other web analytics tools.\n\n# Reading the result\n\nEach band lists `{path, value}` pairs. A page in `poor` at p75 on a high-traffic route is a real, citable problem even if it never changed. Percentiles on low-traffic pages wobble — corroborate a surprising result with a sample count via `execute-sql` before making strong claims. Mobile values run 2–3× desktop, so a pooled percentile can hide a mobile-only problem: when a page looks borderline, re-run with a `$device_type` filter.\n\n# Example\n\nWorst LCP pages at p75, last 7 days, marketing site only:\n\n```json\n{\n \"metric\": \"LCP\",\n \"percentile\": \"p75\",\n \"thresholds\": [2500, 4000],\n \"properties\": [{ \"type\": \"event\", \"key\": \"$host\", \"operator\": \"exact\", \"value\": [\"example.com\"] }]\n}\n```",- "category": "Query wrappers",- "feature": "insights",+ "category": "Web analytics",+ "feature": "web_analytics","summary": "Run a web vitals path breakdown query","title": "Run a web vitals path breakdown query","required_scopes": ["query:read"],diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 4db078375bad..720c7380fd53 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -8260,8 +8260,8 @@},"query-web-overview": {"description": "Run a web analytics overview query — high-level KPIs over a period: visitors, pageviews, sessions, average session duration, and bounce rate. Returns a small list of metric tuples with optional period-over-period comparison. Mirrors the in-product **Web analytics** scene.\n\n# When to use this vs `query-trends`\n\nPick this tool only when the answer needs **session-level math**. Session aggregation is more expensive than per-event queries — only pay for it when needed.\n\nUse `query-web-overview` when the question references just the aggregate values across the period instead of time series for those session-level values: bounce rate, session duration, sessions as a count, or entry/initial values (entry page, initial channel, initial UTM).\n\nUse `query-trends` instead for per-event counts — pageviews, sign-ups, button clicks. Faster.\n\n# Inputs\n\n- `dateRange` — defaults to last 7 days when omitted. Keep ranges short — there is no enforced upper bound and large windows on the slow path can be expensive.\n- `compareFilter: { compare: true }` — return prior-period values for change %. **Roughly doubles query cost** because it runs the same aggregation over the previous period — leave it off unless the user explicitly asks for a comparison.\n- `properties` — event/person/session/cohort filters. Same operator semantics as `query-trends` — see that prompt. Defaults to `[]`.\n- `filterTestAccounts` — exclude internal/test users.\n- `doPathCleaning` — apply team's path-cleaning rules.\n- `conversionGoal` — pass an `actionId` (must belong to the current project) or a `customEventName`. Only set when the user asks about a conversion.\n\nUse `read-data-schema` to validate property names/values when needed.\n\n# Example\n\n```json\n{\n \"kind\": \"WebOverviewQuery\",\n \"dateRange\": { \"date_from\": \"-7d\" }\n}\n```\n\n# Out of scope\n\n`conversionGoal` is supported as an input on this tool. Goal-funnel breakdowns (`WebGoalsQuery`), web vitals, and external clicks aren't exposed as separate query modes — fall back to `execute-sql` for those.",- "category": "Query wrappers",- "feature": "insights",+ "category": "Web analytics",+ "feature": "web_analytics","summary": "Run a web analytics overview query","title": "Run a web analytics overview query","required_scopes": ["query:read"],@@ -8275,8 +8275,8 @@},"query-web-stats": {"description": "Run a web analytics breakdown table query — top pages, UTMs, devices, browsers, countries, etc. — with visitors and pageviews per row, plus optional bounce rate / average time on page. Mirrors the in-product **Web analytics** scene's table tiles.\n\n# When to use this vs `query-trends` / `query-paths`\n\nPick this tool only when the answer needs **session-level math**. Session aggregation is more expensive than per-event queries — only pay for it when needed.\n\nUse `query-web-stats` when the breakdown or metric is session-derived:\n\n- `includeBounceRate=true` or `includeAvgTimeOnPage=true` (per-session metrics)\n- Initial / first-touch breakdowns: `InitialPage`, `InitialChannelType`, `InitialReferringDomain`, `InitialUTMSource`/`Medium`/`Campaign`/`Term`/`Content`\n- `ExitPage` (last event in a session)\n\nUse `query-trends` (with a breakdown) for per-event counts by an event property — no session boundaries needed. Faster.\n\nUse `query-paths` for navigation between arbitrary events when you don't need bounce rate or session-level metrics.\n\n# `breakdownBy` cheat-sheet\n\n- **Path-style** (pair with `includeBounceRate`/`includeAvgTimeOnPage`): `Page`, `InitialPage`, `ExitPage`, `PreviousPage`\n- **Marketing**: `InitialChannelType`, `InitialReferringDomain`, `InitialReferringURL`, `InitialUTMSource`, `InitialUTMMedium`, `InitialUTMCampaign`, `InitialUTMTerm`, `InitialUTMContent`, `InitialUTMSourceMediumCampaign`\n- **Audience / device**: `Browser`, `OS`, `Viewport`, `DeviceType`, `Country`, `Region`, `City`, `Timezone`, `Language`\n- **Other**: `ScreenName`, `ExitClick`, `FrustrationMetrics` (these don't combine with `includeBounceRate` / `includeAvgTimeOnPage`)\n\n# Inputs\n\nSame filter set as `query-web-overview` (`dateRange`, `compareFilter`, `properties`, `filterTestAccounts`, `doPathCleaning`, `conversionGoal`). Plus `breakdownBy` (required), `includeBounceRate`, `includeAvgTimeOnPage`, `includeHost`, `limit`, `offset`. Default `dateRange` is last 7 days.\n\nPerformance hints:\n\n- Leave `compareFilter` off unless the user asks for period-over-period — enabling it roughly doubles query cost.\n- `limit` is capped at 200 by the wrapper. Prefer 10–25 unless the user explicitly asks for more.\n\nUse `read-data-schema` to validate property names/values when needed.\n\n# Example\n\nTop 20 pages by bounce rate, last 7 days:\n\n```json\n{\n \"kind\": \"WebStatsTableQuery\",\n \"breakdownBy\": \"Page\",\n \"includeBounceRate\": true,\n \"limit\": 20,\n \"dateRange\": { \"date_from\": \"-7d\" }\n}\n```\n\n# Out of scope\n\n`conversionGoal` is supported as an input on this tool. Goal-funnel breakdowns (`WebGoalsQuery`), web vitals, and external clicks aren't exposed as separate query modes — fall back to `execute-sql` for those.",- "category": "Query wrappers",- "feature": "insights",+ "category": "Web analytics",+ "feature": "web_analytics","summary": "Run a web analytics breakdown table query","title": "Run a web analytics breakdown table query","required_scopes": ["query:read"],@@ -8290,8 +8290,8 @@},"query-web-vitals": {"description": "Per-page Core Web Vitals breakdown — one metric at one percentile, with pages bucketed into `good` / `needs_improvements` / `poor` bands. Mirrors the in-product **Web analytics → Web vitals** tab.\n\n# When to use this vs `query-trends` / `execute-sql`\n\nUse `query-web-vitals` for **page-level** vitals questions: \"which pages are slow?\", \"where is LCP bad?\", \"audit our Core Web Vitals\". One call replaces a hand-written percentile query over `$web_vitals` and classifies each page against the band thresholds for you.\n\nUse `query-trends` on the `$web_vitals` event (property math on `$web_vitals_LCP_value` etc.) for a **site-wide trend over time** — this tool has no time axis; it aggregates the whole window.\n\nReach for `execute-sql` only for shapes neither covers (e.g. per-page sample counts, device splits per page, or custom baselines).\n\nRequires the project to capture the `$web_vitals` event (`capture_performance` in posthog-js). If results come back empty, check capture with `read-data-schema` before concluding pages are fine.\n\n# Inputs\n\n- `metric` (required): `LCP` (load, ms), `INP` (interactivity, ms), `CLS` (layout stability, unitless), or `FCP` (first paint, ms). One metric per call — run up to four calls for a full audit.\n- `percentile` (required): use `p75` unless the user asks otherwise — the Google bands are defined at p75. `p90`/`p99` show the slow tail.\n- `thresholds` (required): `[good, poor]` boundaries for the chosen metric. Standard Google values:\n\n| Metric | thresholds |\n| ------ | -------------- |\n| LCP | `[2500, 4000]` |\n| INP | `[200, 500]` |\n| CLS | `[0.1, 0.25]` |\n| FCP | `[1800, 3000]` |\n\n- `dateRange`: defaults to the last 7 days — a good window for a stable percentile; shorter windows get noisy on low-traffic pages.\n- `properties`: event and person filters only (the runner ignores session and cohort filters) — e.g. an event filter on `$host` to scope one domain of a multi-domain project, or on `$device_type` (`Mobile`/`Desktop`) to isolate a population.\n- `filterTestAccounts`, `doPathCleaning`: same semantics as the other web analytics tools.\n\n# Reading the result\n\nEach band lists `{path, value}` pairs. A page in `poor` at p75 on a high-traffic route is a real, citable problem even if it never changed. Percentiles on low-traffic pages wobble — corroborate a surprising result with a sample count via `execute-sql` before making strong claims. Mobile values run 2–3× desktop, so a pooled percentile can hide a mobile-only problem: when a page looks borderline, re-run with a `$device_type` filter.\n\n# Example\n\nWorst LCP pages at p75, last 7 days, marketing site only:\n\n```json\n{\n \"metric\": \"LCP\",\n \"percentile\": \"p75\",\n \"thresholds\": [2500, 4000],\n \"properties\": [{ \"type\": \"event\", \"key\": \"$host\", \"operator\": \"exact\", \"value\": [\"example.com\"] }]\n}\n```",- "category": "Query wrappers",- "feature": "insights",+ "category": "Web analytics",+ "feature": "web_analytics","summary": "Run a web vitals path breakdown query","title": "Run a web vitals path breakdown query","required_scopes": ["query:read"],diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.tsindex 0ab58e3eb4d6..53d0d5818d60 100644--- a/services/mcp/scripts/generate-tools.ts+++ b/services/mcp/scripts/generate-tools.ts@@ -1790,6 +1790,12 @@ function generateCategoryFile(if (wrapperConfig.ui_resource_uri) {configParts.push(`uiResourceUri: '${wrapperConfig.ui_resource_uri}'`)}+ // Unlike the definitions-file branch, only an explicit `use_optimized_output` emits a+ // format here — absent keeps the factory default, so pre-existing product wrappers+ // don't silently change encoding.+ if (wrapperConfig.use_optimized_output !== undefined) {+ configParts.push(`outputFormat: '${wrapperConfig.use_optimized_output ? 'optimized' : 'json'}'`)+ }if (wrapperConfig.url_prefix) {configParts.push(`urlPrefix: '${wrapperConfig.url_prefix}'`)}diff --git a/services/mcp/src/tools/generated/query-wrappers.ts b/services/mcp/src/tools/generated/query-wrappers.tsindex a5b3552c1dea..b33788de65d0 100644--- a/services/mcp/src/tools/generated/query-wrappers.ts+++ b/services/mcp/src/tools/generated/query-wrappers.ts@@ -1204,269 +1204,6 @@ const AssistantLifecycleQuery = z.object({.describe('Event or action to analyze. Lifecycle insights only support a single series.'),})-const ActionConversionGoal = z.object({- actionId: integer,-})--const CustomEventConversionGoal = z.object({- customEventName: z.string(),-})--const WebAnalyticsConversionGoal = z.union([ActionConversionGoal, CustomEventConversionGoal])--const PropertyOperator = z.enum([- 'exact',- 'is_not',- 'icontains',- 'not_icontains',- 'regex',- 'not_regex',- 'gt',- 'gte',- 'lt',- 'lte',- 'is_set',- 'is_not_set',- 'is_date_exact',- 'is_date_before',- 'is_date_after',- 'between',- 'not_between',- 'min',- 'max',- 'in',- 'not_in',- 'is_cleaned_path_exact',- 'flag_evaluates_to',- 'semver_eq',- 'semver_neq',- 'semver_gt',- 'semver_gte',- 'semver_lt',- 'semver_lte',- 'semver_tilde',- 'semver_caret',- 'semver_wildcard',- 'icontains_multi',- 'not_icontains_multi',-])--const PropertyFilterBaseValue = z.union([z.string(), z.coerce.number(), z.coerce.boolean()])--const PropertyFilterValue = z.union([PropertyFilterBaseValue, z.array(PropertyFilterBaseValue), z.null()])--const EventPropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator.default('exact'),- type: z.literal('event').describe('Event properties').default('event'),- value: PropertyFilterValue.optional(),-})--const PersonPropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: z.literal('person').describe('Person properties').default('person'),- value: PropertyFilterValue.optional(),-})--const SessionPropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: z.literal('session').default('session'),- value: PropertyFilterValue.optional(),-})--const CohortPropertyFilter = z.object({- cohort_name: z.string().optional(),- key: z.literal('id').default('id'),- label: z.string().optional(),- operator: PropertyOperator.default('in'),- type: z.literal('cohort').default('cohort'),- value: z.coerce.number().int(),-})--const WebAnalyticsPropertyFilter = z.union([- EventPropertyFilter,- PersonPropertyFilter,- SessionPropertyFilter,- CohortPropertyFilter,-])--const WebAnalyticsPropertyFilters = z.array(WebAnalyticsPropertyFilter)--const AssistantWebOverviewQuery = z.object({- compareFilter: CompareFilter.describe(- 'Compare the current period to a prior period. Disabled by default. Enabling roughly doubles query cost — leave it off unless the user explicitly asks for a period-over-period comparison.'- ).optional(),- conversionGoal: z- .union([WebAnalyticsConversionGoal, z.null()])- .describe(- 'Conversion goal — pass an `actionId` (must belong to the current project) or a `customEventName`. Adds conversion columns to the response. Disables the pre-aggregated fast path — only set when the user explicitly asks about a conversion.'- )- .optional(),- dateRange: AssistantDateRangeFilter.describe(- 'Date range for the query. Defaults to the last 7 days when omitted. Keep ranges short — the backend has no upper bound and large windows on the slow path (e.g. with `conversionGoal` or `includeAvgTimeOnPage`) can be expensive.'- ).optional(),- doPathCleaning: z.coerce- .boolean()- .describe("Apply the team's path-cleaning rules to URL-style breakdowns.")- .default(false)- .optional(),- filterTestAccounts: z.coerce- .boolean()- .describe("Exclude internal and test users by applying the team's test-account filter.")- .default(false)- .optional(),- kind: z.literal('WebOverviewQuery').default('WebOverviewQuery'),- properties: WebAnalyticsPropertyFilters.describe(- 'Property filters applied to the query. Accepts event, person, session, or cohort filters.'- )- .default([])- .optional(),-})--const WebStatsBreakdown = z.enum([- 'Page',- 'InitialPage',- 'ExitPage',- 'ExitClick',- 'PreviousPage',- 'ScreenName',- 'InitialChannelType',- 'InitialReferringDomain',- 'InitialReferringURL',- 'InitialUTMSource',- 'InitialUTMCampaign',- 'InitialUTMMedium',- 'InitialUTMTerm',- 'InitialUTMContent',- 'InitialUTMSourceMediumCampaign',- 'FirstPageviewChannelType',- 'FirstPageviewReferringDomain',- 'FirstPageviewUTMSource',- 'FirstPageviewUTMCampaign',- 'FirstPageviewUTMMedium',- 'FirstPageviewUTMTerm',- 'FirstPageviewUTMContent',- 'FirstPageviewUTMSourceMediumCampaign',- 'Browser',- 'OS',- 'Viewport',- 'DeviceType',- 'Country',- 'Region',- 'City',- 'Timezone',- 'Language',- 'FrustrationMetrics',-])--const non_negative_integer = z.coerce.number().int().min(0)--const AssistantWebStatsTableQuery = z.object({- breakdownBy: WebStatsBreakdown.describe(- 'Required. Property to break down the table by. The full enum covers path-style (`Page`, `InitialPage`, `ExitPage`, `PreviousPage`), marketing/source (UTM source/medium/campaign/term/content, channel, referring domain), audience/device (browser, OS, device type, viewport), and geography (country, region, city, timezone, language). Path-style breakdowns pair naturally with `includeBounceRate` / `includeAvgTimeOnPage`.'- ),- compareFilter: CompareFilter.describe(- 'Compare the current period to a prior period. Disabled by default. Enabling roughly doubles query cost — leave it off unless the user explicitly asks for a period-over-period comparison.'- ).optional(),- conversionGoal: z- .union([WebAnalyticsConversionGoal, z.null()])- .describe(- 'Conversion goal — pass an `actionId` (must belong to the current project) or a `customEventName`. Adds conversion columns to the response. Disables the pre-aggregated fast path — only set when the user explicitly asks about a conversion.'- )- .optional(),- dateRange: AssistantDateRangeFilter.describe(- 'Date range for the query. Defaults to the last 7 days when omitted. Keep ranges short — the backend has no upper bound and large windows on the slow path (e.g. with `conversionGoal` or `includeAvgTimeOnPage`) can be expensive.'- ).optional(),- doPathCleaning: z.coerce- .boolean()- .describe("Apply the team's path-cleaning rules to URL-style breakdowns.")- .default(false)- .optional(),- filterTestAccounts: z.coerce- .boolean()- .describe("Exclude internal and test users by applying the team's test-account filter.")- .default(false)- .optional(),- includeAvgTimeOnPage: z.coerce- .boolean()- .describe(- 'Add an average-time-on-page column. Implies a Page-style breakdown. Disables the pre-aggregated fast path.'- )- .default(false)- .optional(),- includeBounceRate: z.coerce- .boolean()- .describe('Add a bounce-rate column. Most useful with a path-style breakdown.')- .default(false)- .optional(),- includeHost: z.coerce- .boolean()- .describe(- 'When using a path-style breakdown (`Page`, `InitialPage`, `ExitPage`, `PreviousPage`), concatenate host + pathname so the same path on different hosts is counted separately.'- )- .default(false)- .optional(),- kind: z.literal('WebStatsTableQuery').default('WebStatsTableQuery'),- limit: positive_integer- .max(200)- .describe(- 'Maximum rows to return. Prefer 10–25 unless the user explicitly asks for more. Hard ceiling enforced at the wrapper.'- )- .optional(),- offset: non_negative_integer.describe('Pagination offset.').optional(),- properties: WebAnalyticsPropertyFilters.describe(- 'Property filters applied to the query. Accepts event, person, session, or cohort filters.'- )- .default([])- .optional(),-})--const WebVitalsMetric = z.enum(['INP', 'LCP', 'CLS', 'FCP'])--const WebVitalsPercentile = z.enum(['p75', 'p90', 'p99'])--const AssistantWebVitalsPathBreakdownQuery = z.object({- dateRange: AssistantDateRangeFilter.describe(- 'Date range for the query. Defaults to the last 7 days when omitted — a good window for a stable percentile.'- ).optional(),- doPathCleaning: z.coerce- .boolean()- .describe("Apply the team's path-cleaning rules to the returned paths.")- .default(false)- .optional(),- filterTestAccounts: z.coerce- .boolean()- .describe("Exclude internal and test users by applying the team's test-account filter.")- .default(false)- .optional(),- kind: z.literal('WebVitalsPathBreakdownQuery').default('WebVitalsPathBreakdownQuery'),- metric: WebVitalsMetric.describe(- 'Required. Which Core Web Vital to break down by: `LCP` (load, ms), `INP` (interactivity, ms), `CLS` (layout stability, unitless score), or `FCP` (first paint, ms).'- ),- percentile: WebVitalsPercentile.describe(- "Required. Percentile to aggregate each page's samples at. Use `p75` unless the user asks otherwise — the Google bands are defined at p75."- ),- properties: z- .array(z.union([EventPropertyFilter, PersonPropertyFilter]))- .describe(- 'Property filters applied to the query. Accepts event and person filters only (the query runner ignores session and cohort filters) — e.g. an event filter on `$host` to scope to one domain, or on `$device_type` to isolate mobile.'- )- .default([])- .optional(),- thresholds: z- .array(z.coerce.number())- .min(2)- .max(2)- .describe(- 'Required. `[good, poor]` band boundaries for the chosen metric. Values below `good` are good, above `poor` are poor, in between need improvement. Use the standard Google thresholds unless the user supplies their own: LCP `[2500, 4000]`, INP `[200, 500]`, CLS `[0.1, 0.25]`, FCP `[1800, 3000]`.'- ),-})-const AssistantTracesQuery = z.object({dateRange: AssistantDateRangeFilter.describe('Date range for the query.').optional(),filterSupportTraces: z.coerce.boolean().describe('Exclude support impersonation traces.').default(false).optional(),@@ -1782,27 +1519,6 @@ export const GENERATED_TOOLS: Record<string, ReturnType<typeof createQueryWrappeuiResourceUri: 'ui://posthog/query-results.html',outputFormat: 'optimized',}),- 'query-web-overview': createQueryWrapper({- name: 'query-web-overview',- schema: AssistantWebOverviewQuery,- kind: 'WebOverviewQuery',- uiResourceUri: 'ui://posthog/query-results.html',- outputFormat: 'json',- }),- 'query-web-stats': createQueryWrapper({- name: 'query-web-stats',- schema: AssistantWebStatsTableQuery,- kind: 'WebStatsTableQuery',- uiResourceUri: 'ui://posthog/query-results.html',- outputFormat: 'json',- }),- 'query-web-vitals': createQueryWrapper({- name: 'query-web-vitals',- schema: AssistantWebVitalsPathBreakdownQuery,- kind: 'WebVitalsPathBreakdownQuery',- uiResourceUri: 'ui://posthog/query-results.html',- outputFormat: 'json',- }),'query-llm-traces-list': createQueryWrapper({name: 'query-llm-traces-list',schema: AssistantTracesQuery,diff --git a/services/mcp/src/tools/generated/web_analytics.ts b/services/mcp/src/tools/generated/web_analytics.tsindex 05907be4fae1..e16c84882245 100644--- a/services/mcp/src/tools/generated/web_analytics.ts+++ b/services/mcp/src/tools/generated/web_analytics.ts@@ -13,6 +13,7 @@ import {SavedRetrieveParams,WebAnalyticsWeeklyDigestQueryParams,} from '@/generated/web_analytics/api'+import { createQueryWrapper } from '@/tools/query-wrapper-factory'import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'@@ -231,6 +232,304 @@ const webAnalyticsWeeklyDigest = (): ToolBase<typeof WebAnalyticsWeeklyDigestSch},})+// --- Query wrapper schemas from schema.json ---++const CompareFilter = z.object({+ compare: z.coerce+ .boolean()+ .describe('Whether to compare the current date range to a previous date range.')+ .default(false)+ .optional(),+ compare_to: z+ .string()+ .describe(+ 'The date range to compare to. The value is a relative date. Examples of relative dates are: `-1y` for 1 year ago, `-14m` for 14 months ago, `-100w` for 100 weeks ago, `-14d` for 14 days ago, `-30h` for 30 hours ago.'+ )+ .optional(),+})++const integer = z.coerce.number().int()++const ActionConversionGoal = z.object({+ actionId: integer,+})++const CustomEventConversionGoal = z.object({+ customEventName: z.string(),+})++const WebAnalyticsConversionGoal = z.union([ActionConversionGoal, CustomEventConversionGoal])++const AssistantDateRange = z.object({+ date_from: z.string().describe('ISO8601 date string.'),+ date_to: z.string().nullable().describe('ISO8601 date string.').optional(),+})++const AssistantDurationRange = z.object({+ date_from: z+ .string()+ .describe(+ "Duration in the past. Supported units are: `h` (hour), `d` (day), `w` (week), `m` (month), `y` (year), `all` (all time). Use the `Start` suffix to define the exact left date boundary. Examples: `-1d` last day from now, `-180d` last 180 days from now, `mStart` this month start, `-1dStart` yesterday's start."+ ),+})++const AssistantDateRangeFilter = z.union([AssistantDateRange, AssistantDurationRange])++const PropertyOperator = z.enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'regex',+ 'not_regex',+ 'gt',+ 'gte',+ 'lt',+ 'lte',+ 'is_set',+ 'is_not_set',+ 'is_date_exact',+ 'is_date_before',+ 'is_date_after',+ 'between',+ 'not_between',+ 'min',+ 'max',+ 'in',+ 'not_in',+ 'is_cleaned_path_exact',+ 'flag_evaluates_to',+ 'semver_eq',+ 'semver_neq',+ 'semver_gt',+ 'semver_gte',+ 'semver_lt',+ 'semver_lte',+ 'semver_tilde',+ 'semver_caret',+ 'semver_wildcard',+ 'icontains_multi',+ 'not_icontains_multi',+])++const PropertyFilterBaseValue = z.union([z.string(), z.coerce.number(), z.coerce.boolean()])++const PropertyFilterValue = z.union([PropertyFilterBaseValue, z.array(PropertyFilterBaseValue), z.null()])++const EventPropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator.default('exact'),+ type: z.literal('event').describe('Event properties').default('event'),+ value: PropertyFilterValue.optional(),+})++const PersonPropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: z.literal('person').describe('Person properties').default('person'),+ value: PropertyFilterValue.optional(),+})++const SessionPropertyFilter = z.object({+ key: z.string(),+ label: z.string().optional(),+ operator: PropertyOperator,+ type: z.literal('session').default('session'),+ value: PropertyFilterValue.optional(),+})++const CohortPropertyFilter = z.object({+ cohort_name: z.string().optional(),+ key: z.literal('id').default('id'),+ label: z.string().optional(),+ operator: PropertyOperator.default('in'),+ type: z.literal('cohort').default('cohort'),+ value: z.coerce.number().int(),+})++const WebAnalyticsPropertyFilter = z.union([+ EventPropertyFilter,+ PersonPropertyFilter,+ SessionPropertyFilter,+ CohortPropertyFilter,+])++const WebAnalyticsPropertyFilters = z.array(WebAnalyticsPropertyFilter)++const AssistantWebOverviewQuery = z.object({+ compareFilter: CompareFilter.describe(+ 'Compare the current period to a prior period. Disabled by default. Enabling roughly doubles query cost — leave it off unless the user explicitly asks for a period-over-period comparison.'+ ).optional(),+ conversionGoal: z+ .union([WebAnalyticsConversionGoal, z.null()])+ .describe(+ 'Conversion goal — pass an `actionId` (must belong to the current project) or a `customEventName`. Adds conversion columns to the response. Disables the pre-aggregated fast path — only set when the user explicitly asks about a conversion.'+ )+ .optional(),+ dateRange: AssistantDateRangeFilter.describe(+ 'Date range for the query. Defaults to the last 7 days when omitted. Keep ranges short — the backend has no upper bound and large windows on the slow path (e.g. with `conversionGoal` or `includeAvgTimeOnPage`) can be expensive.'+ ).optional(),+ doPathCleaning: z.coerce+ .boolean()+ .describe("Apply the team's path-cleaning rules to URL-style breakdowns.")+ .default(false)+ .optional(),+ filterTestAccounts: z.coerce+ .boolean()+ .describe("Exclude internal and test users by applying the team's test-account filter.")+ .default(false)+ .optional(),+ kind: z.literal('WebOverviewQuery').default('WebOverviewQuery'),+ properties: WebAnalyticsPropertyFilters.describe(+ 'Property filters applied to the query. Accepts event, person, session, or cohort filters.'+ )+ .default([])+ .optional(),+})++const WebStatsBreakdown = z.enum([+ 'Page',+ 'InitialPage',+ 'ExitPage',+ 'ExitClick',+ 'PreviousPage',+ 'ScreenName',+ 'InitialChannelType',+ 'InitialReferringDomain',+ 'InitialReferringURL',+ 'InitialUTMSource',+ 'InitialUTMCampaign',+ 'InitialUTMMedium',+ 'InitialUTMTerm',+ 'InitialUTMContent',+ 'InitialUTMSourceMediumCampaign',+ 'FirstPageviewChannelType',+ 'FirstPageviewReferringDomain',+ 'FirstPageviewUTMSource',+ 'FirstPageviewUTMCampaign',+ 'FirstPageviewUTMMedium',+ 'FirstPageviewUTMTerm',+ 'FirstPageviewUTMContent',+ 'FirstPageviewUTMSourceMediumCampaign',+ 'Browser',+ 'OS',+ 'Viewport',+ 'DeviceType',+ 'Country',+ 'Region',+ 'City',+ 'Timezone',+ 'Language',+ 'FrustrationMetrics',+])++const positive_integer = z.coerce.number().int().min(1)++const non_negative_integer = z.coerce.number().int().min(0)++const AssistantWebStatsTableQuery = z.object({+ breakdownBy: WebStatsBreakdown.describe(+ 'Required. Property to break down the table by. The full enum covers path-style (`Page`, `InitialPage`, `ExitPage`, `PreviousPage`), marketing/source (UTM source/medium/campaign/term/content, channel, referring domain), audience/device (browser, OS, device type, viewport), and geography (country, region, city, timezone, language). Path-style breakdowns pair naturally with `includeBounceRate` / `includeAvgTimeOnPage`.'+ ),+ compareFilter: CompareFilter.describe(+ 'Compare the current period to a prior period. Disabled by default. Enabling roughly doubles query cost — leave it off unless the user explicitly asks for a period-over-period comparison.'+ ).optional(),+ conversionGoal: z+ .union([WebAnalyticsConversionGoal, z.null()])+ .describe(+ 'Conversion goal — pass an `actionId` (must belong to the current project) or a `customEventName`. Adds conversion columns to the response. Disables the pre-aggregated fast path — only set when the user explicitly asks about a conversion.'+ )+ .optional(),+ dateRange: AssistantDateRangeFilter.describe(+ 'Date range for the query. Defaults to the last 7 days when omitted. Keep ranges short — the backend has no upper bound and large windows on the slow path (e.g. with `conversionGoal` or `includeAvgTimeOnPage`) can be expensive.'+ ).optional(),+ doPathCleaning: z.coerce+ .boolean()+ .describe("Apply the team's path-cleaning rules to URL-style breakdowns.")+ .default(false)+ .optional(),+ filterTestAccounts: z.coerce+ .boolean()+ .describe("Exclude internal and test users by applying the team's test-account filter.")+ .default(false)+ .optional(),+ includeAvgTimeOnPage: z.coerce+ .boolean()+ .describe(+ 'Add an average-time-on-page column. Implies a Page-style breakdown. Disables the pre-aggregated fast path.'+ )+ .default(false)+ .optional(),+ includeBounceRate: z.coerce+ .boolean()+ .describe('Add a bounce-rate column. Most useful with a path-style breakdown.')+ .default(false)+ .optional(),+ includeHost: z.coerce+ .boolean()+ .describe(+ 'When using a path-style breakdown (`Page`, `InitialPage`, `ExitPage`, `PreviousPage`), concatenate host + pathname so the same path on different hosts is counted separately.'+ )+ .default(false)+ .optional(),+ kind: z.literal('WebStatsTableQuery').default('WebStatsTableQuery'),+ limit: positive_integer+ .max(200)+ .describe(+ 'Maximum rows to return. Prefer 10–25 unless the user explicitly asks for more. Hard ceiling enforced at the wrapper.'+ )+ .optional(),+ offset: non_negative_integer.describe('Pagination offset.').optional(),+ properties: WebAnalyticsPropertyFilters.describe(+ 'Property filters applied to the query. Accepts event, person, session, or cohort filters.'+ )+ .default([])+ .optional(),+})++const WebVitalsMetric = z.enum(['INP', 'LCP', 'CLS', 'FCP'])++const WebVitalsPercentile = z.enum(['p75', 'p90', 'p99'])++const AssistantWebVitalsPathBreakdownQuery = z.object({+ dateRange: AssistantDateRangeFilter.describe(+ 'Date range for the query. Defaults to the last 7 days when omitted — a good window for a stable percentile.'+ ).optional(),+ doPathCleaning: z.coerce+ .boolean()+ .describe("Apply the team's path-cleaning rules to the returned paths.")+ .default(false)+ .optional(),+ filterTestAccounts: z.coerce+ .boolean()+ .describe("Exclude internal and test users by applying the team's test-account filter.")+ .default(false)+ .optional(),+ kind: z.literal('WebVitalsPathBreakdownQuery').default('WebVitalsPathBreakdownQuery'),+ metric: WebVitalsMetric.describe(+ 'Required. Which Core Web Vital to break down by: `LCP` (load, ms), `INP` (interactivity, ms), `CLS` (layout stability, unitless score), or `FCP` (first paint, ms).'+ ),+ percentile: WebVitalsPercentile.describe(+ "Required. Percentile to aggregate each page's samples at. Use `p75` unless the user asks otherwise — the Google bands are defined at p75."+ ),+ properties: z+ .array(z.union([EventPropertyFilter, PersonPropertyFilter]))+ .describe(+ 'Property filters applied to the query. Accepts event and person filters only (the query runner ignores session and cohort filters) — e.g. an event filter on `$host` to scope to one domain, or on `$device_type` to isolate mobile.'+ )+ .default([])+ .optional(),+ thresholds: z+ .array(z.coerce.number())+ .min(2)+ .max(2)+ .describe(+ 'Required. `[good, poor]` band boundaries for the chosen metric. Values below `good` are good, above `poor` are poor, in between need improvement. Use the standard Google thresholds unless the user supplies their own: LCP `[2500, 4000]`, INP `[200, 500]`, CLS `[0.1, 0.25]`, FCP `[1800, 3000]`.'+ ),+})+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'heatmaps-events': heatmapsEvents,'heatmaps-list': heatmapsList,@@ -240,4 +539,25 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'heatmaps-saved-regenerate': heatmapsSavedRegenerate,'heatmaps-saved-update': heatmapsSavedUpdate,'web-analytics-weekly-digest': webAnalyticsWeeklyDigest,+ 'query-web-overview': createQueryWrapper({+ name: 'query-web-overview',+ schema: AssistantWebOverviewQuery,+ kind: 'WebOverviewQuery',+ uiResourceUri: 'ui://posthog/query-results.html',+ outputFormat: 'json',+ }),+ 'query-web-stats': createQueryWrapper({+ name: 'query-web-stats',+ schema: AssistantWebStatsTableQuery,+ kind: 'WebStatsTableQuery',+ uiResourceUri: 'ui://posthog/query-results.html',+ outputFormat: 'json',+ }),+ 'query-web-vitals': createQueryWrapper({+ name: 'query-web-vitals',+ schema: AssistantWebVitalsPathBreakdownQuery,+ kind: 'WebVitalsPathBreakdownQuery',+ uiResourceUri: 'ui://posthog/query-results.html',+ outputFormat: 'json',+ }),}