:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(elements): expose element stats as an MCP tool and finish HogQL conversion (#68440)
Paul D'Ambraf417acda6949
diff --git a/frontend/src/lib/agentScopes.generated.ts b/frontend/src/lib/agentScopes.generated.tsindex da9bce672a49..b052e04fcb19 100644--- a/frontend/src/lib/agentScopes.generated.ts+++ b/frontend/src/lib/agentScopes.generated.ts@@ -37,6 +37,7 @@ export const AGENT_USE_CASE_SCOPES = ['error_tracking:write','evaluation:read','evaluation:write',+ 'element:read','event_definition:read','event_definition:write','experiment:read',diff --git a/posthog/api/element.py b/posthog/api/element.pyindex ee2e2bf2f7d8..a2a2b95a8a8e 100644--- a/posthog/api/element.py+++ b/posthog/api/element.py@@ -1,5 +1,7 @@+import re+import jsonfrom datetime import datetime-from typing import Literal+from typing import Literal, castfrom django.conf import settings@@ -20,11 +22,9 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.api.property_value_metrics import PROPERTY_VALUES_DURATIONfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import ServerTimingsGathered, action-from posthog.clickhouse.client import sync_executefrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models import Element, Filterfrom posthog.models.element.element import build_attributes_filter, chain_to_element_dicts-from posthog.models.element.sql import GET_VALUESfrom posthog.utils import format_query_params_absolute_urltracer = trace.get_tracer(__name__)@@ -34,6 +34,14 @@ ELEMENT_STATS_TIME_HISTOGRAM = Histogram("How long does it take to get element stats?",)+# element properties that appear as string values in elements_chain and can be+# matched by the values regexes below; attr_class is excluded because classes are+# serialized as .classname tokens in the tag part of the chain, not as+# attr_class="..." key-value pairs, so the generic regex cannot match them+SUPPORTED_VALUES_KEYS = {"tag_name", "text", "href", "attr_id"}+_SUPPORTED_VALUES_KEYS_DISPLAY = ", ".join(sorted(SUPPORTED_VALUES_KEYS))+KEYS_WITH_NO_LISTABLE_VALUES = {"selector"}+ELEMENT_STATS_RESULT_COUNT_HISTOGRAM = Histogram("element_stats_result_count","Number of results returned by element stats endpoint",@@ -74,6 +82,10 @@ class ElementStatsResponseSerializer(serializers.Serializer):previous = serializers.CharField(allow_null=True, help_text="URL for the previous page of results, if any")+class ElementValueSerializer(serializers.Serializer):+ name = serializers.CharField(help_text="A distinct value of the requested element property")++@extend_schema(extensions={"x-product": ProductKey.PRODUCT_ANALYTICS})class ElementViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):scope_object = "element"@@ -89,7 +101,10 @@ class ElementViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"include",type=str,many=True,- description="Event types to include: $autocapture, $rageclick, $dead_click. Defaults to all three.",+ description=(+ "Event types to include: $autocapture, $rageclick, $dead_click. Defaults to all three. "+ "Accepts repeated parameters, a JSON array, or a comma-separated list."+ ),),OpenApiParameter("limit", type=int, description="Maximum rows per page"),OpenApiParameter("offset", type=int, description="Pagination offset"),@@ -112,16 +127,33 @@ class ElementViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):type=str,description="End of the date range (e.g. 2024-01-31). Defaults to now.",),+ OpenApiParameter(+ "properties",+ type=str,+ description=(+ "JSON-encoded list of property filters to apply to the underlying events, e.g. "+ '[{"key": "$current_url", "value": "https://example.com/page"}] or '+ '[{"key": "email", "value": "@posthog.com", "operator": "icontains", "type": "person"}]. '+ "Supports event, person, cohort, element, and HogQL property filter types."+ ),+ ),+ OpenApiParameter(+ "filter_test_accounts",+ type=bool,+ description=(+ "When true, applies the project's internal-and-test-account filters to the underlying events. "+ "Pass the lowercase string true; other truthy spellings are ignored."+ ),+ ),],responses=ElementStatsResponseSerializer,)@action(methods=["GET"], detail=False)def stats(self, request: request.Request, **kwargs) -> response.Response:"""- The original version of this API always and only returned $autocapture elements- If no include query parameter is sent this remains true.- Now, you can pass a combination of include query parameters to get different types of elements- Currently only $autocapture and $rageclick and $dead_click are supported+ Counts of $autocapture, $rageclick, and $dead_click events grouped by the element chain+ they occurred on, ordered by count. Defaults to all three event types; narrow with the+ include parameter."""with (@@ -265,7 +297,21 @@ class ElementViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"$rageclick","$dead_click",}- events_to_include = set(request.query_params.getlist("include", []))+ # accept repeated params (the toolbar), a JSON array string (the MCP client+ # serializes arrays with JSON.stringify), or a comma-separated list+ # (agents hand-typing comma-separated lists, e.g. "$rageclick, $autocapture")+ events_to_include: set[str] = set()+ for raw in request.query_params.getlist("include", []):+ if raw.startswith("["):+ try:+ parsed = json.loads(raw)+ except json.JSONDecodeError:+ raise ValidationError("include must be a valid JSON array when passed as one")+ if not isinstance(parsed, list) or not all(isinstance(item, str) for item in parsed):+ raise ValidationError("include must be a JSON array of event names")+ events_to_include.update(parsed)+ else:+ events_to_include.update(part.strip() for part in raw.split(",") if part.strip())if not events_to_include:return tuple(supported_events)@@ -273,9 +319,25 @@ class ElementViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):if not events_to_include.issubset(supported_events):raise ValidationError("Only $autocapture, $rageclick, and $dead_click are supported.")- return tuple(events_to_include)+ return tuple(cast(set[Literal["$autocapture", "$rageclick", "$dead_click"]], events_to_include))- @action(methods=["GET"], detail=False)+ @extend_schema(+ parameters=[+ OpenApiParameter(+ "key",+ type=str,+ required=True,+ description="Element property to list values for: tag_name, text, href, or attr_id.",+ ),+ OpenApiParameter(+ "value",+ type=str,+ description="Optional substring to filter values by (case-sensitive contains match).",+ ),+ ],+ responses=ElementValueSerializer(many=True),+ )+ @action(methods=["GET"], detail=False, pagination_class=None)def values(self, request: request.Request, **kwargs) -> response.Response:with (PROPERTY_VALUES_DURATION.labels(endpoint_type="element").time(),@@ -284,37 +346,56 @@ class ElementViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):key = request.GET.get("key")value = request.GET.get("value")+ # the taxonomic filter offers selector and eagerly fetches its values,+ # but selectors are computed, not stored in elements_chain+ if key in KEYS_WITH_NO_LISTABLE_VALUES:+ return response.Response([])++ if key not in SUPPORTED_VALUES_KEYS:+ raise ValidationError(f"key must be one of {_SUPPORTED_VALUES_KEYS_DISPLAY}")+span.set_attribute("team_id", self.team.pk)- span.set_attribute("property_key", key or "")+ span.set_attribute("property_key", key)span.set_attribute("has_value_filter", value is not None)- select_regex = '[:|"]{}="(.*?)"'.format(key)-- # Make sure key exists, otherwise could lead to sql injection lower down- if key not in self.serializer_class.Meta.fields:- return response.Response([])+ # the value is a user-typed substring, so escape it before it lands in a regex+ escaped_value = re.escape(value) if value else Noneif key == "tag_name":select_regex = r"^([-_a-zA-Z0-9]*?)[\.|:]"- filter_regex = select_regex- if value:- filter_regex = r"^([-_a-zA-Z0-9]*?{}[-_a-zA-Z0-9]*?)[\.|:]".format(value)+ filter_regex = (+ r"^([-_a-zA-Z0-9]*?{}[-_a-zA-Z0-9]*?)[\.|:]".format(escaped_value)+ if escaped_value+ else select_regex+ )else:- if value:- filter_regex = '[:|"]{}=".*?{}.*?"'.format(key, value)- else:- filter_regex = select_regex-- result = sync_execute(- GET_VALUES.format(),- {- "team_id": self.team.id,- "regex": select_regex,- "filter_regex": filter_regex,+ select_regex = '[:|"]{}="(.*?)"'.format(key)+ filter_regex = '[:|"]{}=".*?{}.*?"'.format(key, escaped_value) if escaped_value else select_regex++ # no explicit team filter: execute_hogql_query scopes the events table to self.team+ select = parse_select(+ """+ SELECT extract(elements_chain, {select_regex}) AS value, count() AS occurrences+ FROM (+ SELECT elements_chain+ FROM events+ WHERE event = '$autocapture'+ AND elements_chain != ''+ AND match(elements_chain, {filter_regex})+ LIMIT 100000+ )+ GROUP BY value+ ORDER BY occurrences DESC+ LIMIT 100+ """,+ placeholders={+ "select_regex": ast.Constant(value=select_regex),+ "filter_regex": ast.Constant(value=filter_regex),},)+ result = execute_hogql_query(query=select, team=self.team, query_type="elements_values").resultsspan.set_attribute("result_count", len(result))- return response.Response([{"name": value[0]} for value in result])+ return response.Response([{"name": row[0]} for row in result])class LegacyElementViewSet(ElementViewSet):diff --git a/posthog/api/test/test_element.py b/posthog/api/test/test_element.pyindex cc4b4a4602f8..6dcae47e120b 100644--- a/posthog/api/test/test_element.py+++ b/posthog/api/test/test_element.py@@ -149,6 +149,48 @@ class TestElement(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(response[0]["name"], "click here")self.assertEqual(len(response), 1)+ # value is a substring, not a regex fragment: metacharacters match literally, never 500+ response = self.client.get("/api/element/values/?key=text&value=click(")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), [])++ @parameterized.expand(["", "key=order", "key=unknown", "key=attr_class"])+ def test_event_property_values_rejects_unsupported_keys(self, query: str) -> None:+ response = self.client.get(f"/api/element/values/?{query}")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_event_property_values_returns_empty_for_selector(self) -> None:+ # the taxonomic filter eagerly fetches selector values; a 400 here surfaces as an error toast+ response = self.client.get("/api/element/values/?key=selector")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), [])++ @parameterized.expand(+ [+ ("tag_name", "a"),+ ("text", "click here"),+ ("href", "https://posthog.com/about"),+ ("attr_id", "my-btn"),+ ]+ )+ def test_event_property_values_returns_values_for_each_supported_key(self, key: str, expected_value: str) -> None:+ _create_event(+ team=self.team,+ distinct_id="test",+ event="$autocapture",+ elements=[+ Element(+ tag_name="a",+ href="https://posthog.com/about",+ text="click here",+ attr_id="my-btn",+ )+ ],+ )+ response = self.client.get(f"/api/element/values/?key={key}").json()+ self.assertEqual(len(response), 1)+ self.assertEqual(response[0]["name"], expected_value)+# checking postgres, don't care about person on events@override_settings(PERSON_ON_EVENTS_OVERRIDE=False, PERSON_ON_EVENTS_V2_OVERRIDE=False)@snapshot_postgres_queries@@ -270,7 +312,15 @@ class TestElement(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert results == expected_rage_click_data_response_results# no include params is equivalent to autocapture and rageclick- @parameterized.expand(["&include=$rageclick&include=$autocapture", ""])+ @parameterized.expand(+ [+ "&include=$rageclick&include=$autocapture",+ "",+ '&include=["$rageclick","$autocapture"]',+ "&include=$rageclick,$autocapture",+ "&include=$rageclick,%20$autocapture", # comma+space (agents hand-typing lists)+ ]+ )def test_element_stats_can_load_rageclick_and_autocapture_data(self, include_params) -> None:self._setup_events()@@ -365,6 +415,8 @@ class TestElement(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):("non_numeric_limit", "limit=not-a-number"),("non_numeric_offset", "offset=not-a-number"),("unexpected_include", "include=$autocapture&include=$rageclick&include=$pageview"),+ ("malformed_json_include", "include=%5Bnot-json"),+ ("non_string_members_in_json_include", "include=%5B%7B%7D%5D"),("zero_limit", "limit=0"),("negative_limit", "limit=-1"),("limit_at_printer_cap", "limit=1000000"),diff --git a/posthog/models/element/sql.py b/posthog/models/element/sql.pydeleted file mode 100644index 70c43fa74bfe..000000000000--- a/posthog/models/element/sql.py+++ /dev/null@@ -1,16 +0,0 @@-GET_VALUES = """-SELECT- extract(elements_chain, %(regex)s) as value, count(1) as count-FROM (- SELECT elements_chain- FROM events- WHERE team_id = %(team_id)s- AND event = '$autocapture'- AND elements_chain != ''- AND match(elements_chain, %(filter_regex)s)- LIMIT 100000-)-GROUP BY value-ORDER BY count desc-LIMIT 100;-"""diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 5e12ecfeccde..44e539960ee6 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -205,6 +205,11 @@ export interface ElementStatsResponseApi {previous: string | null}+export interface ElementValueApi {+ /** A distinct value of the requested element property */+ name: string+}+export type InsightVizNodeApiKind = (typeof InsightVizNodeApiKind)[keyof typeof InsightVizNodeApiKind]export const InsightVizNodeApiKind = {@@ -7806,7 +7811,11 @@ export type ElementsStatsRetrieveParams = {*/date_to?: string/**- * Event types to include: $autocapture, $rageclick, $dead_click. Defaults to all three.+ * When true, applies the project's internal-and-test-account filters to the underlying events. Pass the lowercase string true; other truthy spellings are ignored.+ */+ filter_test_accounts?: boolean+ /**+ * Event types to include: $autocapture, $rageclick, $dead_click. Defaults to all three. Accepts repeated parameters, a JSON array, or a comma-separated list.*/include?: string[]/**@@ -7817,12 +7826,27 @@ export type ElementsStatsRetrieveParams = {* Pagination offset*/offset?: number+ /**+ * JSON-encoded list of property filters to apply to the underlying events, e.g. [{"key": "$current_url", "value": "https://example.com/page"}] or [{"key": "email", "value": "@posthog.com", "operator": "icontains", "type": "person"}]. Supports event, person, cohort, element, and HogQL property filter types.+ */+ properties?: string/*** Sampling factor between 0 and 1*/sampling_factor?: number}+export type ElementsValuesListParams = {+ /**+ * Element property to list values for: tag_name, text, href, or attr_id.+ */+ key: string+ /**+ * Optional substring to filter values by (case-sensitive contains match).+ */+ value?: string+}+export type InsightsListParams = {/*** Return basic insight metadata only (no results, faster).diff --git a/products/product_analytics/frontend/generated/api.ts b/products/product_analytics/frontend/generated/api.tsindex b9eb3969c279..f78bf0b84d91 100644--- a/products/product_analytics/frontend/generated/api.ts+++ b/products/product_analytics/frontend/generated/api.ts@@ -16,8 +16,10 @@ import type {ColumnConfigurationsListParams,ElementApi,ElementStatsResponseApi,+ ElementValueApi,ElementsListParams,ElementsStatsRetrieveParams,+ ElementsValuesListParams,InsightApi,InsightViewedRequestApi,InsightsActivityRetrieveParams,@@ -292,10 +294,9 @@ export const getElementsStatsRetrieveUrl = (projectId: string, params?: Elements}/**- * The original version of this API always and only returned $autocapture elements- * If no include query parameter is sent this remains true.- * Now, you can pass a combination of include query parameters to get different types of elements- * Currently only $autocapture and $rageclick and $dead_click are supported+ * Counts of $autocapture, $rageclick, and $dead_click events grouped by the element chain+ * they occurred on, ordered by count. Defaults to all three event types; narrow with the+ * include parameter.*/export const elementsStatsRetrieve = async (projectId: string,@@ -308,12 +309,28 @@ export const elementsStatsRetrieve = async (})}-export const getElementsValuesRetrieveUrl = (projectId: string) => {- return `/api/projects/${projectId}/elements/values/`+export const getElementsValuesListUrl = (projectId: string, params: ElementsValuesListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/elements/values/?${stringifiedParams}`+ : `/api/projects/${projectId}/elements/values/`}-export const elementsValuesRetrieve = async (projectId: string, options?: RequestInit): Promise<void> => {- return apiMutator<void>(getElementsValuesRetrieveUrl(projectId), {+export const elementsValuesList = async (+ projectId: string,+ params: ElementsValuesListParams,+ options?: RequestInit+): Promise<ElementValueApi[]> => {+ return apiMutator<ElementValueApi[]>(getElementsValuesListUrl(projectId, params), {...options,method: 'GET',})diff --git a/products/product_analytics/mcp/tools.yaml b/products/product_analytics/mcp/tools.yamlindex d9f34cd3a531..d658849ae9e9 100644--- a/products/product_analytics/mcp/tools.yaml+++ b/products/product_analytics/mcp/tools.yaml@@ -48,12 +48,26 @@ tools:enabled: falseelements-stats-retrieve:operation: elements_stats_retrieve- enabled: false+ enabled: true+ scopes:+ - element:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get element click stats+ description: >+ Counts of autocapture clicks, rage clicks, and dead clicks grouped by page element, ordered by count. Each+ result carries the parsed element chain (tag, text, href, attributes) of the clicked element. Filter by date+ range, event types, URL or other event/person properties, and the project's internal-test-account filters.+ This powers heatmap/clickmap views; use it to answer "what do users click most" and "which elements get rage+ or dead clicks". Responses can be very large on busy projects — always pass a small `limit` (e.g. 100) and+ paginate with `offset` if you need more results.elements-update:operation: elements_updateenabled: false- elements-values-retrieve:- operation: elements_values_retrieve+ elements-values-list:+ operation: elements_values_listenabled: falseinsight-create:operation: insights_creatediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex da96e2549ea2..9ce18040a09e 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -2271,6 +2271,20 @@"readOnlyHint": true}},+ "elements-stats-retrieve": {+ "description": "Counts of autocapture clicks, rage clicks, and dead clicks grouped by page element, ordered by count. Each result carries the parsed element chain (tag, text, href, attributes) of the clicked element. Filter by date range, event types, URL or other event/person properties, and the project's internal-test-account filters. This powers heatmap/clickmap views; use it to answer \"what do users click most\" and \"which elements get rage or dead clicks\". Responses can be very large on busy projects — always pass a small `limit` (e.g. 100) and paginate with `offset` if you need more results.",+ "category": "Product analytics",+ "feature": "product_analytics",+ "summary": "Get element click stats",+ "title": "Get element click stats",+ "required_scopes": ["element:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"endpoint-create": {"description": "Create a new API endpoint from a HogQL or insight query. The name must be URL-safe (letters, numbers, hyphens, underscores, starts with a letter, max 128 chars). Materialization is auto-enabled if the query is eligible.","category": "Endpoints",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 51e2d879d782..e6ba157a3169 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -2315,6 +2315,20 @@"readOnlyHint": true}},+ "elements-stats-retrieve": {+ "description": "Counts of autocapture clicks, rage clicks, and dead clicks grouped by page element, ordered by count. Each result carries the parsed element chain (tag, text, href, attributes) of the clicked element. Filter by date range, event types, URL or other event/person properties, and the project's internal-test-account filters. This powers heatmap/clickmap views; use it to answer \"what do users click most\" and \"which elements get rage or dead clicks\". Responses can be very large on busy projects — always pass a small `limit` (e.g. 100) and paginate with `offset` if you need more results.",+ "category": "Product analytics",+ "feature": "product_analytics",+ "summary": "Get element click stats",+ "title": "Get element click stats",+ "required_scopes": ["element:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"endpoint-create": {"description": "Create a new API endpoint from a HogQL or insight query. The name must be URL-safe (letters, numbers, hyphens, underscores, starts with a letter, max 128 chars). Materialization is auto-enabled if the query is eligible.","category": "Endpoints",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 221eab619d7b..61f51b502823 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18361,6 +18361,11 @@ export namespace Schemas {text?: string | null;}+ export interface ElementValue {+ /** A distinct value of the requested element property */+ name: string;+ }+/*** Highest htmlID suffix per element type, e.g. {"u_row": 1, "u_content_text": 2}.*/@@ -56492,7 +56497,11 @@ export namespace Schemas {*/date_to?: string;/**- * Event types to include: $autocapture, $rageclick, $dead_click. Defaults to all three.+ * When true, applies the project's internal-and-test-account filters to the underlying events. Pass the lowercase string true; other truthy spellings are ignored.+ */+ filter_test_accounts?: boolean;+ /**+ * Event types to include: $autocapture, $rageclick, $dead_click. Defaults to all three. Accepts repeated parameters, a JSON array, or a comma-separated list.*/include?: string[];/**@@ -56503,12 +56512,27 @@ export namespace Schemas {* Pagination offset*/offset?: number;+ /**+ * JSON-encoded list of property filters to apply to the underlying events, e.g. [{"key": "$current_url", "value": "https://example.com/page"}] or [{"key": "email", "value": "@posthog.com", "operator": "icontains", "type": "person"}]. Supports event, person, cohort, element, and HogQL property filter types.+ */+ properties?: string;/*** Sampling factor between 0 and 1*/sampling_factor?: number;};+ export type EnvironmentsElementsValuesListParams = {+ /**+ * Element property to list values for: tag_name, text, href, or attr_id.+ */+ key: string;+ /**+ * Optional substring to filter values by (case-sensitive contains match).+ */+ value?: string;+ };+export type EnvironmentsEndpointsListParams = {created_by?: number;is_active?: boolean;@@ -62575,7 +62599,11 @@ export namespace Schemas {*/date_to?: string;/**- * Event types to include: $autocapture, $rageclick, $dead_click. Defaults to all three.+ * When true, applies the project's internal-and-test-account filters to the underlying events. Pass the lowercase string true; other truthy spellings are ignored.+ */+ filter_test_accounts?: boolean;+ /**+ * Event types to include: $autocapture, $rageclick, $dead_click. Defaults to all three. Accepts repeated parameters, a JSON array, or a comma-separated list.*/include?: string[];/**@@ -62586,12 +62614,27 @@ export namespace Schemas {* Pagination offset*/offset?: number;+ /**+ * JSON-encoded list of property filters to apply to the underlying events, e.g. [{"key": "$current_url", "value": "https://example.com/page"}] or [{"key": "email", "value": "@posthog.com", "operator": "icontains", "type": "person"}]. Supports event, person, cohort, element, and HogQL property filter types.+ */+ properties?: string;/*** Sampling factor between 0 and 1*/sampling_factor?: number;};+ export type ElementsValuesListParams = {+ /**+ * Element property to list values for: tag_name, text, href, or attr_id.+ */+ key: string;+ /**+ * Optional substring to filter values by (case-sensitive contains match).+ */+ value?: string;+ };+export type EndpointsListParams = {created_by?: number;is_active?: boolean;diff --git a/services/mcp/src/generated/product_analytics/api.ts b/services/mcp/src/generated/product_analytics/api.tsindex 768388313615..ea639a1c40a2 100644--- a/services/mcp/src/generated/product_analytics/api.ts+++ b/services/mcp/src/generated/product_analytics/api.ts@@ -3,11 +3,59 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 8 enabled ops+ * PostHog API - MCP 9 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'+/**+ * Counts of $autocapture, $rageclick, and $dead_click events grouped by the element chain+ * they occurred on, ordered by count. Defaults to all three event types; narrow with the+ * include parameter.+ */+export const ElementsStatsRetrieveParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const ElementsStatsRetrieveQueryParams = /* @__PURE__ */ zod.object({+ data_attributes: zod+ .string()+ .optional()+ .describe(+ "Comma-separated data attribute names (wildcards allowed, e.g. data-*). When provided, each element's attributes map is filtered to matching attr__* keys, shrinking the response."+ ),+ date_from: zod+ .string()+ .optional()+ .describe('Start of the date range (e.g. -7d, 2024-01-01). Defaults to last 7 days.'),+ date_to: zod.string().optional().describe('End of the date range (e.g. 2024-01-31). Defaults to now.'),+ filter_test_accounts: zod+ .boolean()+ .optional()+ .describe(+ "When true, applies the project's internal-and-test-account filters to the underlying events. Pass the lowercase string true; other truthy spellings are ignored."+ ),+ include: zod+ .array(zod.string())+ .optional()+ .describe(+ 'Event types to include: $autocapture, $rageclick, $dead_click. Defaults to all three. Accepts repeated parameters, a JSON array, or a comma-separated list.'+ ),+ limit: zod.number().optional().describe('Maximum rows per page'),+ offset: zod.number().optional().describe('Pagination offset'),+ properties: zod+ .string()+ .optional()+ .describe(+ 'JSON-encoded list of property filters to apply to the underlying events, e.g. [{"key": "$current_url", "value": "https://example.com/page"}] or [{"key": "email", "value": "@posthog.com", "operator": "icontains", "type": "person"}]. Supports event, person, cohort, element, and HogQL property filter types.'+ ),+ sampling_factor: zod.number().optional().describe('Sampling factor between 0 and 1'),+})+/*** DRF ViewSet mixin that gates coalesced responses behind permission checks.*diff --git a/services/mcp/src/tools/generated/product_analytics.ts b/services/mcp/src/tools/generated/product_analytics.tsindex fb4b0cf6a119..8554841a7d93 100644--- a/services/mcp/src/tools/generated/product_analytics.ts+++ b/services/mcp/src/tools/generated/product_analytics.ts@@ -3,6 +3,7 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import {+ ElementsStatsRetrieveQueryParams,InsightsActivityRetrieveParams,InsightsActivityRetrieveQueryParams,InsightsAllActivityRetrieveQueryParams,@@ -164,6 +165,32 @@ const AssistantDataVisualizationNode = z.object({const InsightQuery = z.union([AssistantInsightVizNode, AssistantDataVisualizationNode])+const ElementsStatsRetrieveSchema = ElementsStatsRetrieveQueryParams++const elementsStatsRetrieve = (): ToolBase<typeof ElementsStatsRetrieveSchema, Schemas.ElementStatsResponse> => ({+ name: 'elements-stats-retrieve',+ schema: ElementsStatsRetrieveSchema,+ handler: async (context: Context, params: z.infer<typeof ElementsStatsRetrieveSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.ElementStatsResponse>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/elements/stats/`,+ query: {+ data_attributes: params.data_attributes,+ date_from: params.date_from,+ date_to: params.date_to,+ filter_test_accounts: params.filter_test_accounts,+ include: params.include,+ limit: params.limit,+ offset: params.offset,+ properties: params.properties,+ sampling_factor: params.sampling_factor,+ },+ })+ return result+ },+})+const InsightCreateSchema = InsightsCreateBody.omit({derived_name: true,order: true,@@ -521,6 +548,7 @@ const insightsTrendingRetrieve = (): ToolBase<})export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'elements-stats-retrieve': elementsStatsRetrieve,'insight-create': insightCreate,'insight-delete': insightDelete,'insight-get': insightGet,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/elements-stats-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/elements-stats-retrieve.jsonnew file mode 100644index 000000000000..774de2ec8e77--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/elements-stats-retrieve.json@@ -0,0 +1,45 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "data_attributes": {+ "description": "Comma-separated data attribute names (wildcards allowed, e.g. data-*). When provided, each element's attributes map is filtered to matching attr__* keys, shrinking the response.",+ "type": "string"+ },+ "date_from": {+ "description": "Start of the date range (e.g. -7d, 2024-01-01). Defaults to last 7 days.",+ "type": "string"+ },+ "date_to": {+ "description": "End of the date range (e.g. 2024-01-31). Defaults to now.",+ "type": "string"+ },+ "filter_test_accounts": {+ "description": "When true, applies the project's internal-and-test-account filters to the underlying events. Pass the lowercase string true; other truthy spellings are ignored.",+ "type": "boolean"+ },+ "include": {+ "description": "Event types to include: $autocapture, $rageclick, $dead_click. Defaults to all three. Accepts repeated parameters, a JSON array, or a comma-separated list.",+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "limit": {+ "description": "Maximum rows per page",+ "type": "number"+ },+ "offset": {+ "description": "Pagination offset",+ "type": "number"+ },+ "properties": {+ "description": "JSON-encoded list of property filters to apply to the underlying events, e.g. [{\"key\": \"$current_url\", \"value\": \"https://example.com/page\"}] or [{\"key\": \"email\", \"value\": \"@posthog.com\", \"operator\": \"icontains\", \"type\": \"person\"}]. Supports event, person, cohort, element, and HogQL property filter types.",+ "type": "string"+ },+ "sampling_factor": {+ "description": "Sampling factor between 0 and 1",+ "type": "number"+ }+ },+ "type": "object"+}