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.

fix(data-catalog): four fixes for the metric creation flow (#84500)

Thiago Salvatore2573eada7d10
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 0fd7a8e90613..a1c017750cfe 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -2,6 +2,8 @@ import { router } from 'kea-router'
import { expectLogic, partial } from 'kea-test-utils'
import posthog from 'posthog-js'
+import { LemonDialog } from '@posthog/lemon-ui'
+
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
@@ -174,6 +176,8 @@ function createMockEditor(): any {
setModel: jest.fn(),
focus: jest.fn(),
getModel: () => null,
+ getSelection: () => null,
+ getPosition: () => null,
}
}
@@ -1066,6 +1070,92 @@ describe('sqlEditorLogic', () => {
})
})
+ describe('Save as metric', () => {
+ const PREFILL = {
+ name: 'monthly_active_users',
+ display_name: 'Monthly active users',
+ description: 'Unique users seen in the last 30 days',
+ unit: 'users',
+ }
+
+ function mountEditor(): void {
+ logic = sqlEditorLogic({
+ tabId: TAB_ID,
+ monaco: createMockMonaco(),
+ editor: createMockEditor(),
+ })
+ logic.mount()
+ }
+
+ it('picks up a prefill written by urls.sqlEditor', async () => {
+ mountEditor()
+
+ router.actions.push(urls.sqlEditor({ source: 'metric', metricPrefill: PREFILL }))
+
+ await expectLogic(logic).toDispatchActions(['setMetricPrefill']).toMatchValues({ metricPrefill: PREFILL })
+ })
+
+ it.each([
+ ['a bare string', 'monthly_active_users'],
+ ['an array', ['monthly_active_users']],
+ ['keys the dialog does not accept', { definition: 'SELECT 1', owner: 'me' }],
+ ['non-string values', { name: 42, description: true }],
+ ])('leaves an existing prefill untouched when the param is %s', async (_case, metricPrefill) => {
+ mountEditor()
+ logic.actions.setMetricPrefill(PREFILL)
+
+ router.actions.push(urls.sqlEditor(), { source: 'metric', metric_prefill: metricPrefill })
+
+ await expectLogic(logic).toDispatchActions(['createTab']).toMatchValues({ metricPrefill: PREFILL })
+ })
+
+ it('seeds the dialog with the prefill', async () => {
+ const openForm = jest.spyOn(LemonDialog, 'openForm').mockImplementation(() => {})
+ mountEditor()
+ logic.actions.setMetricPrefill(PREFILL)
+
+ logic.actions.saveAsMetric()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(openForm.mock.calls.at(-1)?.[0].initialValues).toEqual(PREFILL)
+ openForm.mockRestore()
+ })
+
+ it.each([
+ [
+ 'posts the optional fields when they are filled in',
+ PREFILL,
+ { display_name: 'Monthly active users', unit: 'users' },
+ ],
+ [
+ 'omits the optional fields when they are blank',
+ { ...PREFILL, display_name: '', unit: '' },
+ { display_name: undefined, unit: undefined },
+ ],
+ ])('%s', async (_case, fields, expectedOptionalFields) => {
+ let createBody: Record<string, any> | undefined
+ useMocks({
+ post: {
+ '/api/projects/:team_id/data_catalog/metrics/': async ({ request }) => {
+ createBody = (await request.json()) as Record<string, any>
+ return [200, { name: fields.name }]
+ },
+ },
+ })
+ mountEditor()
+ logic.actions.setMetricPrefill(PREFILL)
+ logic.actions.setQueryInput('SELECT count() FROM events')
+
+ logic.actions.saveAsMetricSubmit(fields)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(createBody).toMatchObject({ name: fields.name, description: fields.description })
+ expect(createBody?.display_name).toEqual(expectedOptionalFields.display_name)
+ expect(createBody?.unit).toEqual(expectedOptionalFields.unit)
+ expect(logic.values.metricPrefill).toBeNull()
+ })
+ })
+
describe('Update view', () => {
it('advances the saved baseline after updating so reverting to the original query re-enables Update view', async () => {
logic = sqlEditorLogic({
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index 7ffb39417313..6acfb5ae2c57 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -37,6 +37,7 @@ import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { clearLogicReference, initModel } from 'lib/monaco/CodeEditor'
@@ -82,7 +83,12 @@ import {
QueryBasedInsightModel,
} from '~/types'
-import { validateMetricDescription, validateMetricName } from 'products/data_catalog/frontend/common'
+import {
+ METRIC_FIELD_COPY,
+ MetricFormPrefill,
+ validateMetricDescription,
+ validateMetricName,
+} from 'products/data_catalog/frontend/common'
import {
dataCatalogMetricsCreate,
dataCatalogMetricsPartialUpdate,
@@ -270,6 +276,13 @@ export interface QueryTab {
export type SqlEditorSource = 'insight' | 'endpoint' | 'view' | 'metric'
+export interface SaveAsMetricFields {
+ name: string
+ display_name: string
+ description: string
+ unit: string
+}
+
export interface DataWarehouseAccessControlModalProps {
resource:
| AccessControlResourceType.WarehouseTable
@@ -430,6 +443,22 @@ function getTabHash(values: sqlEditorLogicType['values']): Record<string, any> {
return hash
}
+function parseMetricPrefill(value: unknown): MetricFormPrefill | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ return null
+ }
+
+ const source = value as Record<string, unknown>
+ const prefill: MetricFormPrefill = {}
+ for (const field of ['name', 'display_name', 'description', 'unit'] as const) {
+ if (typeof source[field] === 'string') {
+ prefill[field] = source[field] as string
+ }
+ }
+
+ return Object.keys(prefill).length ? prefill : null
+}
+
function parseOutputTab(value: unknown): OutputTab | null {
if (Object.values(OutputTab).includes(value as OutputTab)) {
return value as OutputTab
@@ -555,6 +584,7 @@ export interface sqlEditorLogicValues {
materializationModalView: DataWarehouseSavedQuery | null
metadata: HogQLMetadataResponse | null
metadataLoading: boolean
+ metricPrefill: MetricFormPrefill | null
metricUpdating: boolean
originalQueryInput: string | null | undefined
queryInput: string | null
@@ -934,12 +964,10 @@ export interface sqlEditorLogicActions {
value: true
}
saveAsMetricSubmit: (
- name: string,
- description: string,
+ fields: SaveAsMetricFields,
queryOverride?: string
) => {
- description: string
- name: string
+ fields: SaveAsMetricFields
queryOverride: string | undefined
}
saveAsView: (
@@ -1049,6 +1077,9 @@ export interface sqlEditorLogicActions {
setMetadataLoading: (loading: boolean) => {
loading: boolean
}
+ setMetricPrefill: (metricPrefill: MetricFormPrefill | null) => {
+ metricPrefill: MetricFormPrefill | null
+ }
setMetricUpdating: (updating: boolean) => {
updating: boolean
}
@@ -1321,11 +1352,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
dagId,
}),
saveAsMetric: true,
- saveAsMetricSubmit: (name: string, description: string, queryOverride?: string) => ({
- name,
- description,
+ saveAsMetricSubmit: (fields: SaveAsMetricFields, queryOverride?: string) => ({
+ fields,
queryOverride,
}),
+ setMetricPrefill: (metricPrefill: MetricFormPrefill | null) => ({ metricPrefill }),
setEditingMetricName: (metricName: string | null) => ({ metricName }),
updateEditingMetric: true,
setMetricUpdating: (updating: boolean) => ({ updating }),
@@ -1567,6 +1598,12 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
setEditorSource: (_, { source }) => source,
},
],
+ metricPrefill: [
+ null as MetricFormPrefill | null,
+ {
+ setMetricPrefill: (_, { metricPrefill }) => metricPrefill,
+ },
+ ],
dashboardId: [
null as number | null,
{
@@ -2671,14 +2708,35 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
const selectedRef = { current: candidates.queries[candidates.initialIndex] }
LemonDialog.openForm({
title: 'Save as metric',
- initialValues: { name: '', description: '' },
+ initialValues: {
+ name: '',
+ display_name: '',
+ description: '',
+ unit: '',
+ ...values.metricPrefill,
+ },
content: (
<>
- <LemonField name="name" label="Name">
- <LemonInput placeholder="monthly_active_users" autoFocus />
+ <LemonField name="name" label={METRIC_FIELD_COPY.name.label}>
+ <LemonInput placeholder={METRIC_FIELD_COPY.name.placeholder} autoFocus />
</LemonField>
- <LemonField name="description" label="Description" className="mt-2">
- <LemonInput placeholder="What this metric measures and how to read it" />
+ <LemonField
+ name="display_name"
+ label={METRIC_FIELD_COPY.displayName.label}
+ className="mt-2"
+ >
+ <LemonInput placeholder={METRIC_FIELD_COPY.displayName.placeholder} />
+ </LemonField>
+ <LemonField name="description" label={METRIC_FIELD_COPY.description.label} className="mt-2">
+ {/* stopPropagation keeps Enter from reaching the dialog form and submitting mid-sentence */}
+ <LemonTextArea
+ placeholder={METRIC_FIELD_COPY.description.placeholder}
+ minRows={2}
+ stopPropagation
+ />
+ </LemonField>
+ <LemonField name="unit" label={METRIC_FIELD_COPY.unit.label} className="mt-2">
+ <LemonInput placeholder={METRIC_FIELD_COPY.unit.placeholder} />
</LemonField>
<SaveTargetCycler
candidates={candidates}
@@ -2693,22 +2751,33 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
description: (description) =>
!description?.trim() ? 'Add a description' : validateMetricDescription(description.trim()),
},
- onSubmit: async ({ name, description }) =>
- actions.saveAsMetricSubmit(name.trim(), description.trim(), selectedRef.current),
+ onSubmit: async ({ name, display_name, description, unit }) =>
+ actions.saveAsMetricSubmit(
+ {
+ name: name.trim(),
+ display_name: display_name.trim(),
+ description: description.trim(),
+ unit: unit.trim(),
+ },
+ selectedRef.current
+ ),
})
},
- saveAsMetricSubmit: async ({ name, description, queryOverride }) => {
+ saveAsMetricSubmit: async ({ fields, queryOverride }) => {
const biEditorState = getActiveBIEditorState()
try {
const metric = await dataCatalogMetricsCreate(String(ApiConfig.getCurrentTeamId()), {
- name,
- description,
+ name: fields.name,
+ display_name: fields.display_name || undefined,
+ description: fields.description,
+ unit: fields.unit || undefined,
definition: normalizeRawQuerySource({
...(values.sourceQuery.source as HogQLQuery),
query: queryOverride ?? values.queryInput ?? '',
}) as unknown as Record<string, unknown>,
})
captureBIEditorQuerySaved(biEditorState, 'metric', 'create')
+ actions.setMetricPrefill(null)
lemonToast.success('Metric created')
router.actions.push(urls.dataCatalogMetric(metric.name))
} catch (error: any) {
@@ -3331,6 +3400,10 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
) {
actions.setEditorSource(searchParams.source)
}
+ const metricPrefillFromUrl = parseMetricPrefill(searchParams.metric_prefill)
+ if (metricPrefillFromUrl) {
+ actions.setMetricPrefill(metricPrefillFromUrl)
+ }
if (searchParams.dashboard) {
const parsed = parseInt(searchParams.dashboard, 10)
if (!isNaN(parsed)) {
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index 261c57a39f87..96021dd3ebbc 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -12,6 +12,8 @@ import {
} from '~/queries/schema/schema-general'
import { ActivityTab, AnnotationType, CommentType, OnboardingStepKey, SDKKey } from '~/types'
+import type { MetricFormPrefill } from 'products/data_catalog/frontend/common'
+
import type { BillingSectionId } from './billing/types'
import { DataPipelinesNewSceneKind } from './data-pipelines/DataPipelinesNewScene'
import { OutputTab } from './data-warehouse/editor/outputPaneLogic'
@@ -78,6 +80,7 @@ export const urls = {
dashboard,
filters,
metricName,
+ metricPrefill,
}: {
/** Raw SQL, or a node whose visualization settings (display, chartSettings) should survive the trip */
query?: string | DataVisualizationNode | DataTableNode
@@ -93,6 +96,8 @@ export const urls = {
filters?: HogQLFilters
/** Opens the editor bound to this data catalog metric so its query can be updated in place */
metricName?: string
+ /** Seeds the editor's "Save as metric" dialog with values already typed in the new metric modal */
+ metricPrefill?: MetricFormPrefill
} = {}): string => {
const params = new URLSearchParams()
@@ -122,6 +127,13 @@ export const urls = {
params.set('edit_metric', metricName)
}
+ if (metricPrefill) {
+ const filledPrefill = Object.fromEntries(Object.entries(metricPrefill).filter(([, value]) => !!value))
+ if (Object.keys(filledPrefill).length) {
+ params.set('metric_prefill', JSON.stringify(filledPrefill))
+ }
+ }
+
if (dashboard) {
params.set('dashboard', String(dashboard))
}
diff --git a/products/data_catalog/frontend/DataCatalogMetricScene.tsx b/products/data_catalog/frontend/DataCatalogMetricScene.tsx
index be938a22c85c..b1b8012f99e2 100644
--- a/products/data_catalog/frontend/DataCatalogMetricScene.tsx
+++ b/products/data_catalog/frontend/DataCatalogMetricScene.tsx
@@ -14,15 +14,12 @@ import {
} from '@posthog/icons'
import { LemonBanner, LemonButton, LemonDialog, LemonDivider, LemonTag } from '@posthog/lemon-ui'
-import { CodeSnippet, Language } from 'lib/components/CodeSnippet/CodeSnippet'
import { NotFound } from 'lib/components/NotFound'
import { TZLabel } from 'lib/components/TZLabel'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonInput } from 'lib/lemon-ui/LemonInput'
-import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
-import { LemonTable } from 'lib/lemon-ui/LemonTable'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
@@ -43,14 +40,9 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ScenePanel, ScenePanelActionsSection, ScenePanelInfoSection } from '~/layout/scenes/SceneLayout'
import { InsightShortId, SidePanelTab } from '~/types'
-import {
- humanizeDefinitionKind,
- METRIC_DESCRIPTION_MAX_LENGTH,
- METRIC_MARKDOWN_MAX_LENGTH,
- validateMetricName,
-} from './common'
-import { MetricMarkdownEditorField } from './components/MetricMarkdownEditorField'
-import { buildMetricRunPrompt, RunMetricWithAIButton } from './components/RunMetricWithAIButton'
+import { humanizeDefinitionKind, METRIC_DESCRIPTION_MAX_LENGTH, validateMetricName } from './common'
+import { MetricDefinition } from './components/MetricDefinition'
+import { buildMetricRunPrompt } from './components/RunMetricWithAIButton'
import {
dataCatalogMetricSceneLogic,
DataCatalogMetricSceneLogicProps,
@@ -482,267 +474,3 @@ function UnitEditor({ unit, onSave }: { unit: string; onSave: (unit: string) =>
</LemonField.Pure>
)
}
-
-function MarkdownDefinitionEditor({
- draftMarkdown,
- saving,
- onDraftMarkdown,
- onSave,
- onCancel,
-}: {
- draftMarkdown: string
- saving: boolean
- onDraftMarkdown: (value: string) => void
- onSave: (markdown: string) => void
- onCancel: () => void
-}): JSX.Element {
- const saveDisabledReason = !draftMarkdown.trim()
- ? 'Add the markdown definition'
- : draftMarkdown.length > METRIC_MARKDOWN_MAX_LENGTH
- ? `Keep the definition under ${METRIC_MARKDOWN_MAX_LENGTH} characters`
- : undefined
-
- return (
- <>
- <MetricMarkdownEditorField value={draftMarkdown} onChange={onDraftMarkdown} />
- <div className="flex gap-2">
- <LemonButton
- type="primary"
- size="small"
- loading={saving}
- disabledReason={saveDisabledReason}
- onClick={() => onSave(draftMarkdown)}
- >
- Save
- </LemonButton>
- <LemonButton type="secondary" size="small" onClick={onCancel}>
- Cancel
- </LemonButton>
- </div>
- </>
- )
-}
-
-function MetricDefinition({
- metric,
- editingDefinition,
- draftMarkdown,
- saving,
- runResult,
- runResultLoading,
- onDraftMarkdown,
- onEdit,
- onStartEditingMarkdown,
- onSaveMarkdown,
- onRun,
- onRunWithAI,
- runWithAIDisabledReason,
-}: {
- metric: DataCatalogMetricApi
- editingDefinition: boolean
- draftMarkdown: string
- saving: boolean
- runResult: DataCatalogMetricRunResult | null
- runResultLoading: boolean
- onDraftMarkdown: (value: string) => void
- onEdit: (editing: boolean) => void
- onStartEditingMarkdown: () => void
- onSaveMarkdown: (markdown: string) => void
- onRun: () => void
- onRunWithAI: () => void
- runWithAIDisabledReason?: string
-}): JSX.Element {
- const kind = metric.definition_kind
- const sql = definitionField(metric, 'query')
-
- const runButton = (
- <LemonButton
- type="primary"
- size="small"
- icon={<IconPlay />}
- loading={runResultLoading}
- disabledReason={kind ? undefined : 'This metric has no runnable definition yet'}
- onClick={onRun}
- >
- Run metric
- </LemonButton>
- )
- const results = runResult ? <RunResult runResult={runResult} /> : null
-
- if (kind === 'HogQLQuery') {
- return (
- <Section title="Definition">
- <CodeSnippet language={Language.SQL}>{sql}</CodeSnippet>
- <div className="flex gap-2">
- {runButton}
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconServer />}
- to={urls.sqlEditor({ source: 'metric', metricName: metric.name })}
- >
- Open in SQL editor
- </LemonButton>
- </div>
- {results}
- </Section>
- )
- }
-
- if (kind === 'MarkdownDefinition') {
- return (
- <Section title="Definition">
- {editingDefinition ? (
- <MarkdownDefinitionEditor
- draftMarkdown={draftMarkdown}
- saving={saving}
- onDraftMarkdown={onDraftMarkdown}
- onSave={onSaveMarkdown}
- onCancel={() => onEdit(false)}
- />
- ) : (
- <>
- <LemonMarkdown disableImages>
- {definitionField(metric, 'markdown') || '_No instructions yet._'}
- </LemonMarkdown>
- <div className="flex gap-2">
- <RunMetricWithAIButton onRun={onRunWithAI} disabledReason={runWithAIDisabledReason} />
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconPencil />}
- onClick={() => onEdit(true)}
- >
- Edit
- </LemonButton>
- </div>
- {/* No run result here: the envelope only echoes the definition above, and the
- agent reports the number in the side panel. */}
- </>
- )}
- </Section>
- )
- }
-
- if (!kind) {
- return (
- <Section title="Definition">
- {editingDefinition ? (
- <MarkdownDefinitionEditor
- draftMarkdown={draftMarkdown}
- saving={saving}
- onDraftMarkdown={onDraftMarkdown}
- onSave={onSaveMarkdown}
- onCancel={() => onEdit(false)}
- />
- ) : (
- <LemonBanner type="info">
- This metric is a stub with no definition. Add one to make it runnable.
- <div className="flex gap-2 mt-2">
- <LemonButton
- type="secondary"
- size="small"
- to={urls.sqlEditor({ source: 'metric', metricName: metric.name })}
- >
- Write SQL
- </LemonButton>
- <LemonButton type="secondary" size="small" onClick={onStartEditingMarkdown}>
- Write markdown
- </LemonButton>
- </div>
- </LemonBanner>
- )}
- </Section>
- )
- }
-
- return (
- <Section title="Definition">
- <p className="text-secondary">
- This metric is derived from an insight. Edit the query in the insight, then refresh the metric.
- </p>
- <div className="flex gap-2">
- {runButton}
- {metric.source_insight_short_id && (
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconGraph />}
- to={urls.insightView(metric.source_insight_short_id as InsightShortId)}
- >
- View source insight
- </LemonButton>
- )}
- </div>
- {results}
- </Section>
- )
-}
-
-interface DataCatalogMetricRunResult {
- results?: unknown
- instructions?: string | null
- compiled_query?: string | null
-}
-
-function RunResult({ runResult }: { runResult: DataCatalogMetricRunResult }): JSX.Element {
- return (
- <div className="flex flex-col gap-2">
- {runResult.instructions ? (
- <LemonMarkdown disableImages>{runResult.instructions}</LemonMarkdown>
- ) : (
- <ResultsTable results={runResult.results} />
- )}
- {runResult.compiled_query && (
- <LemonCollapse
- panels={[
- {
- key: 'compiled',
- header: 'Compiled query',
- content: <CodeSnippet language={Language.SQL}>{runResult.compiled_query}</CodeSnippet>,
- },
- ]}
- />
- )}
- </div>
- )
-}
-
-function ResultsTable({ results }: { results: unknown }): JSX.Element {
- const rows = Array.isArray(results) ? results : []
- if (rows.length === 0) {
- return <p className="text-secondary">No results.</p>
- }
- const first = rows[0]
- if (first && typeof first === 'object' && !Array.isArray(first)) {
- const keys = Object.keys(first as Record<string, unknown>)
- return (
- <LemonTable
- dataSource={rows as Record<string, unknown>[]}
- columns={keys.map((columnKey) => ({
- title: columnKey,
- key: columnKey,
- render: (_: unknown, row: Record<string, unknown>) => formatCell(row[columnKey]),
- }))}
- size="small"
- />
- )
- }
- return <CodeSnippet language={Language.JSON}>{JSON.stringify(results, null, 2)}</CodeSnippet>
-}
-
-function formatCell(value: unknown): string {
- if (value == null) {
- return ''
- }
- return typeof value === 'object' ? JSON.stringify(value) : String(value)
-}
-
-function Section({ title, children }: { title: string; children: ReactNode }): JSX.Element {
- return (
- <div className="flex flex-col gap-2">
- <h3 className="mb-0">{title}</h3>
- {children}
- </div>
- )
-}
diff --git a/products/data_catalog/frontend/common.ts b/products/data_catalog/frontend/common.ts
index 5235d822c8eb..4c298f5576e9 100644
--- a/products/data_catalog/frontend/common.ts
+++ b/products/data_catalog/frontend/common.ts
@@ -1,5 +1,20 @@
export const METRIC_NAME_REGEX = /^[A-Za-z][A-Za-z0-9_]*$/
+/** Values typed in the new metric modal, carried into the SQL editor's "Save as metric" dialog. */
+export interface MetricFormPrefill {
+ name?: string
+ display_name?: string
+ description?: string
+ unit?: string
+}
+
+export const METRIC_FIELD_COPY = {
+ name: { label: 'Name', placeholder: 'monthly_active_users' },
+ displayName: { label: 'Display name', placeholder: 'Monthly active users' },
+ description: { label: 'Description', placeholder: 'What this metric measures and how to read it' },
+ unit: { label: 'Unit', placeholder: 'users' },
+} as const
+
export function humanizeDefinitionKind(kind: string | null): string {
if (!kind) {
return 'Stub'
diff --git a/products/data_catalog/frontend/components/MetricDefinition.tsx b/products/data_catalog/frontend/components/MetricDefinition.tsx
new file mode 100644
index 000000000000..11e4ddddb52e
--- /dev/null
+++ b/products/data_catalog/frontend/components/MetricDefinition.tsx
@@ -0,0 +1,297 @@
+import { IconGraph, IconPencil, IconPlay, IconServer } from '@posthog/icons'
+import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
+
+import { CodeSnippet, Language } from 'lib/components/CodeSnippet/CodeSnippet'
+import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
+import { LemonTable } from 'lib/lemon-ui/LemonTable'
+import { urls } from 'scenes/urls'
+
+import { InsightShortId } from '~/types'
+
+import { METRIC_MARKDOWN_MAX_LENGTH } from '../common'
+import { definitionField } from '../dataCatalogMetricSceneLogic'
+import type { DataCatalogMetricApi } from '../generated/api.schemas'
+import { MetricMarkdownEditorField } from './MetricMarkdownEditorField'
+import { RunMetricWithAIButton } from './RunMetricWithAIButton'
+import { Section } from './Section'
+
+export interface DataCatalogMetricRunResult {
+ results?: unknown
+ instructions?: string | null
+ compiled_query?: string | null
+}
+
+export function MetricDefinition({
+ metric,
+ editingDefinition,
+ draftMarkdown,
+ saving,
+ runResult,
+ runResultLoading,
+ onDraftMarkdown,
+ onEdit,
+ onStartEditingMarkdown,
+ onSaveMarkdown,
+ onRun,
+ onRunWithAI,
+ runWithAIDisabledReason,
+}: {
+ metric: DataCatalogMetricApi
+ editingDefinition: boolean
+ draftMarkdown: string
+ saving: boolean
+ runResult: DataCatalogMetricRunResult | null
+ runResultLoading: boolean
+ onDraftMarkdown: (value: string) => void
+ onEdit: (editing: boolean) => void
+ onStartEditingMarkdown: () => void
+ onSaveMarkdown: (markdown: string) => void
+ onRun: () => void
+ onRunWithAI: () => void
+ runWithAIDisabledReason?: string
+}): JSX.Element {
+ const kind = metric.definition_kind
+ const sql = definitionField(metric, 'query')
+
+ const runButton = (
+ <LemonButton
+ type="primary"
+ size="small"
+ icon={<IconPlay />}
+ loading={runResultLoading}
+ disabledReason={kind ? undefined : 'This metric has no runnable definition yet'}
+ onClick={onRun}
+ >
+ Run metric
+ </LemonButton>
+ )
+ const results = runResult ? <RunResult runResult={runResult} /> : null
+
+ const sourceInsightButton = metric.source_insight_short_id ? (
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconGraph />}
+ to={urls.insightView(metric.source_insight_short_id as InsightShortId)}
+ >
+ View source insight
+ </LemonButton>
+ ) : null
+
+ if (kind === 'HogQLQuery') {
+ return (
+ <Section title="Definition">
+ <CodeSnippet language={Language.SQL}>{sql}</CodeSnippet>
+ <div className="flex gap-2">
+ {runButton}
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconServer />}
+ to={urls.sqlEditor({ source: 'metric', metricName: metric.name })}
+ >
+ Open in SQL editor
+ </LemonButton>
+ {sourceInsightButton}
+ </div>
+ {results}
+ </Section>
+ )
+ }
+
+ if (kind === 'MarkdownDefinition') {
+ return (
+ <Section title="Definition">
+ {editingDefinition ? (
+ <MarkdownDefinitionEditor
+ draftMarkdown={draftMarkdown}
+ saving={saving}
+ onDraftMarkdown={onDraftMarkdown}
+ onSave={onSaveMarkdown}
+ onCancel={() => onEdit(false)}
+ />
+ ) : (
+ <>
+ <LemonMarkdown disableImages>
+ {definitionField(metric, 'markdown') || '_No instructions yet._'}
+ </LemonMarkdown>
+ <div className="flex gap-2">
+ <RunMetricWithAIButton onRun={onRunWithAI} disabledReason={runWithAIDisabledReason} />
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconPencil />}
+ onClick={() => onEdit(true)}
+ >
+ Edit
+ </LemonButton>
+ </div>
+ {/* No run result here: the envelope only echoes the definition above, and the
+ agent reports the number in the side panel. */}
+ </>
+ )}
+ </Section>
+ )
+ }
+
+ if (!kind) {
+ return (
+ <Section title="Definition">
+ {editingDefinition ? (
+ <MarkdownDefinitionEditor
+ draftMarkdown={draftMarkdown}
+ saving={saving}
+ onDraftMarkdown={onDraftMarkdown}
+ onSave={onSaveMarkdown}
+ onCancel={() => onEdit(false)}
+ />
+ ) : (
+ <LemonBanner type="info">
+ This metric is a stub with no definition. Add one to make it runnable.
+ <div className="flex gap-2 mt-2">
+ <LemonButton
+ type="secondary"
+ size="small"
+ to={urls.sqlEditor({ source: 'metric', metricName: metric.name })}
+ >
+ Write SQL
+ </LemonButton>
+ <LemonButton type="secondary" size="small" onClick={onStartEditingMarkdown}>
+ Write markdown
+ </LemonButton>
+ </div>
+ </LemonBanner>
+ )}
+ </Section>
+ )
+ }
+
+ return (
+ <Section title="Definition">
+ {sourceInsightButton ? (
+ <p className="text-secondary">
+ This metric is derived from an insight. Edit the query in the insight, then refresh the metric.
+ </p>
+ ) : (
+ <>
+ <p className="text-secondary">
+ This metric was created from a query definition and has no linked insight. Run it to see the
+ current results.
+ </p>
+ <LemonCollapse
+ panels={[
+ {
+ key: 'definition',
+ header: 'View definition',
+ content: (
+ <CodeSnippet language={Language.JSON}>
+ {JSON.stringify(metric.definition, null, 2)}
+ </CodeSnippet>
+ ),
+ },
+ ]}
+ />
+ </>
+ )}
+ <div className="flex gap-2">
+ {runButton}
+ {sourceInsightButton}
+ </div>
+ {results}
+ </Section>
+ )
+}
+
+function MarkdownDefinitionEditor({
+ draftMarkdown,
+ saving,
+ onDraftMarkdown,
+ onSave,
+ onCancel,
+}: {
+ draftMarkdown: string
+ saving: boolean
+ onDraftMarkdown: (value: string) => void
+ onSave: (markdown: string) => void
+ onCancel: () => void
+}): JSX.Element {
+ const saveDisabledReason = !draftMarkdown.trim()
+ ? 'Add the markdown definition'
+ : draftMarkdown.length > METRIC_MARKDOWN_MAX_LENGTH
+ ? `Keep the definition under ${METRIC_MARKDOWN_MAX_LENGTH} characters`
+ : undefined
+
+ return (
+ <>
+ <MetricMarkdownEditorField value={draftMarkdown} onChange={onDraftMarkdown} />
+ <div className="flex gap-2">
+ <LemonButton
+ type="primary"
+ size="small"
+ loading={saving}
+ disabledReason={saveDisabledReason}
+ onClick={() => onSave(draftMarkdown)}
+ >
+ Save
+ </LemonButton>
+ <LemonButton type="secondary" size="small" onClick={onCancel}>
+ Cancel
+ </LemonButton>
+ </div>
+ </>
+ )
+}
+
+function RunResult({ runResult }: { runResult: DataCatalogMetricRunResult }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-2">
+ {runResult.instructions ? (
+ <LemonMarkdown disableImages>{runResult.instructions}</LemonMarkdown>
+ ) : (
+ <ResultsTable results={runResult.results} />
+ )}
+ {runResult.compiled_query && (
+ <LemonCollapse
+ panels={[
+ {
+ key: 'compiled',
+ header: 'Compiled query',
+ content: <CodeSnippet language={Language.SQL}>{runResult.compiled_query}</CodeSnippet>,
+ },
+ ]}
+ />
+ )}
+ </div>
+ )
+}
+
+function ResultsTable({ results }: { results: unknown }): JSX.Element {
+ const rows = Array.isArray(results) ? results : []
+ if (rows.length === 0) {
+ return <p className="text-secondary">No results.</p>
+ }
+ const first = rows[0]
+ if (first && typeof first === 'object' && !Array.isArray(first)) {
+ const keys = Object.keys(first as Record<string, unknown>)
+ return (
+ <LemonTable
+ dataSource={rows as Record<string, unknown>[]}
+ columns={keys.map((columnKey) => ({
+ title: columnKey,
+ key: columnKey,
+ render: (_: unknown, row: Record<string, unknown>) => formatCell(row[columnKey]),
+ }))}
+ size="small"
+ />
+ )
+ }
+ return <CodeSnippet language={Language.JSON}>{JSON.stringify(results, null, 2)}</CodeSnippet>
+}
+
+function formatCell(value: unknown): string {
+ if (value == null) {
+ return ''
+ }
+ return typeof value === 'object' ? JSON.stringify(value) : String(value)
+}
diff --git a/products/data_catalog/frontend/components/NewMetricModal.tsx b/products/data_catalog/frontend/components/NewMetricModal.tsx
index 66dee890d6bd..ffa536184014 100644
--- a/products/data_catalog/frontend/components/NewMetricModal.tsx
+++ b/products/data_catalog/frontend/components/NewMetricModal.tsx
@@ -9,7 +9,7 @@ import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'
-import { validateMetricDescription, validateMetricName } from '../common'
+import { METRIC_FIELD_COPY, validateMetricDescription, validateMetricName } from '../common'
import { metricsLogic, NewMetricDefinitionType } from '../metricsLogic'
const DEFINITION_TYPE_OPTIONS: { value: NewMetricDefinitionType; label: string }[] = [
@@ -43,44 +43,50 @@ export function NewMetricModal(): JSX.Element {
<LemonModal.Content>
<div className="flex flex-col gap-4">
<LemonField.Pure
- label="Name"
+ label={METRIC_FIELD_COPY.name.label}
error={newMetricForm.name.trim() ? nameError : undefined}
info="A unique identifier for the metric, like monthly_active_users."
>
<LemonInput
value={newMetricForm.name}
onChange={(name) => setNewMetricForm({ name })}
- placeholder="monthly_active_users"
+ placeholder={METRIC_FIELD_COPY.name.placeholder}
autoFocus
/>
</LemonField.Pure>
- <LemonField.Pure label="Display name" info="A human-friendly name shown in the catalog.">
+ <LemonField.Pure
+ label={METRIC_FIELD_COPY.displayName.label}
+ info="A human-friendly name shown in the catalog."
+ >
<LemonInput
value={newMetricForm.display_name}
onChange={(display_name) => setNewMetricForm({ display_name })}
- placeholder="Monthly active users"
+ placeholder={METRIC_FIELD_COPY.displayName.placeholder}
/>
</LemonField.Pure>
<LemonField.Pure
- label="Description"
+ label={METRIC_FIELD_COPY.description.label}
error={descriptionError}
info="1-3 sentences: what the metric means and what it serves."
>
<LemonTextArea
value={newMetricForm.description}
onChange={(description) => setNewMetricForm({ description })}
- placeholder="What this metric measures and how to read it"
+ placeholder={METRIC_FIELD_COPY.description.placeholder}
minRows={2}
/>
</LemonField.Pure>
- <LemonField.Pure label="Unit" info="How the result is measured, like users, dollars, or percent.">
+ <LemonField.Pure
+ label={METRIC_FIELD_COPY.unit.label}
+ info="How the result is measured, like users, dollars, or percent."
+ >
<LemonInput
value={newMetricForm.unit}
onChange={(unit) => setNewMetricForm({ unit })}
- placeholder="users"
+ placeholder={METRIC_FIELD_COPY.unit.placeholder}
/>
</LemonField.Pure>
@@ -93,13 +99,13 @@ export function NewMetricModal(): JSX.Element {
</LemonField.Pure>
{newMetricForm.definitionType === 'markdown' && (
- <LemonBanner type="info">
+ <LemonBanner type="info" hideIcon>
You'll write the definition on the metric page after creating it.
</LemonBanner>
)}
{newMetricForm.definitionType === 'sql' && (
- <LemonBanner type="info">
+ <LemonBanner type="info" hideIcon>
<div className="flex flex-col items-start gap-2">
<span>Write the query in the SQL editor, then use Save as metric to define it.</span>
<LemonButton
diff --git a/products/data_catalog/frontend/components/Section.tsx b/products/data_catalog/frontend/components/Section.tsx
new file mode 100644
index 000000000000..56b5f011de25
--- /dev/null
+++ b/products/data_catalog/frontend/components/Section.tsx
@@ -0,0 +1,10 @@
+import { ReactNode } from 'react'
+
+export function Section({ title, children }: { title: string; children: ReactNode }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-2">
+ <h3 className="mb-0">{title}</h3>
+ {children}
+ </div>
+ )
+}
diff --git a/products/data_catalog/frontend/components/metricDefinition.test.tsx b/products/data_catalog/frontend/components/metricDefinition.test.tsx
new file mode 100644
index 000000000000..e338d74ba0c6
--- /dev/null
+++ b/products/data_catalog/frontend/components/metricDefinition.test.tsx
@@ -0,0 +1,73 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+
+import { initKeaTests } from '~/test/init'
+
+import type { DataCatalogMetricApi } from '../generated/api.schemas'
+import { MetricDefinition } from './MetricDefinition'
+
+const SOURCE_INSIGHT_ACTION = 'View source insight'
+
+function buildMetric(overrides: Partial<DataCatalogMetricApi> = {}): DataCatalogMetricApi {
+ return {
+ id: 'metric-1',
+ name: 'weekly_file_uploads',
+ description: 'Weekly file uploads',
+ definition_kind: 'TrendsQuery',
+ definition: { kind: 'TrendsQuery', series: [{ kind: 'EventsNode', event: 'uploaded_file' }] },
+ source_insight_short_id: null,
+ status: 'proposed',
+ is_drifted: false,
+ owner: null,
+ ...overrides,
+ } as DataCatalogMetricApi
+}
+
+function renderDefinition(metric: DataCatalogMetricApi): void {
+ render(
+ <MetricDefinition
+ metric={metric}
+ editingDefinition={false}
+ draftMarkdown=""
+ saving={false}
+ runResult={null}
+ runResultLoading={false}
+ onDraftMarkdown={jest.fn()}
+ onEdit={jest.fn()}
+ onStartEditingMarkdown={jest.fn()}
+ onSaveMarkdown={jest.fn()}
+ onRun={jest.fn()}
+ onRunWithAI={jest.fn()}
+ />
+ )
+}
+
+describe('MetricDefinition', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ it.each([
+ ['a SQL metric', 'HogQLQuery'],
+ ['a structured-query metric', 'TrendsQuery'],
+ ])('links back to the source insight for %s that has one', (_label, definitionKind) => {
+ renderDefinition(buildMetric({ definition_kind: definitionKind, source_insight_short_id: 'abc123' }))
+
+ expect(screen.getByText(SOURCE_INSIGHT_ACTION)).toBeInTheDocument()
+ })
+
+ it('offers the definition instead of claiming an insight when none is linked', () => {
+ renderDefinition(buildMetric({ source_insight_short_id: null }))
+
+ // The panel used to claim every non-SQL, non-markdown metric came from an insight, leaving
+ // the reader with copy that pointed at nothing.
+ expect(screen.queryByText(/derived from an insight/)).not.toBeInTheDocument()
+ expect(screen.queryByText(SOURCE_INSIGHT_ACTION)).not.toBeInTheDocument()
+ expect(screen.getByText('View definition')).toBeInTheDocument()
+ })
+})
diff --git a/products/data_catalog/frontend/metricsLogic.test.ts b/products/data_catalog/frontend/metricsLogic.test.ts
index 2924f2fbe202..94633248cf93 100644
--- a/products/data_catalog/frontend/metricsLogic.test.ts
+++ b/products/data_catalog/frontend/metricsLogic.test.ts
@@ -154,6 +154,36 @@ describe('metricsLogic', () => {
expect(logic.values.newMetricModalOpen).toEqual(true)
})
+ it.each([
+ [
+ 'carries the typed values into the SQL editor URL',
+ {
+ name: 'monthly_active_users',
+ display_name: 'Monthly active users',
+ description: 'Unique users seen in the last 30 days',
+ unit: 'users',
+ },
+ {
+ name: 'monthly_active_users',
+ display_name: 'Monthly active users',
+ description: 'Unique users seen in the last 30 days',
+ unit: 'users',
+ },
+ ],
+ ['omits the prefill from the SQL editor URL when nothing was typed', {}, undefined],
+ ])('%s', async (_case, formValues, expectedPrefill) => {
+ logic.actions.openNewMetricModal()
+ logic.actions.setNewMetricForm(formValues)
+
+ logic.actions.openSqlEditorForNewMetric()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.newMetricModalOpen).toEqual(false)
+ expect(router.values.location.pathname).toContain(urls.sqlEditor())
+ expect(router.values.searchParams.source).toEqual('metric')
+ expect(router.values.searchParams.metric_prefill).toEqual(expectedPrefill)
+ })
+
it('removes the row when delete succeeds', async () => {
;(dataCatalogMetricsDestroy as jest.Mock).mockResolvedValue(undefined)
diff --git a/products/data_catalog/frontend/metricsLogic.tsx b/products/data_catalog/frontend/metricsLogic.tsx
index 66ee60bb3193..536f1d185b5b 100644
--- a/products/data_catalog/frontend/metricsLogic.tsx
+++ b/products/data_catalog/frontend/metricsLogic.tsx
@@ -325,8 +325,11 @@ export const metricsLogic = kea<metricsLogicType>([
openNewMetricModal: () => actions.loadSavedInsights(),
setInsightSearch: () => actions.loadSavedInsights(),
openSqlEditorForNewMetric: () => {
+ const { name, display_name, description, unit } = values.newMetricForm
actions.closeNewMetricModal()
- router.actions.push(urls.sqlEditor({ source: 'metric' }))
+ router.actions.push(
+ urls.sqlEditor({ source: 'metric', metricPrefill: { name, display_name, description, unit } })
+ )
},
createMetric: async () => {
if (values.isCreatingMetric) {
diff --git a/products/data_catalog/mcp/tools.yaml b/products/data_catalog/mcp/tools.yaml
index ee907cc931b4..25d65a599a18 100644
--- a/products/data_catalog/mcp/tools.yaml
+++ b/products/data_catalog/mcp/tools.yaml
@@ -129,7 +129,10 @@ tools:
metric. Keep 'description' to 1-3 sentences saying what the metric means and what it serves - never a
walkthrough of the query or calculation steps (the definition carries those); put rationale for the chosen
definition in 'reasoning'. There is no list tool: discover existing metrics with execute-sql over
- system.information_schema.metrics.
+ system.information_schema.metrics. When the metric comes from an existing saved insight, pass that insight's
+ 'source_insight_short_id' instead of copying its query into 'definition' - the two are mutually exclusive.
+ The server snapshots the insight's query, tracks drift against it, and the metric then links back to the
+ insight so a person can edit the query where it lives.
exclude_params:
- created_source
inject_body:
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index a36a67891b66..cc679b04de0d 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2444,7 +2444,7 @@
"feature_flag": "product-data-catalog"
},
"data-catalog-metric-create": {
- "description": "Create a canonical metric, or refine the live one already holding this name (upsert on name; always lands 'proposed'). A deleted metric's name is available again - creating with it starts a fresh metric with no history carried over. The definition can be an executable query (HogQLQuery / TrendsQuery / FunnelsQuery / an event node) that the query runner computes, OR an agent-calculated markdown definition - {\"kind\": \"MarkdownDefinition\", \"markdown\": \"<numbered steps to calculate the metric>\"} - which an agent follows to produce the number. Prefer an executable definition when the metric is deterministic; use a markdown definition when the calculation needs judgment or multiple steps. Only propose a definition that was explicitly asked for or that you have seen reused at least twice - do not speculatively catalog one-off queries. If you derived a number and no metric exists for it, offer to save the derivation as a proposed metric. Keep 'description' to 1-3 sentences saying what the metric means and what it serves - never a walkthrough of the query or calculation steps (the definition carries those); put rationale for the chosen definition in 'reasoning'. There is no list tool: discover existing metrics with execute-sql over system.information_schema.metrics.",
+ "description": "Create a canonical metric, or refine the live one already holding this name (upsert on name; always lands 'proposed'). A deleted metric's name is available again - creating with it starts a fresh metric with no history carried over. The definition can be an executable query (HogQLQuery / TrendsQuery / FunnelsQuery / an event node) that the query runner computes, OR an agent-calculated markdown definition - {\"kind\": \"MarkdownDefinition\", \"markdown\": \"<numbered steps to calculate the metric>\"} - which an agent follows to produce the number. Prefer an executable definition when the metric is deterministic; use a markdown definition when the calculation needs judgment or multiple steps. Only propose a definition that was explicitly asked for or that you have seen reused at least twice - do not speculatively catalog one-off queries. If you derived a number and no metric exists for it, offer to save the derivation as a proposed metric. Keep 'description' to 1-3 sentences saying what the metric means and what it serves - never a walkthrough of the query or calculation steps (the definition carries those); put rationale for the chosen definition in 'reasoning'. There is no list tool: discover existing metrics with execute-sql over system.information_schema.metrics. When the metric comes from an existing saved insight, pass that insight's 'source_insight_short_id' instead of copying its query into 'definition' - the two are mutually exclusive. The server snapshots the insight's query, tracks drift against it, and the metric then links back to the insight so a person can edit the query where it lives.",
"category": "Data catalog",
"feature": "data_catalog",
"summary": "Create or refine a catalog metric",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 69f5052a834b..dd5c4abce4c2 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2459,7 +2459,7 @@
"feature_flag": "product-data-catalog"
},
"data-catalog-metric-create": {
- "description": "Create a canonical metric, or refine the live one already holding this name (upsert on name; always lands 'proposed'). A deleted metric's name is available again - creating with it starts a fresh metric with no history carried over. The definition can be an executable query (HogQLQuery / TrendsQuery / FunnelsQuery / an event node) that the query runner computes, OR an agent-calculated markdown definition - {\"kind\": \"MarkdownDefinition\", \"markdown\": \"<numbered steps to calculate the metric>\"} - which an agent follows to produce the number. Prefer an executable definition when the metric is deterministic; use a markdown definition when the calculation needs judgment or multiple steps. Only propose a definition that was explicitly asked for or that you have seen reused at least twice - do not speculatively catalog one-off queries. If you derived a number and no metric exists for it, offer to save the derivation as a proposed metric. Keep 'description' to 1-3 sentences saying what the metric means and what it serves - never a walkthrough of the query or calculation steps (the definition carries those); put rationale for the chosen definition in 'reasoning'. There is no list tool: discover existing metrics with execute-sql over system.information_schema.metrics.",
+ "description": "Create a canonical metric, or refine the live one already holding this name (upsert on name; always lands 'proposed'). A deleted metric's name is available again - creating with it starts a fresh metric with no history carried over. The definition can be an executable query (HogQLQuery / TrendsQuery / FunnelsQuery / an event node) that the query runner computes, OR an agent-calculated markdown definition - {\"kind\": \"MarkdownDefinition\", \"markdown\": \"<numbered steps to calculate the metric>\"} - which an agent follows to produce the number. Prefer an executable definition when the metric is deterministic; use a markdown definition when the calculation needs judgment or multiple steps. Only propose a definition that was explicitly asked for or that you have seen reused at least twice - do not speculatively catalog one-off queries. If you derived a number and no metric exists for it, offer to save the derivation as a proposed metric. Keep 'description' to 1-3 sentences saying what the metric means and what it serves - never a walkthrough of the query or calculation steps (the definition carries those); put rationale for the chosen definition in 'reasoning'. There is no list tool: discover existing metrics with execute-sql over system.information_schema.metrics. When the metric comes from an existing saved insight, pass that insight's 'source_insight_short_id' instead of copying its query into 'definition' - the two are mutually exclusive. The server snapshots the insight's query, tracks drift against it, and the metric then links back to the insight so a person can edit the query where it lives.",
"category": "Data catalog",
"feature": "data_catalog",
"summary": "Create or refine a catalog metric",
diff --git a/services/mcp/tests/unit/data-catalog-metric-scopes.test.ts b/services/mcp/tests/unit/data-catalog-metric-scopes.test.ts
new file mode 100644
index 000000000000..58d0a528dd4a
--- /dev/null
+++ b/services/mcp/tests/unit/data-catalog-metric-scopes.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest'
+
+import { hasScopes } from '@/lib/api'
+import { getToolDefinition } from '@/tools/toolDefinitions'
+
+// Tool scopes are all-or-nothing at catalog-filter time (`hasScopes` requires every declared
+// scope), while MetricViewSet.dangerously_get_required_scopes only demands insight:read when the
+// request supplies source_insight_short_id. Declaring insight:read statically would hide these
+// tools from a data_catalog:write-only credential doing an ordinary definition write.
+describe('data catalog metric write tools', () => {
+ it.each(['data-catalog-metric-create', 'data-catalog-metric-update'])(
+ '%s stays visible to a data_catalog:write-only credential',
+ (toolName) => {
+ const required = getToolDefinition(toolName).required_scopes ?? []
+
+ expect(hasScopes(['data_catalog:write'], required)).toBe(true)
+ }
+ )
+})