: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(mcp-analytics): filter dashboard and tool quality queries (#103007)
Lucas Fariaaea7d9d7a8e3
diff --git a/bin/patch-schema-property-filter-discriminator.py b/bin/patch-schema-property-filter-discriminator.pyindex 9f00e79c2b36..d8b8877b0e71 100644--- a/bin/patch-schema-property-filter-discriminator.py+++ b/bin/patch-schema-property-filter-discriminator.py@@ -73,7 +73,7 @@ EXPECTED_SITE_COUNTS = {# recursive site, discriminated including the group via its AND/OR -> property_group tag."recursive": 1,# Plain inlined runs: list[<members>], optionally `| PropertyGroupFilter` / `| None`.- "plain": 65,+ "plain": 61,}diff --git a/docs/internal/mcp-analytics-filter-navigation.md b/docs/internal/mcp-analytics-filter-navigation.mdindex 66e56f3ce0e4..2880ea6c488b 100644--- a/docs/internal/mcp-analytics-filter-navigation.md+++ b/docs/internal/mcp-analytics-filter-navigation.md@@ -4,5 +4,6 @@ The Dashboard stores its property filters and internal/test-user choice in the UTab links, KPI links, and tool-report links carry those parameters so the Dashboard restores the same selection when someone returns.An absent or invalid `filter_test_accounts` value follows the project's default; `true` and `false` are explicit overrides.-This first layer preserves the selection but does not make other tabs use it in their queries.-Tool quality, Sessions, and Activity need their own query and UI wiring before their metrics can be described as filtered by these parameters.+The Tool quality queries accept event, person, and session property filters and the test-account choice.+The Tool quality tab will not apply them until its UI wiring lands.+Tool reports, Sessions, and Activity still need query and UI wiring before their metrics can be described as filtered by these parameters.diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 0f5c9512cc60..7e1a15986842 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -31550,6 +31550,19 @@"required": ["type"],"type": "object"},+ "MCPAnalyticsPropertyFilter": {+ "anyOf": [+ {+ "$ref": "#/definitions/EventPropertyFilter"+ },+ {+ "$ref": "#/definitions/PersonPropertyFilter"+ },+ {+ "$ref": "#/definitions/SessionPropertyFilter"+ }+ ]+ },"MCPHarnessBreakdownItem": {"additionalProperties": false,"description": "One row of the MCP harness (client) breakdown: a resolved customer label and its activity.",@@ -31594,7 +31607,7 @@},"properties": {"items": {- "$ref": "#/definitions/AnyPropertyFilter"+ "$ref": "#/definitions/MCPAnalyticsPropertyFilter"},"type": "array"},@@ -31870,7 +31883,7 @@},"properties": {"items": {- "$ref": "#/definitions/AnyPropertyFilter"+ "$ref": "#/definitions/MCPAnalyticsPropertyFilter"},"type": "array"},@@ -31999,7 +32012,7 @@},"properties": {"items": {- "$ref": "#/definitions/AnyPropertyFilter"+ "$ref": "#/definitions/MCPAnalyticsPropertyFilter"},"type": "array"},@@ -32124,7 +32137,7 @@},"properties": {"items": {- "$ref": "#/definitions/AnyPropertyFilter"+ "$ref": "#/definitions/MCPAnalyticsPropertyFilter"},"type": "array"},@@ -32214,6 +32227,9 @@"dateRange": {"$ref": "#/definitions/DateRange"},+ "filterTestAccounts": {+ "type": "boolean"+ },"kind": {"const": "MCPToolCategoriesQuery","type": "string"@@ -32222,6 +32238,12 @@"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"},+ "properties": {+ "items": {+ "$ref": "#/definitions/MCPAnalyticsPropertyFilter"+ },+ "type": "array"+ },"response": {"$ref": "#/definitions/MCPToolCategoriesQueryResponse"},@@ -32322,6 +32344,9 @@"dateRange": {"$ref": "#/definitions/DateRange"},+ "filterTestAccounts": {+ "type": "boolean"+ },"kind": {"const": "MCPToolCategoryCountsQuery","type": "string"@@ -32330,6 +32355,12 @@"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"},+ "properties": {+ "items": {+ "$ref": "#/definitions/MCPAnalyticsPropertyFilter"+ },+ "type": "array"+ },"response": {"$ref": "#/definitions/MCPToolCategoryCountsQueryResponse"},@@ -33207,6 +33238,9 @@"dateRange": {"$ref": "#/definitions/DateRange"},+ "filterTestAccounts": {+ "type": "boolean"+ },"interval": {"$ref": "#/definitions/IntervalType","description": "Bucket granularity; the frontend passes getDefaultInterval. Defaults to day."@@ -33219,6 +33253,12 @@"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"},+ "properties": {+ "items": {+ "$ref": "#/definitions/MCPAnalyticsPropertyFilter"+ },+ "type": "array"+ },"response": {"$ref": "#/definitions/MCPToolQualityDailyStatsQueryResponse"},@@ -33369,6 +33409,9 @@"dateRange": {"$ref": "#/definitions/DateRange"},+ "filterTestAccounts": {+ "type": "boolean"+ },"kind": {"const": "MCPToolQualityRowsQuery","type": "string"@@ -33385,6 +33428,12 @@"$ref": "#/definitions/integer","description": "Number of matching tools to skip."},+ "properties": {+ "items": {+ "$ref": "#/definitions/MCPAnalyticsPropertyFilter"+ },+ "type": "array"+ },"response": {"$ref": "#/definitions/MCPToolQualityRowsQueryResponse"},diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex e4e1f5f7266e..58435d373fd1 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -3443,6 +3443,8 @@ export interface MCPToolCallBreakdownItem {calls: integer}+export type MCPAnalyticsPropertyFilter = EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter+export interface MCPToolCallBreakdownQueryResponse extends AnalyticsQueryResponseBase {results: MCPToolCallBreakdownItem[]}@@ -3451,7 +3453,7 @@ export interface MCPToolCallBreakdownQueryResponse extends AnalyticsQueryResponsexport interface MCPToolCallBreakdownQuery extends DataNode<MCPToolCallBreakdownQueryResponse> {kind: NodeKind.MCPToolCallBreakdownQuerydateRange?: DateRange- properties?: AnyPropertyFilter[]+ properties?: MCPAnalyticsPropertyFilter[]filterTestAccounts?: boolean/** Bucket granularity; the frontend passes getDefaultInterval. Defaults to day. */interval?: IntervalType@@ -3476,7 +3478,7 @@ export interface MCPToolCallsAndErrorsQueryResponse extends AnalyticsQueryResponexport interface MCPToolCallsAndErrorsQuery extends DataNode<MCPToolCallsAndErrorsQueryResponse> {kind: NodeKind.MCPToolCallsAndErrorsQuerydateRange?: DateRange- properties?: AnyPropertyFilter[]+ properties?: MCPAnalyticsPropertyFilter[]filterTestAccounts?: boolean/** Bucket granularity; the frontend passes getDefaultInterval. Defaults to day. */interval?: IntervalType@@ -3502,7 +3504,7 @@ export interface MCPHarnessBreakdownQueryResponse extends AnalyticsQueryResponseexport interface MCPHarnessBreakdownQuery extends DataNode<MCPHarnessBreakdownQueryResponse> {kind: NodeKind.MCPHarnessBreakdownQuerydateRange?: DateRange- properties?: AnyPropertyFilter[]+ properties?: MCPAnalyticsPropertyFilter[]filterTestAccounts?: boolean/** When set, scope to a single effective tool's new-SDK calls (the per-tool "By harness" table). */toolName?: string@@ -3526,7 +3528,7 @@ export interface MCPModelBreakdownQueryResponse extends AnalyticsQueryResponseBaexport interface MCPModelBreakdownQuery extends DataNode<MCPModelBreakdownQueryResponse> {kind: NodeKind.MCPModelBreakdownQuerydateRange?: DateRange- properties?: AnyPropertyFilter[]+ properties?: MCPAnalyticsPropertyFilter[]filterTestAccounts?: boolean/** Return individual reported models, excluding Unknown, instead of the top-six grouping. */includeAllModels?: boolean@@ -3726,6 +3728,8 @@ export interface MCPToolQualityRowsQueryResponse extends AnalyticsQueryResponseBexport interface MCPToolQualityRowsQuery extends DataNode<MCPToolQualityRowsQueryResponse> {kind: NodeKind.MCPToolQualityRowsQuerydateRange?: DateRange+ properties?: MCPAnalyticsPropertyFilter[]+ filterTestAccounts?: boolean/** Restrict to these $mcp_tool_category values; empty or omitted means all categories. */categories?: string[]/** Case-insensitive substring search on the effective tool name. */@@ -3760,6 +3764,8 @@ export interface MCPToolQualityDailyStatsQueryResponse extends AnalyticsQueryResexport interface MCPToolQualityDailyStatsQuery extends DataNode<MCPToolQualityDailyStatsQueryResponse> {kind: NodeKind.MCPToolQualityDailyStatsQuerydateRange?: DateRange+ properties?: MCPAnalyticsPropertyFilter[]+ filterTestAccounts?: boolean/** Bucket granularity; the frontend passes getDefaultInterval. Defaults to day. */interval?: IntervalType/** Restrict to these $mcp_tool_category values; empty or omitted means all categories. */@@ -3784,6 +3790,8 @@ export interface MCPToolCategoryCountsQueryResponse extends AnalyticsQueryResponexport interface MCPToolCategoryCountsQuery extends DataNode<MCPToolCategoryCountsQueryResponse> {kind: NodeKind.MCPToolCategoryCountsQuerydateRange?: DateRange+ properties?: MCPAnalyticsPropertyFilter[]+ filterTestAccounts?: boolean}export type CachedMCPToolCategoryCountsQueryResponse = CachedQueryResponse<MCPToolCategoryCountsQueryResponse>@@ -3801,6 +3809,8 @@ export interface MCPToolCategoriesQueryResponse extends AnalyticsQueryResponseBaexport interface MCPToolCategoriesQuery extends DataNode<MCPToolCategoriesQueryResponse> {kind: NodeKind.MCPToolCategoriesQuerydateRange?: DateRange+ properties?: MCPAnalyticsPropertyFilter[]+ filterTestAccounts?: boolean}export type CachedMCPToolCategoriesQueryResponse = CachedQueryResponse<MCPToolCategoriesQueryResponse>diff --git a/posthog/schema.py b/posthog/schema.pyindex a2899010fc36..ff39d293c268 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -27477,7 +27477,7 @@ class MCPHarnessBreakdownQuery(BaseModel):filterTestAccounts: bool | None = Nonekind: Literal["MCPHarnessBreakdownQuery"] = "MCPHarnessBreakdownQuery"modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")- properties: list[AnyPropertyFilterDiscriminated] | None = None+ properties: list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter] | None = Noneresponse: MCPHarnessBreakdownQueryResponse | None = Nonetags: QueryLogTags | None = NonetoolName: str | None = Field(@@ -27528,7 +27528,7 @@ class MCPModelBreakdownQuery(BaseModel):default=None,description=("Number of individual models to skip when includeAllModels is enabled."),)- properties: list[AnyPropertyFilterDiscriminated] | None = None+ properties: list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter] | None = Noneresponse: MCPModelBreakdownQueryResponse | None = Nonetags: QueryLogTags | None = Noneversion: float | None = Field(default=None, description="version of the node, used for schema migrations")@@ -27546,7 +27546,7 @@ class MCPToolCallBreakdownQuery(BaseModel):)kind: Literal["MCPToolCallBreakdownQuery"] = "MCPToolCallBreakdownQuery"modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")- properties: list[AnyPropertyFilterDiscriminated] | None = None+ properties: list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter] | None = Noneresponse: MCPToolCallBreakdownQueryResponse | None = Nonetags: QueryLogTags | None = Noneversion: float | None = Field(default=None, description="version of the node, used for schema migrations")@@ -27564,7 +27564,7 @@ class MCPToolCallsAndErrorsQuery(BaseModel):)kind: Literal["MCPToolCallsAndErrorsQuery"] = "MCPToolCallsAndErrorsQuery"modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")- properties: list[AnyPropertyFilterDiscriminated] | None = None+ properties: list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter] | None = Noneresponse: MCPToolCallsAndErrorsQueryResponse | None = Nonetags: QueryLogTags | None = Noneversion: float | None = Field(default=None, description="version of the node, used for schema migrations")@@ -27575,8 +27575,10 @@ class MCPToolCategoriesQuery(BaseModel):extra="forbid",)dateRange: DateRange | None = None+ filterTestAccounts: bool | None = Nonekind: Literal["MCPToolCategoriesQuery"] = "MCPToolCategoriesQuery"modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ properties: list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter] | None = Noneresponse: MCPToolCategoriesQueryResponse | None = Nonetags: QueryLogTags | None = Noneversion: float | None = Field(default=None, description="version of the node, used for schema migrations")@@ -27587,8 +27589,10 @@ class MCPToolCategoryCountsQuery(BaseModel):extra="forbid",)dateRange: DateRange | None = None+ filterTestAccounts: bool | None = Nonekind: Literal["MCPToolCategoryCountsQuery"] = "MCPToolCategoryCountsQuery"modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ properties: list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter] | None = Noneresponse: MCPToolCategoryCountsQueryResponse | None = Nonetags: QueryLogTags | None = Noneversion: float | None = Field(default=None, description="version of the node, used for schema migrations")@@ -27717,12 +27721,14 @@ class MCPToolQualityDailyStatsQuery(BaseModel):description=("Restrict to these $mcp_tool_category values; empty or omitted means all categories."),)dateRange: DateRange | None = None+ filterTestAccounts: bool | None = Noneinterval: IntervalType | None = Field(default=None,description=("Bucket granularity; the frontend passes getDefaultInterval. Defaults to day."),)kind: Literal["MCPToolQualityDailyStatsQuery"] = "MCPToolQualityDailyStatsQuery"modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ properties: list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter] | None = Noneresponse: MCPToolQualityDailyStatsQueryResponse | None = Nonetags: QueryLogTags | None = NonetoolName: str | None = Field(@@ -27741,6 +27747,7 @@ class MCPToolQualityRowsQuery(BaseModel):description=("Restrict to these $mcp_tool_category values; empty or omitted means all categories."),)dateRange: DateRange | None = None+ filterTestAccounts: bool | None = Nonekind: Literal["MCPToolQualityRowsQuery"] = "MCPToolQualityRowsQuery"limit: int | None = Field(default=None,@@ -27748,6 +27755,7 @@ class MCPToolQualityRowsQuery(BaseModel):)modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")offset: int | None = Field(default=None, description="Number of matching tools to skip.")+ properties: list[EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter] | None = Noneresponse: MCPToolQualityRowsQueryResponse | None = Nonesearch: str | None = Field(default=None,diff --git a/posthog/test/test_property_filter_discriminator.py b/posthog/test/test_property_filter_discriminator.pyindex d0cdb14499c2..674586ba3113 100644--- a/posthog/test/test_property_filter_discriminator.py+++ b/posthog/test/test_property_filter_discriminator.py@@ -1,7 +1,7 @@from django.test.testcases import SimpleTestCasefrom parameterized import parameterized-from pydantic import ValidationError+from pydantic import BaseModel, ValidationErrorfrom posthog.schema import (AccountCustomPropertyFilter,@@ -27,6 +27,8 @@ from posthog.schema import (LogPropertyFilter,LogPropertyFilterType,MCPModelBreakdownQuery,+ MCPToolCallBreakdownQuery,+ MCPToolQualityRowsQuery,MetricPropertyFilter,PersonMetadataPropertyFilter,PersonPropertyFilter,@@ -42,6 +44,13 @@ from posthog.schema import ()+# Mirrors TrendsQueryWithTemplateVariables in filter_to_query.py: subclassing a schema+# model from another module only works if the parent's annotations resolved at class+# creation, i.e. the discriminated aliases were emitted before their usage sites.+class TrendsQuerySubclassedElsewhere(TrendsQuery):+ pass++class TestPropertyFilterDiscriminator(SimpleTestCase):# The AnyPropertyFilter union was an undiscriminated smart union — Pydantic walked# every member per item, so one malformed filter produced an error per member and@@ -273,17 +282,50 @@ class TestPropertyFilterDiscriminator(SimpleTestCase):assert len(errors) == 3, f"expected exactly one error per item, got {len(errors)}: {errors}"assert all(error["type"] == "extra_forbidden" for error in errors)- def test_mcp_model_breakdown_properties_use_the_discriminated_filter(self) -> None:- query = MCPModelBreakdownQuery.model_validate(- {- "kind": "MCPModelBreakdownQuery",- "properties": [{"type": "event", "key": "$mcp_llm_model", "operator": "exact"}],- }+ def test_subclass_in_another_module_resolves_the_alias(self) -> None:+ query = TrendsQuerySubclassedElsewhere.model_validate(+ {"kind": "TrendsQuery", "series": [], "properties": [{"type": "event", "key": "k", "operator": "exact"}]})-- assert query.properties is not None+ assert isinstance(query.properties, list)assert type(query.properties[0]) is EventPropertyFilter+ @parameterized.expand(+ [+ ("MCPToolCallBreakdownQuery", MCPToolCallBreakdownQuery, {}),+ ("MCPModelBreakdownQuery", MCPModelBreakdownQuery, {}),+ ("MCPToolQualityRowsQuery", MCPToolQualityRowsQuery, {}),+ ]+ )+ def test_mcp_analytics_properties_use_the_discriminated_filter(+ self, kind: str, model: type[BaseModel], extra_fields: dict+ ) -> None:+ supported_filters: list[tuple[str, type[BaseModel]]] = [+ ("event", EventPropertyFilter),+ ("person", PersonPropertyFilter),+ ("session", SessionPropertyFilter),+ ]+ for property_type, expected in supported_filters:+ query = model.model_validate(+ {+ "kind": kind,+ "properties": [{"type": property_type, "key": "k", "operator": "exact"}],+ **extra_fields,+ }+ )+ properties = query.properties # type: ignore[attr-defined]+ assert properties is not None+ assert type(properties[0]) is expected++ for property_type in ["cohort", "hogql"]:+ with self.assertRaises(ValidationError):+ model.model_validate(+ {+ "kind": kind,+ "properties": [{"type": property_type, "key": "k", "operator": "exact"}],+ **extra_fields,+ }+ )+def test_serialization_round_trip_is_stable(self) -> None:node = EventsNode(properties=[diff --git a/products/mcp_analytics/backend/hogql_queries/base.py b/products/mcp_analytics/backend/hogql_queries/base.pyindex bf247b65a802..f985f710e08d 100644--- a/products/mcp_analytics/backend/hogql_queries/base.py+++ b/products/mcp_analytics/backend/hogql_queries/base.py@@ -6,20 +6,25 @@ its harness-label SQL."""import json+from collections.abc import Sequencefrom datetime import datetimefrom typing import TYPE_CHECKINGimport posthoganalytics+from posthog.schema import EmptyPropertyFilter, EventPropertyFilter, PersonPropertyFilter, SessionPropertyFilter+from posthog.hogql import ast+from posthog.hogql.errors import QueryErrorfrom posthog.hogql.parser import parse_expr+from posthog.hogql.property import property_to_exprfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom products.access_control.backend.facade.user_access_control import UserAccessControl, UserAccessControlErrorif TYPE_CHECKING:- from posthog.schema import DateRange, IntervalType+ from posthog.schema import AnyPropertyFilterDiscriminated, DateRange, IntervalTypefrom posthog.models.team import Teamfrom posthog.models.user import User@@ -61,6 +66,30 @@ def tool_scope_exprs(tool: str) -> list[ast.Expr]:]+def shared_filter_exprs(+ team: "Team",+ properties: "Sequence[AnyPropertyFilterDiscriminated] | None",+ filter_test_accounts: bool | None,+) -> list[ast.Expr]:+ """Property filters plus, when enabled, the team's default test-account exclusions.++ Every MCP analytics runner that accepts the dashboard's shared property filters and+ "Filter out internal and test users" switch applies them through this one expression,+ so the two behave identically everywhere they're wired in.+ """+ all_properties = [+ property_filter for property_filter in properties or [] if not isinstance(property_filter, EmptyPropertyFilter)+ ]+ if any(+ not isinstance(property_filter, EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter)+ for property_filter in all_properties+ ):+ raise QueryError("Only event, person, and session property filters are supported.")+ if filter_test_accounts:+ all_properties += team.test_account_filters or []+ return [property_to_expr(all_properties, team)] if all_properties else []++def display_person_properties(*, email: str, name: str) -> str:"""JSON of only the person fields a row's person cell renders, omitting blanks.diff --git a/products/mcp_analytics/backend/hogql_queries/dashboard_series.py b/products/mcp_analytics/backend/hogql_queries/dashboard_series.pyindex 3cf35d7d460c..3156cb31fde9 100644--- a/products/mcp_analytics/backend/hogql_queries/dashboard_series.py+++ b/products/mcp_analytics/backend/hogql_queries/dashboard_series.py@@ -1,5 +1,6 @@"""Query runners for the MCP analytics dashboard's interval-bucketed charts."""+from collections.abc import Sequencefrom functools import cached_propertyfrom typing import TYPE_CHECKING@@ -17,7 +18,6 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.parser import parse_expr, parse_select-from posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context@@ -25,7 +25,11 @@ from posthog.hogql_queries.query_runner import AnalyticsQueryRunnerfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom products.mcp_analytics.backend.constants import MCP_TOOL_CALL_EVENT-from products.mcp_analytics.backend.hogql_queries.base import mcp_query_date_range, validate_mcp_analytics_access+from products.mcp_analytics.backend.hogql_queries.base import (+ mcp_query_date_range,+ shared_filter_exprs,+ validate_mcp_analytics_access,+)if TYPE_CHECKING:from posthog.models.team import Team@@ -36,7 +40,7 @@ _IS_ERROR = "toBool(properties.$mcp_is_error)"def _dashboard_where(date_range: QueryDateRange,- properties: list[AnyPropertyFilterDiscriminated] | None,+ properties: Sequence[AnyPropertyFilterDiscriminated] | None,filter_test_accounts: bool | None,team: "Team",) -> ast.Expr:@@ -47,12 +51,8 @@ def _dashboard_where(parse_expr("timestamp <= {date_to}", placeholders={"date_to": date_range.date_to_as_hogql()}),parse_expr("properties.$mcp_tool_name IS NOT NULL"),parse_expr("properties.$mcp_tool_name != ''"),+ *shared_filter_exprs(team, properties, filter_test_accounts),]- all_properties = list(properties or [])- if filter_test_accounts:- all_properties += team.test_account_filters or []- if all_properties:- exprs.append(property_to_expr(all_properties, team))return ast.And(exprs=exprs)diff --git a/products/mcp_analytics/backend/hogql_queries/harness_breakdown.py b/products/mcp_analytics/backend/hogql_queries/harness_breakdown.pyindex 3498f0100438..25846feccffb 100644--- a/products/mcp_analytics/backend/hogql_queries/harness_breakdown.py+++ b/products/mcp_analytics/backend/hogql_queries/harness_breakdown.py@@ -10,7 +10,6 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.parser import parse_expr, parse_select-from posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context@@ -21,6 +20,7 @@ from products.mcp_analytics.backend import mcp_harnessfrom products.mcp_analytics.backend.constants import MCP_TOOL_CALL_EVENTfrom products.mcp_analytics.backend.hogql_queries.base import (mcp_query_date_range,+ shared_filter_exprs,tool_scope_exprs,validate_mcp_analytics_access,)@@ -59,11 +59,7 @@ class MCPHarnessBreakdownQueryRunner(AnalyticsQueryRunner[MCPHarnessBreakdownQue]if self.query.toolName:exprs.extend(tool_scope_exprs(self.query.toolName))- properties = list(self.query.properties or [])- if self.query.filterTestAccounts:- properties += self.team.test_account_filters or []- if properties:- exprs.append(property_to_expr(properties, self.team))+ exprs.extend(shared_filter_exprs(self.team, self.query.properties, self.query.filterTestAccounts))return ast.And(exprs=exprs)def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:@@ -105,6 +101,7 @@ class MCPHarnessBreakdownQueryRunner(AnalyticsQueryRunner[MCPHarnessBreakdownQueresponse = execute_hogql_query(query=self.to_query(),team=self.team,+ user=self.user,query_type="mcp_harness_breakdown_query",timings=self.timings,modifiers=self.modifiers,diff --git a/products/mcp_analytics/backend/hogql_queries/model_breakdown.py b/products/mcp_analytics/backend/hogql_queries/model_breakdown.pyindex 1e5c28006d2c..61a150fd3b40 100644--- a/products/mcp_analytics/backend/hogql_queries/model_breakdown.py+++ b/products/mcp_analytics/backend/hogql_queries/model_breakdown.py@@ -10,7 +10,6 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.parser import parse_expr, parse_select-from posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context@@ -18,7 +17,11 @@ from posthog.hogql_queries.query_runner import AnalyticsQueryRunnerfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom products.mcp_analytics.backend.constants import MCP_TOOL_CALL_EVENT-from products.mcp_analytics.backend.hogql_queries.base import mcp_query_date_range, validate_mcp_analytics_access+from products.mcp_analytics.backend.hogql_queries.base import (+ mcp_query_date_range,+ shared_filter_exprs,+ validate_mcp_analytics_access,+)if TYPE_CHECKING:from posthog.models.user import User@@ -52,11 +55,7 @@ class MCPModelBreakdownQueryRunner(AnalyticsQueryRunner[MCPModelBreakdownQueryRe),parse_expr("timestamp <= {date_to}", placeholders={"date_to": self.query_date_range.date_to_as_hogql()}),]- properties = list(self.query.properties or [])- if self.query.filterTestAccounts:- properties += self.team.test_account_filters or []- if properties:- exprs.append(property_to_expr(properties, self.team))+ exprs.extend(shared_filter_exprs(self.team, self.query.properties, self.query.filterTestAccounts))return ast.And(exprs=exprs)def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:diff --git a/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py b/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.pyindex d50be5360c60..aa2d6ed7555d 100644--- a/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py+++ b/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py@@ -4,6 +4,7 @@ The per-tool table and activity series resolve the effective tool name so exec-wcalls match the per-tool detail runners. Category queries use the event-supplied category."""+from collections.abc import Sequencefrom functools import cached_propertyfrom typing import TYPE_CHECKING, Literal, cast@@ -42,10 +43,14 @@ from products.mcp_analytics.backend.constants import MCP_TOOL_CALL_EVENTfrom products.mcp_analytics.backend.hogql_queries.base import (EFFECTIVE_TOOL_SQL,mcp_query_date_range,+ shared_filter_exprs,validate_mcp_analytics_access,)if TYPE_CHECKING:+ from posthog.schema import AnyPropertyFilterDiscriminated++ from posthog.models.team import Teamfrom posthog.models.user import User# The tab scopes to $mcp_tool_call events that carry a tool name. Category and tool are event-supplied@@ -83,6 +88,9 @@ def _category_in(categories: list[str] | None) -> list[ast.Expr]:def _named_tool_where(date_range: QueryDateRange,categories: list[str] | None,+ team: "Team",+ properties: "Sequence[AnyPropertyFilterDiscriminated] | None" = None,+ filter_test_accounts: bool | None = None,*,tool_name: str | None = None,search: str | None = None,@@ -95,6 +103,7 @@ def _named_tool_where(parse_expr("{tool} IS NOT NULL", placeholders={"tool": parse_expr(EFFECTIVE_TOOL_SQL)}),parse_expr("{tool} != ''", placeholders={"tool": parse_expr(EFFECTIVE_TOOL_SQL)}),*_category_in(categories),+ *shared_filter_exprs(team, properties, filter_test_accounts),]if tool_name:exprs.append(@@ -170,7 +179,14 @@ class MCPToolQualityRowsQueryRunner(AnalyticsQueryRunner[MCPToolQualityRowsQuery"_P50": parse_expr(_P50),"_P95": parse_expr(_P95),"_P99": parse_expr(_P99),- "where": _named_tool_where(self.query_date_range, self.query.categories, search=search),+ "where": _named_tool_where(+ self.query_date_range,+ self.query.categories,+ self.team,+ self.query.properties,+ self.query.filterTestAccounts,+ search=search,+ ),"limit": ast.Constant(value=limit),"offset": ast.Constant(value=offset),},@@ -275,7 +291,14 @@ class MCPToolQualityDailyStatsQueryRunner(AnalyticsQueryRunner[MCPToolQualityDai"_P50": parse_expr(_P50),"_P95": parse_expr(_P95),"_P99": parse_expr(_P99),- "where": _named_tool_where(self.query_date_range, self.query.categories, tool_name=self.query.toolName),+ "where": _named_tool_where(+ self.query_date_range,+ self.query.categories,+ self.team,+ self.query.properties,+ self.query.filterTestAccounts,+ tool_name=self.query.toolName,+ ),},)@@ -334,6 +357,7 @@ class MCPToolCategoryCountsQueryRunner(AnalyticsQueryRunner[MCPToolCategoryCountparse_expr("timestamp <= {date_to}", placeholders={"date_to": self.query_date_range.date_to_as_hogql()}),+ *shared_filter_exprs(self.team, self.query.properties, self.query.filterTestAccounts),])return parse_select(@@ -395,6 +419,7 @@ class MCPToolCategoriesQueryRunner(AnalyticsQueryRunner[MCPToolCategoriesQueryRe),parse_expr("properties.$mcp_tool_category IS NOT NULL"),parse_expr("properties.$mcp_tool_category != ''"),+ *shared_filter_exprs(self.team, self.query.properties, self.query.filterTestAccounts),])return parse_select(diff --git a/products/mcp_analytics/backend/tests/test_tool_quality_tables.py b/products/mcp_analytics/backend/tests/test_tool_quality_tables.pyindex 1a77e0fcc575..5766d1c461bc 100644--- a/products/mcp_analytics/backend/tests/test_tool_quality_tables.py+++ b/products/mcp_analytics/backend/tests/test_tool_quality_tables.py@@ -8,6 +8,8 @@ from parameterized import parameterizedfrom posthog.schema import (DateRange,+ EventPropertyFilter,+ HogQLPropertyFilter,IntervalType,MCPToolCategoriesQuery,MCPToolCategoryCountsQuery,@@ -15,11 +17,14 @@ from posthog.schema import (MCPToolQualityDailyStatsQuery,MCPToolQualityRowsQuery,MCPToolQualityRowsQueryResponse,+ PropertyOperator,)from posthog.hogql import ast+from posthog.hogql.errors import QueryErrorfrom products.access_control.backend.facade.user_access_control import UserAccessControlError+from products.mcp_analytics.backend.hogql_queries.base import shared_filter_exprsfrom products.mcp_analytics.backend.hogql_queries.tool_quality_tables import (MCPToolCategoriesQueryRunner,MCPToolCategoryCountsQueryRunner,@@ -243,6 +248,88 @@ class TestMCPToolCategoryMapQueryRunner(_MCPAnalyticsTeamScopedTestMixin, Clickhassert pairs == [("query_run", "Insights"), ("query_run", "SQL")]+def _setup_included_and_excluded_tools(team: Any) -> None:+ """One event on the shared property filter's match, one off it, to prove the filter+ reaches every runner below the same way it reaches the Tool quality rows table."""+ _emit(team, tool_name="included_tool", category="Data")+ _emit(team, tool_name="excluded_tool", category="Insights")+++class TestMCPToolQualitySharedFilters(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):+ """Every runner here resolves its WHERE through `_named_tool_where` or applies+ `shared_filter_exprs` directly, so the dashboard's shared property filters and "Filter out+ internal and test users" switch (see hogql_queries/base.py) reach all of them. One+ parameterized case per runner proves that, rather than duplicating a property-filter test+ and a filterTestAccounts test per runner.+ """++ def test_rejects_executable_property_filters(self) -> None:+ with self.assertRaisesRegex(QueryError, "Only event, person, and session property filters"):+ shared_filter_exprs(self.team, [HogQLPropertyFilter(key="1 = 1")], None)++ @parameterized.expand(+ [+ ("quality_rows", MCPToolQualityRowsQueryRunner, MCPToolQualityRowsQuery, len, 2, 1),+ (+ "quality_daily_stats",+ MCPToolQualityDailyStatsQueryRunner,+ MCPToolQualityDailyStatsQuery,+ lambda rows: sum(r.calls for r in rows),+ 2,+ 1,+ ),+ (+ "category_counts",+ MCPToolCategoryCountsQueryRunner,+ MCPToolCategoryCountsQuery,+ lambda rows: sum(r.calls for r in rows),+ 2,+ 1,+ ),+ (+ "categories",+ MCPToolCategoriesQueryRunner,+ MCPToolCategoriesQuery,+ lambda rows: {r.category for r in rows},+ {"Data", "Insights"},+ {"Data"},+ ),+ ]+ )+ def test_property_filter_and_test_accounts_narrow_the_results(+ self,+ _name: str,+ runner_cls: Any,+ query_cls: Any,+ metric_fn: Any,+ expected_unfiltered: Any,+ expected_filtered: Any,+ ) -> None:+ _setup_included_and_excluded_tools(self.team)+ flush_persons_and_events()++ def run(**filter_kwargs: Any) -> Any:+ query = query_cls(dateRange=DateRange(date_from="-7d"), **filter_kwargs)+ return metric_fn(runner_cls(query=query, team=self.team).calculate().results)++ assert run() == expected_unfiltered++ assert (+ run(+ properties=[+ EventPropertyFilter(key="$mcp_tool_name", value=["included_tool"], operator=PropertyOperator.EXACT)+ ]+ )+ == expected_filtered+ )++ self.team.test_account_filters = [+ {"key": "$mcp_tool_name", "value": ["excluded_tool"], "operator": "is_not", "type": "event"}+ ]+ self.team.save()+ assert run(filterTestAccounts=True) == expected_filtered++class TestMCPToolQualityGate(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):# The whole point of the migration: each kind gates on `mcp-analytics`, so the generic /query/# endpoint can't reach it without the flag. Every other test here calls calculate() with the flagdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7ddd9455c526..5a373df42dc8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -49038,7 +49038,7 @@ export namespace Schemas {kind?: 'MCPToolCallBreakdownQuery';/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;- properties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter | BehavioralPropertyFilter)[] | null;+ properties?: (EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter)[] | null;response?: MCPToolCallBreakdownQueryResponse | null;tags?: QueryLogTags | null;/** version of the node, used for schema migrations */@@ -49082,7 +49082,7 @@ export namespace Schemas {kind?: 'MCPToolCallsAndErrorsQuery';/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;- properties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter | BehavioralPropertyFilter)[] | null;+ properties?: (EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter)[] | null;response?: MCPToolCallsAndErrorsQueryResponse | null;tags?: QueryLogTags | null;/** version of the node, used for schema migrations */@@ -49126,7 +49126,7 @@ export namespace Schemas {kind?: 'MCPHarnessBreakdownQuery';/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;- properties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter | BehavioralPropertyFilter)[] | null;+ properties?: (EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter)[] | null;response?: MCPHarnessBreakdownQueryResponse | null;tags?: QueryLogTags | null;/** When set, scope to a single effective tool's new-SDK calls (the per-tool "By harness" table). */@@ -49176,7 +49176,7 @@ export namespace Schemas {modifiers?: HogQLQueryModifiers | null;/** Number of individual models to skip when includeAllModels is enabled. */offset?: number | null;- properties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter | BehavioralPropertyFilter)[] | null;+ properties?: (EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter)[] | null;response?: MCPModelBreakdownQueryResponse | null;tags?: QueryLogTags | null;/** version of the node, used for schema migrations */@@ -49490,6 +49490,7 @@ export namespace Schemas {/** Restrict to these $mcp_tool_category values; empty or omitted means all categories. */categories?: string[] | null;dateRange?: DateRange | null;+ filterTestAccounts?: boolean | null;kind?: 'MCPToolQualityRowsQuery';/** Page size. The server defaults to 50 and caps this at 100. */limit?: number | null;@@ -49497,6 +49498,7 @@ export namespace Schemas {modifiers?: HogQLQueryModifiers | null;/** Number of matching tools to skip. */offset?: number | null;+ properties?: (EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter)[] | null;response?: MCPToolQualityRowsQueryResponse | null;/** Case-insensitive substring search on the effective tool name. */search?: string | null;@@ -49544,11 +49546,13 @@ export namespace Schemas {/** Restrict to these $mcp_tool_category values; empty or omitted means all categories. */categories?: string[] | null;dateRange?: DateRange | null;+ filterTestAccounts?: boolean | null;/** Bucket granularity; the frontend passes getDefaultInterval. Defaults to day. */interval?: IntervalType | null;kind?: 'MCPToolQualityDailyStatsQuery';/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;+ properties?: (EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter)[] | null;response?: MCPToolQualityDailyStatsQueryResponse | null;tags?: QueryLogTags | null;/** Restrict to a single $mcp_tool_name; omitted means the aggregate across all tools. */@@ -49586,9 +49590,11 @@ export namespace Schemas {export interface MCPToolCategoryCountsQuery {dateRange?: DateRange | null;+ filterTestAccounts?: boolean | null;kind?: 'MCPToolCategoryCountsQuery';/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;+ properties?: (EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter)[] | null;response?: MCPToolCategoryCountsQueryResponse | null;tags?: QueryLogTags | null;/** version of the node, used for schema migrations */@@ -49623,9 +49629,11 @@ export namespace Schemas {export interface MCPToolCategoriesQuery {dateRange?: DateRange | null;+ filterTestAccounts?: boolean | null;kind?: 'MCPToolCategoriesQuery';/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;+ properties?: (EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter)[] | null;response?: MCPToolCategoriesQueryResponse | null;tags?: QueryLogTags | null;/** version of the node, used for schema migrations */diff --git a/services/mcp/src/tools/generated/mcp_analytics.ts b/services/mcp/src/tools/generated/mcp_analytics.tsindex 0dc71fa0013e..5fa11bd1cd01 100644--- a/services/mcp/src/tools/generated/mcp_analytics.ts+++ b/services/mcp/src/tools/generated/mcp_analytics.ts@@ -294,33 +294,6 @@ const PersonPropertyFilter = z.object({value: PropertyFilterValue.optional(),})-const PersonMetadataPropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: z- .literal('person_metadata')- .describe('Top-level columns on the persons table (e.g. created_at), not properties JSON')- .default('person_metadata'),- value: PropertyFilterValue.optional(),-})--const ElementPropertyFilter = z.object({- key: z.enum(['tag_name', 'text', 'href', 'selector']),- label: z.string().optional(),- operator: PropertyOperator,- type: z.literal('element').default('element'),- value: PropertyFilterValue.optional(),-})--const EventMetadataPropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: z.literal('event_metadata').default('event_metadata'),- value: PropertyFilterValue.optional(),-})-const SessionPropertyFilter = z.object({key: z.string(),label: z.string().optional(),@@ -329,240 +302,13 @@ const SessionPropertyFilter = z.object({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 DurationType = z.enum(['duration', 'active_seconds', 'inactive_seconds'])--const RecordingPropertyFilter = z.object({- key: z.union([- DurationType,- z.literal('snapshot_source'),- z.literal('visited_page'),- z.literal('comment_text'),- z.literal('click_count'),- z.literal('keypress_count'),- z.literal('mouse_activity_count'),- ]),- label: z.string().optional(),- operator: PropertyOperator,- type: z.literal('recording').default('recording'),- value: PropertyFilterValue.optional(),-})--const LogEntryPropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: z.literal('log_entry').default('log_entry'),- value: PropertyFilterValue.optional(),-})--const GroupPropertyFilter = z.object({- group_key_names: z.record(z.string(), z.string()).optional(),- group_type_index: z.union([z.number().int(), z.null()]).optional(),- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: z.literal('group').default('group'),- value: PropertyFilterValue.optional(),-})--const FeaturePropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: z.literal('feature').describe('Event property with "$feature/" prepended').default('feature'),- value: PropertyFilterValue.optional(),-})--const FlagPropertyFilter = z.object({- key: z.string().describe('The key should be the flag ID'),- label: z.string().optional(),- operator: z- .literal('flag_evaluates_to')- .describe('Only flag_evaluates_to operator is allowed for flag dependencies')- .default('flag_evaluates_to'),- type: z.literal('flag').describe('Feature flag dependency').default('flag'),- value: z.union([z.boolean(), z.string()]).describe('The value can be true, false, or a variant name'),-})--const HogQLPropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- type: z.literal('hogql').default('hogql'),- value: PropertyFilterValue.optional(),-})--const EmptyPropertyFilter = z.object({- type: z.literal('empty').default('empty').optional(),-})--const DataWarehousePropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: z.literal('data_warehouse').default('data_warehouse'),- value: PropertyFilterValue.optional(),-})--const DataWarehousePersonPropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: z.literal('data_warehouse_person_property').default('data_warehouse_person_property'),- value: PropertyFilterValue.optional(),-})--const ErrorTrackingIssueFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: z.literal('error_tracking_issue').default('error_tracking_issue'),- value: PropertyFilterValue.optional(),-})--const LogPropertyFilterType = z.enum(['log', 'log_attribute', 'log_resource_attribute'])--const LogPropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: LogPropertyFilterType,- value: PropertyFilterValue.optional(),-})--const MetricPropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: z.literal('metric_attribute').default('metric_attribute'),- value: PropertyFilterValue.optional(),-})--const SpanPropertyFilterType = z.enum(['span', 'span_attribute', 'span_resource_attribute'])--const SpanPropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: SpanPropertyFilterType,- value: PropertyFilterValue.optional(),-})--const RevenueAnalyticsPropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: z.literal('revenue_analytics').default('revenue_analytics'),- value: PropertyFilterValue.optional(),-})--const AccountCustomPropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: z- .literal('account_custom_property')- .describe('Customer analytics account custom property — the key is the property definition id')- .default('account_custom_property'),- value: PropertyFilterValue.optional(),-})--const WorkflowVariablePropertyFilter = z.object({- key: z.string(),- label: z.string().optional(),- operator: PropertyOperator,- type: z.literal('workflow_variable').default('workflow_variable'),- value: PropertyFilterValue.optional(),-})--const BehavioralEventSource = z.enum(['events', 'actions'])--const TimeUnitType = z.enum(['day', 'week', 'month', 'year'])--const InlineBehavioralType = z.enum(['performed_event', 'performed_event_multiple'])--const BehavioralPropertyFilter = z.object({- event_filters: z- .array(- z.union([- EventPropertyFilter,- PersonPropertyFilter,- ElementPropertyFilter,- FeaturePropertyFilter,- HogQLPropertyFilter,- ])- )- .describe(- 'Extra property filters the matching events must satisfy. Deliberately excludes nested behavioral/cohort filters and groups'- )- .optional(),- event_type: BehavioralEventSource,- explicit_datetime: z- .string()- .describe('Absolute or relative (e.g. -30d) lower date bound — alternative to time_value/time_interval')- .optional(),- explicit_datetime_to: z.string().optional(),- key: z.string().describe("Event name, or action id when event_type is 'actions'"),- label: z.string().optional(),- negation: z.coerce- .boolean()- .describe(- 'Match persons who did NOT satisfy the criterion. Not the same as a low count — zero-occurrence persons never match count operators'- )- .optional(),- operator: PropertyOperator.describe('Count comparison for performed_event_multiple, defaults to exact').optional(),- operator_value: z.coerce.number().int().describe('Count threshold for performed_event_multiple').optional(),- time_interval: TimeUnitType.optional(),- time_value: z.coerce.number().int().describe('Relative time window size, paired with time_interval').optional(),- type: z- .literal('behavioral')- .describe(- "Person performed (or didn't perform) an event in a time window. ClickHouse-only — not evaluable by flags or CDP"- )- .default('behavioral'),- value: InlineBehavioralType,-})--const AnyPropertyFilter = z.union([- EventPropertyFilter,- PersonPropertyFilter,- PersonMetadataPropertyFilter,- ElementPropertyFilter,- EventMetadataPropertyFilter,- SessionPropertyFilter,- CohortPropertyFilter,- RecordingPropertyFilter,- LogEntryPropertyFilter,- GroupPropertyFilter,- FeaturePropertyFilter,- FlagPropertyFilter,- HogQLPropertyFilter,- EmptyPropertyFilter,- DataWarehousePropertyFilter,- DataWarehousePersonPropertyFilter,- ErrorTrackingIssueFilter,- LogPropertyFilter,- MetricPropertyFilter,- SpanPropertyFilter,- RevenueAnalyticsPropertyFilter,- AccountCustomPropertyFilter,- WorkflowVariablePropertyFilter,- BehavioralPropertyFilter,-])+const MCPAnalyticsPropertyFilter = z.union([EventPropertyFilter, PersonPropertyFilter, SessionPropertyFilter])const MCPHarnessBreakdownQuery = z.object({dateRange: DateRange.optional(),filterTestAccounts: z.coerce.boolean().optional(),kind: z.literal('MCPHarnessBreakdownQuery').default('MCPHarnessBreakdownQuery'),- properties: z.array(AnyPropertyFilter).optional(),+ properties: z.array(MCPAnalyticsPropertyFilter).optional(),toolName: z.string().describe('When set, scope to a single effective tool\'s new-SDK calls (the per-tool "By harness" table).')