: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
fix(metrics): add picker-only metric names endpoint (#99847)
Frank Hamande537159a3701
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex 00c5e731e715..09245f329e24 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -39,7 +39,7 @@ from products.metrics.backend.metric_attributes_query_runner import (MetricAttributeValuesQueryRunner,)from products.metrics.backend.metric_event_samples_query_runner import MetricEventSamplesQueryRunner-from products.metrics.backend.metric_names_query_runner import cached_metric_names+from products.metrics.backend.metric_names_query_runner import MetricNamesQueryRunner, cached_metric_namesfrom products.metrics.backend.metric_query_runner import MetricQueryRunnerfrom products.metrics.backend.metrics_overview_query_runner import MetricsOverviewQueryRunner@@ -237,6 +237,24 @@ def list_metric_names(return cached_metric_names(team=team, search=search, limit=limit, services=services)+def list_metric_picker_names(+ *,+ team: Team,+ search: str = "",+ limit: int = 100,+ services: Sequence[str] = (),+) -> list[dict[str, Any]]:+ """List current metric names for the viewer picker without sparklines or caching."""+ rows = MetricNamesQueryRunner(+ team=team,+ search=search,+ limit=limit,+ services=services,+ include_sparklines=False,+ ).run()+ return [{"name": row["name"], "metric_type": row["metric_type"]} for row in rows]++def get_metrics_overview(*, team: Team, lookback: dt.timedelta | None = None) -> MetricsOverview:"""Ingestion rollup for the overview page: freshness of the newestdatapoint plus window-scoped metric/series counts per service.diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.pyindex 58dae004ed1a..8f8132610429 100644--- a/products/metrics/backend/presentation/api.py+++ b/products/metrics/backend/presentation/api.py@@ -35,6 +35,7 @@ from products.metrics.backend.facade.api import (list_metric_error_spikes,list_metric_event_samples,list_metric_names,+ list_metric_picker_names,run_metric_query,team_has_metrics,)@@ -481,10 +482,21 @@ class _MetricNameSerializer(serializers.Serializer):)+class _MetricPickerNameSerializer(serializers.Serializer):+ name = serializers.CharField(help_text="Metric name as it appears in the team's data.")+ metric_type = serializers.CharField(+ help_text="OTel metric type (gauge, sum, histogram, summary, exponential_histogram)."+ )++class _MetricNamesResponseSerializer(serializers.Serializer):results = _MetricNameSerializer(many=True, help_text="Distinct metric names ordered by recent activity.")+class _MetricPickerNamesResponseSerializer(serializers.Serializer):+ results = _MetricPickerNameSerializer(many=True, help_text="Distinct metric names ordered by recent activity.")++class _MetricAttributeKeysParamsSerializer(serializers.Serializer):search = serializers.CharField(required=False,@@ -891,7 +903,7 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):throttle_classes=[ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle],)def values(self, request: Request, *args, **kwargs) -> Response:- """Distinct metric names for the team. Backs the picker UI."""+ """Distinct metric names for the team. Backs the catalog UI."""tag_queries(product=Product.METRICS, feature=Feature.QUERY)params = _MetricValuesParamsSerializer(data=request.query_params)@@ -909,6 +921,35 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):return Response({"results": results}, status=status.HTTP_200_OK)+ @extend_schema(+ parameters=[_MetricValuesParamsSerializer],+ responses={200: _MetricPickerNamesResponseSerializer},+ )+ @action(+ detail=False,+ methods=["GET"],+ required_scopes=["metrics:read"],+ throttle_classes=[ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle],+ )+ def names(self, request: Request, *args, **kwargs) -> Response:+ """Distinct metric names for the viewer picker, without sparklines or caching."""+ tag_queries(product=Product.METRICS, feature=Feature.QUERY)++ params = _MetricValuesParamsSerializer(data=request.query_params)+ params.is_valid(raise_exception=True)++ try:+ results = list_metric_picker_names(+ team=self.team,+ search=params.validated_data["value"],+ limit=params.validated_data["limit"],+ services=params.validated_data["service"],+ )+ except ValueError as exc:+ raise ParseError(str(exc))++ return Response({"results": results}, status=status.HTTP_200_OK)+@extend_schema(parameters=[_MetricAttributeKeysParamsSerializer],responses={200: _MetricAttributeKeysResponseSerializer},diff --git a/products/metrics/backend/tests/test_metric_names_query_runner.py b/products/metrics/backend/tests/test_metric_names_query_runner.pyindex 04b064b7c02c..b72ebb20cff5 100644--- a/products/metrics/backend/tests/test_metric_names_query_runner.py+++ b/products/metrics/backend/tests/test_metric_names_query_runner.py@@ -9,6 +9,7 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from products.metrics.backend.facade.api import list_metric_picker_namesfrom products.metrics.backend.metric_names_query_runner import (MAX_PICKER_SERVICES,MetricNamesQueryRunner,@@ -155,6 +156,13 @@ class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):self.assertEqual(cached_metric_names(self.team, services=["worker"]), run.return_value)self.assertEqual(run.call_count, 4)+ def test_picker_names_do_not_cache(self):+ with patch.object(MetricNamesQueryRunner, "run") as run:+ run.return_value = [{"name": "m1", "metric_type": "gauge"}]+ self.assertEqual(list_metric_picker_names(team=self.team), run.return_value)+ self.assertEqual(list_metric_picker_names(team=self.team), run.return_value)+ self.assertEqual(run.call_count, 2)+def test_exact_match_floats_to_top(self):anchor = timezone.now().replace(microsecond=0)_seed_point(@@ -251,6 +259,15 @@ class TestMetricsValuesAPI(ClickhouseTestMixin, APIBaseTest):body = response.json()names = {row["name"] for row in body["results"]}self.assertEqual(names, {"m1", "m2"})+ self.assertIn("sparkline", body["results"][0])++ def test_names_returns_picker_fields_only(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ _seed_point(team_id=self.team.id, metric_name="m1", value=1.0, timestamp=anchor)++ response = self.client.get(f"/api/projects/{self.team.id}/metrics/names/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"results": [{"name": "m1", "metric_type": "gauge"}]})def test_values_search_param(self):anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)diff --git a/products/metrics/frontend/components/MetricsViewer.test.tsx b/products/metrics/frontend/components/MetricsViewer.test.tsxindex 4df75f87b4b9..147b62befec4 100644--- a/products/metrics/frontend/components/MetricsViewer.test.tsx+++ b/products/metrics/frontend/components/MetricsViewer.test.tsx@@ -18,7 +18,7 @@ import {import {metricsAttributesRetrieve,metricsQueryCreate,- metricsValuesRetrieve,+ metricsNamesRetrieve,} from 'products/metrics/frontend/generated/api'import { MetricsViewer } from './MetricsViewer'@@ -26,7 +26,7 @@ import { metricsViewerLogic } from './metricsViewerLogic'jest.mock('products/metrics/frontend/generated/api', () => ({...jest.requireActual('products/metrics/frontend/generated/api'),- metricsValuesRetrieve: jest.fn(),+ metricsNamesRetrieve: jest.fn(),metricsQueryCreate: jest.fn(),metricsSamplesCreate: jest.fn(),metricsAttributesRetrieve: jest.fn(),@@ -56,7 +56,7 @@ describe('MetricsViewer', () => {} as AppContextuseMocks({ get: { '/api/environments/:team_id/dashboards/': { count: 0, results: [] } } })initKeaTests()- jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: [] })+ jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: [] })jest.mocked(metricsQueryCreate).mockResolvedValue({ results: [] })jest.mocked(metricsAttributesRetrieve).mockResolvedValue({ results: [], count: 0 })jest.mocked(insightsApi.create).mockResolvedValue(SAVED_INSIGHT as QueryBasedInsightModel)diff --git a/products/metrics/frontend/components/metricNamePickerLogic.ts b/products/metrics/frontend/components/metricNamePickerLogic.tsindex 6efe617db627..3afc26daeaaf 100644--- a/products/metrics/frontend/components/metricNamePickerLogic.ts+++ b/products/metrics/frontend/components/metricNamePickerLogic.ts@@ -3,11 +3,11 @@ import { loaders } from 'kea-loaders'import { teamLogic } from 'scenes/teamLogic'-import { metricsValuesRetrieve } from 'products/metrics/frontend/generated/api'-import type { _MetricNameApi } from 'products/metrics/frontend/generated/api.schemas'+import { metricsNamesRetrieve } from 'products/metrics/frontend/generated/api'+import type { _MetricPickerNameApi } from 'products/metrics/frontend/generated/api.schemas'import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'-export type MetricNameItem = _MetricNameApi+export type MetricNameItem = _MetricPickerNameApi// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface metricNamePickerLogicValues {@@ -31,12 +31,12 @@ export interface metricNamePickerLogicActions {errorObject?: any}loadItemsSuccess: (- items: _MetricNameApi[],+ items: _MetricPickerNameApi[],payload?: {debounce: boolean}) => {- items: _MetricNameApi[]+ items: _MetricPickerNameApi[]payload?: {debounce: boolean}@@ -80,7 +80,7 @@ export const metricNamePickerLogic = kea<metricNamePickerLogicType>([if (debounce) {await breakpoint(300)}- const response = await metricsValuesRetrieve(String(values.currentTeamId), {+ const response = await metricsNamesRetrieve(String(values.currentTeamId), {value: values.search,limit: 100,// Joined here rather than passed as an array: the generateddiff --git a/products/metrics/frontend/components/metricsCatalogLogic.test.ts b/products/metrics/frontend/components/metricsCatalogLogic.test.tsindex 54f4684755f5..a9b10136ed2d 100644--- a/products/metrics/frontend/components/metricsCatalogLogic.test.ts+++ b/products/metrics/frontend/components/metricsCatalogLogic.test.ts@@ -3,7 +3,7 @@ import { expectLogic } from 'kea-test-utils'import { initKeaTests } from '~/test/init'import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'-import { metricsValuesRetrieve } from '../generated/api'+import { metricsNamesRetrieve, metricsValuesRetrieve } from '../generated/api'import { metricsSceneLogic } from '../metricsSceneLogic'import { metricNamePickerLogic } from './metricNamePickerLogic'import { metricsCatalogLogic } from './metricsCatalogLogic'@@ -11,6 +11,7 @@ import { metricsViewerLogic } from './metricsViewerLogic'jest.mock('../generated/api', () => ({...jest.requireActual('../generated/api'),+ metricsNamesRetrieve: jest.fn(),metricsValuesRetrieve: jest.fn(),metricsQueryCreate: jest.fn(),}))@@ -47,6 +48,7 @@ describe('metricsCatalogLogic', () => {initKeaTests()jest.mocked(metricsValuesRetrieve).mockReset()jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: CATALOG_ITEMS } as any)+ jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: CATALOG_ITEMS } as any)})afterEach(() => {diff --git a/products/metrics/frontend/components/metricsOverviewLogic.test.ts b/products/metrics/frontend/components/metricsOverviewLogic.test.tsindex b1a58e5bb4a4..baeccfeb8994 100644--- a/products/metrics/frontend/components/metricsOverviewLogic.test.ts+++ b/products/metrics/frontend/components/metricsOverviewLogic.test.ts@@ -3,7 +3,7 @@ import { expectLogic } from 'kea-test-utils'import { initKeaTests } from '~/test/init'import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'-import { metricsOverviewRetrieve, metricsValuesRetrieve } from '../generated/api'+import { metricsNamesRetrieve, metricsOverviewRetrieve } from '../generated/api'import type { _MetricsOverviewResponseApi } from '../generated/api.schemas'import { metricsSceneLogic } from '../metricsSceneLogic'import { metricNamePickerLogic } from './metricNamePickerLogic'@@ -19,7 +19,7 @@ jest.mock('../generated/api', () => ({metricsOverviewRetrieve: jest.fn(),metricsQueryCreate: jest.fn(),metricsSamplesCreate: jest.fn(),- metricsValuesRetrieve: jest.fn(),+ metricsNamesRetrieve: jest.fn(),}))const OVERVIEW_FIXTURE: _MetricsOverviewResponseApi = {@@ -48,7 +48,7 @@ describe('metricsOverviewLogic', () => {jest.mocked(metricsOverviewRetrieve).mockReset()jest.mocked(metricsOverviewRetrieve).mockResolvedValue(OVERVIEW_FIXTURE as any)// The name picker mounts alongside the viewer logic and loads on mount.- jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: [] } as any)+ jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: [] } as any)})afterEach(() => {diff --git a/products/metrics/frontend/components/metricsStarterDashboardLogic.test.ts b/products/metrics/frontend/components/metricsStarterDashboardLogic.test.tsindex 00a0b88b8caf..1c781850ca41 100644--- a/products/metrics/frontend/components/metricsStarterDashboardLogic.test.ts+++ b/products/metrics/frontend/components/metricsStarterDashboardLogic.test.ts@@ -6,13 +6,13 @@ import { insightsApi } from 'scenes/insights/utils/api'import { initKeaTests } from '~/test/init'-import { metricsAttributeValuesRetrieve, metricsValuesRetrieve } from 'products/metrics/frontend/generated/api'+import { metricsAttributeValuesRetrieve, metricsNamesRetrieve } from 'products/metrics/frontend/generated/api'import { metricOptionKey, metricsStarterDashboardLogic } from './metricsStarterDashboardLogic'jest.mock('products/metrics/frontend/generated/api', () => ({...jest.requireActual('products/metrics/frontend/generated/api'),- metricsValuesRetrieve: jest.fn(),+ metricsNamesRetrieve: jest.fn(),metricsAttributeValuesRetrieve: jest.fn(),}))jest.mock('scenes/insights/utils/api', () => ({@@ -22,7 +22,7 @@ jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({lemonToast: { success: jest.fn(), warning: jest.fn(), error: jest.fn() },}))-const mockNames = metricsValuesRetrieve as jest.MockedFunction<typeof metricsValuesRetrieve>+const mockNames = metricsNamesRetrieve as jest.MockedFunction<typeof metricsNamesRetrieve>const mockValues = metricsAttributeValuesRetrieve as jest.MockedFunction<typeof metricsAttributeValuesRetrieve>const mockInsightCreate = insightsApi.create as jest.MockedFunction<typeof insightsApi.create>diff --git a/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx b/products/metrics/frontend/components/metricsStarterDashboardLogic.tsxindex 7b354d3478fa..07070b991ade 100644--- a/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx+++ b/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx@@ -12,8 +12,8 @@ import { NodeKind } from '~/queries/schema/schema-general'import type { MetricsQuery, MetricsQueryClause } from '~/queries/schema/schema-general'import type { DashboardType } from '~/types'-import { metricsAttributeValuesRetrieve, metricsValuesRetrieve } from 'products/metrics/frontend/generated/api'-import type { _MetricNameApi } from 'products/metrics/frontend/generated/api.schemas'+import { metricsAttributeValuesRetrieve, metricsNamesRetrieve } from 'products/metrics/frontend/generated/api'+import type { _MetricPickerNameApi } from 'products/metrics/frontend/generated/api.schemas'import type { InsightModel } from '../../../../frontend/src/types'import { RECOMMENDED_AGGREGATION_BY_TYPE, nodeAggregationFields, toKnownMetricType } from './metricsViewerLogic'@@ -28,7 +28,7 @@ export interface metricsStarterDashboardLogicValues {creating: booleandashboardName: stringisModalOpen: boolean- metricOptions: _MetricNameApi[]+ metricOptions: _MetricPickerNameApi[]metricOptionsLoading: booleanselectedMetrics: string[]serviceName: string@@ -63,10 +63,10 @@ export interface metricsStarterDashboardLogicActions {errorObject?: any}loadMetricOptionsSuccess: (- metricOptions: _MetricNameApi[],+ metricOptions: _MetricPickerNameApi[],payload?: any) => {- metricOptions: _MetricNameApi[]+ metricOptions: _MetricPickerNameApi[]payload?: any}loadServices: (_: any) => any@@ -161,11 +161,11 @@ export const metricsStarterDashboardLogic = kea<metricsStarterDashboardLogicType},],metricOptions: [- [] as _MetricNameApi[],+ [] as _MetricPickerNameApi[],{loadMetricOptions: async (_, breakpoint) => {await breakpoint(100)- const response = await metricsValuesRetrieve(String(values.currentTeamId), {})+ const response = await metricsNamesRetrieve(String(values.currentTeamId), {})breakpoint()return response.results},@@ -189,12 +189,12 @@ export const metricsStarterDashboardLogic = kea<metricsStarterDashboardLogicTypeconst name = values.dashboardName.trim()const selectedMetrics = [...values.selectedMetrics]const serviceName = values.serviceName- const optionByKey: Record<string, _MetricNameApi> = Object.fromEntries(+ const optionByKey: Record<string, _MetricPickerNameApi> = Object.fromEntries(values.metricOptions.map((option) => [metricOptionKey(option.name, option.metric_type), option]))// Resolve keys to options up front so a name shared by two OTel types// keeps the type the user actually picked.- const pickedMetrics: _MetricNameApi[] = selectedMetrics.map(+ const pickedMetrics: _MetricPickerNameApi[] = selectedMetrics.map((key) => optionByKey[key] ?? { name: key, metric_type: '' })let dashboard: DashboardType | null = nulldiff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.tsindex b16f6ec85d7a..644f031cdd6b 100644--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts@@ -9,11 +9,7 @@ import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-generaimport { initKeaTests } from '~/test/init'import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'-import {- metricsQueryCreate,- metricsSamplesCreate,- metricsValuesRetrieve,-} from 'products/metrics/frontend/generated/api'+import { metricsQueryCreate, metricsSamplesCreate, metricsNamesRetrieve } from 'products/metrics/frontend/generated/api'import type { _MetricEventSampleApi } from 'products/metrics/frontend/generated/api.schemas'import { metricsSceneLogic } from '../metricsSceneLogic'@@ -26,7 +22,7 @@ jest.mock('posthog-js')jest.mock('products/metrics/frontend/generated/api', () => ({...jest.requireActual('products/metrics/frontend/generated/api'),- metricsValuesRetrieve: jest.fn(),+ metricsNamesRetrieve: jest.fn(),metricsQueryCreate: jest.fn(),metricsSamplesCreate: jest.fn(),metricsCharacterizeCreate: jest.fn(),@@ -74,7 +70,7 @@ describe('metricsUsageTrackingLogic', () => {} as AppContextinitKeaTests()jest.mocked(posthog.capture).mockClear()- jest.mocked(metricsValuesRetrieve).mockReset().mockResolvedValue({ results: [] })+ jest.mocked(metricsNamesRetrieve).mockReset().mockResolvedValue({ results: [] })jest.mocked(metricsQueryCreate).mockReset().mockResolvedValue({ results: [] })jest.mocked(metricsSamplesCreate).mockReset().mockResolvedValue({ results: [] })logic = metricsUsageTrackingLogic()diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.tsindex 18a9780baeb7..4b9b533872ff 100644--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts@@ -21,7 +21,7 @@ import {metricsAttributesRetrieve,metricsCharacterizeCreate,metricsQueryCreate,- metricsValuesRetrieve,+ metricsNamesRetrieve,} from 'products/metrics/frontend/generated/api'import { metricNamePickerLogic } from './metricNamePickerLogic'@@ -29,7 +29,7 @@ import { metricsViewerLogic } from './metricsViewerLogic'jest.mock('products/metrics/frontend/generated/api', () => ({...jest.requireActual('products/metrics/frontend/generated/api'),- metricsValuesRetrieve: jest.fn(),+ metricsNamesRetrieve: jest.fn(),metricsAttributesRetrieve: jest.fn(),metricsQueryCreate: jest.fn(),metricsCharacterizeCreate: jest.fn(),@@ -78,7 +78,7 @@ describe('metricsViewerLogic', () => {beforeEach(() => {setResourceAccess({})initKeaTests()- jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: PICKER_ITEMS })+ jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: PICKER_ITEMS })jest.mocked(metricsQueryCreate).mockReset().mockResolvedValue({ results: [] })jest.mocked(metricsAttributesRetrieve).mockReset()jest.mocked(metricsCharacterizeCreate).mockReset()@@ -666,7 +666,7 @@ describe('metricsViewerLogic', () => {it('does not call metrics APIs without metrics viewer access', async () => {setResourceAccess({ [AccessControlResourceType.Metrics]: AccessControlLevel.None })- jest.mocked(metricsValuesRetrieve).mockClear()+ jest.mocked(metricsNamesRetrieve).mockClear()await expectLogic(metricNamePickerLogic, () => {metricNamePickerLogic.actions.loadItems({ debounce: true })@@ -680,7 +680,7 @@ describe('metricsViewerLogic', () => {logic.actions.setGroupBySearch('env')}).toDispatchActions(['loadAttributeKeyOptionsSuccess'])- expect(metricsValuesRetrieve).not.toHaveBeenCalled()+ expect(metricsNamesRetrieve).not.toHaveBeenCalled()expect(metricsQueryCreate).not.toHaveBeenCalled()expect(metricsAttributesRetrieve).not.toHaveBeenCalled()})diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex 7728dcb48cf0..0a312fc64557 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -50,7 +50,7 @@ import type {import { canCreateMetricsInsight, canViewMetrics } from 'products/metrics/frontend/metricsAccess'import type { Node } from '../../../../frontend/src/queries/schema/schema-general'-import type { _MetricNameApi } from '../generated/api.schemas'+import type { _MetricPickerNameApi } from '../generated/api.schemas'import { type MetricTopMoverRow, topMoverRows } from '../metricsAnomaly'import { EMPTY_SERVICE_PATTERN, SERVICE_NAME_KEY } from '../metricsAttributes'import { correlationServiceNames } from '../metricsLinks'@@ -394,14 +394,14 @@ export interface metricsViewerLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface metricsViewerLogicActions {loadItemsSuccess: (- items: _MetricNameApi[],+ items: _MetricPickerNameApi[],payload?:| {debounce: boolean}| undefined) => {- items: _MetricNameApi[]+ items: _MetricPickerNameApi[]payload?: {debounce: boolean}diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex ee5a73e4e0dd..728266cf8b9d 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -531,6 +531,18 @@ export interface _HasMetricsResponseApi {hasMetrics: boolean}+export interface _MetricPickerNameApi {+ /** Metric name as it appears in the team's data. */+ name: string+ /** OTel metric type (gauge, sum, histogram, summary, exponential_histogram). */+ metric_type: string+}++export interface _MetricPickerNamesResponseApi {+ /** Distinct metric names ordered by recent activity. */+ results: _MetricPickerNameApi[]+}+export interface _MetricsOverviewServiceApi {/** Service that reported metrics inside the window. */service_name: string@@ -861,6 +873,25 @@ export type MetricsErrorSpikesRetrieveParams = {dateTo?: string}+export type MetricsNamesRetrieveParams = {+ /**+ * Max number of names to return. Defaults to 100; maximum 1000.+ * @minimum 1+ * @maximum 1000+ */+ limit?: number+ /**+ * Comma-separated services to narrow the list to, e.g. `service=web,worker`. Omit for every service. Send it empty to select only series whose sender did not set `service.name`. A service name containing a comma cannot be selected.+ * @maxLength 1024+ */+ service?: string+ /**+ * Substring filter (case-insensitive) applied to metric names.+ * @maxLength 255+ */+ value?: string+}+export type MetricsValuesRetrieveParams = {/*** Max number of names to return. Defaults to 100; maximum 1000.diff --git a/products/metrics/frontend/generated/api.ts b/products/metrics/frontend/generated/api.tsindex fb4e3de668d1..7272ef3385f7 100644--- a/products/metrics/frontend/generated/api.ts+++ b/products/metrics/frontend/generated/api.ts@@ -14,6 +14,7 @@ import type {MetricsAttributeValuesRetrieveParams,MetricsAttributesRetrieveParams,MetricsErrorSpikesRetrieveParams,+ MetricsNamesRetrieveParams,MetricsValuesRetrieveParams,_HasMetricsResponseApi,_MetricAnomalyReportApi,@@ -24,6 +25,7 @@ import type {_MetricExplainRequestApi,_MetricExplainResponseApi,_MetricNamesResponseApi,+ _MetricPickerNamesResponseApi,_MetricQueryRequestApi,_MetricQueryResponseApi,_MetricSamplesRequestApi,@@ -228,6 +230,36 @@ export const metricsHasMetricsRetrieve = async (})}+export const getMetricsNamesRetrieveUrl = (projectId: string, params?: MetricsNamesRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/metrics/names/?${stringifiedParams}`+ : `/api/projects/${projectId}/metrics/names/`+}++/**+ * Distinct metric names for the viewer picker, without sparklines or caching.+ */+export const metricsNamesRetrieve = async (+ projectId: string,+ params?: MetricsNamesRetrieveParams,+ options?: RequestInit+): Promise<_MetricPickerNamesResponseApi> => {+ return apiMutator<_MetricPickerNamesResponseApi>(getMetricsNamesRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getMetricsOverviewRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/metrics/overview/`}@@ -301,7 +333,7 @@ export const getMetricsValuesRetrieveUrl = (projectId: string, params?: MetricsV}/**- * Distinct metric names for the team. Backs the picker UI.+ * Distinct metric names for the team. Backs the catalog UI.*/export const metricsValuesRetrieve = async (projectId: string,diff --git a/products/metrics/frontend/metricsSceneLogic.test.ts b/products/metrics/frontend/metricsSceneLogic.test.tsindex 2be7ad2d768b..06206e8b7813 100644--- a/products/metrics/frontend/metricsSceneLogic.test.ts+++ b/products/metrics/frontend/metricsSceneLogic.test.ts@@ -12,14 +12,14 @@ import {UniversalFiltersGroup,} from '~/types'-import { metricsQueryCreate, metricsValuesRetrieve } from 'products/metrics/frontend/generated/api'+import { metricsNamesRetrieve, metricsQueryCreate } from 'products/metrics/frontend/generated/api'import { metricsViewerLogic } from './components/metricsViewerLogic'import { metricsSceneLogic } from './metricsSceneLogic'jest.mock('products/metrics/frontend/generated/api', () => ({...jest.requireActual('products/metrics/frontend/generated/api'),- metricsValuesRetrieve: jest.fn(),+ metricsNamesRetrieve: jest.fn(),metricsQueryCreate: jest.fn(),}))@@ -57,7 +57,7 @@ describe('metricsSceneLogic', () => {},} as AppContextinitKeaTests()- jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: PICKER_ITEMS })+ jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: PICKER_ITEMS })jest.mocked(metricsQueryCreate).mockReset().mockResolvedValue({ results: [] })logic = metricsSceneLogic()logic.mount()diff --git a/products/metrics/mcp/tools.yaml b/products/metrics/mcp/tools.yamlindex 70880f737e24..83c8b9dd2388 100644--- a/products/metrics/mcp/tools.yaml+++ b/products/metrics/mcp/tools.yaml@@ -53,6 +53,9 @@ tools:metrics-has-metrics-retrieve:operation: metrics_has_metrics_retrieveenabled: false+ metrics-names-retrieve:+ operation: metrics_names_retrieve+ enabled: falsemetrics-overview-retrieve:operation: metrics_overview_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4cfc7f8e82f0..2eee979ec7d4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -93043,6 +93043,18 @@ export namespace Schemas {results: _MetricName[];}+ export interface _MetricPickerName {+ /** Metric name as it appears in the team's data. */+ name: string;+ /** OTel metric type (gauge, sum, histogram, summary, exponential_histogram). */+ metric_type: string;+ }++ export interface _MetricPickerNamesResponse {+ /** Distinct metric names ordered by recent activity. */+ results: _MetricPickerName[];+ }+export interface _MetricQueryBody {/*** Exact metric name to query (e.g. 'http.server.duration'). Single-clause shorthand — mutually exclusive with 'clauses'.@@ -102152,6 +102164,25 @@ export namespace Schemas {dateTo?: string;};+ export type MetricsNamesRetrieveParams = {+ /**+ * Max number of names to return. Defaults to 100; maximum 1000.+ * @minimum 1+ * @maximum 1000+ */+ limit?: number;+ /**+ * Comma-separated services to narrow the list to, e.g. `service=web,worker`. Omit for every service. Send it empty to select only series whose sender did not set `service.name`. A service name containing a comma cannot be selected.+ * @maxLength 1024+ */+ service?: string;+ /**+ * Substring filter (case-insensitive) applied to metric names.+ * @maxLength 255+ */+ value?: string;+ };+export type MetricsValuesRetrieveParams = {/*** Max number of names to return. Defaults to 100; maximum 1000.diff --git a/services/mcp/src/generated/metrics/api.ts b/services/mcp/src/generated/metrics/api.tsindex b802a35979e0..406cbb6a383b 100644--- a/services/mcp/src/generated/metrics/api.ts+++ b/services/mcp/src/generated/metrics/api.ts@@ -394,7 +394,7 @@ export const MetricsQueryCreateBody = () => zod.object({})/**- * Distinct metric names for the team. Backs the picker UI.+ * Distinct metric names for the team. Backs the catalog UI.*/export const MetricsValuesRetrieveParams = () => zod.object({project_id: zod