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-analytics): scope intent clustering by tool category (#86459)

Daniel Visca2cf989864f42
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 53d6b3bd579b..6b964dd36d4f 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6985,9 +6985,9 @@ snapshots:
scenes-app-mcp-analytics--dashboard-with-menu-bar--light:
hash: v1.k794b7964.0ac0bf1b02890312bdc239db7a4842f1a377468aa9c5ad67c926aecaccf510ce.V7Onp6uOX4j46-gDndut-qkT9N6LwIUCq5z4hVn-VZg
scenes-app-mcp-analytics--intent-clustering--dark:
- hash: v1.k794b7964.64563081f2752d9d272a03b440d1d8d464e9401f7bba052ad69565ea3af0bc6e.T2vzGEgBaTrMVGr03LZiEmlTcTpJ9yApyM-oMO6RDiw
+ hash: v1.k794b7964.e56c2b8b08a970df9e0fe9d6d618092c631d23d7c72a22b32bf571a663fcf9e9.84fphIJJ3z1hojod_YDTvqtsP_PexYwYUmbFcqCw-xQ
scenes-app-mcp-analytics--intent-clustering--light:
- hash: v1.k794b7964.5db1fed9a3e5a5490f0d8135c781bffe4a0005510654cc3552978e21094d0d44.LJXBicQp3MWkKTBnnngZdfvu6ZZhmV1exzkPabI3rKs
+ hash: v1.k794b7964.0496d3f05595d775c03763449254e74d495aeafee448579dae3a3a7e6cc57410.VRPMdh1JoIxzB79GzZM8yPe4SA9YW_02HQJNJxEHtL0
scenes-app-mcp-analytics--sessions--dark:
hash: v1.k794b7964.e44b6747efcbc630753707078c16ebb36a05f9701fa89c014d8eebec1eabc4fb.i5C5Ib24E2xi_tzTLXniz3WM8UKaAFOj4aqVnMmtIiI
scenes-app-mcp-analytics--sessions--light:
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index b574a413af99..980d354551c3 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -1738,6 +1738,9 @@
{
"$ref": "#/definitions/MCPToolCategoriesQuery"
},
+ {
+ "$ref": "#/definitions/MCPToolCategoryMapQuery"
+ },
{
"$ref": "#/definitions/MCPToolDescriptionsQuery"
},
@@ -9852,6 +9855,106 @@
],
"type": "object"
},
+ "CachedMCPToolCategoryMapQueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "cache_key": {
+ "type": "string"
+ },
+ "cache_target_age": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "calculation_trigger": {
+ "description": "What triggered the calculation of the query, leave empty if user/immediate",
+ "type": "string"
+ },
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "is_cached": {
+ "type": "boolean"
+ },
+ "last_refresh": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "next_allowed_client_refresh": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "query_metadata": {
+ "type": "object"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "items": {
+ "$ref": "#/definitions/MCPToolCategoryMapItem"
+ },
+ "type": "array"
+ },
+ "timezone": {
+ "type": "string"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "cache_key",
+ "is_cached",
+ "last_refresh",
+ "next_allowed_client_refresh",
+ "results",
+ "timezone"
+ ],
+ "type": "object"
+ },
"CachedMCPToolDailyStatsQueryResponse": {
"additionalProperties": false,
"properties": {
@@ -31578,6 +31681,114 @@
"required": ["category"],
"type": "object"
},
+ "MCPToolCategoryMapItem": {
+ "additionalProperties": false,
+ "description": "One tool paired with one $mcp_tool_category it was called under.",
+ "properties": {
+ "category": {
+ "type": "string"
+ },
+ "tool": {
+ "type": "string"
+ }
+ },
+ "required": ["tool", "category"],
+ "type": "object"
+ },
+ "MCPToolCategoryMapQuery": {
+ "additionalProperties": false,
+ "description": "Which categories each tool was called under. The intent clustering snapshot is precomputed and stores tool names without categories, so this is what lets that tab scope by category. A tool recategorised mid-window appears once per category, rather than one row silently winning.",
+ "properties": {
+ "dateRange": {
+ "$ref": "#/definitions/DateRange"
+ },
+ "kind": {
+ "const": "MCPToolCategoryMapQuery",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "response": {
+ "$ref": "#/definitions/MCPToolCategoryMapQueryResponse"
+ },
+ "tags": {
+ "$ref": "#/definitions/QueryLogTags"
+ },
+ "version": {
+ "description": "version of the node, used for schema migrations",
+ "type": "number"
+ }
+ },
+ "required": ["kind"],
+ "type": "object"
+ },
+ "MCPToolCategoryMapQueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "items": {
+ "$ref": "#/definitions/MCPToolCategoryMapItem"
+ },
+ "type": "array"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": ["results"],
+ "type": "object"
+ },
"MCPToolDailyStatItem": {
"additionalProperties": false,
"description": "One day of activity for a single MCP tool.",
@@ -36551,6 +36762,7 @@
"MCPToolQualityDailyStatsQuery",
"MCPToolCategoryCountsQuery",
"MCPToolCategoriesQuery",
+ "MCPToolCategoryMapQuery",
"MCPToolDescriptionsQuery",
"MCPToolSampleIntentsQuery",
"MCPToolNeighborsQuery",
@@ -46229,6 +46441,71 @@
"required": ["results"],
"type": "object"
},
+ {
+ "additionalProperties": false,
+ "properties": {
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "items": {
+ "$ref": "#/definitions/MCPToolCategoryMapItem"
+ },
+ "type": "array"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": ["results"],
+ "type": "object"
+ },
{
"additionalProperties": false,
"properties": {
@@ -46772,6 +47049,9 @@
{
"$ref": "#/definitions/MCPToolCategoriesQuery"
},
+ {
+ "$ref": "#/definitions/MCPToolCategoryMapQuery"
+ },
{
"$ref": "#/definitions/MCPToolDescriptionsQuery"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index d89534e3ee78..43ac18f80c21 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -204,6 +204,7 @@ export enum NodeKind {
MCPToolQualityDailyStatsQuery = 'MCPToolQualityDailyStatsQuery',
MCPToolCategoryCountsQuery = 'MCPToolCategoryCountsQuery',
MCPToolCategoriesQuery = 'MCPToolCategoriesQuery',
+ MCPToolCategoryMapQuery = 'MCPToolCategoryMapQuery',
MCPToolDescriptionsQuery = 'MCPToolDescriptionsQuery',
MCPToolSampleIntentsQuery = 'MCPToolSampleIntentsQuery',
MCPToolNeighborsQuery = 'MCPToolNeighborsQuery',
@@ -286,6 +287,7 @@ export type AnyDataNode =
| MCPToolQualityDailyStatsQuery
| MCPToolCategoryCountsQuery
| MCPToolCategoriesQuery
+ | MCPToolCategoryMapQuery
| MCPToolDescriptionsQuery
| MCPToolSampleIntentsQuery
| MCPToolNeighborsQuery
@@ -415,6 +417,7 @@ export type QuerySchema =
| MCPToolQualityDailyStatsQuery
| MCPToolCategoryCountsQuery
| MCPToolCategoriesQuery
+ | MCPToolCategoryMapQuery
| MCPToolDescriptionsQuery
| MCPToolSampleIntentsQuery
| MCPToolNeighborsQuery
@@ -3518,6 +3521,28 @@ export interface MCPToolCategoriesQuery extends DataNode<MCPToolCategoriesQueryR
export type CachedMCPToolCategoriesQueryResponse = CachedQueryResponse<MCPToolCategoriesQueryResponse>
+/** One tool paired with one $mcp_tool_category it was called under. */
+export interface MCPToolCategoryMapItem {
+ tool: string
+ category: string
+}
+
+export interface MCPToolCategoryMapQueryResponse extends AnalyticsQueryResponseBase {
+ results: MCPToolCategoryMapItem[]
+}
+
+/**
+ * Which categories each tool was called under. The intent clustering snapshot is precomputed and
+ * stores tool names without categories, so this is what lets that tab scope by category. A tool
+ * recategorised mid-window appears once per category, rather than one row silently winning.
+ */
+export interface MCPToolCategoryMapQuery extends DataNode<MCPToolCategoryMapQueryResponse> {
+ kind: NodeKind.MCPToolCategoryMapQuery
+ dateRange?: DateRange
+}
+
+export type CachedMCPToolCategoryMapQueryResponse = CachedQueryResponse<MCPToolCategoryMapQueryResponse>
+
/** One distinct description seen for a single MCP tool, with the last time it was reported. */
export interface MCPToolDescriptionItem {
description: string
diff --git a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
index 4bfe2b6e5fd7..50c03d806585 100644
--- a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
+++ b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
@@ -682,6 +682,12 @@ export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {
icon: IconPieChart,
inMenu: false,
},
+ [NodeKind.MCPToolCategoryMapQuery]: {
+ name: 'MCP tool categories by tool',
+ description: 'Which categories each tool belongs to, for the intent clustering scope selector.',
+ icon: IconPieChart,
+ inMenu: false,
+ },
}
export const INSIGHT_TYPES_METADATA: Record<InsightType, InsightTypeMetadata> = {
diff --git a/posthog/api/query.py b/posthog/api/query.py
index 09a8ba645b32..e5ad534330f1 100644
--- a/posthog/api/query.py
+++ b/posthog/api/query.py
@@ -180,6 +180,7 @@ _QUERY_KIND_SCOPES: dict[str, list[str]] = {
"MCPToolFailureOccurrencesQuery": ["query:read", "mcp_analytics:read"],
"MCPToolCallsAndErrorsQuery": ["query:read", "mcp_analytics:read"],
"MCPToolCallBreakdownQuery": ["query:read", "mcp_analytics:read"],
+ "MCPToolCategoryMapQuery": ["query:read", "mcp_analytics:read"],
}
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 3f267a0531da..f5372d370bbc 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -288,6 +288,7 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:
| NodeKind.MCP_TOOL_QUALITY_DAILY_STATS_QUERY
| NodeKind.MCP_TOOL_CATEGORY_COUNTS_QUERY
| NodeKind.MCP_TOOL_CATEGORIES_QUERY
+ | NodeKind.MCP_TOOL_CATEGORY_MAP_QUERY
| NodeKind.MCP_TOOL_DESCRIPTIONS_QUERY
| NodeKind.MCP_TOOL_SAMPLE_INTENTS_QUERY
| NodeKind.MCP_TOOL_NEIGHBORS_QUERY
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 73f753a847d3..481e25f47118 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -55,6 +55,7 @@ from posthog.schema import (
MCPToolCallsAndErrorsQuery,
MCPToolCategoriesQuery,
MCPToolCategoryCountsQuery,
+ MCPToolCategoryMapQuery,
MCPToolDailyStatsQuery,
MCPToolDescriptionsQuery,
MCPToolFailureOccurrencesQuery,
@@ -485,6 +486,7 @@ RunnableQueryNode = Union[
MCPToolQualityDailyStatsQuery,
MCPToolCategoryCountsQuery,
MCPToolCategoriesQuery,
+ MCPToolCategoryMapQuery,
MCPToolDescriptionsQuery,
MCPToolSampleIntentsQuery,
MCPToolNeighborsQuery,
@@ -1277,6 +1279,17 @@ def get_query_runner(
modifiers=modifiers,
user=user,
)
+ if kind == "MCPToolCategoryMapQuery":
+ from products.mcp_analytics.backend.facade.queries import MCPToolCategoryMapQueryRunner
+
+ return MCPToolCategoryMapQueryRunner(
+ query=cast(MCPToolCategoryMapQuery | dict[str, Any], query),
+ team=team,
+ timings=timings,
+ limit_context=limit_context,
+ modifiers=modifiers,
+ user=user,
+ )
if kind == "MCPToolDescriptionsQuery":
from products.mcp_analytics.backend.facade.queries import MCPToolDescriptionsQueryRunner
diff --git a/posthog/schema.py b/posthog/schema.py
index 20fc57753f3c..0cc9243e6436 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -1728,6 +1728,14 @@ class MCPToolCategoryItem(BaseModel):
category: str
+class MCPToolCategoryMapItem(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ category: str
+ tool: str
+
+
class MCPToolDescriptionItem(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -11939,6 +11947,64 @@ class CachedMCPToolCategoryCountsQueryResponse(BaseModel):
)
+class CachedMCPToolCategoryMapQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ cache_key: str
+ cache_target_age: AwareDatetime | None = None
+ calculation_trigger: str | None = Field(
+ default=None,
+ description=("What triggered the calculation of the query, leave empty if user/immediate"),
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ is_cached: bool
+ last_refresh: AwareDatetime
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ next_allowed_client_refresh: AwareDatetime
+ query_metadata: dict[str, Any] | None = None
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: list[MCPToolCategoryMapItem]
+ timezone: str
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
class CachedMCPToolDailyStatsQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -18016,6 +18082,53 @@ class MCPToolCategoryCountsQueryResponse(BaseModel):
)
+class MCPToolCategoryMapQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: list[MCPToolCategoryMapItem]
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
class MCPToolDailyStatsQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -23437,7 +23550,7 @@ class QueryResponseAlternative105(BaseModel):
resolved_date_range: ResolvedDateRangeResponse | None = Field(
default=None, description="The date range used for the query"
)
- results: list[MCPToolDescriptionItem]
+ results: list[MCPToolCategoryMapItem]
timings: list[QueryTiming] | None = Field(
default=None,
description=("Measured timings for different parts of the query generation process"),
@@ -23484,7 +23597,7 @@ class QueryResponseAlternative106(BaseModel):
resolved_date_range: ResolvedDateRangeResponse | None = Field(
default=None, description="The date range used for the query"
)
- results: list[MCPToolSampleIntentItem]
+ results: list[MCPToolDescriptionItem]
timings: list[QueryTiming] | None = Field(
default=None,
description=("Measured timings for different parts of the query generation process"),
@@ -23531,7 +23644,7 @@ class QueryResponseAlternative107(BaseModel):
resolved_date_range: ResolvedDateRangeResponse | None = Field(
default=None, description="The date range used for the query"
)
- results: list[MCPToolNeighborItem]
+ results: list[MCPToolSampleIntentItem]
timings: list[QueryTiming] | None = Field(
default=None,
description=("Measured timings for different parts of the query generation process"),
@@ -23556,6 +23669,53 @@ class QueryResponseAlternative107(BaseModel):
class QueryResponseAlternative108(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: list[MCPToolNeighborItem]
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
+class QueryResponseAlternative109(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -25934,6 +26094,18 @@ class MCPToolCategoryCountsQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+class MCPToolCategoryMapQuery(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ dateRange: DateRange | None = None
+ kind: Literal["MCPToolCategoryMapQuery"] = "MCPToolCategoryMapQuery"
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ response: MCPToolCategoryMapQueryResponse | None = None
+ tags: QueryLogTags | None = None
+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+
+
class MCPToolDailyStatsQuery(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -28692,6 +28864,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative106
| QueryResponseAlternative107
| QueryResponseAlternative108
+ | QueryResponseAlternative109
]
):
root: (
@@ -28800,6 +28973,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative106
| QueryResponseAlternative107
| QueryResponseAlternative108
+ | QueryResponseAlternative109
)
@@ -29769,6 +29943,7 @@ class HogQLAutocomplete(BaseModel):
| MCPToolQualityDailyStatsQuery
| MCPToolCategoryCountsQuery
| MCPToolCategoriesQuery
+ | MCPToolCategoryMapQuery
| MCPToolDescriptionsQuery
| MCPToolSampleIntentsQuery
| MCPToolNeighborsQuery
@@ -29882,6 +30057,7 @@ class HogQLMetadata(BaseModel):
| MCPToolQualityDailyStatsQuery
| MCPToolCategoryCountsQuery
| MCPToolCategoriesQuery
+ | MCPToolCategoryMapQuery
| MCPToolDescriptionsQuery
| MCPToolSampleIntentsQuery
| MCPToolNeighborsQuery
@@ -30023,6 +30199,7 @@ class MaxInsightContext(BaseModel):
| MCPToolQualityDailyStatsQuery
| MCPToolCategoryCountsQuery
| MCPToolCategoriesQuery
+ | MCPToolCategoryMapQuery
| MCPToolDescriptionsQuery
| MCPToolSampleIntentsQuery
| MCPToolNeighborsQuery
@@ -30160,6 +30337,7 @@ class QueryRequest(BaseModel):
| MCPToolQualityDailyStatsQuery
| MCPToolCategoryCountsQuery
| MCPToolCategoriesQuery
+ | MCPToolCategoryMapQuery
| MCPToolDescriptionsQuery
| MCPToolSampleIntentsQuery
| MCPToolNeighborsQuery
@@ -30289,6 +30467,7 @@ class QuerySchemaRoot(
| MCPToolQualityDailyStatsQuery
| MCPToolCategoryCountsQuery
| MCPToolCategoriesQuery
+ | MCPToolCategoryMapQuery
| MCPToolDescriptionsQuery
| MCPToolSampleIntentsQuery
| MCPToolNeighborsQuery
@@ -30388,6 +30567,7 @@ class QuerySchemaRoot(
| MCPToolQualityDailyStatsQuery
| MCPToolCategoryCountsQuery
| MCPToolCategoriesQuery
+ | MCPToolCategoryMapQuery
| MCPToolDescriptionsQuery
| MCPToolSampleIntentsQuery
| MCPToolNeighborsQuery
@@ -30492,6 +30672,7 @@ class QueryUpgradeRequest(BaseModel):
| MCPToolQualityDailyStatsQuery
| MCPToolCategoryCountsQuery
| MCPToolCategoriesQuery
+ | MCPToolCategoryMapQuery
| MCPToolDescriptionsQuery
| MCPToolSampleIntentsQuery
| MCPToolNeighborsQuery
@@ -30596,6 +30777,7 @@ class QueryUpgradeResponse(BaseModel):
| MCPToolQualityDailyStatsQuery
| MCPToolCategoryCountsQuery
| MCPToolCategoriesQuery
+ | MCPToolCategoryMapQuery
| MCPToolDescriptionsQuery
| MCPToolSampleIntentsQuery
| MCPToolNeighborsQuery
@@ -30886,6 +31068,7 @@ class VisualizationArtifactContent(BaseModel):
| MCPToolQualityDailyStatsQuery
| MCPToolCategoryCountsQuery
| MCPToolCategoriesQuery
+ | MCPToolCategoryMapQuery
| MCPToolDescriptionsQuery
| MCPToolSampleIntentsQuery
| MCPToolNeighborsQuery
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 34797ee1e6b9..c70e271c2728 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -3379,6 +3379,7 @@ class NodeKind(StrEnum):
MCP_TOOL_QUALITY_DAILY_STATS_QUERY = "MCPToolQualityDailyStatsQuery"
MCP_TOOL_CATEGORY_COUNTS_QUERY = "MCPToolCategoryCountsQuery"
MCP_TOOL_CATEGORIES_QUERY = "MCPToolCategoriesQuery"
+ MCP_TOOL_CATEGORY_MAP_QUERY = "MCPToolCategoryMapQuery"
MCP_TOOL_DESCRIPTIONS_QUERY = "MCPToolDescriptionsQuery"
MCP_TOOL_SAMPLE_INTENTS_QUERY = "MCPToolSampleIntentsQuery"
MCP_TOOL_NEIGHBORS_QUERY = "MCPToolNeighborsQuery"
diff --git a/products/mcp_analytics/backend/facade/queries.py b/products/mcp_analytics/backend/facade/queries.py
index 7c0587f0ce2f..0010a76399bd 100644
--- a/products/mcp_analytics/backend/facade/queries.py
+++ b/products/mcp_analytics/backend/facade/queries.py
@@ -13,6 +13,7 @@ from products.mcp_analytics.backend.hogql_queries.harness_breakdown import MCPHa
from products.mcp_analytics.backend.hogql_queries.tool_quality_tables import (
MCPToolCategoriesQueryRunner,
MCPToolCategoryCountsQueryRunner,
+ MCPToolCategoryMapQueryRunner,
MCPToolQualityDailyStatsQueryRunner,
MCPToolQualityRowsQueryRunner,
)
@@ -33,6 +34,7 @@ __all__ = [
"MCPToolCallsAndErrorsQueryRunner",
"MCPToolCategoriesQueryRunner",
"MCPToolCategoryCountsQueryRunner",
+ "MCPToolCategoryMapQueryRunner",
"MCPToolDailyStatsQueryRunner",
"MCPToolDescriptionsQueryRunner",
"MCPToolFailureOccurrencesQueryRunner",
diff --git a/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py b/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py
index 9e7246e9cba1..9fd9c1385a75 100644
--- a/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py
+++ b/products/mcp_analytics/backend/hogql_queries/tool_quality_tables.py
@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING
from posthog.schema import (
CachedMCPToolCategoriesQueryResponse,
CachedMCPToolCategoryCountsQueryResponse,
+ CachedMCPToolCategoryMapQueryResponse,
CachedMCPToolQualityDailyStatsQueryResponse,
CachedMCPToolQualityRowsQueryResponse,
MCPToolCategoriesQuery,
@@ -20,6 +21,9 @@ from posthog.schema import (
MCPToolCategoryCountsQuery,
MCPToolCategoryCountsQueryResponse,
MCPToolCategoryItem,
+ MCPToolCategoryMapItem,
+ MCPToolCategoryMapQuery,
+ MCPToolCategoryMapQueryResponse,
MCPToolQualityDailyStatItem,
MCPToolQualityDailyStatsQuery,
MCPToolQualityDailyStatsQueryResponse,
@@ -354,3 +358,73 @@ class MCPToolCategoriesQueryRunner(AnalyticsQueryRunner[MCPToolCategoriesQueryRe
return MCPToolCategoriesQueryResponse(
results=results, timings=response.timings, hogql=response.hogql, modifiers=self.modifiers
)
+
+
+class MCPToolCategoryMapQueryRunner(AnalyticsQueryRunner[MCPToolCategoryMapQueryResponse]):
+ query: MCPToolCategoryMapQuery
+ cached_response: CachedMCPToolCategoryMapQueryResponse
+
+ def validate_query_runner_access(self, user: "User") -> bool:
+ return validate_mcp_analytics_access(self.team, user)
+
+ @cached_property
+ def query_date_range(self) -> QueryDateRange:
+ return mcp_query_date_range(self.team, self.query.dateRange)
+
+ def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
+ where = ast.And(
+ exprs=[
+ parse_expr("event = {event}", placeholders={"event": ast.Constant(value=MCP_TOOL_CALL_EVENT)}),
+ parse_expr(
+ "timestamp >= {date_from}", placeholders={"date_from": self.query_date_range.date_from_as_hogql()}
+ ),
+ parse_expr(
+ "timestamp <= {date_to}", placeholders={"date_to": self.query_date_range.date_to_as_hogql()}
+ ),
+ parse_expr("properties.$mcp_tool_name IS NOT NULL"),
+ parse_expr("properties.$mcp_tool_name != ''"),
+ parse_expr("properties.$mcp_tool_category IS NOT NULL"),
+ parse_expr("properties.$mcp_tool_category != ''"),
+ ]
+ )
+ # A tool recategorised mid-window yields a row per category rather than one arbitrary
+ # winner, so the caller can decide. The limit sits well above MAX_TOOLS_IN_SNAPSHOT (300)
+ # so the map always covers every tool a snapshot can name.
+ return parse_select(
+ """
+ SELECT DISTINCT
+ toString(properties.$mcp_tool_name) AS tool,
+ toString(properties.$mcp_tool_category) AS category
+ FROM events
+ WHERE {where}
+ ORDER BY tool, category
+ LIMIT 2000
+ """,
+ placeholders={"where": where},
+ )
+
+ def _calculate(self) -> MCPToolCategoryMapQueryResponse:
+ with tags_context(
+ product=Product.MCP_ANALYTICS,
+ feature=Feature.QUERY,
+ team_id=self.team.id,
+ name="mcp_tool_category_map_query",
+ ):
+ response = execute_hogql_query(
+ query=self.to_query(),
+ team=self.team,
+ user=self.user,
+ query_type="mcp_tool_category_map_query",
+ timings=self.timings,
+ modifiers=self.modifiers,
+ limit_context=self.limit_context,
+ )
+
+ results = [
+ MCPToolCategoryMapItem(tool=str(row[0] or ""), category=str(row[1] or ""))
+ for row in (response.results or [])
+ if row[0] and row[1]
+ ]
+ return MCPToolCategoryMapQueryResponse(
+ results=results, timings=response.timings, hogql=response.hogql, modifiers=self.modifiers
+ )
diff --git a/products/mcp_analytics/backend/tests/test_dashboard_series.py b/products/mcp_analytics/backend/tests/test_dashboard_series.py
index ad8709c95c6a..12102d869ec5 100644
--- a/products/mcp_analytics/backend/tests/test_dashboard_series.py
+++ b/products/mcp_analytics/backend/tests/test_dashboard_series.py
@@ -239,7 +239,7 @@ class TestMCPDashboardSeriesGate(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTes
@parameterized.expand(
[
(kind, scopes, expected_status)
- for kind in ("MCPToolCallsAndErrorsQuery", "MCPToolCallBreakdownQuery")
+ for kind in ("MCPToolCallsAndErrorsQuery", "MCPToolCallBreakdownQuery", "MCPToolCategoryMapQuery")
for scopes, expected_status in (
(["query:read"], 403),
(["mcp_analytics:read"], 403),
diff --git a/products/mcp_analytics/backend/tests/test_tool_quality_tables.py b/products/mcp_analytics/backend/tests/test_tool_quality_tables.py
index 833eca830819..28bfb53883ad 100644
--- a/products/mcp_analytics/backend/tests/test_tool_quality_tables.py
+++ b/products/mcp_analytics/backend/tests/test_tool_quality_tables.py
@@ -11,6 +11,7 @@ from posthog.schema import (
IntervalType,
MCPToolCategoriesQuery,
MCPToolCategoryCountsQuery,
+ MCPToolCategoryMapQuery,
MCPToolQualityDailyStatsQuery,
MCPToolQualityRowsQuery,
)
@@ -20,6 +21,7 @@ from posthog.rbac.user_access_control import UserAccessControlError
from products.mcp_analytics.backend.hogql_queries.tool_quality_tables import (
MCPToolCategoriesQueryRunner,
MCPToolCategoryCountsQueryRunner,
+ MCPToolCategoryMapQueryRunner,
MCPToolQualityDailyStatsQueryRunner,
MCPToolQualityRowsQueryRunner,
)
@@ -152,6 +154,40 @@ class TestMCPToolCategoriesQueryRunner(_MCPAnalyticsTeamScopedTestMixin, Clickho
assert categories == ["Data", "Insights"]
+class TestMCPToolCategoryMapQueryRunner(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):
+ def test_pairs_are_deduped_and_skip_rows_missing_either_side(self) -> None:
+ _emit(self.team, tool_name="query_run", category="Insights")
+ _emit(self.team, tool_name="query_run", category="Insights")
+ _emit(self.team, tool_name="docs_search", category="Data")
+ # No category: the tool is real but unclassifiable, so it must not appear at all
+ # rather than land under an empty-string category the scope selector would show.
+ _emit(self.team, tool_name="orphan_tool", category=None)
+ flush_persons_and_events()
+
+ runner = MCPToolCategoryMapQueryRunner(
+ query=MCPToolCategoryMapQuery(dateRange=DateRange(date_from="-7d")),
+ team=self.team,
+ )
+ pairs = [(r.tool, r.category) for r in runner.calculate().results]
+
+ assert pairs == [("docs_search", "Data"), ("query_run", "Insights")]
+
+ def test_recategorised_tool_keeps_both_categories(self) -> None:
+ # Filtering by either category has to keep finding the tool, so both rows survive
+ # instead of one arbitrarily winning.
+ _emit(self.team, tool_name="query_run", category="Insights")
+ _emit(self.team, tool_name="query_run", category="SQL")
+ flush_persons_and_events()
+
+ runner = MCPToolCategoryMapQueryRunner(
+ query=MCPToolCategoryMapQuery(dateRange=DateRange(date_from="-7d")),
+ team=self.team,
+ )
+ pairs = [(r.tool, r.category) for r in runner.calculate().results]
+
+ assert pairs == [("query_run", "Insights"), ("query_run", "SQL")]
+
+
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 flag
@@ -162,6 +198,7 @@ class TestMCPToolQualityGate(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMix
(MCPToolQualityDailyStatsQueryRunner, MCPToolQualityDailyStatsQuery()),
(MCPToolCategoryCountsQueryRunner, MCPToolCategoryCountsQuery()),
(MCPToolCategoriesQueryRunner, MCPToolCategoriesQuery()),
+ (MCPToolCategoryMapQueryRunner, MCPToolCategoryMapQuery()),
]
)
def test_runner_gates_on_mcp_analytics_flag(self, runner_cls: Any, query: Any) -> None:
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
index 808d1391c214..26e86740c7a8 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
@@ -179,6 +179,16 @@ const DAILY_STATS = [
const CATEGORY_LIST = [['Data exploration'], ['Insights'], ['Dashboards'], ['Cohorts']]
+// One category per tool in the clustering fixture. Deliberately selective: `SQL` and
+// `Insights` each cover two of the three clusters, so picking one visibly narrows the list
+// rather than leaving it whole.
+const TOOL_CATEGORY_MAP = [
+ ['execute-sql', 'SQL'],
+ ['insight-create', 'Insights'],
+ ['query-trends', 'Product analytics'],
+ ['read-data-schema', 'Data schema'],
+]
+
const CATEGORY_COUNTS = [
['Data exploration', 2240],
['Insights', 950],
@@ -646,6 +656,9 @@ const meta: Meta = {
if (body?.query?.kind === 'MCPToolCategoriesQuery') {
return [200, { results: CATEGORY_LIST.map((r) => ({ category: r[0] })) }]
}
+ if (body?.query?.kind === 'MCPToolCategoryMapQuery') {
+ return [200, { results: TOOL_CATEGORY_MAP.map((r) => ({ tool: r[0], category: r[1] })) }]
+ }
if (body?.query?.kind === 'MCPToolCategoryCountsQuery') {
return [200, { results: CATEGORY_COUNTS.map((r) => ({ category: r[0], calls: r[1] })) }]
}
diff --git a/products/mcp_analytics/frontend/clustering/ClusterDetailPanel.tsx b/products/mcp_analytics/frontend/clustering/ClusterDetailPanel.tsx
index 1e5ee60dfc5b..881c4c94c1af 100644
--- a/products/mcp_analytics/frontend/clustering/ClusterDetailPanel.tsx
+++ b/products/mcp_analytics/frontend/clustering/ClusterDetailPanel.tsx
@@ -18,7 +18,7 @@ import { humanFriendlyNumber } from 'lib/utils/numbers'
import type { MCPIntentClusterApi } from '../generated/api.schemas'
import { ClusterJourneySankey } from './ClusterJourneySankey'
import { EntropyBadge } from './EntropyBadge'
-import { mcpClusteringLogic } from './mcpClusteringLogic'
+import { clusterCategories, mcpClusteringLogic } from './mcpClusteringLogic'
function SectionLabel({ children, hint }: { children: string; hint?: string }): JSX.Element {
return (
@@ -35,7 +35,7 @@ function SectionLabel({ children, hint }: { children: string; hint?: string }):
* sections scroll — the selected label is the only thing tying the two panes together.
*/
export function ClusterDetailPanel(): JSX.Element {
- const { selectedCluster, clusters } = useValues(mcpClusteringLogic)
+ const { selectedCluster, clusters, categoriesByTool } = useValues(mcpClusteringLogic)
if (!selectedCluster) {
return (
@@ -49,7 +49,10 @@ export function ClusterDetailPanel(): JSX.Element {
return (
<div className="flex h-full min-h-0 flex-col overflow-hidden rounded border border-primary bg-surface-primary">
- <ClusterDetailHeader cluster={selectedCluster} />
+ <ClusterDetailHeader
+ cluster={selectedCluster}
+ categories={clusterCategories(selectedCluster, categoriesByTool)}
+ />
<div className="flex-1 min-h-0 overflow-y-auto flex flex-col gap-4 p-4" data-quill>
<IntentsSection cluster={selectedCluster} />
<RoutingSection cluster={selectedCluster} />
@@ -63,7 +66,13 @@ export function ClusterDetailPanel(): JSX.Element {
)
}
-function ClusterDetailHeader({ cluster }: { cluster: MCPIntentClusterApi }): JSX.Element {
+function ClusterDetailHeader({
+ cluster,
+ categories,
+}: {
+ cluster: MCPIntentClusterApi
+ categories: string[]
+}): JSX.Element {
const worstTool = [...cluster.tool_distribution].sort((a, b) => b.error_rate_pct - a.error_rate_pct)[0]
return (
@@ -71,6 +80,15 @@ function ClusterDetailHeader({ cluster }: { cluster: MCPIntentClusterApi }): JSX
<div className="flex flex-col gap-1">
<span className="text-xs uppercase text-muted font-medium">Selected intent group</span>
<h3 className="text-lg font-semibold leading-tight m-0">{cluster.label}</h3>
+ {categories.length > 0 ? (
+ <div className="flex flex-wrap items-center gap-1">
+ {categories.map((category) => (
+ <Badge key={category} variant="info">
+ {category}
+ </Badge>
+ ))}
+ </div>
+ ) : null}
</div>
<div className="flex flex-wrap items-center gap-2">
<EntropyBadge entropy={cluster.routing_entropy} />
diff --git a/products/mcp_analytics/frontend/clustering/ClusterListPanel.tsx b/products/mcp_analytics/frontend/clustering/ClusterListPanel.tsx
index f231750408c0..3feab28cff8c 100644
--- a/products/mcp_analytics/frontend/clustering/ClusterListPanel.tsx
+++ b/products/mcp_analytics/frontend/clustering/ClusterListPanel.tsx
@@ -28,14 +28,25 @@ const SORT_OPTIONS: { value: ClusterSortKey; label: string }[] = [
]
export function ClusterListPanel(): JSX.Element {
- const { filteredClusters, selectedClusterId, sortKey, toolSearch, clusterFilter, totalClusterCount, clusters } =
- useValues(mcpClusteringLogic)
- const { selectCluster, setSortKey, setToolSearch, setClusterFilter } = useActions(mcpClusteringLogic)
+ const {
+ filteredClusters,
+ selectedClusterId,
+ sortKey,
+ toolSearch,
+ clusterFilter,
+ selectedCategories,
+ totalClusterCount,
+ clusters,
+ } = useValues(mcpClusteringLogic)
+ const { selectCluster, setSortKey, setToolSearch, setClusterFilter, setSelectedCategories } =
+ useActions(mcpClusteringLogic)
// Resolved once here: the row component renders per cluster and the theme hook is not free.
const theme = useChartTheme()
const barColor = seriesColor(theme, PRIMARY_SERIES)
- const isNarrowed = clusterFilter !== 'all' || toolSearch.trim() !== ''
+ // The category scope narrows this list too, so the count has to include it — otherwise
+ // "3 of 30 shown" sits next to a Clear button that only restores some of the 30.
+ const isNarrowed = clusterFilter !== 'all' || toolSearch.trim() !== '' || selectedCategories.length > 0
return (
<div className="flex h-full min-h-0 flex-col overflow-hidden rounded border border-primary bg-surface-primary">
@@ -84,6 +95,7 @@ export function ClusterListPanel(): JSX.Element {
onClick={() => {
setClusterFilter('all')
setToolSearch('')
+ setSelectedCategories([])
}}
data-attr="mcp-clustering-clear-filters"
>
diff --git a/products/mcp_analytics/frontend/clustering/DiscoveryScatter.tsx b/products/mcp_analytics/frontend/clustering/DiscoveryScatter.tsx
index a6e53d42ac91..fab847a0dc4f 100644
--- a/products/mcp_analytics/frontend/clustering/DiscoveryScatter.tsx
+++ b/products/mcp_analytics/frontend/clustering/DiscoveryScatter.tsx
@@ -36,7 +36,7 @@ function radius(callCount: number, maxCalls: number): number {
* undersells what the tool does.
*/
export function DiscoveryScatter(): JSX.Element | null {
- const { scatterPoints, tools, fitMedian, discoveryMedian } = useValues(mcpClusteringLogic)
+ const { scatterPoints, scopedTools, fitMedian, discoveryMedian } = useValues(mcpClusteringLogic)
const theme = useChartTheme()
if (scatterPoints.length === 0) {
@@ -56,7 +56,9 @@ export function DiscoveryScatter(): JSX.Element | null {
const maxCalls = Math.max(...scatterPoints.map((p) => p.callCount))
const plotX: [number, number] = [PAD.left, WIDTH - PAD.right]
const plotY: [number, number] = [HEIGHT - PAD.bottom, PAD.top]
- const unplotted = tools.length - scatterPoints.length
+ // Counted against the scoped tools the plot draws from, not every tool in the snapshot,
+ // or a category filter leaves the footnote claiming more omissions than there are tools.
+ const unplotted = scopedTools.length - scatterPoints.length
const bubbleColor = seriesColor(theme, PRIMARY_SERIES)
return (
@@ -162,8 +164,8 @@ export function DiscoveryScatter(): JSX.Element | null {
</svg>
{unplotted > 0 ? (
<span className="text-[10px] text-muted">
- {unplotted} tool{unplotted === 1 ? ' is' : 's are'} not plotted: they lack a captured description or
- enough advertised sessions to measure discovery.
+ {unplotted} tool{unplotted === 1 ? '' : 's'} not plotted: no captured description, or too few
+ advertised sessions to measure discovery.
</span>
) : null}
</div>
diff --git a/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx b/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx
index 8cca1b08ea5f..d5cc994f9c61 100644
--- a/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx
+++ b/products/mcp_analytics/frontend/clustering/MCPAnalyticsClustering.tsx
@@ -3,6 +3,7 @@ import { useActions, useValues } from 'kea'
import { IconRefresh, IconSparkles } from '@posthog/icons'
import { Button, Skeleton, Spinner } from '@posthog/quill-primitives'
+import { TagsCombobox } from 'lib/components/Scenes/TagsCombobox'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
@@ -40,6 +41,34 @@ function ViewToggle(): JSX.Element {
)
}
+/**
+ * Scopes both views to tools in the chosen categories. Hidden until a category is worth
+ * showing: an always-visible empty dropdown would read as broken on a project that never
+ * sets $mcp_tool_category. A selection carried in from the url counts, so a failed map
+ * load still leaves the user a way to see and clear it.
+ */
+function CategoryScope(): JSX.Element | null {
+ const { categoryScopeOptions, selectedCategories } = useValues(mcpClusteringLogic)
+ const { setSelectedCategories } = useActions(mcpClusteringLogic)
+
+ if (categoryScopeOptions.length === 0) {
+ return null
+ }
+
+ return (
+ <div className="w-full max-w-[420px] sm:w-[320px]">
+ <TagsCombobox
+ options={categoryScopeOptions}
+ value={selectedCategories}
+ onChange={setSelectedCategories}
+ placeholder="All categories"
+ allowCustomValues={false}
+ dataAttr="mcp-clustering-category-scope"
+ />
+ </div>
+ )
+}
+
function StatusRow(): JSX.Element | null {
const { snapshot, isComputing } = useValues(mcpClusteringLogic)
const { recompute } = useActions(mcpClusteringLogic)
@@ -194,7 +223,10 @@ export function MCPAnalyticsClustering(): JSX.Element {
return (
<div className="flex flex-col gap-4" data-quill>
<StatusRow />
- <ViewToggle />
+ <div className="flex flex-wrap items-center gap-3">
+ <ViewToggle />
+ <CategoryScope />
+ </div>
{viewMode === 'tools' ? <ToolsView /> : <IntentsView />}
</div>
)
diff --git a/products/mcp_analytics/frontend/clustering/ToolDetailPanel.tsx b/products/mcp_analytics/frontend/clustering/ToolDetailPanel.tsx
index 0d7bb7b62dd8..0f6663a01f12 100644
--- a/products/mcp_analytics/frontend/clustering/ToolDetailPanel.tsx
+++ b/products/mcp_analytics/frontend/clustering/ToolDetailPanel.tsx
@@ -5,7 +5,7 @@ import { ToolIntentDetail } from './ToolIntentDetail'
/** The selected tool's intents and competitors, pinned beside the tool list. */
export function ToolDetailPanel(): JSX.Element {
- const { selectedTool, clusters } = useValues(mcpClusteringLogic)
+ const { selectedTool, clusters, categoriesByTool } = useValues(mcpClusteringLogic)
if (!selectedTool) {
return (
@@ -19,7 +19,11 @@ export function ToolDetailPanel(): JSX.Element {
// Scrolls both ways: the intents table carries a competitor column that a narrow
// pane can't fit, and clipping it silently would hide the comparison it exists for.
<div className="h-full min-h-0 overflow-auto">
- <ToolIntentDetail tool={selectedTool} clusters={clusters} />
+ <ToolIntentDetail
+ tool={selectedTool}
+ clusters={clusters}
+ categories={categoriesByTool[selectedTool.tool] ?? []}
+ />
</div>
)
}
diff --git a/products/mcp_analytics/frontend/clustering/ToolIntentDetail.tsx b/products/mcp_analytics/frontend/clustering/ToolIntentDetail.tsx
index bbb94142f70d..9ca96b2f13e3 100644
--- a/products/mcp_analytics/frontend/clustering/ToolIntentDetail.tsx
+++ b/products/mcp_analytics/frontend/clustering/ToolIntentDetail.tsx
@@ -44,11 +44,17 @@ export function ToolIntentDetail({
tool,
clusters,
showToolLink = true,
+ categories = [],
}: {
tool: MCPToolPivotApi
/** The snapshot's clusters — the pivot's entries carry only ids and join against these. */
clusters: readonly MCPIntentClusterApi[]
showToolLink?: boolean
+ /**
+ * Categories the tool is called under. Passed in rather than read from the clustering
+ * logic, because the tool detail scene renders this without that logic mounted.
+ */
+ categories?: string[]
}): JSX.Element {
const switches = collectSwitches(tool.tool, clusters)
const clusterRows = toolClusterRows(tool, clusters)
@@ -66,6 +72,15 @@ export function ToolIntentDetail({
) : (
<h3 className="text-lg font-semibold leading-tight font-mono">{tool.tool}</h3>
)}
+ {categories.length > 0 ? (
+ <div className="flex flex-wrap items-center gap-1">
+ {categories.map((category) => (
+ <Badge key={category} variant="info">
+ {category}
+ </Badge>
+ ))}
+ </div>
+ ) : null}
</div>
<div className="flex flex-wrap items-center gap-2 shrink-0">
<Badge variant="default">{humanFriendlyNumber(tool.call_count)} calls</Badge>
diff --git a/products/mcp_analytics/frontend/clustering/ToolPivotTable.tsx b/products/mcp_analytics/frontend/clustering/ToolPivotTable.tsx
index a811e5354bd2..52362887ca15 100644
--- a/products/mcp_analytics/frontend/clustering/ToolPivotTable.tsx
+++ b/products/mcp_analytics/frontend/clustering/ToolPivotTable.tsx
@@ -89,6 +89,15 @@ export function ToolPivotTable(): JSX.Element {
</TableRow>
</TableHeader>
<TableBody>
+ {sortedTools.length === 0 ? (
+ <TableRow>
+ {/* A category can name tools this snapshot never saw, so an empty
+ table is reachable and has to say why rather than show bare headers. */}
+ <TableCell colSpan={7} className="p-4 text-center text-sm text-muted">
+ No tools match the current category scope or search.
+ </TableCell>
+ </TableRow>
+ ) : null}
{sortedTools.map((tool) => (
<TableRow
key={tool.tool}
diff --git a/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.test.ts b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.test.ts
index 1513745bb4f6..54b6647b2c7e 100644
--- a/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.test.ts
+++ b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.test.ts
@@ -1,6 +1,8 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import api from 'lib/api'
+
import { urls } from '~/scenes/urls'
import { initKeaTests } from '~/test/init'
@@ -15,6 +17,7 @@ import type {
import {
type ClusterFilter,
type RouteShape,
+ clusterCategories,
fitDomain,
mcpClusteringLogic,
routeShape,
@@ -30,6 +33,7 @@ jest.mock('../generated/api', () => ({
}))
const mockRetrieve = mcpAnalyticsIntentClustersRetrieve as jest.Mock
+const mockQuery = api.query as jest.Mock
function cluster(id: number, overrides: Partial<MCPIntentClusterApi> = {}): MCPIntentClusterApi {
return {
@@ -305,6 +309,300 @@ function pivot(clusters: MCPToolPivotClusterEntryApi[]): MCPToolPivotApi {
}
}
+// Categories live on the events, not in the precomputed snapshot, so they arrive as a
+// separate tool→category map that every view joins against by tool name.
+describe('mcpClusteringLogic category scope', () => {
+ let logic: ReturnType<typeof mcpClusteringLogic.build>
+
+ // `a` and `c` are Data, `b` is Insights, and `loner` deliberately has no category row.
+ const CATEGORY_MAP = [
+ { tool: 'a', category: 'Data' },
+ { tool: 'b', category: 'Insights' },
+ { tool: 'c', category: 'Data' },
+ ]
+
+ // Distinct call counts so the pivot's volume ordering is explicit rather than
+ // resting on sort stability.
+ const named = (tool: string, callCount: number): MCPToolPivotApi => ({
+ ...pivot([]),
+ tool,
+ call_count: callCount,
+ })
+
+ const SCOPED_SNAPSHOT: MCPIntentClusterSnapshotApi = {
+ ...SNAPSHOT,
+ tools: [named('a', 30), named('b', 20), named('loner', 10)],
+ tool_overlaps: [
+ {
+ tool_a: 'a',
+ tool_b: 'b',
+ contested_calls: 10,
+ sessions_with_both: 2,
+ sessions_with_either: 5,
+ top_cluster_id: SPREAD_ID,
+ },
+ {
+ tool_a: 'loner',
+ tool_b: 'stranger',
+ contested_calls: 3,
+ sessions_with_both: 1,
+ sessions_with_either: 4,
+ top_cluster_id: SPREAD_ID,
+ },
+ ],
+ }
+
+ beforeEach(async () => {
+ jest.clearAllMocks()
+ initKeaTests()
+ mockRetrieve.mockResolvedValue(SCOPED_SNAPSHOT)
+ mockQuery.mockResolvedValue({ results: CATEGORY_MAP })
+ router.actions.push(urls.mcpAnalyticsIntentClustering())
+ logic = mcpClusteringLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ // Selecting nothing has to mean everything. An empty selection that produced an empty
+ // scope set instead of "no scope" would blank the whole tab on first load.
+ it('shows every cluster and tool while no category is selected', () => {
+ expect(logic.values.selectedCategories).toEqual([])
+ expect(logic.values.scopedClusters).toHaveLength(SHAPED_CLUSTERS.length)
+ expect(logic.values.scopedTools.map((t) => t.tool)).toEqual(['a', 'b', 'loner'])
+ })
+
+ // Matching only the cluster's top tool would be an easy simplification, and it would
+ // silently drop clusters whose secondary tool is the one in the chosen category.
+ it('keeps a cluster when any tool it routes to is in the category, not just its top one', () => {
+ logic.actions.setSelectedCategories(['Insights'])
+
+ // `b` is second by volume in clusters 1 and 4, and third in cluster 3.
+ expect(logic.values.scopedClusters.map((c) => c.id)).toEqual([CONCENTRATED_ID, SPREAD_ID, MIXED_ID])
+ })
+
+ it('drops clusters routing to no tool in the selected categories', () => {
+ logic.actions.setSelectedCategories(['Insights'])
+
+ const ids = logic.values.scopedClusters.map((c) => c.id)
+ expect(ids).not.toContain(NO_TOOLS_ID)
+ expect(ids).not.toContain(FAILING_ID)
+ })
+
+ // A tool the map never mentions belongs to no category, so a live filter must exclude
+ // it — keeping it visible would contradict the scope the user picked.
+ it('excludes an uncategorized tool once a category is selected', () => {
+ expect(logic.values.scopedTools.map((t) => t.tool)).toContain('loner')
+
+ logic.actions.setSelectedCategories(['Data'])
+
+ expect(logic.values.scopedTools.map((t) => t.tool)).toEqual(['a'])
+ })
+
+ // Either side in scope, not both: a contested pair is worth seeing precisely when the
+ // competitor sits in another category.
+ it('keeps a contested pair when only one side is in scope', () => {
+ logic.actions.setSelectedCategories(['Insights'])
+
+ expect(logic.values.toolOverlaps.map((o) => [o.tool_a, o.tool_b])).toEqual([['a', 'b']])
+ })
+
+ it('moves the selection into the scoped set when the category excludes it', () => {
+ logic.actions.selectTool('loner')
+
+ logic.actions.setSelectedCategories(['Data'])
+
+ expect(logic.values.selectedToolName).toBe('a')
+ })
+
+ // A shared `?categories=…&cluster=…` link applies the selection before the category map
+ // has loaded, so the scope isn't known yet and the reconcile has nothing to work with.
+ // Once the map arrives the selection must move into the scoped list — otherwise the list
+ // is scoped but the detail pane sits on a cluster the scope excludes, with no row lit up.
+ it('reconciles an out-of-scope url selection once the category map arrives', async () => {
+ logic.unmount()
+ router.actions.push(urls.mcpAnalyticsIntentClustering(), {
+ categories: 'Data',
+ cluster: String(NO_TOOLS_ID),
+ })
+ logic = mcpClusteringLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ // NO_TOOLS_ID routes to no Data tool, so it is never in the Data scope.
+ const scopedIds = logic.values.scopedClusters.map((c) => c.id)
+ expect(scopedIds).not.toContain(NO_TOOLS_ID)
+ expect(scopedIds).toContain(logic.values.selectedClusterId)
+ })
+
+ // The 30-day category window is wider than the snapshot's, so a category can name only
+ // tools the snapshot never carried. Its scope then matches nothing, and the selection
+ // must clear rather than strand the detail pane on a cluster the scope excludes.
+ it('clears the selection when the selected category matches nothing in the snapshot', async () => {
+ logic.unmount()
+ mockQuery.mockResolvedValue({ results: [...CATEGORY_MAP, { tool: 'ghost', category: 'Ghost' }] })
+ router.actions.push(urls.mcpAnalyticsIntentClustering())
+ logic = mcpClusteringLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setSelectedCategories(['Ghost'])
+
+ expect(logic.values.scopedClusters).toEqual([])
+ expect(logic.values.scopedTools).toEqual([])
+ expect(logic.values.selectedClusterId).toBeNull()
+ expect(logic.values.selectedToolName).toBeNull()
+ })
+
+ // A recompute reloads the snapshot but not the category map, so the reload's own reconcile
+ // has to honour the active scope. Reconciling against the unscoped snapshot would fall back
+ // to the highest-volume cluster overall, which can sit outside the scope — stranding the
+ // detail there while the list shows the scoped subset.
+ it('falls back to the scoped top, not the snapshot top, when a recompute drops the selection', async () => {
+ logic.actions.setSelectedCategories(['Insights'])
+ logic.actions.selectCluster(CONCENTRATED_ID)
+ expect(logic.values.selectedClusterId).toBe(CONCENTRATED_ID)
+
+ // Drop the selected cluster. The new unscoped top is cluster 2, which routes only to Data
+ // tools, so an unscoped fallback would land the detail outside the Insights scope.
+ const survivors = SHAPED_CLUSTERS.filter((c) => c.id !== CONCENTRATED_ID)
+ mockRetrieve.mockResolvedValue({ ...SCOPED_SNAPSHOT, clusters: survivors })
+ logic.actions.loadSnapshot()
+ await expectLogic(logic).toFinishAllListeners()
+
+ // SPREAD_ID is the highest-volume Insights cluster left, so the reconcile picks it.
+ expect(logic.values.selectedClusterId).toBe(SPREAD_ID)
+ expect(logic.values.scopedClusters.map((c) => c.id)).toContain(logic.values.selectedClusterId)
+ })
+
+ // The map is a slower query than the stored snapshot and can also fail or return nothing.
+ // A category carried in from a bookmarked url must not scope every view down to nothing when
+ // there is no map to scope against — the views render unscoped until (if ever) the map lands.
+ it('applies no scope when a category is selected but the map load fails', async () => {
+ logic.unmount()
+ mockQuery.mockRejectedValue(new Error('clickhouse timeout'))
+ router.actions.push(urls.mcpAnalyticsIntentClustering(), { categories: 'Data' })
+ logic = mcpClusteringLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.selectedCategories).toEqual(['Data'])
+ expect(logic.values.categoryMap).toEqual([])
+ expect(logic.values.toolsInScope).toBeNull()
+ expect(logic.values.scopedClusters).toHaveLength(SHAPED_CLUSTERS.length)
+ expect(logic.values.scopedTools.map((t) => t.tool)).toEqual(['a', 'b', 'loner'])
+ })
+
+ // Requesting the map sets a flag that stops urlToAction refetching on every click. Left set
+ // through a failure, one blip makes the tab unfilterable for the session; cleared without a
+ // bound, a failing ClickHouse query lands behind every row the user clicks.
+ it('retries a failed category map once, then stops', async () => {
+ logic.unmount()
+ mockQuery.mockRejectedValue(new Error('clickhouse timeout'))
+ router.actions.push(urls.mcpAnalyticsIntentClustering())
+ const before = mockQuery.mock.calls.length
+ logic = mcpClusteringLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockQuery.mock.calls.length - before).toBe(1)
+
+ logic.actions.selectCluster(SPREAD_ID)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockQuery.mock.calls.length - before).toBe(2)
+
+ logic.actions.selectTool('b')
+ router.actions.push(urls.mcpAnalyticsIntentClustering(), { view: 'tools' })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockQuery.mock.calls.length - before).toBe(2)
+ })
+
+ // The selector hides itself when no tool carries a category, which is also what a failed
+ // map load looks like. Offering only what the map knows would hide a category arriving from
+ // a bookmarked url behind no control at all, leaving no way to see or clear it.
+ it('keeps a url category clearable when the map load fails', async () => {
+ logic.unmount()
+ mockQuery.mockRejectedValue(new Error('clickhouse timeout'))
+ router.actions.push(urls.mcpAnalyticsIntentClustering(), { categories: 'Data' })
+ logic = mcpClusteringLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.availableCategories).toEqual([])
+ expect(logic.values.categoryScopeOptions).toEqual(['Data'])
+ })
+
+ // Tool names come from events, so a call named `__proto__` or `constructor` can reach the
+ // category map. A plain-object lookup resolves those to inherited values and throws on the
+ // `.includes` check, taking the whole view down; the map has to be prototype-free.
+ it('handles tool names that collide with object prototype keys', async () => {
+ logic.unmount()
+ mockQuery.mockResolvedValue({
+ results: [
+ { tool: '__proto__', category: 'Data' },
+ { tool: '__proto__', category: 'Insights' },
+ { tool: 'constructor', category: 'Data' },
+ ],
+ })
+ router.actions.push(urls.mcpAnalyticsIntentClustering())
+ logic = mcpClusteringLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.categoriesByTool['__proto__']).toEqual(['Data', 'Insights'])
+ expect(logic.values.categoriesByTool['constructor']).toEqual(['Data'])
+ })
+
+ // A single category comes back from the url as a bare string rather than an array,
+ // which would otherwise scope to the individual characters of its name.
+ it.each([
+ ['one category', 'Insights', ['Insights']],
+ ['several categories', ['Data', 'Insights'], ['Data', 'Insights']],
+ ])('round-trips %s through the url', async (_label, param, expected) => {
+ logic.unmount()
+ router.actions.push(urls.mcpAnalyticsIntentClustering(), { categories: param })
+ logic = mcpClusteringLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.selectedCategories).toEqual(expected)
+ })
+
+ it('offers only categories that some tool actually belongs to', () => {
+ expect(logic.values.availableCategories).toEqual(['Data', 'Insights'])
+ })
+
+ // Selecting a cluster rewrites the url, which re-runs urlToAction. Refetching the map
+ // on every click would put a ClickHouse query behind each row.
+ it('fetches the category map once however often the url is rewritten', () => {
+ const before = mockQuery.mock.calls.length
+
+ logic.actions.selectCluster(SPREAD_ID)
+ logic.actions.selectTool('b')
+ router.actions.push(urls.mcpAnalyticsIntentClustering(), { view: 'tools' })
+
+ expect(mockQuery.mock.calls.length).toBe(before)
+ })
+
+ // The dashboard tab connects to this logic purely for cluster counts, so mounting it
+ // there must not fire the category query.
+ it('does not fetch the category map when mounted away from the clustering tab', async () => {
+ logic.unmount()
+ jest.clearAllMocks()
+ mockRetrieve.mockResolvedValue(SCOPED_SNAPSHOT)
+ router.actions.push(urls.mcpAnalyticsDashboard())
+
+ logic = mcpClusteringLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockQuery).not.toHaveBeenCalled()
+ expect(logic.values.availableCategories).toEqual([])
+ })
+})
+
describe('mcpClusteringLogic helpers', () => {
// A cluster with no tool distribution used to fall through to a `?? 100` default and
// be counted as the best-routed shape there is, inflating the headline number.
@@ -408,6 +706,24 @@ describe('mcpClusteringLogic helpers', () => {
// The pivot no longer ships the cluster's label with every entry, so a broken
// join renders the intents table with blank rows instead of intent text.
+ // Two tools in one category used to mean the badge rendered twice, which React also
+ // flags as a duplicate key.
+ it('clusterCategories lists each category once, busiest tool first', () => {
+ const c = cluster(1, {
+ tool_distribution: dist([
+ ['b', 60],
+ ['a', 30],
+ ['c', 10],
+ ]),
+ })
+
+ expect(clusterCategories(c, { a: ['Data'], b: ['Insights'], c: ['Data'] })).toEqual(['Insights', 'Data'])
+ })
+
+ it('clusterCategories is empty when none of the cluster tools are mapped', () => {
+ expect(clusterCategories(cluster(1, { tool_distribution: dist([['a', 100]]) }), {})).toEqual([])
+ })
+
it('toolClusterRows joins each entry to the cluster it points at', () => {
const rows = toolClusterRows(pivot([entry({ cluster_id: 3 }), entry({ cluster_id: 1 })]), [
cluster(1),
diff --git a/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts
index b2ad09f6b8c3..68db7adea61e 100644
--- a/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts
+++ b/products/mcp_analytics/frontend/clustering/mcpClusteringLogic.ts
@@ -4,8 +4,10 @@ import { actionToUrl, router, urlToAction } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
+import api from 'lib/api'
import { teamLogic } from 'scenes/teamLogic'
+import { MCPToolCategoryMapItem, NodeKind } from '~/queries/schema/schema-general'
import { urls } from '~/scenes/urls'
import { mcpAnalyticsIntentClustersRecompute, mcpAnalyticsIntentClustersRetrieve } from '../generated/api'
@@ -30,6 +32,15 @@ const EMPTY_SNAPSHOT: MCPIntentClusterSnapshotApi = {
const POLL_INTERVAL_MS = 3000
+// Categories are read over a fixed window rather than the snapshot's own lookback, which is
+// 7 days by default but configurable per run. A wider window can only add tools the snapshot
+// never names — harmless — while a narrower one would drop tools from the filter entirely.
+const CATEGORY_LOOKBACK = '-30d'
+// A failed map load has to be retryable, or one blip leaves the tab unfilterable for the
+// session. It cannot retry freely either: urlToAction re-runs on every selection, so an
+// unbounded re-arm would refetch on each click. One retry, then the tab stays unscoped.
+const MAX_CATEGORY_MAP_ATTEMPTS = 2
+
/** Segments drawn on a cluster row's routing bar before the rest is aggregated. */
export const ROUTING_BAR_SEGMENTS = 3
@@ -170,6 +181,25 @@ const FIT_DOMAIN_MIN_SPAN = 0.1
const FIT_DOMAIN_PADDING = 0.1
/** Padded x-domain around the observed fits, with a floor on the span so a single point can't collapse it. */
+/**
+ * Every category the cluster's tools belong to, in call-volume order so the busiest
+ * category leads. A cluster routing across categories is the interesting case — it means
+ * one goal is being served by tools the catalog files under different headings.
+ */
+export function clusterCategories(cluster: MCPIntentClusterApi, categoriesByTool: Record<string, string[]>): string[] {
+ const seen = new Set<string>()
+ const ordered: string[] = []
+ for (const entry of cluster.tool_distribution) {
+ for (const category of categoriesByTool[entry.tool] ?? []) {
+ if (!seen.has(category)) {
+ seen.add(category)
+ ordered.push(category)
+ }
+ }
+ }
+ return ordered
+}
+
export function fitDomain(fits: number[]): [number, number] {
if (fits.length === 0) {
return [0, 1]
@@ -192,6 +222,13 @@ function median(values: number[]): number | null {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpClusteringLogicValues {
currentProjectId: number | string // teamLogic
+ availableCategories: string[]
+ categoriesByTool: Record<string, string[]>
+ categoryMap: MCPToolCategoryMapItem[]
+ categoryMapAttempts: number
+ categoryMapLoading: boolean
+ categoryMapRequested: boolean
+ categoryScopeOptions: string[]
clusterFilter: ClusterFilter
clusters: readonly MCPIntentClusterApi[]
discoveryMedian: number | null
@@ -202,7 +239,10 @@ export interface mcpClusteringLogicValues {
isComputing: boolean
routeShapeCounts: RouteShapeCounts
scatterPoints: ScatterPoint[]
+ scopedClusters: MCPIntentClusterApi[]
+ scopedTools: readonly MCPToolPivotApi[]
searchedClusters: MCPIntentClusterApi[]
+ selectedCategories: string[]
selectedCluster: MCPIntentClusterApi | null
selectedClusterId: number | null
selectedTool: MCPToolPivotApi | null
@@ -216,6 +256,7 @@ export interface mcpClusteringLogicValues {
toolSearch: string
toolSortKey: ToolSortKey
tools: readonly MCPToolPivotApi[]
+ toolsInScope: Set<string> | null
totalClusterCount: number
viewMode: ClusteringViewMode
}
@@ -225,6 +266,21 @@ export interface mcpClusteringLogicActions {
keepSelectionVisible: () => {
value: true
}
+ loadCategoryMap: () => any
+ loadCategoryMapFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadCategoryMapSuccess: (
+ categoryMap: MCPToolCategoryMapItem[],
+ payload?: any
+ ) => {
+ categoryMap: MCPToolCategoryMapItem[]
+ payload?: any
+ }
loadSnapshot: () => any
loadSnapshotFailure: (
error: string,
@@ -255,6 +311,9 @@ export interface mcpClusteringLogicActions {
setClusterFilter: (clusterFilter: ClusterFilter) => {
clusterFilter: ClusterFilter
}
+ setSelectedCategories: (categories: string[]) => {
+ categories: string[]
+ }
setSortKey: (sortKey: ClusterSortKey) => {
sortKey: ClusterSortKey
}
@@ -295,21 +354,33 @@ export interface mcpClusteringLogicMeta {
__keaTypeGenInternalSelectorTypes: {
clusters: (snapshot: MCPIntentClusterSnapshotApi) => readonly MCPIntentClusterApi[]
tools: (snapshot: MCPIntentClusterSnapshotApi) => readonly MCPToolPivotApi[]
- toolOverlaps: (snapshot: MCPIntentClusterSnapshotApi) => readonly MCPToolOverlapApi[]
+ categoriesByTool: (categoryMap: MCPToolCategoryMapItem[]) => Record<string, string[]>
+ availableCategories: (categoryMap: MCPToolCategoryMapItem[]) => string[]
+ categoryScopeOptions: (availableCategories: string[], selectedCategories: string[]) => string[]
+ toolsInScope: (categoryMap: MCPToolCategoryMapItem[], selectedCategories: string[]) => Set<string> | null
+ toolOverlaps: (
+ snapshot: MCPIntentClusterSnapshotApi,
+ toolsInScope: Set<string> | null
+ ) => readonly MCPToolOverlapApi[]
hasToolPivot: (tools: readonly MCPToolPivotApi[]) => boolean
sortedClusters: (clusters: readonly MCPIntentClusterApi[], sortKey: ClusterSortKey) => MCPIntentClusterApi[]
- searchedClusters: (sortedClusters: MCPIntentClusterApi[], toolSearch: string) => MCPIntentClusterApi[]
+ scopedClusters: (
+ sortedClusters: MCPIntentClusterApi[],
+ toolsInScope: Set<string> | null
+ ) => MCPIntentClusterApi[]
+ searchedClusters: (scopedClusters: MCPIntentClusterApi[], toolSearch: string) => MCPIntentClusterApi[]
filteredClusters: (
searchedClusters: MCPIntentClusterApi[],
clusterFilter: ClusterFilter
) => MCPIntentClusterApi[]
+ scopedTools: (tools: readonly MCPToolPivotApi[], toolsInScope: Set<string> | null) => readonly MCPToolPivotApi[]
sortedTools: (
- tools: readonly MCPToolPivotApi[],
+ scopedTools: readonly MCPToolPivotApi[],
toolSortKey: ToolSortKey,
toolSearch: string
) => MCPToolPivotApi[]
selectedTool: (tools: readonly MCPToolPivotApi[], selectedToolName: string | null) => MCPToolPivotApi | null
- scatterPoints: (tools: readonly MCPToolPivotApi[]) => ScatterPoint[]
+ scatterPoints: (scopedTools: readonly MCPToolPivotApi[]) => ScatterPoint[]
fitMedian: (scatterPoints: ScatterPoint[]) => number | null
discoveryMedian: (scatterPoints: ScatterPoint[]) => number | null
totalClusterCount: (snapshot: MCPIntentClusterSnapshotApi) => number
@@ -343,6 +414,7 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
setViewMode: (viewMode: ClusteringViewMode) => ({ viewMode }),
setToolSearch: (toolSearch: string) => ({ toolSearch }),
setClusterFilter: (clusterFilter: ClusterFilter) => ({ clusterFilter }),
+ setSelectedCategories: (categories: string[]) => ({ categories }),
keepSelectionVisible: true,
recompute: true,
startPolling: true,
@@ -369,6 +441,23 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
},
},
],
+ // The snapshot stores tool names but no categories, so the mapping is fetched
+ // separately and joined by tool name. Keeping it out of the snapshot means an
+ // existing snapshot gains category filtering without being recomputed.
+ categoryMap: [
+ [] as MCPToolCategoryMapItem[],
+ {
+ loadCategoryMap: async (): Promise<MCPToolCategoryMapItem[]> => {
+ const response = (await api.query({
+ kind: NodeKind.MCPToolCategoryMapQuery,
+ dateRange: { date_from: CATEGORY_LOOKBACK },
+ })) as { results?: MCPToolCategoryMapItem[] } | undefined
+ // An absent map costs only the filter, so it must not take the page down
+ // with it — every view still renders, just unscoped.
+ return response?.results ?? []
+ },
+ },
+ ],
})),
reducers({
selectedClusterId: [
@@ -413,6 +502,30 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
setClusterFilter: (_, { clusterFilter }) => clusterFilter,
},
],
+ selectedCategories: [
+ [] as string[],
+ {
+ setSelectedCategories: (_, { categories }) => categories,
+ },
+ ],
+ // Every selection writes the url back, which re-runs urlToAction. Without this the
+ // map would refetch on each click. Set on request, not on success, so an in-flight
+ // load is not started twice.
+ categoryMapRequested: [
+ false,
+ {
+ loadCategoryMap: () => true,
+ // Re-arm on failure so a later navigation can retry; the attempt count is
+ // what stops that from becoming a request per click.
+ loadCategoryMapFailure: () => false,
+ },
+ ],
+ categoryMapAttempts: [
+ 0,
+ {
+ loadCategoryMap: (state: number) => state + 1,
+ },
+ ],
}),
selectors({
clusters: [
@@ -423,9 +536,70 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
(s) => [s.snapshot],
(snapshot: MCPIntentClusterSnapshotApi): readonly MCPToolPivotApi[] => snapshot.tools ?? [],
],
+ // Every category a tool has been called under. A tool recategorised mid-window
+ // belongs to both, so filtering by either keeps finding it.
+ categoriesByTool: [
+ (s) => [s.categoryMap],
+ (categoryMap: MCPToolCategoryMapItem[]): Record<string, string[]> => {
+ // Tool names come from events, so a call named `__proto__` or `constructor`
+ // would resolve `byTool[tool]` to an inherited value and throw on `.includes`.
+ // A prototype-free map keys those names as ordinary data.
+ const byTool: Record<string, string[]> = Object.create(null)
+ for (const { tool, category } of categoryMap) {
+ const existing = byTool[tool]
+ if (!existing) {
+ byTool[tool] = [category]
+ } else if (!existing.includes(category)) {
+ existing.push(category)
+ }
+ }
+ return byTool
+ },
+ ],
+ // Drawn from the tool map rather than the full category vocabulary, so the selector
+ // never offers a category that no tool in the data belongs to.
+ availableCategories: [
+ (s) => [s.categoryMap],
+ (categoryMap: MCPToolCategoryMapItem[]): string[] =>
+ Array.from(new Set(categoryMap.map((row) => row.category))).sort((a, b) => a.localeCompare(b)),
+ ],
+ // What the scope selector offers, which is not the same as what the map knows. A
+ // category carried in from the url survives a failed map load, and the selector is
+ // the only way to clear it, so the selection is always offered back even when the
+ // map contributed nothing.
+ categoryScopeOptions: [
+ (s) => [s.availableCategories, s.selectedCategories],
+ (availableCategories: string[], selectedCategories: string[]): string[] =>
+ Array.from(new Set([...availableCategories, ...selectedCategories])).sort((a, b) => a.localeCompare(b)),
+ ],
+ // Null rather than an empty set means "no scope, show everything". Two cases return it:
+ // nothing is selected, or there is no map to scope against — still loading, the query
+ // failed, or the project sent no $mcp_tool_category in the window. Without the second
+ // guard a category carried in from the url would scope every view down to nothing while
+ // the map is absent, and the selector hides itself (no categories to offer), leaving no
+ // way to clear it. A real scope only exists once the map has data, so this renders
+ // unscoped meanwhile, matching the loader's "an absent map costs only the filter" intent.
+ toolsInScope: [
+ (s) => [s.categoryMap, s.selectedCategories],
+ (categoryMap: MCPToolCategoryMapItem[], selectedCategories: string[]): Set<string> | null => {
+ if (selectedCategories.length === 0 || categoryMap.length === 0) {
+ return null
+ }
+ const wanted = new Set(selectedCategories)
+ return new Set(categoryMap.filter((row) => wanted.has(row.category)).map((row) => row.tool))
+ },
+ ],
+ // Either side in scope, not both: the point of a contested pair is spotting a tool
+ // competing with one it shouldn't, and that competitor is often in another category.
toolOverlaps: [
- (s) => [s.snapshot],
- (snapshot: MCPIntentClusterSnapshotApi): readonly MCPToolOverlapApi[] => snapshot.tool_overlaps ?? [],
+ (s) => [s.snapshot, s.toolsInScope],
+ (snapshot: MCPIntentClusterSnapshotApi, toolsInScope: Set<string> | null): readonly MCPToolOverlapApi[] => {
+ const overlaps = snapshot.tool_overlaps ?? []
+ if (!toolsInScope) {
+ return overlaps
+ }
+ return overlaps.filter((o) => toolsInScope.has(o.tool_a) || toolsInScope.has(o.tool_b))
+ },
],
// Snapshots computed before the per-call pipeline have no tool sections;
// the tools view offers a recompute instead of rendering empty tables.
@@ -449,17 +623,31 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
}
},
],
+ // A cluster is in scope when any tool it routes to is, mirroring how the tool
+ // search matches. Scoping sits ahead of the search so the scorecards, the search
+ // and the list all count the same population.
+ scopedClusters: [
+ (s) => [s.sortedClusters, s.toolsInScope],
+ (sortedClusters: MCPIntentClusterApi[], toolsInScope: Set<string> | null): MCPIntentClusterApi[] => {
+ if (!toolsInScope) {
+ return sortedClusters
+ }
+ return sortedClusters.filter((cluster) =>
+ cluster.tool_distribution.some((entry) => toolsInScope.has(entry.tool))
+ )
+ },
+ ],
// The tool search narrows the population both the scorecards count and the
// list filter read. Splitting it out keeps the two in lockstep: the scorecards
// count shapes within the searched set, and each card's filter draws from it.
searchedClusters: [
- (s) => [s.sortedClusters, s.toolSearch],
- (sortedClusters: MCPIntentClusterApi[], toolSearch: string): MCPIntentClusterApi[] => {
+ (s) => [s.scopedClusters, s.toolSearch],
+ (scopedClusters: MCPIntentClusterApi[], toolSearch: string): MCPIntentClusterApi[] => {
const query = toolSearch.trim().toLowerCase()
if (!query) {
- return sortedClusters
+ return scopedClusters
}
- return sortedClusters.filter((cluster) =>
+ return scopedClusters.filter((cluster) =>
cluster.tool_distribution.some((e) => e.tool.toLowerCase().includes(query))
)
},
@@ -475,11 +663,22 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
})
},
],
+ // A tool with no category row is out of scope once a filter is on: it belongs to
+ // none of the selected categories, so keeping it would contradict the filter.
+ scopedTools: [
+ (s) => [s.tools, s.toolsInScope],
+ (tools: readonly MCPToolPivotApi[], toolsInScope: Set<string> | null): readonly MCPToolPivotApi[] =>
+ toolsInScope ? tools.filter((tool) => toolsInScope.has(tool.tool)) : tools,
+ ],
sortedTools: [
- (s) => [s.tools, s.toolSortKey, s.toolSearch],
- (tools: readonly MCPToolPivotApi[], toolSortKey: ToolSortKey, toolSearch: string): MCPToolPivotApi[] => {
+ (s) => [s.scopedTools, s.toolSortKey, s.toolSearch],
+ (
+ scopedTools: readonly MCPToolPivotApi[],
+ toolSortKey: ToolSortKey,
+ toolSearch: string
+ ): MCPToolPivotApi[] => {
const query = toolSearch.trim().toLowerCase()
- const arr = tools.filter((tool) => !query || tool.tool.toLowerCase().includes(query))
+ const arr = scopedTools.filter((tool) => !query || tool.tool.toLowerCase().includes(query))
switch (toolSortKey) {
case 'contested':
return arr.sort((a, b) => (b.contested_score ?? -1) - (a.contested_score ?? -1))
@@ -502,9 +701,9 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
},
],
scatterPoints: [
- (s) => [s.tools],
- (tools: readonly MCPToolPivotApi[]): ScatterPoint[] =>
- tools.flatMap((tool) => {
+ (s) => [s.scopedTools],
+ (scopedTools: readonly MCPToolPivotApi[]): ScatterPoint[] =>
+ scopedTools.flatMap((tool) => {
const fit = weightedMeanFit(tool)
if (fit === null || tool.discovery_rate_pct === null) {
return []
@@ -588,20 +787,25 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
} else {
actions.stopPolling()
}
- // Fill or reconcile the selection: fall back to the highest-traffic cluster
- // when nothing is selected, and also when the current selection is absent from
- // this snapshot. A `?cluster=` link or a recompute that reassigned ids would
- // otherwise leave the detail pane empty with the fallback suppressed.
- const clusterPresent = snapshot.clusters.some((c) => c.id === values.selectedClusterId)
- if (!clusterPresent && snapshot.clusters.length > 0) {
- const top = [...snapshot.clusters].sort((a, b) => b.call_count - a.call_count)[0]
- actions.selectCluster(top.id)
- }
- const tools = snapshot.tools ?? []
- const toolPresent = tools.some((t) => t.tool === values.selectedToolName)
- if (!toolPresent && tools.length > 0) {
- const topTool = [...tools].sort((a, b) => b.call_count - a.call_count)[0]
- actions.selectTool(topTool.tool)
+ // Fill or reconcile the selection against the scoped list. A `?cluster=` link, a
+ // recompute that reassigned ids, or an active category scope can all leave the
+ // selection pointing at a cluster or tool this snapshot no longer shows; follow
+ // the list so the detail pane never lands on one the list omits.
+ actions.keepSelectionVisible()
+ },
+ // The category map arrives after the url has already applied the selection, so the
+ // scope is only known now. Reconcile against it: without this the list becomes scoped
+ // while the selection can sit outside it, leaving the detail pane on an excluded item.
+ loadCategoryMapSuccess: () => {
+ actions.keepSelectionVisible()
+ },
+ // Only once the retry is spent: a toast on the first failure would fire twice, and
+ // silence would leave a category in the url quietly doing nothing.
+ loadCategoryMapFailure: () => {
+ if (values.categoryMapAttempts >= MAX_CATEGORY_MAP_ATTEMPTS) {
+ lemonToast.error(
+ 'Could not load tool categories, so category filtering is unavailable. Refresh the page to try again.'
+ )
}
},
triggerRecomputeSuccess: ({ snapshot }) => {
@@ -641,13 +845,44 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
setToolSearch: () => {
actions.keepSelectionVisible()
},
+ setSelectedCategories: () => {
+ actions.keepSelectionVisible()
+ },
keepSelectionVisible: () => {
- const { filteredClusters, selectedClusterId, sortedTools, selectedToolName } = values
- if (filteredClusters.length > 0 && !filteredClusters.some((c) => c.id === selectedClusterId)) {
- actions.selectCluster(filteredClusters[0].id)
+ const {
+ filteredClusters,
+ selectedClusterId,
+ clusters,
+ scopedClusters,
+ sortedTools,
+ selectedToolName,
+ tools,
+ scopedTools,
+ categoryMapLoading,
+ } = values
+ // Reconcile each selection against the list its pane renders: move it to the top of
+ // the list when the current one is no longer there, and clear it only when the scope
+ // genuinely excludes every row the snapshot carries. While the category map is still
+ // loading the scope isn't known, so an empty scoped list means "not ready" rather
+ // than "excluded" — leave the selection be so a deep-linked cluster or tool survives
+ // until its data arrives. A plain search or filter that matches nothing keeps the
+ // selection too; only a category scope that names none of the snapshot's tools clears
+ // it, so the detail pane can never describe an item the scope hides.
+ const clusterScopeExcludesAll = !categoryMapLoading && clusters.length > 0 && scopedClusters.length === 0
+ if (!filteredClusters.some((c) => c.id === selectedClusterId)) {
+ if (filteredClusters.length > 0) {
+ actions.selectCluster(filteredClusters[0].id)
+ } else if (clusterScopeExcludesAll && selectedClusterId !== null) {
+ actions.selectCluster(null)
+ }
}
- if (sortedTools.length > 0 && !sortedTools.some((t) => t.tool === selectedToolName)) {
- actions.selectTool(sortedTools[0].tool)
+ const toolScopeExcludesAll = !categoryMapLoading && tools.length > 0 && scopedTools.length === 0
+ if (!sortedTools.some((t) => t.tool === selectedToolName)) {
+ if (sortedTools.length > 0) {
+ actions.selectTool(sortedTools[0].tool)
+ } else if (toolScopeExcludesAll && selectedToolName !== null) {
+ actions.selectTool(null)
+ }
}
},
})),
@@ -669,16 +904,26 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
delete searchParams[key]
}
}
+ // An array, not a joined string, so a category containing a comma survives the trip.
+ if (values.selectedCategories.length > 0) {
+ searchParams.categories = values.selectedCategories
+ } else {
+ delete searchParams.categories
+ }
return [currentLocation.pathname, searchParams, currentLocation.hashParams, { replace: true }]
}
return {
selectCluster: syncUrl,
selectTool: syncUrl,
setViewMode: syncUrl,
+ setSelectedCategories: syncUrl,
}
}),
urlToAction(({ actions, values }) => ({
[urls.mcpAnalyticsIntentClustering()]: (_, searchParams) => {
+ if (!values.categoryMapRequested && values.categoryMapAttempts < MAX_CATEGORY_MAP_ATTEMPTS) {
+ actions.loadCategoryMap()
+ }
const viewMode: ClusteringViewMode = searchParams.view === 'tools' ? 'tools' : 'intents'
if (viewMode !== values.viewMode) {
actions.setViewMode(viewMode)
@@ -694,6 +939,15 @@ export const mcpClusteringLogic = kea<mcpClusteringLogicType>([
if (typeof searchParams.tool === 'string' && searchParams.tool !== values.selectedToolName) {
actions.selectTool(searchParams.tool)
}
+ // A single category arrives as a bare string rather than a one-element array.
+ const categories = Array.isArray(searchParams.categories)
+ ? searchParams.categories.map(String)
+ : typeof searchParams.categories === 'string' && searchParams.categories
+ ? [searchParams.categories]
+ : []
+ if (JSON.stringify(categories) !== JSON.stringify(values.selectedCategories)) {
+ actions.setSelectedCategories(categories)
+ }
},
})),
afterMount(({ actions }) => {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index fe01afcb9341..ddc7b0640de2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -43152,6 +43152,44 @@ export namespace Schemas {
version?: number | null;
}
+ export interface MCPToolCategoryMapItem {
+ category: string;
+ tool: string;
+ }
+
+ export interface MCPToolCategoryMapQueryResponse {
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatus | null;
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponse | null;
+ results: MCPToolCategoryMapItem[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
+ }
+
+ export interface MCPToolCategoryMapQuery {
+ dateRange?: DateRange | null;
+ kind?: 'MCPToolCategoryMapQuery';
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ response?: MCPToolCategoryMapQueryResponse | null;
+ tags?: QueryLogTags | null;
+ /** version of the node, used for schema migrations */
+ version?: number | null;
+ }
+
export interface MCPToolDescriptionItem {
description: string;
last_seen: string;
@@ -43314,7 +43352,7 @@ export namespace Schemas {
query: string;
response?: HogQLMetadataResponse | null;
/** Query within which "expr" and "template" are validated. Defaults to "select * from events" */
- sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
tags?: QueryLogTags | null;
/** Variables to be subsituted into the query */
variables?: HogQLMetadataVariables;
@@ -43340,7 +43378,7 @@ export namespace Schemas {
query: string;
response?: HogQLAutocompleteResponse | null;
/** Query in whose context to validate. */
- sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
/** Start position of the editor word */
startPosition: number;
tags?: QueryLogTags | null;
@@ -67869,7 +67907,7 @@ export namespace Schemas {
* ```
*
* For more details on HogQL queries, see the [PostHog HogQL documentation](/docs/hogql#api-access). */
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
/** Whether results should be calculated sync or async, and how much to rely on the cache:
* - `'blocking'` - calculate synchronously (returning only when the query is done), UNLESS there are very fresh results in the cache
* - `'async'` - kick off background calculation (returning immediately with a query status), UNLESS there are very fresh results in the cache
@@ -70299,7 +70337,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: MCPToolDescriptionItem[];
+ results: MCPToolCategoryMapItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -70321,7 +70359,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: MCPToolSampleIntentItem[];
+ results: MCPToolDescriptionItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -70343,7 +70381,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: MCPToolNeighborItem[];
+ results: MCPToolSampleIntentItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -70353,6 +70391,28 @@ export namespace Schemas {
}
export interface QueryResponseAlternative108 {
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatus | null;
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponse | null;
+ results: MCPToolNeighborItem[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
+ }
+
+ export interface QueryResponseAlternative109 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -70374,18 +70434,18 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative12 | QueryResponseAlternative13 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | unknown | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106 | QueryResponseAlternative107 | QueryResponseAlternative108;
+ export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative12 | QueryResponseAlternative13 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | unknown | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106 | QueryResponseAlternative107 | QueryResponseAlternative108 | QueryResponseAlternative109;
export interface QueryStatusResponse {
query_status: QueryStatus;
}
export interface QueryUpgradeRequest {
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
}
export interface QueryUpgradeResponse {
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingFingerprintProjectionQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolCategoryMapQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
}
export interface QuotaResourceLimit {