:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): scope MCP analytics tool quality by tool category (#62596)
Daniel Visca0aa2979e65d5
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsxindex 5d8e80af2618..7a885a699b45 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx@@ -1,5 +1,6 @@import { useActions, useValues } from 'kea'+import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'import { Link } from 'lib/lemon-ui/Link'import { Tooltip } from 'lib/lemon-ui/Tooltip'import { humanFriendlyDuration } from 'lib/utils'@@ -53,6 +54,40 @@ function errorRateClass(rate: number): string {return 'text-danger'}+function CategoryScopeBar(): JSX.Element {+ const { availableCategories, availableCategoriesLoading, selectedCategories, scopeShare } =+ useValues(mcpAnalyticsToolQualityLogic)+ const { setSelectedCategories } = useActions(mcpAnalyticsToolQualityLogic)++ const hasScope = selectedCategories.length > 0+ const sharePct = scopeShare.pct === null ? null : Math.round(scopeShare.pct * 10) / 10++ return (+ <div className="flex flex-wrap items-center gap-3">+ <div className="min-w-[280px] flex-1 max-w-[480px]">+ <LemonInputSelect+ mode="multiple"+ value={selectedCategories}+ onChange={setSelectedCategories}+ options={availableCategories.map((category) => ({ key: category, label: category }))}+ loading={availableCategoriesLoading}+ placeholder="All categories"+ data-attr="mcp-tool-quality-category-scope"+ />+ </div>+ {hasScope && sharePct !== null ? (+ <Tooltip+ title={`${scopeShare.inScope.toLocaleString()} of ${scopeShare.total.toLocaleString()} MCP tool calls in the last 7 days were in the selected categories`}+ >+ <div className="text-sm text-muted">+ <span className="font-semibold text-default">{sharePct}%</span> of MCP usage (last 7d)+ </div>+ </Tooltip>+ ) : null}+ </div>+ )+}+export function MCPAnalyticsToolQuality(): JSX.Element {const { toolQualityQuery, toolQualitySort, topToolsQuery, errorTrendQuery, durationTrendQuery } =useValues(mcpAnalyticsToolQualityLogic)@@ -60,6 +95,7 @@ export function MCPAnalyticsToolQuality(): JSX.Element {return (<div className="flex flex-col gap-4">+ <CategoryScopeBar /><div className="grid grid-cols-1 lg:grid-cols-3 gap-4"><div className="bg-bg-light border rounded p-2 min-h-[260px] flex flex-col"><div className="text-muted text-xs font-medium uppercase mb-2 px-2 pt-1">Top tools by calls</div>diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.tsindex de6b992fd001..938b3297d51f 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts@@ -1,13 +1,59 @@-import { actions, kea, path, reducers, selectors } from 'kea'+import { actions, afterMount, kea, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { hogqlQuery } from '~/queries/query'import { DataTableNode, InsightVizNode, NodeKind } from '~/queries/schema/schema-general'-import { BaseMathType, ChartDisplayType, PropertyMathType } from '~/types'+import { hogql } from '~/queries/utils'+import {+ type AnyPropertyFilter,+ BaseMathType,+ ChartDisplayType,+ PropertyFilterType,+ PropertyMathType,+ PropertyOperator,+} from '~/types'import toolQualityQueryTemplate from '../backend/templates/tool_quality.sql?raw'import type { mcpAnalyticsToolQualityLogicType } from './mcpAnalyticsToolQualityLogicType'+// `$mcp_tool_category` is stamped onto every mcp_tool_call event by the producer+// (PostHog's MCP server from its catalog; external servers via the SDK). We read+// the available categories straight from the data so the scope selector works for+// any project's taxonomy without a hardcoded tool→category map.+const CATEGORIES_QUERY = hogql`+SELECT DISTINCT toString(properties.$mcp_tool_category) AS category+FROM events+WHERE event = 'mcp_tool_call'+ AND timestamp >= now() - INTERVAL 30 DAY+ AND properties.$mcp_tool_category IS NOT NULL+ AND properties.$mcp_tool_category != ''+ORDER BY category+`++// Per-category call counts over a fixed 7-day window powering the "share of MCP+// usage" headline. Rows with an empty category count toward the total but not the+// in-scope numerator, so uncategorized traffic dilutes the share as expected.+const CATEGORY_COUNTS_QUERY = hogql`+SELECT toString(properties.$mcp_tool_category) AS category, count() AS calls+FROM events+WHERE event = 'mcp_tool_call'+ AND timestamp >= now() - INTERVAL 7 DAY+GROUP BY category+`++export interface CategoryCount {+ category: string+ calls: number+}++export interface ScopeShare {+ inScope: number+ total: number+ pct: number | null+}+export type SortDirection = 'ASC' | 'DESC'export interface SortState {@@ -29,6 +75,7 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypeactions({setToolQualitySort: (column: string, direction: SortDirection) => ({ column, direction }),setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),+ setSelectedCategories: (categories: string[]) => ({ categories }),}),reducers({@@ -44,12 +91,69 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypesetDateFilter: (_, { dateFrom, dateTo }): DateFilter => ({ dateFrom, dateTo }),},],+ selectedCategories: [+ [] as string[],+ {+ setSelectedCategories: (_, { categories }): string[] => categories,+ },+ ],+ }),++ loaders({+ availableCategories: [+ [] as string[],+ {+ loadAvailableCategories: async (): Promise<string[]> => {+ const response = await hogqlQuery(CATEGORIES_QUERY)+ return ((response?.results as unknown[][]) ?? []).map((r) => String(r[0] ?? '')).filter(Boolean)+ },+ },+ ],+ categoryCounts: [+ [] as CategoryCount[],+ {+ loadCategoryCounts: async (): Promise<CategoryCount[]> => {+ const response = await hogqlQuery(CATEGORY_COUNTS_QUERY)+ return ((response?.results as unknown[][]) ?? []).map((r) => ({+ category: String(r[0] ?? ''),+ calls: Number(r[1] ?? 0),+ }))+ },+ },+ ],}),selectors({+ // Event property filter applied to every query so the whole tab scopes to+ // the selected categories. Empty selection means "all categories".+ categoryProperties: [+ (s) => [s.selectedCategories],+ (selectedCategories: string[]): AnyPropertyFilter[] =>+ selectedCategories.length > 0+ ? [+ {+ key: '$mcp_tool_category',+ value: selectedCategories,+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+ },+ ]+ : [],+ ],+ scopeShare: [+ (s) => [s.categoryCounts, s.selectedCategories],+ (categoryCounts: CategoryCount[], selectedCategories: string[]): ScopeShare => {+ const total = categoryCounts.reduce((acc, row) => acc + row.calls, 0)+ const selected = new Set(selectedCategories)+ const inScope = categoryCounts+ .filter((row) => selected.has(row.category))+ .reduce((acc, row) => acc + row.calls, 0)+ return { inScope, total, pct: total > 0 ? (inScope / total) * 100 : null }+ },+ ],toolQualityQuery: [- (s) => [s.dateFilter, s.toolQualitySort],- (dateFilter: DateFilter, sort: SortState): DataTableNode => {+ (s) => [s.dateFilter, s.toolQualitySort, s.categoryProperties],+ (dateFilter: DateFilter, sort: SortState, categoryProperties: AnyPropertyFilter[]): DataTableNode => {const query = toolQualityQueryTemplate.replace('__ORDER_BY__', sort.column).replace('__ORDER_DIRECTION__', sort.direction)@@ -64,6 +168,7 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypedate_from: dateFilter.dateFrom,date_to: dateFilter.dateTo,},+ ...(categoryProperties.length > 0 ? { properties: categoryProperties } : {}),},},columns: [@@ -91,8 +196,8 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType},],topToolsQuery: [- (s) => [s.dateFilter],- (dateFilter: DateFilter): InsightVizNode => ({+ (s) => [s.dateFilter, s.categoryProperties],+ (dateFilter: DateFilter, categoryProperties: AnyPropertyFilter[]): InsightVizNode => ({kind: NodeKind.InsightVizNode,source: {kind: NodeKind.TrendsQuery,@@ -104,6 +209,7 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypemath: BaseMathType.TotalCount,},],+ properties: categoryProperties,breakdownFilter: {breakdown_type: 'event',breakdown: '$mcp_tool_name',@@ -124,8 +230,8 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType}),],errorTrendQuery: [- (s) => [s.dateFilter],- (dateFilter: DateFilter): InsightVizNode => ({+ (s) => [s.dateFilter, s.categoryProperties],+ (dateFilter: DateFilter, categoryProperties: AnyPropertyFilter[]): InsightVizNode => ({kind: NodeKind.InsightVizNode,source: {kind: NodeKind.TrendsQuery,@@ -137,6 +243,7 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypemath: BaseMathType.TotalCount,},],+ properties: categoryProperties,breakdownFilter: {breakdown_type: 'event',breakdown: '$mcp_is_error',@@ -152,8 +259,8 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType}),],durationTrendQuery: [- (s) => [s.dateFilter],- (dateFilter: DateFilter): InsightVizNode => ({+ (s) => [s.dateFilter, s.categoryProperties],+ (dateFilter: DateFilter, categoryProperties: AnyPropertyFilter[]): InsightVizNode => ({kind: NodeKind.InsightVizNode,source: {kind: NodeKind.TrendsQuery,@@ -173,6 +280,7 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypemath_property: '$mcp_duration_ms',},],+ properties: categoryProperties,trendsFilter: {display: ChartDisplayType.ActionsLineGraph,},@@ -184,4 +292,9 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType}),],}),++ afterMount(({ actions }) => {+ actions.loadAvailableCategories()+ actions.loadCategoryCounts()+ }),])