:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp-analytics): filter tool quality and reports (#103008)
Lucas Faria35d3d2e803b4
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 0c16a912581d..921dc47b53dd 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9761,9 +9761,9 @@ snapshots:scenes-app-mcp-analytics--sessions--light:hash: v1.k794b7964.17f5e27f60024ff6e083bc6b799427b40e475fddb3bf7900aaab5f935d509b23.cgze06ZKpLRtg_doPvcuWuj_yfLplR3PlkqRGeqxzfEscenes-app-mcp-analytics--tool-quality--dark:- hash: v1.k794b7964.697b42ee7e043ae0dd4bf56ffcab59f24810196459f4303be1a418ed8e0f128d.hxsxWCzwdJI2stSHMmN6oMhjhsnPtB4iv8_OJxgzScs+ hash: v1.k794b7964.a490856eb234e8d317eb752b283d3b66796e6206f9855c8ecb4223c0be740ba1.zvXGsy66NnJM8yiFuDhn9bu9dJvWTNeLfG-OWwgqph0scenes-app-mcp-analytics--tool-quality--light:- hash: v1.k794b7964.300079bee41e9d28fd0178c202eb98880cf4a53cbd076509baa4f7a324cf0841.BoiNKYH0TEabgg4n1BveSSpZklEXn3Fo9s66RfkKExA+ hash: v1.k794b7964.0db52b49904cb908663bc7f32ea53bdbfc37ea32718183e311b51d9edb84ddf6.Ydhkj6pemSOwpAcF4NZfNGif-jJuNXsB1aED5WkHz5Uscenes-app-mcp-analytics-dashboard-cards--daily-calls-and-errors--dark:hash: v1.k794b7964.7302f068e1b6a63086ac35ffb7e7e1b9d10b8608cb7c6bb7033d341638e2d695.51PNQHMCZinl1fgHrAFmryj0im81JG1jIjU-DQc0oPYscenes-app-mcp-analytics-dashboard-cards--daily-calls-and-errors--light:diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsxindex e4385903b86a..12d98401ea29 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx@@ -42,6 +42,7 @@ import { SceneExport } from '~/scenes/sceneTypes'import { PersonDisplay } from 'products/persons/frontend/components/PersonDisplay'import { ToolDetailIntentsSection } from './clustering/ToolDetailIntentsSection'+import { McpSharedFilters } from './components/McpSharedFilters'import { formatMs, formatMsAsSeconds, formatNumber } from './dashboard/formatters'import { HarnessLogo, HarnessPill } from './dashboard/harness'import { MetricTile } from './dashboard/MetricTile'@@ -540,6 +541,10 @@ function MCPAnalyticsToolDetailContent({ toolName }: { toolName: string }): JSX.}}/>+ <div className="flex flex-wrap items-center gap-3 px-4 pb-2">+ <McpSharedFilters pageKey="mcp-tool-detail" dataAttrPrefix="mcp-tool-detail" />+ </div>+<div className="flex flex-col gap-3 px-4 pb-4"><DescriptionBlock descriptions={descriptions} loading={descriptionsLoading} /><StatTilesdiff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsxindex 902bc27e94d7..6d0640d3587b 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx@@ -11,6 +11,7 @@ import { teamLogic } from 'scenes/teamLogic'import { McpDateFilter } from './components/McpDateFilter'import { McpIntervalFilter } from './components/McpIntervalFilter'+import { McpSharedFilters } from './components/McpSharedFilters'import { mcpAnalyticsToolQualityLogic, mcpToolReportUrl } from './mcpAnalyticsToolQualityLogic'import { ToolQualityCharts } from './tool-quality/ToolQualityCharts'import { ToolQualityTable } from './tool-quality/ToolQualityTable'@@ -113,18 +114,25 @@ export function MCPAnalyticsToolQuality(): JSX.Element {const theme = useChartTheme()return (- <div className="flex flex-col gap-4" data-quill>- <FilterBar />- <ChartsScopeHeader />- <ToolQualityCharts- data={dailyChartData}- loading={dailyStatsLoading}- theme={theme}- timezone={timezone}- interval={interval}- incompleteTail={incompleteTail}- />- <ToolQualityTable />+ <div className="flex flex-col gap-4">+ <div data-quill>+ <FilterBar />+ </div>+ {/* Stays outside the quill scope: `[data-quill]` redefines the `--color-*` tokens, which+ paints the checked test-account switch as unchecked. */}+ <McpSharedFilters pageKey="mcp-tool-quality" dataAttrPrefix="mcp-tool-quality" />+ <div className="flex flex-col gap-4" data-quill>+ <ChartsScopeHeader />+ <ToolQualityCharts+ data={dailyChartData}+ loading={dailyStatsLoading}+ theme={theme}+ timezone={timezone}+ interval={interval}+ incompleteTail={incompleteTail}+ />+ <ToolQualityTable />+ </div></div>)}diff --git a/products/mcp_analytics/frontend/components/McpSharedFilters.tsx b/products/mcp_analytics/frontend/components/McpSharedFilters.tsxnew file mode 100644index 000000000000..2dbaac1c3cc8--- /dev/null+++ b/products/mcp_analytics/frontend/components/McpSharedFilters.tsx@@ -0,0 +1,41 @@+import { useActions, useValues } from 'kea'++import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch'++import { mcpAnalyticsFiltersLogic } from '../mcpAnalyticsFiltersLogic'++export interface McpSharedFiltersProps {+ pageKey: string+ dataAttrPrefix: string+}++export function McpSharedFilters({ pageKey, dataAttrPrefix }: McpSharedFiltersProps): JSX.Element {+ const { filterTestAccounts, propertyFilters } = useValues(mcpAnalyticsFiltersLogic)+ const { setFilterTestAccounts, setPropertyFilters } = useActions(mcpAnalyticsFiltersLogic)++ return (+ <>+ <div data-attr={`${dataAttrPrefix}-property-filter`}>+ <PropertyFilters+ pageKey={pageKey}+ propertyFilters={propertyFilters}+ onChange={setPropertyFilters}+ taxonomicGroupTypes={[+ TaxonomicFilterGroupType.MCPProperties,+ TaxonomicFilterGroupType.EventProperties,+ TaxonomicFilterGroupType.EventFeatureFlags,+ ]}+ eventNames={['$mcp_tool_call']}+ buttonText="Add filter"+ />+ </div>+ <TestAccountFilterSwitch+ checked={filterTestAccounts}+ onChange={setFilterTestAccounts}+ data-attr={`${dataAttrPrefix}-test-account-filter`}+ />+ </>+ )+}diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.test.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.test.tsindex 87df8da5c5af..4ed5179e1f81 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.test.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.test.ts@@ -3,6 +3,7 @@ import { expectLogic } from 'kea-test-utils'import api from 'lib/api'import { initKeaTests } from '~/test/init'+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'import { type DailyToolStat, buildDailyChartData, mcpAnalyticsToolDetailLogic } from './mcpAnalyticsToolDetailLogic'@@ -147,7 +148,7 @@ describe('failure drill-down', () => {// Guards the stale-response race: bucket A selected, then bucket B before A resolves.// Without the loader breakpoint, A's late response would overwrite B's occurrences// while the modal header still shows B.- it('discards a superseded bucket load so a slow earlier bucket cannot overwrite the latest one', async () => {+ it.each(['select another bucket', 'deselect'])('discards a pending failure load on %s', async (change) => {const logic = mcpAnalyticsToolDetailLogic({ toolName: 'query_run' })logic.mount()const occurrenceFor = (id: string): Record<string, string> => ({@@ -177,17 +178,25 @@ describe('failure drill-down', () => {})await expectLogic(logic, () => {logic.actions.selectFailure(bucket('api_5xx'))- logic.actions.selectFailure(bucket('internal'))- }).toDispatchActions(['loadFailureOccurrencesSuccess'])- expect(logic.values.failureOccurrences).toEqual([occurrenceFor('bucketB')])+ if (change === 'select another bucket') {+ logic.actions.selectFailure(bucket('internal'))+ } else {+ logic.actions.selectFailure(null)+ }+ }).toMatchValues({ selectedFailure: change === 'deselect' ? null : bucket('internal') })+ const expected = change === 'deselect' ? [] : [occurrenceFor('bucketB')]+ if (change === 'select another bucket') {+ await expectLogic(logic).toMatchValues({ failureOccurrences: expected })+ }// Bucket A's request resolves late — its stale result must be discarded.- resolveSlowA({ results: [occurrenceFor('bucketA')] })- await new Promise((resolve) => setTimeout(resolve, 0))- expect(logic.values.failureOccurrences).toEqual([occurrenceFor('bucketB')])+ await expectLogic(logic, () => {+ resolveSlowA({ results: [occurrenceFor('bucketA')] })+ }).toFinishAllListeners()+ expect(logic.values.failureOccurrences).toEqual(expected)})- it('clears the previous bucket occurrences when deselecting', async () => {+ it.each(['deselect', 'properties', 'test accounts'])('clears the open failure on %s', async (change) => {const logic = mcpAnalyticsToolDetailLogic({ toolName: 'query_run' })logic.mount()jest.spyOn(mockApi, 'query').mockResolvedValue({@@ -216,7 +225,111 @@ describe('failure drill-down', () => {}).toDispatchActions(['loadFailureOccurrencesSuccess'])await expectLogic(logic, () => {- logic.actions.selectFailure(null)+ if (change === 'properties') {+ logic.actions.setPropertyFilters([+ {+ key: '$mcp_tool_name',+ value: ['query_run'],+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+ },+ ])+ } else if (change === 'test accounts') {+ logic.actions.setFilterTestAccounts(true)+ } else {+ logic.actions.selectFailure(null)+ }}).toMatchValues({ selectedFailure: null, failureOccurrences: [] })})})++describe('shared filter wiring', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ initKeaTests()+ jest.spyOn(mockApi, 'query').mockResolvedValue({ results: [] })+ })++ function queryCallsSince(callIndex: number): Record<string, any>[] {+ return mockApi.query.mock.calls.slice(callIndex).map((call) => call[0] as any)+ }++ const EVENT_FILTER: AnyPropertyFilter = {+ key: '$mcp_tool_name',+ value: ['query_run'],+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+ }++ it('spreads the shared property filters into every section query and reloads on change', async () => {+ const logic = mcpAnalyticsToolDetailLogic({ toolName: 'query_run' })+ logic.mount()+ await expectLogic(logic, () => {+ logic.actions.loadAllSections()+ }).toFinishAllListeners()+ const callsBefore = mockApi.query.mock.calls.length++ await expectLogic(logic, () => {+ logic.actions.setPropertyFilters([EVENT_FILTER])+ }).toFinishAllListeners()++ const reloads = queryCallsSince(callsBefore)+ expect(reloads.length).toBe(10)+ expect(reloads.every((call) => JSON.stringify(call.properties) === JSON.stringify([EVENT_FILTER]))).toBe(true)+ })++ it('spreads filterTestAccounts into every section query and reloads on change', async () => {+ const logic = mcpAnalyticsToolDetailLogic({ toolName: 'query_run' })+ logic.mount()+ await expectLogic(logic, () => {+ logic.actions.loadAllSections()+ }).toFinishAllListeners()+ const callsBefore = mockApi.query.mock.calls.length++ await expectLogic(logic, () => {+ logic.actions.setFilterTestAccounts(true)+ }).toFinishAllListeners()++ const reloads = queryCallsSince(callsBefore)+ expect(reloads.length).toBe(10)+ expect(reloads.every((call) => call.filterTestAccounts === true)).toBe(true)+ })++ it('reloads sections once when both shared filters hydrate from the URL', async () => {+ const logic = mcpAnalyticsToolDetailLogic({ toolName: 'query_run' })+ logic.mount()+ await expectLogic(logic, () => logic.actions.loadAllSections()).toFinishAllListeners()+ const callsBefore = mockApi.query.mock.calls.length++ await expectLogic(logic, () => logic.actions.hydrateFilters(true, [EVENT_FILTER])).toFinishAllListeners()++ const reloads = queryCallsSince(callsBefore)+ expect(reloads).toHaveLength(10)+ expect(reloads.every((call) => call.filterTestAccounts === true)).toBe(true)+ expect(reloads.every((call) => JSON.stringify(call.properties) === JSON.stringify([EVENT_FILTER]))).toBe(true)+ })++ it('discards a superseded summary response so a slow earlier request cannot overwrite it', async () => {+ const logic = mcpAnalyticsToolDetailLogic({ toolName: 'query_run' })+ logic.mount()++ let resolveSlow: (value: unknown) => void = () => {}+ const slow = new Promise((resolve) => {+ resolveSlow = resolve+ })+ jest.spyOn(mockApi, 'query')+ .mockImplementationOnce(() => slow as any)+ .mockImplementationOnce(() => Promise.resolve({ results: [{ calls: 42 }] }))++ await expectLogic(logic, () => {+ logic.actions.loadSummary()+ logic.actions.loadSummary()+ }).toDispatchActions(['loadSummarySuccess'])++ expect(logic.values.summary?.calls).toBe(42)++ resolveSlow({ results: [{ calls: 1 }] })+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(logic.values.summary?.calls).toBe(42)+ })+})diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.tsindex 473adc1d1ee4..a373887f2226 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts@@ -1,4 +1,4 @@-import { MakeLogicType, actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { urlToAction } from 'kea-router'@@ -29,6 +29,9 @@ import {NodeKind,} from '~/queries/schema/schema-general'import { IntervalType } from '~/types'++import { type MCPSharedQueryFilters, mcpAnalyticsFiltersLogic } from './mcpAnalyticsFiltersLogic'+export interface ToolSummary {calls: numbererrors: number@@ -121,19 +124,22 @@ const DEFAULT_DATE_FILTER: DateFilter = { dateFrom: '-30d', dateTo: null }async function neighborRows(toolName: string,direction: 'before' | 'after',- dateRange: DateRange+ dateRange: DateRange,+ sharedQueryFilters: MCPSharedQueryFilters): Promise<ResultRows> {const response = (await api.query({kind: NodeKind.MCPToolNeighborsQuery,toolName,neighborDirection: direction,dateRange,+ ...sharedQueryFilters,})) as { results?: MCPToolNeighborItem[] }return (response?.results ?? []).map((r) => [r.neighbor_tool, r.co_occurrences])}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpAnalyticsToolDetailLogicValues {+ sharedQueryFilters: MCPSharedQueryFilters // mcpAnalyticsFiltersLogicbyHarnessRows: ResultRowsbyHarnessRowsLoading: booleandailyChartData: DailyChartData@@ -169,10 +175,23 @@ export interface mcpAnalyticsToolDetailLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpAnalyticsToolDetailLogicActions {+ hydrateFilters: (+ filterTestAccountsOverride: boolean | null,+ propertyFilters: import('~/types').AnyPropertyFilter[]+ ) => {+ filterTestAccountsOverride: boolean | null+ propertyFilters: import('~/types').AnyPropertyFilter[]+ } // mcpAnalyticsFiltersLogic+ setFilterTestAccounts: (filterTestAccounts: boolean | null) => {+ filterTestAccounts: boolean | null+ } // mcpAnalyticsFiltersLogic+ setPropertyFilters: (properties: import('~/types').AnyPropertyFilter[]) => {+ properties: import('~/types').AnyPropertyFilter[]+ } // mcpAnalyticsFiltersLogicloadAllSections: () => {value: true}- loadByHarnessRows: () => any+ loadByHarnessRows: (_: void) => voidloadByHarnessRowsFailure: (error: string,errorObject?: any@@ -182,10 +201,10 @@ export interface mcpAnalyticsToolDetailLogicActions {}loadByHarnessRowsSuccess: (byHarnessRows: ResultRows,- payload?: any+ payload?: void) => {byHarnessRows: ResultRows- payload?: any+ payload?: void}loadDailyStats: (_: void) => voidloadDailyStatsFailure: (@@ -202,7 +221,7 @@ export interface mcpAnalyticsToolDetailLogicActions {dailyStats: DailyToolStat[]payload?: void}- loadDescriptions: () => any+ loadDescriptions: (_: void) => voidloadDescriptionsFailure: (error: string,errorObject?: any@@ -212,12 +231,12 @@ export interface mcpAnalyticsToolDetailLogicActions {}loadDescriptionsSuccess: (descriptions: DescriptionRevision[],- payload?: any+ payload?: void) => {descriptions: DescriptionRevision[]- payload?: any+ payload?: void}- loadFailureBuckets: () => any+ loadFailureBuckets: (_: void) => voidloadFailureBucketsFailure: (error: string,errorObject?: any@@ -227,10 +246,10 @@ export interface mcpAnalyticsToolDetailLogicActions {}loadFailureBucketsSuccess: (failureBuckets: MCPToolFailureItem[],- payload?: any+ payload?: void) => {failureBuckets: MCPToolFailureItem[]- payload?: any+ payload?: void}loadFailureOccurrences: (bucket: MCPToolFailureItem) => MCPToolFailureItemloadFailureOccurrencesFailure: (@@ -247,7 +266,7 @@ export interface mcpAnalyticsToolDetailLogicActions {failureOccurrences: MCPToolFailureOccurrenceItem[]payload?: MCPToolFailureItem}- loadIntentCoverage: () => any+ loadIntentCoverage: (_: void) => voidloadIntentCoverageFailure: (error: string,errorObject?: any@@ -257,12 +276,12 @@ export interface mcpAnalyticsToolDetailLogicActions {}loadIntentCoverageSuccess: (intentCoverage: IntentCoverage | null,- payload?: any+ payload?: void) => {intentCoverage: IntentCoverage | null- payload?: any+ payload?: void}- loadNeighborsAfterRows: () => any+ loadNeighborsAfterRows: (_: void) => voidloadNeighborsAfterRowsFailure: (error: string,errorObject?: any@@ -272,12 +291,12 @@ export interface mcpAnalyticsToolDetailLogicActions {}loadNeighborsAfterRowsSuccess: (neighborsAfterRows: ResultRows,- payload?: any+ payload?: void) => {neighborsAfterRows: ResultRows- payload?: any+ payload?: void}- loadNeighborsBeforeRows: () => any+ loadNeighborsBeforeRows: (_: void) => voidloadNeighborsBeforeRowsFailure: (error: string,errorObject?: any@@ -287,12 +306,12 @@ export interface mcpAnalyticsToolDetailLogicActions {}loadNeighborsBeforeRowsSuccess: (neighborsBeforeRows: ResultRows,- payload?: any+ payload?: void) => {neighborsBeforeRows: ResultRows- payload?: any+ payload?: void}- loadSampleIntentRows: () => any+ loadSampleIntentRows: (_: void) => voidloadSampleIntentRowsFailure: (error: string,errorObject?: any@@ -302,12 +321,12 @@ export interface mcpAnalyticsToolDetailLogicActions {}loadSampleIntentRowsSuccess: (sampleIntentRows: ResultRows,- payload?: any+ payload?: void) => {sampleIntentRows: ResultRows- payload?: any+ payload?: void}- loadSummary: () => any+ loadSummary: (_: void) => voidloadSummaryFailure: (error: string,errorObject?: any@@ -317,12 +336,12 @@ export interface mcpAnalyticsToolDetailLogicActions {}loadSummarySuccess: (summary: ToolSummary | null,- payload?: any+ payload?: void) => {summary: ToolSummary | null- payload?: any+ payload?: void}- loadTopUserRows: () => any+ loadTopUserRows: (_: void) => voidloadTopUserRowsFailure: (error: string,errorObject?: any@@ -332,10 +351,10 @@ export interface mcpAnalyticsToolDetailLogicActions {}loadTopUserRowsSuccess: (topUserRows: ResultRows,- payload?: any+ payload?: void) => {topUserRows: ResultRows- payload?: any+ payload?: void}selectFailure: (bucket: MCPToolFailureItem | null) => {bucket: MCPToolFailureItem | null@@ -382,6 +401,11 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(key((props: MCPAnalyticsToolDetailLogicProps) => props.toolName),props({} as MCPAnalyticsToolDetailLogicProps),+ connect(() => ({+ values: [mcpAnalyticsFiltersLogic, ['queryFilters as sharedQueryFilters']],+ actions: [mcpAnalyticsFiltersLogic, ['hydrateFilters', 'setFilterTestAccounts', 'setPropertyFilters']],+ })),+actions({setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),setPinnedInterval: (interval: IntervalType | null) => ({ interval }),@@ -410,12 +434,14 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(summary: [null as ToolSummary | null,{- loadSummary: async (): Promise<ToolSummary | null> => {+ loadSummary: async (_: void, breakpoint): Promise<ToolSummary | null> => {const response = (await api.query({kind: NodeKind.MCPToolStatsQuery,toolName: props.toolName,dateRange: values.dateRange,+ ...values.sharedQueryFilters,})) as { results?: MCPToolStatsItem[] }+ breakpoint()const row = response?.results?.[0]if (!row) {return null@@ -434,12 +460,14 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(descriptions: [[] as DescriptionRevision[],{- loadDescriptions: async (): Promise<DescriptionRevision[]> => {+ loadDescriptions: async (_: void, breakpoint): Promise<DescriptionRevision[]> => {const response = (await api.query({kind: NodeKind.MCPToolDescriptionsQuery,toolName: props.toolName,dateRange: values.dateRange,+ ...values.sharedQueryFilters,})) as { results?: MCPToolDescriptionItem[] }+ breakpoint()return (response?.results ?? []).map((r) => ({description: r.description,last_seen: r.last_seen,@@ -451,12 +479,14 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(null as IntentCoverage | null,{// Reads the same MCPToolStatsQuery as `summary`; the coverage denominator is the call count.- loadIntentCoverage: async (): Promise<IntentCoverage | null> => {+ loadIntentCoverage: async (_: void, breakpoint): Promise<IntentCoverage | null> => {const response = (await api.query({kind: NodeKind.MCPToolStatsQuery,toolName: props.toolName,dateRange: values.dateRange,+ ...values.sharedQueryFilters,})) as { results?: MCPToolStatsItem[] }+ breakpoint()const row = response?.results?.[0]if (!row) {return null@@ -477,6 +507,7 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(toolName: props.toolName,dateRange: values.dateRange,interval: values.interval,+ ...values.sharedQueryFilters,})) as { results?: MCPToolDailyStatItem[] }breakpoint()return (response?.results ?? []).map((r) => ({@@ -494,12 +525,14 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(failureBuckets: [[] as MCPToolFailureItem[],{- loadFailureBuckets: async (): Promise<MCPToolFailureItem[]> => {+ loadFailureBuckets: async (_: void, breakpoint): Promise<MCPToolFailureItem[]> => {const response = (await api.query({kind: NodeKind.MCPToolFailuresQuery,toolName: props.toolName,dateRange: values.dateRange,+ ...values.sharedQueryFilters,})) as { results?: MCPToolFailureItem[] }+ breakpoint()return response?.results ?? []},},@@ -519,10 +552,14 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(errorType: bucket.error_type,errorStatus: bucket.error_status || undefined,dateRange: values.dateRange,+ ...values.sharedQueryFilters,})) as { results?: MCPToolFailureOccurrenceItem[] }// Bail if a newer bucket was selected while this request was in flight,// so a slow earlier bucket can't overwrite the latest one.breakpoint()+ if (values.selectedFailure !== bucket) {+ return []+ }return response?.results ?? []},},@@ -530,12 +567,14 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(sampleIntentRows: [[] as ResultRows,{- loadSampleIntentRows: async (): Promise<ResultRows> => {+ loadSampleIntentRows: async (_: void, breakpoint): Promise<ResultRows> => {const response = (await api.query({kind: NodeKind.MCPToolSampleIntentsQuery,toolName: props.toolName,dateRange: values.dateRange,+ ...values.sharedQueryFilters,})) as { results?: MCPToolSampleIntentItem[] }+ breakpoint()return (response?.results ?? []).map((r) => [r.timestamp, r.intent, r.intent_source, r.harness])},},@@ -543,15 +582,31 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(neighborsBeforeRows: [[] as ResultRows,{- loadNeighborsBeforeRows: async (): Promise<ResultRows> =>- neighborRows(props.toolName, 'before', values.dateRange),+ loadNeighborsBeforeRows: async (_: void, breakpoint): Promise<ResultRows> => {+ const rows = await neighborRows(+ props.toolName,+ 'before',+ values.dateRange,+ values.sharedQueryFilters+ )+ breakpoint()+ return rows+ },},],neighborsAfterRows: [[] as ResultRows,{- loadNeighborsAfterRows: async (): Promise<ResultRows> =>- neighborRows(props.toolName, 'after', values.dateRange),+ loadNeighborsAfterRows: async (_: void, breakpoint): Promise<ResultRows> => {+ const rows = await neighborRows(+ props.toolName,+ 'after',+ values.dateRange,+ values.sharedQueryFilters+ )+ breakpoint()+ return rows+ },},],byHarnessRows: [@@ -559,12 +614,14 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>({// Server-resolved harness labels via the same runner as the dashboard (scoped to this// tool's new-SDK calls by toolName), so the pill matches the dashboard's bucketing exactly.- loadByHarnessRows: async (): Promise<ResultRows> => {+ loadByHarnessRows: async (_: void, breakpoint): Promise<ResultRows> => {const response = (await api.query({kind: NodeKind.MCPHarnessBreakdownQuery,toolName: props.toolName,dateRange: values.dateRange,+ ...values.sharedQueryFilters,})) as { results?: MCPHarnessBreakdownItem[] }+ breakpoint()return (response?.results ?? []).map((r) => [r.harness,r.total_calls,@@ -579,12 +636,14 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>([] as ResultRows,{// The person tuple is rebuilt into the [distinct_id, _, properties] shape renderPersonCell expects.- loadTopUserRows: async (): Promise<ResultRows> => {+ loadTopUserRows: async (_: void, breakpoint): Promise<ResultRows> => {const response = (await api.query({kind: NodeKind.MCPToolTopUsersQuery,toolName: props.toolName,dateRange: values.dateRange,+ ...values.sharedQueryFilters,})) as { results?: MCPToolTopUserItem[] }+ breakpoint()return (response?.results ?? []).map((r) => [[r.distinct_id, '', r.person_properties],r.calls,@@ -674,6 +733,21 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(}),listeners(({ actions }) => ({+ // The window and pinned interval reload through the urlToAction handler below instead of a+ // listener on setDateFilter; the shared filters have no URL round-trip of their own here, so+ // they reload directly the same way that handler reloads on a date change.+ setFilterTestAccounts: () => {+ actions.selectFailure(null)+ actions.loadAllSections()+ },+ setPropertyFilters: () => {+ actions.selectFailure(null)+ actions.loadAllSections()+ },+ hydrateFilters: () => {+ actions.selectFailure(null)+ actions.loadAllSections()+ },loadAllSections: () => {actions.loadSummary()actions.loadDescriptions()diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.tsindex 96dcf2d05b27..a2430a535f36 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts@@ -4,6 +4,7 @@ import api from 'lib/api'import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'import { formatMsAsSeconds } from './dashboard/formatters'import { type DailyToolStat, buildDailyChartData, mcpAnalyticsToolQualityLogic } from './mcpAnalyticsToolQualityLogic'@@ -295,4 +296,100 @@ describe('mcpAnalyticsToolQualityLogic', () => {expect(logic.values.interval).toBe('hour')})})++ describe('shared filter wiring', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ initKeaTests()+ jest.spyOn(mockApi, 'query').mockImplementation(async (query: any) =>+ query.kind === NodeKind.MCPToolQualityRowsQuery ? emptyToolRowsResponse : { results: [] }+ )+ })++ function queryCallsSince(callIndex: number): Record<string, any>[] {+ return mockApi.query.mock.calls.slice(callIndex).map((call) => call[0] as any)+ }++ const EVENT_FILTER: AnyPropertyFilter = {+ key: '$mcp_tool_name',+ value: ['query_run'],+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+ }++ it('spreads the shared property filters into every query and reloads on change', async () => {+ const logic = mcpAnalyticsToolQualityLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ const callsBefore = mockApi.query.mock.calls.length++ await expectLogic(logic, () => {+ logic.actions.setPropertyFilters([EVENT_FILTER])+ }).toFinishAllListeners()++ const reloads = queryCallsSince(callsBefore)+ expect(reloads.length).toBe(4)+ expect(reloads.every((call) => JSON.stringify(call.properties) === JSON.stringify([EVENT_FILTER]))).toBe(+ true+ )+ })++ it('spreads filterTestAccounts into every query and reloads on change', async () => {+ const logic = mcpAnalyticsToolQualityLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ const callsBefore = mockApi.query.mock.calls.length++ await expectLogic(logic, () => {+ logic.actions.setFilterTestAccounts(true)+ }).toFinishAllListeners()++ const reloads = queryCallsSince(callsBefore)+ expect(reloads.length).toBe(4)+ expect(reloads.every((call) => call.filterTestAccounts === true)).toBe(true)+ })++ it('reloads once when both shared filters hydrate from the URL', async () => {+ const logic = mcpAnalyticsToolQualityLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ const callsBefore = mockApi.query.mock.calls.length++ await expectLogic(logic, () => {+ logic.actions.hydrateFilters(true, [EVENT_FILTER])+ }).toFinishAllListeners()++ const reloads = queryCallsSince(callsBefore)+ expect(reloads).toHaveLength(4)+ expect(reloads.every((call) => call.filterTestAccounts === true)).toBe(true)+ expect(reloads.every((call) => JSON.stringify(call.properties) === JSON.stringify([EVENT_FILTER]))).toBe(+ true+ )+ })++ it('discards a superseded available-categories response so a slow earlier request cannot overwrite it', async () => {+ const logic = mcpAnalyticsToolQualityLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ let resolveSlow: (value: unknown) => void = () => {}+ const slow = new Promise((resolve) => {+ resolveSlow = resolve+ })+ jest.spyOn(mockApi, 'query')+ .mockImplementationOnce(() => slow as any)+ .mockImplementationOnce(() => Promise.resolve({ results: [{ category: 'fresh' }] }))++ await expectLogic(logic, () => {+ logic.actions.loadAvailableCategories()+ logic.actions.loadAvailableCategories()+ }).toDispatchActions(['loadAvailableCategoriesSuccess'])++ expect(logic.values.availableCategories).toEqual(['fresh'])++ resolveSlow({ results: [{ category: 'stale' }] })+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(logic.values.availableCategories).toEqual(['fresh'])+ })+ })})diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.tsindex a08e1fea3f16..2dc82748d7cb 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts@@ -1,4 +1,4 @@-import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { actionToUrl, combineUrl, router, urlToAction } from 'kea-router'@@ -26,6 +26,8 @@ import {} from '~/queries/schema/schema-general'import { IntervalType } from '~/types'+import { type MCPSharedQueryFilters, mcpAnalyticsFiltersLogic } from './mcpAnalyticsFiltersLogic'+export interface CategoryCount {category: stringcalls: number@@ -55,9 +57,18 @@ interface ToolRowsPage extends MCPToolQualityRowsQueryResponse {// Carry the selected window across navigation as date_from / date_to, plus the grouping interval// when one is pinned, mirroring the tab's actionToUrl. Only set them when present so a cleared range-// and an auto interval stay out of the URL.-export function mcpDateSearchParams(dateFilter: DateFilter, interval?: IntervalType | null): Record<string, string> {- const params: Record<string, string> = {}+// and an auto interval stay out of the URL. `properties` and `filter_test_accounts` ride along+// straight off the current URL, since mcpAnalyticsFiltersLogic's actionToUrl already keeps them+// there, so a link between tabs never re-encodes them from state and risks drifting from what's applied.+export function mcpDateSearchParams(dateFilter: DateFilter, interval?: IntervalType | null): Record<string, any> {+ const { properties, filter_test_accounts } = router.values.currentLocation.searchParams+ const params: Record<string, any> = {}+ if (properties !== undefined) {+ params.properties = properties+ }+ if (filter_test_accounts !== undefined) {+ params.filter_test_accounts = filter_test_accounts+ }if (dateFilter.dateFrom) {params.date_from = dateFilter.dateFrom}@@ -138,6 +149,7 @@ export function buildDailyChartData(dailyStats: DailyToolStat[], bucketKeys: str// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpAnalyticsToolQualityLogicValues {+ sharedQueryFilters: MCPSharedQueryFilters // mcpAnalyticsFiltersLogicavailableCategories: string[]availableCategoriesLoading: booleancategoryCounts: CategoryCount[]@@ -166,7 +178,20 @@ export interface mcpAnalyticsToolQualityLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpAnalyticsToolQualityLogicActions {- loadAvailableCategories: () => any+ hydrateFilters: (+ filterTestAccountsOverride: boolean | null,+ propertyFilters: import('~/types').AnyPropertyFilter[]+ ) => {+ filterTestAccountsOverride: boolean | null+ propertyFilters: import('~/types').AnyPropertyFilter[]+ } // mcpAnalyticsFiltersLogic+ setFilterTestAccounts: (filterTestAccounts: boolean | null) => {+ filterTestAccounts: boolean | null+ } // mcpAnalyticsFiltersLogic+ setPropertyFilters: (properties: import('~/types').AnyPropertyFilter[]) => {+ properties: import('~/types').AnyPropertyFilter[]+ } // mcpAnalyticsFiltersLogic+ loadAvailableCategories: (_: void) => voidloadAvailableCategoriesFailure: (error: string,errorObject?: any@@ -176,12 +201,12 @@ export interface mcpAnalyticsToolQualityLogicActions {}loadAvailableCategoriesSuccess: (availableCategories: string[],- payload?: any+ payload?: void) => {availableCategories: string[]- payload?: any+ payload?: void}- loadCategoryCounts: () => any+ loadCategoryCounts: (_: void) => voidloadCategoryCountsFailure: (error: string,errorObject?: any@@ -191,10 +216,10 @@ export interface mcpAnalyticsToolQualityLogicActions {}loadCategoryCountsSuccess: (categoryCounts: CategoryCount[],- payload?: any+ payload?: void) => {categoryCounts: CategoryCount[]- payload?: any+ payload?: void}loadDailyStats: (_: void) => voidloadDailyStatsFailure: (@@ -290,6 +315,11 @@ export type mcpAnalyticsToolQualityLogicType = MakeLogicType<export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType>([path(['products', 'mcp_analytics', 'frontend', 'mcpAnalyticsToolQualityLogic']),+ connect(() => ({+ values: [mcpAnalyticsFiltersLogic, ['queryFilters as sharedQueryFilters']],+ actions: [mcpAnalyticsFiltersLogic, ['hydrateFilters', 'setFilterTestAccounts', 'setPropertyFilters']],+ })),+actions({setToolQualitySort: (column: ToolQualitySortColumn, direction: SortDirection) => ({ column, direction }),setToolQualityPageIndex: (pageIndex: number) => ({ pageIndex }),@@ -353,12 +383,15 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypeavailableCategories: [[] as string[],{- loadAvailableCategories: async (): Promise<string[]> => {- // Fixed 30-day window so the scope selector lists every category regardless of the tab filter.+ loadAvailableCategories: async (_: void, breakpoint): Promise<string[]> => {+ // Fixed 30-day window so the scope selector lists every category regardless of the tab's+ // date filter, though the shared property filters and test-account switch still narrow it.const response = (await api.query({kind: NodeKind.MCPToolCategoriesQuery,dateRange: { date_from: '-30d' },+ ...values.sharedQueryFilters,})) as { results?: MCPToolCategoryItem[] }+ breakpoint()return (response.results ?? []).map((r) => r.category).filter(Boolean)},},@@ -366,11 +399,13 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypecategoryCounts: [[] as CategoryCount[],{- loadCategoryCounts: async (): Promise<CategoryCount[]> => {+ loadCategoryCounts: async (_: void, breakpoint): Promise<CategoryCount[]> => {const response = (await api.query({kind: NodeKind.MCPToolCategoryCountsQuery,dateRange: { date_from: values.dateFilter.dateFrom, date_to: values.dateFilter.dateTo },+ ...values.sharedQueryFilters,})) as { results?: MCPToolCategoryCountItem[] }+ breakpoint()return (response.results ?? []).map((r) => ({ category: r.category, calls: r.calls }))},},@@ -390,6 +425,7 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypesortDirection: values.toolQualitySort.direction,limit: TOOL_QUALITY_PAGE_SIZE,offset: pageIndex * TOOL_QUALITY_PAGE_SIZE,+ ...values.sharedQueryFilters,})) as MCPToolQualityRowsQueryResponsebreakpoint()return { ...response, pageIndex }@@ -407,6 +443,7 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypeinterval: values.interval,categories: values.selectedCategories,...(values.selectedTool ? { toolName: values.selectedTool } : {}),+ ...values.sharedQueryFilters,})) as { results?: MCPToolQualityDailyStatItem[] }breakpoint()return (response.results ?? []).map((r) => ({@@ -509,6 +546,24 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicTypeloadUnscopedDailyStats()actions.loadCategoryCounts()},+ setFilterTestAccounts: () => {+ loadFirstToolPage()+ loadUnscopedDailyStats()+ actions.loadCategoryCounts()+ actions.loadAvailableCategories()+ },+ setPropertyFilters: () => {+ loadFirstToolPage()+ loadUnscopedDailyStats()+ actions.loadCategoryCounts()+ actions.loadAvailableCategories()+ },+ hydrateFilters: () => {+ loadFirstToolPage()+ loadUnscopedDailyStats()+ actions.loadCategoryCounts()+ actions.loadAvailableCategories()+ },setSelectedCategories: () => {loadFirstToolPage()loadUnscopedDailyStats()