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.

5.6 KB
Raw Blame
import { describe, expect, it } from 'vitest'
import { z } from 'zod'

import { GENERATED_TOOLS } from '@/tools/generated/product_analytics'

const BARE_TRENDS_QUERY = {
    kind: 'TrendsQuery',
    series: [{ kind: 'EventsNode', event: '$pageview', name: '$pageview' }],
    dateRange: { date_from: '-7d' },
    interval: 'day',
}

// Every shape `MCPInsightSerializer.validate_query` normalizes and saves. The bare ones are
// wrapped server-side, so the tool boundary has to pass them through rather than reject them.
const acceptedQueries = [
    {
        shape: 'wrapped InsightVizNode',
        query: { kind: 'InsightVizNode', source: BARE_TRENDS_QUERY },
    },
    {
        shape: 'wrapped DataVisualizationNode',
        query: {
            kind: 'DataVisualizationNode',
            source: { kind: 'HogQLQuery', query: 'select 1 as value' },
            chartSettings: { legendPosition: 'bottom', showAnnotations: true },
            tableSettings: {
                columns: [{ column: 'value', settings: { display: { description: 'Value in USD' } } }],
            },
        },
    },
    {
        shape: 'BI worksheet',
        query: {
            kind: 'BIVisualizationNode',
            source: { kind: 'HogQLQuery', query: 'SELECT 1 AS total' },
            display: 'ActionsTable',
            tableSettings: { columns: [{ column: 'total', settings: { display: { label: 'Total' } } }] },
            config: {
                chartType: 'ActionsTable',
                source: null,
                rows: [],
                columns: [],
                values: [],
                filters: [],
                limit: 1000,
                sort: null,
                querySnapshot: { kind: 'HogQLQuery', query: 'SELECT 1 AS total' },
                catalogMetric: 'example_total',
                rowFilterGroup: { operator: 'AND', filters: [], groups: [{ operator: 'OR', filters: [], groups: [] }] },
            },
        },
    },
    { shape: 'bare TrendsQuery', query: BARE_TRENDS_QUERY },
    { shape: 'bare HogQLQuery', query: { kind: 'HogQLQuery', query: 'select 1' } },
    {
        shape: 'bare WebStatsTableQuery',
        query: { kind: 'WebStatsTableQuery', breakdownBy: 'Page', properties: [], dateRange: { date_from: '-7d' } },
    },
    {
        shape: 'bare MetricsQuery',
        query: {
            kind: 'MetricsQuery',
            clauses: [{ name: 'a', metricName: 'process.cpu.utilization', aggregation: 'avg' }],
            dateRange: { date_from: '-24h' },
        },
    },
    {
        shape: 'bare MetricsHistogramQuery',
        query: { kind: 'MetricsHistogramQuery', metricName: 'http.server.duration' },
    },
]

const tools = [
    { tool: 'insight-create', base: {} },
    { tool: 'insight-update', base: { id: 1 } },
]

const cases = tools.flatMap(({ tool, base }) => acceptedQueries.map((accepted) => ({ tool, base, ...accepted })))

describe('insight query shapes', () => {
    it.each(cases)('$tool accepts a $shape', ({ tool, base, query }) => {
        const { schema } = GENERATED_TOOLS[tool]!()

        const result = schema.safeParse({ ...base, query })
        expect(result.success).toBe(true)
        expect(result.data?.query).toMatchObject(query)
    })

    it.each(tools)('$tool sends a bare query on to the endpoint whole', ({ tool, base }) => {
        const { schema } = GENERATED_TOOLS[tool]!()

        const result = schema.safeParse({ ...base, query: BARE_TRENDS_QUERY })

        // The bare branches carry an index signature so the query keeps its body. Without it zod
        // strips every key it does not declare, and the insight saves as an empty TrendsQuery.
        expect(result.success).toBe(true)
        expect((result.data as { query: unknown }).query).toEqual(BARE_TRENDS_QUERY)
    })

    it.each(tools)('$tool keeps the pie chart options of a wrapped query', ({ tool, base }) => {
        const { schema } = GENERATED_TOOLS[tool]!()
        const query = {
            kind: 'InsightVizNode',
            source: { ...BARE_TRENDS_QUERY, trendsFilter: { display: 'ActionsPie' } },
            vizSpecificOptions: { ActionsPie: { hideAggregation: true } },
        }

        const result = schema.safeParse({ ...base, query })

        expect(result.success).toBe(true)
        expect((result.data as { query: unknown }).query).toEqual(query)
    })

    it.each(tools)('$tool rejects a query kind the endpoint refuses to save', ({ tool, base }) => {
        const { schema } = GENERATED_TOOLS[tool]!()

        const query = { kind: 'ErrorTrackingQuery', dateRange: { date_from: '-7d' }, orderBy: 'last_seen' }

        expect(schema.safeParse({ ...base, query }).success).toBe(false)
    })

    it.each(tools)('$tool names every SQL display type in the display guidance', ({ tool }) => {
        const schema = z.toJSONSchema(GENERATED_TOOLS[tool]!().schema, { io: 'input', reused: 'inline' })
        const display = findSqlDisplay(schema)!

        for (const value of display.enum) {
            expect(display.description).toContain(`\`${value}\``)
        }
    })
})

function findSqlDisplay(node: unknown): { enum: string[]; description: string } | undefined {
    if (!node || typeof node !== 'object') {
        return undefined
    }
    const display = (node as { properties?: { display?: { enum?: string[]; description: string } } }).properties
        ?.display
    if (display?.enum?.includes('ActionsTable')) {
        return display as { enum: string[]; description: string }
    }
    for (const child of Object.values(node)) {
        const found = findSqlDisplay(child)
        if (found) {
            return found
        }
    }
    return undefined
}