Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(mcp): render web stats and web overview results as tables (#114358)

Sam Pennington62ef2afe79eb
diff --git a/products/web_analytics/mcp/prompts/query-web-stats.md b/products/web_analytics/mcp/prompts/query-web-stats.md
index 320d12d8b034..429de466b73d 100644
--- a/products/web_analytics/mcp/prompts/query-web-stats.md
+++ b/products/web_analytics/mcp/prompts/query-web-stats.md
@@ -32,6 +32,15 @@ Performance hints:
Use `read-data-schema` to validate property names/values when needed.
+# Reading the results
+
+Each row in `results` is a positional array. The `columns` array in the response names each position, so read the cells by column name, not by a fixed index. The optional bounce rate and average time columns shift the positions after them.
+
+- `context.columns.breakdown_value`: the breakdown value, such as the page path.
+- `context.columns.visitors`, `context.columns.views`, `context.columns.avg_time_on_page`, `context.columns.bounce_rate`: each cell is a `[current, previous]` pair. When `compareFilter` is off, ignore `previous`: the backend can return `null` or `0` there, and neither value is a measured comparison. `bounce_rate` is a fraction from 0 to 1. `avg_time_on_page` is in seconds.
+- `context.columns.ui_fill_fraction`: the share of the total for the row bar in the UI. Ignore it for analysis.
+- `context.columns.cross_sell`: an empty placeholder for the UI. Ignore it.
+
# Example
Top 20 pages by bounce rate, last 7 days:
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 3d322b1d4884..7735da8b2b50 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -10891,7 +10891,7 @@
"system_prompt_hint": "Web analytics KPIs — visitors, sessions, bounce rate, session duration"
},
"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.",
+ "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# Reading the results\n\nEach row in `results` is a positional array. The `columns` array in the response names each position, so read the cells by column name, not by a fixed index. The optional bounce rate and average time columns shift the positions after them.\n\n- `context.columns.breakdown_value`: the breakdown value, such as the page path.\n- `context.columns.visitors`, `context.columns.views`, `context.columns.avg_time_on_page`, `context.columns.bounce_rate`: each cell is a `[current, previous]` pair. When `compareFilter` is off, ignore `previous`: the backend can return `null` or `0` there, and neither value is a measured comparison. `bounce_rate` is a fraction from 0 to 1. `avg_time_on_page` is in seconds.\n- `context.columns.ui_fill_fraction`: the share of the total for the row bar in the UI. Ignore it for analysis.\n- `context.columns.cross_sell`: an empty placeholder for the UI. Ignore it.\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": "Web analytics",
"feature": "web_analytics",
"summary": "Run a web analytics breakdown table query",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 4bea21ee745e..1ff8f8300bc9 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -11482,7 +11482,7 @@
"system_prompt_hint": "Web analytics KPIs — visitors, sessions, bounce rate, session duration"
},
"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.",
+ "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# Reading the results\n\nEach row in `results` is a positional array. The `columns` array in the response names each position, so read the cells by column name, not by a fixed index. The optional bounce rate and average time columns shift the positions after them.\n\n- `context.columns.breakdown_value`: the breakdown value, such as the page path.\n- `context.columns.visitors`, `context.columns.views`, `context.columns.avg_time_on_page`, `context.columns.bounce_rate`: each cell is a `[current, previous]` pair. When `compareFilter` is off, ignore `previous`: the backend can return `null` or `0` there, and neither value is a measured comparison. `bounce_rate` is a fraction from 0 to 1. `avg_time_on_page` is in seconds.\n- `context.columns.ui_fill_fraction`: the share of the total for the row bar in the UI. Ignore it for analysis.\n- `context.columns.cross_sell`: an empty placeholder for the UI. Ignore it.\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": "Web analytics",
"feature": "web_analytics",
"summary": "Run a web analytics breakdown table query",
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index a3b6ed7deeb6..91becc527c9e 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -1587,11 +1587,13 @@ export class ApiClient {
query: Record<string, unknown>
}): Promise<{
results: unknown
+ columns?: unknown[] | null
formatted_results?: string
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null
}> => {
return this.request<{
results: unknown
+ columns?: unknown[] | null
formatted_results?: string
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null
}>({
diff --git a/services/mcp/src/tools/query-wrapper-factory.ts b/services/mcp/src/tools/query-wrapper-factory.ts
index d9c8274b7218..f80bb4a65cf5 100644
--- a/services/mcp/src/tools/query-wrapper-factory.ts
+++ b/services/mcp/src/tools/query-wrapper-factory.ts
@@ -238,6 +238,9 @@ export function createQueryWrapper<T extends ZodObjectAny>(config: QueryWrapperC
_posthogUrl: buildInsightUrl('InsightVizNode', query, baseUrl, config.urlPrefix),
query,
results: isTraceQuery ? redactTraceResults(data.results) : data.results,
+ // Table queries (e.g. WebStatsTableQuery) return positional rows, so the
+ // column names are the only way to read each cell.
+ ...(Array.isArray(data.columns) && Array.isArray(data.results) ? { columns: data.columns } : {}),
...(data.warnings ? { warnings: data.warnings } : {}),
}
if (isTraceQuery) {
diff --git a/services/mcp/src/ui-apps/components/Component.tsx b/services/mcp/src/ui-apps/components/Component.tsx
index 611e473bb70c..35e26425a4a6 100644
--- a/services/mcp/src/ui-apps/components/Component.tsx
+++ b/services/mcp/src/ui-apps/components/Component.tsx
@@ -28,7 +28,7 @@ import type {
TrendsQuery,
TrendsResult,
} from './types'
-import { insightQueryProperties } from './utils'
+import { insightQueryProperties, toTableResult } from './utils'
/** Data payload from MCP tools */
interface DataPayload {
@@ -50,6 +50,8 @@ interface DataPayload {
| HogQLResult
/** Saved insight from `insight-query`; its `query` keeps the wrapper node that `query` drops */
insight?: { query?: unknown }
+ /** Column names for table-shaped results such as `WebStatsTableQuery` */
+ columns?: string[]
_posthogUrl?: string
}
@@ -141,7 +143,7 @@ export function Component({ data }: ComponentProps): ReactElement {
return <PathsVisualizer results={payload.results as PathsResult} />
case 'table':
- return <TableVisualizer results={payload.results as HogQLResult} />
+ return <TableVisualizer results={toTableResult(payload.query, payload.results, payload.columns)} />
default:
return <div className="text-muted-foreground">Unknown visualization type: {visualizationType}</div>
diff --git a/services/mcp/src/ui-apps/components/infer-visualization.ts b/services/mcp/src/ui-apps/components/infer-visualization.ts
index c6da8b42430c..8fc1462fe173 100644
--- a/services/mcp/src/ui-apps/components/infer-visualization.ts
+++ b/services/mcp/src/ui-apps/components/infer-visualization.ts
@@ -182,7 +182,7 @@ export function inferVisualizationType(data: unknown): VisualizationType | null
if (kind === 'PathsQuery') {
return 'paths'
}
- if (kind === 'HogQLQuery') {
+ if (kind === 'HogQLQuery' || kind === 'WebStatsTableQuery' || kind === 'WebOverviewQuery') {
return 'table'
}
diff --git a/services/mcp/src/ui-apps/components/types.ts b/services/mcp/src/ui-apps/components/types.ts
index 1a34f882519e..c6bd68f0731c 100644
--- a/services/mcp/src/ui-apps/components/types.ts
+++ b/services/mcp/src/ui-apps/components/types.ts
@@ -151,6 +151,13 @@ export interface HogQLResult {
results?: unknown[][]
}
+export interface WebOverviewItem {
+ key: string
+ kind: 'unit' | 'duration_s' | 'percentage' | 'currency'
+ value?: number | null
+ changeFromPreviousPct?: number | null
+}
+
export type RetentionAggregationType = 'count' | 'sum' | 'avg'
export type RetentionReference = 'total' | 'previous'
export type RetentionPeriod = 'Hour' | 'Day' | 'Week' | 'Month'
diff --git a/services/mcp/src/ui-apps/components/utils.ts b/services/mcp/src/ui-apps/components/utils.ts
index d6d13c9b2a74..ad7732f5dade 100644
--- a/services/mcp/src/ui-apps/components/utils.ts
+++ b/services/mcp/src/ui-apps/components/utils.ts
@@ -1,6 +1,13 @@
import type { Series } from '@posthog/quill-charts'
-import type { ChartDisplayType, FunnelResult, TrendsQuery, TrendsResultItem } from './types'
+import type {
+ ChartDisplayType,
+ FunnelResult,
+ HogQLResult,
+ TrendsQuery,
+ TrendsResultItem,
+ WebOverviewItem,
+} from './types'
export function getDisplayType(query: TrendsQuery | undefined): ChartDisplayType {
return query?.trendsFilter?.display || 'ActionsLineGraph'
@@ -128,3 +135,65 @@ export function normalizeFunnelSteps(results: FunnelResult): Array<{ name: strin
})
)
}
+
+// Web stats columns that drive the web analytics UI only, not data.
+const HIDDEN_WEB_STATS_COLUMNS = new Set(['ui_fill_fraction', 'cross_sell'])
+
+function humanizeKey(key: string): string {
+ const text = key.replace(/_/g, ' ')
+ return text.charAt(0).toUpperCase() + text.slice(1)
+}
+
+function formatWebOverviewValue({ kind, value }: WebOverviewItem): string | null {
+ if (value === null || value === undefined) {
+ return null
+ }
+ if (kind === 'percentage') {
+ return `${value.toFixed(1)}%`
+ }
+ if (kind === 'duration_s') {
+ return formatDuration(value * 1000)
+ }
+ return formatNumber(value)
+}
+
+function webStatsCell(column: string, value: unknown): unknown {
+ // Metric cells are `[current, previous]` tuples; multi-part breakdowns (city, region) are tuples too.
+ if (Array.isArray(value) && column === 'breakdown_value') {
+ return value.filter((part) => part !== null && part !== '').join(', ')
+ }
+ const current = Array.isArray(value) ? value[0] : value
+ return typeof current === 'number' && /rate|percentage/.test(column) ? formatPercent(current) : current
+}
+
+/** Maps query results that have no chart of their own into the `columns`/`results` shape of the table. */
+export function toTableResult(query: unknown, results: unknown, columns: string[] | undefined): HogQLResult {
+ const node = (query ?? {}) as { kind?: unknown; breakdownBy?: unknown }
+ if (node.kind === 'WebOverviewQuery' && Array.isArray(results)) {
+ return {
+ columns: ['Metric', 'Value', 'Change'],
+ results: (results as WebOverviewItem[]).map((item) => [
+ humanizeKey(item.key),
+ formatWebOverviewValue(item),
+ typeof item.changeFromPreviousPct === 'number'
+ ? `${item.changeFromPreviousPct > 0 ? '+' : ''}${item.changeFromPreviousPct}%`
+ : null,
+ ]),
+ }
+ }
+ if (node.kind === 'WebStatsTableQuery' && Array.isArray(results)) {
+ const names = (columns ?? []).map((column) => column.replace(/^context\.columns\./, ''))
+ const kept = names.flatMap((name, index) => (HIDDEN_WEB_STATS_COLUMNS.has(name) ? [] : [index]))
+ return {
+ columns: kept.map((index) =>
+ names[index] === 'breakdown_value' && typeof node.breakdownBy === 'string'
+ ? node.breakdownBy
+ : humanizeKey(names[index]!)
+ ),
+ results: (results as unknown[][]).map((row) =>
+ kept.map((index) => webStatsCell(names[index]!, row[index]))
+ ),
+ }
+ }
+ return results as HogQLResult
+}
diff --git a/services/mcp/tests/unit/insight-visualizations.test.ts b/services/mcp/tests/unit/insight-visualizations.test.ts
index 53a94aabd403..39364dc2be91 100644
--- a/services/mcp/tests/unit/insight-visualizations.test.ts
+++ b/services/mcp/tests/unit/insight-visualizations.test.ts
@@ -19,6 +19,7 @@ import {
getSeriesLabel,
insightQueryProperties,
normalizeFunnelSteps,
+ toTableResult,
} from '@/ui-apps/components/utils'
import { insightResults, queryPayload } from '../fixtures/insight-fixtures'
@@ -75,6 +76,8 @@ describe('insight visualizations', () => {
['RetentionQuery', 'retention'],
['PathsQuery', 'paths'],
['HogQLQuery', 'table'],
+ ['WebStatsTableQuery', 'table'],
+ ['WebOverviewQuery', 'table'],
] as const)('falls back to %s when results are empty', (kind, expected) => {
expect(inferVisualizationType(queryPayload([], kind))).toBe(expected)
})
@@ -235,6 +238,45 @@ describe('insight visualizations', () => {
})
})
+ describe('toTableResult', () => {
+ it('flattens web stats tuples and hides UI-only columns', () => {
+ const columns = [
+ 'context.columns.breakdown_value',
+ 'context.columns.visitors',
+ 'context.columns.bounce_rate',
+ 'context.columns.ui_fill_fraction',
+ 'context.columns.cross_sell',
+ ]
+ const rows = [
+ ['/pricing', [1200, 1100], [0.42, 0.5], 1, ''],
+ [['US', 'Chicago'], [300, null], [0.1, null], 0.25, ''],
+ ]
+ expect(toTableResult({ kind: 'WebStatsTableQuery', breakdownBy: 'Page' }, rows, columns)).toEqual({
+ columns: ['Page', 'Visitors', 'Bounce rate'],
+ results: [
+ ['/pricing', 1200, '42.0%'],
+ ['US, Chicago', 300, '10.0%'],
+ ],
+ })
+ })
+
+ it('maps web overview items to metric rows', () => {
+ const items = [
+ { key: 'visitors', kind: 'unit', value: 1500, changeFromPreviousPct: 12 },
+ { key: 'session duration', kind: 'duration_s', value: 95, changeFromPreviousPct: -3 },
+ { key: 'bounce rate', kind: 'percentage', value: 41.25, changeFromPreviousPct: null },
+ ]
+ expect(toTableResult({ kind: 'WebOverviewQuery' }, items, undefined)).toEqual({
+ columns: ['Metric', 'Value', 'Change'],
+ results: [
+ ['Visitors', '1.5K', '+12%'],
+ ['Session duration', '1m 35s', '-3%'],
+ ['Bounce rate', '41.3%', null],
+ ],
+ })
+ })
+ })
+
describe('buildProportionBarSeries', () => {
it.each([
[
diff --git a/services/mcp/tests/unit/query-wrapper-factory.test.ts b/services/mcp/tests/unit/query-wrapper-factory.test.ts
index b9c4d262e4db..4ed2c8881e24 100644
--- a/services/mcp/tests/unit/query-wrapper-factory.test.ts
+++ b/services/mcp/tests/unit/query-wrapper-factory.test.ts
@@ -639,3 +639,44 @@ describe('createQueryWrapper warnings', () => {
expect(result).not.toHaveProperty('warnings')
})
})
+
+describe('createQueryWrapper columns', () => {
+ const schema = z.object({ breakdownBy: z.string() })
+
+ function contextWithRunQuery(data: Record<string, unknown>): Context {
+ return {
+ api: {
+ query: vi.fn().mockReturnValue({ runQuery: vi.fn().mockResolvedValue(data) }),
+ getProjectBaseUrl: vi.fn().mockReturnValue('http://localhost:8010/project/1'),
+ },
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('1') },
+ } as unknown as Context
+ }
+
+ it('forwards the column names that label each positional web stats row', async () => {
+ const columns = [
+ 'context.columns.breakdown_value',
+ 'context.columns.visitors',
+ 'context.columns.views',
+ 'context.columns.avg_time_on_page',
+ 'context.columns.bounce_rate',
+ 'context.columns.ui_fill_fraction',
+ 'context.columns.cross_sell',
+ ]
+ const results = [['/pricing', [120, null], [300, null], [42.5, null], [0.35, null], 0.6, '']]
+ const tool = createQueryWrapper({ name: 'query-web-stats', schema, kind: 'WebStatsTableQuery' })()
+
+ const result = (await tool.handler(contextWithRunQuery({ columns, results }), { breakdownBy: 'Page' })) as any
+
+ expect(result.columns).toEqual(columns)
+ expect(result.results).toEqual(results)
+ })
+
+ it('omits the key when the backend returns no columns', async () => {
+ const tool = createQueryWrapper({ name: 'test', schema, kind: 'TrendsQuery' })()
+
+ const result = (await tool.handler(contextWithRunQuery({ results: [] }), { breakdownBy: 'Page' })) as any
+
+ expect(result).not.toHaveProperty('columns')
+ })
+})