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(mcp-analytics): probe setup from event definitions (#74098)

Rafael Audibert50b83035a2b0
diff --git a/.agents/skills/writing-kea-logics/SKILL.md b/.agents/skills/writing-kea-logics/SKILL.md
index 51433da3fb81..06fe7ca4bd29 100644
--- a/.agents/skills/writing-kea-logics/SKILL.md
+++ b/.agents/skills/writing-kea-logics/SKILL.md
@@ -57,6 +57,8 @@ If your work overlaps it, read the companion skill first.
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import * as api from 'products/foo/frontend/generated/api'
+
export interface FooLogicProps {
fooId: string
}
@@ -81,7 +83,7 @@ export const fooLogic = kea<fooLogicType>([
connect(() => ({ values: [teamLogic, ['currentTeamId']] })),
actions({ setName: (name: string) => ({ name }) }),
loaders(({ props }) => ({
- foo: [null as Foo | null, { loadFoo: async () => api.foos.get(props.fooId) }],
+ foo: [null as Foo | null, { loadFoo: async () => api.foosRetrieve(props.fooId) }],
})),
reducers({ name: ['', { setName: (_, { name }) => name }] }),
selectors({ nameUpper: [(s) => [s.name], (name): string => name.toUpperCase()] }),
@@ -164,22 +166,18 @@ Inline type blocks are produced by `kea-typegen` 3.8.3. Commands:
- `pnpm --filter=@posthog/frontend typegen:write` — one-shot write
- `pnpm --filter=@posthog/frontend typegen:check` — CI parity check
-### Iterating on one logic — skip the full scan
+### Iterating on one logic
-Full typegen + `tsc --noEmit` over the whole codebase is slow. When you're iterating
-on a single logic, scope both to that file:
+Full typegen over the whole codebase is slow. When you're iterating on a single
+logic, scope typegen to that file:
```sh
# Regenerate the type for one logic
pnpm --filter=@posthog/frontend typegen:file frontend/src/scenes/foo/fooLogic.ts
-
-# Type-check just that file (and its imports — fast, but won't catch downstream
-# breakage in other files that consume the new types)
-pnpm --filter=@posthog/frontend exec tsgo --noEmit \
- frontend/src/scenes/foo/fooLogic.ts
```
-Use this loop while writing the logic; run the full `typegen:check` /
+Use this loop while writing the logic. The current `tsgo` does not support combining
+the project config with a file argument, so run the full `typegen:check` and
`typescript:check` once at the end to confirm nothing else broke.
Do not create or import a separate `*LogicType.ts` file. Change the logic and re-run
diff --git a/.agents/skills/writing-kea-logics/references/loading-data.md b/.agents/skills/writing-kea-logics/references/loading-data.md
index 5e9cf5b6b443..2d672e3da1ae 100644
--- a/.agents/skills/writing-kea-logics/references/loading-data.md
+++ b/.agents/skills/writing-kea-logics/references/loading-data.md
@@ -4,6 +4,21 @@ Use `kea-loaders` for any state whose value comes from an async source (an HTTP
a query helper, anything that returns a promise). Don't roll your own
`isLoadingFoo` reducer.
+## API imports
+
+Import generated endpoint modules as a namespace and call functions through `api`:
+
+```ts
+import * as api from 'products/foo/frontend/generated/api'
+
+const foo = await api.foosRetrieve(fooId)
+```
+
+This keeps API calls recognizable at the call site and avoids a growing list of
+named endpoint imports. Use the appropriate generated module for the endpoint:
+`~/generated/core/api` for core endpoints or
+`products/<product>/frontend/generated/api` for product endpoints.
+
## Why a loader and not a reducer + listener
A loader on a key `foo` generates:
@@ -22,12 +37,14 @@ no cancellation. Don't.
```ts
import { loaders } from 'kea-loaders'
+import * as api from 'products/foo/frontend/generated/api'
+
loaders(({ values, props }) => ({
foo: [
null as Foo | null,
{
loadFoo: async () => {
- return await api.foos.get(props.fooId)
+ return await api.foosRetrieve(props.fooId)
},
},
],
@@ -46,7 +63,7 @@ loaders(({ values }) => ({
[] as Result[],
{
search: async ({ query }: { query: string }) => {
- return await api.search.list({ query })
+ return await api.searchList({ query })
},
},
],
@@ -65,7 +82,7 @@ loaders(({ values }) => ({
{
search: async ({ query }: { query: string }, breakpoint) => {
await breakpoint(300) // debounce
- const results = await api.search.list({ query })
+ const results = await api.searchList({ query })
breakpoint() // discard if superseded
return results
},
diff --git a/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts
index eef6dabd9a56..44a8fc5e4ca0 100644
--- a/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts
+++ b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts
@@ -1,15 +1,15 @@
import { MakeLogicType, actions, afterMount, connect, isBreakpoint, kea, listeners, path } from 'kea'
-import api from 'lib/api'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { teamLogic } from 'scenes/teamLogic'
import { productSetupProbes } from '~/products'
-import { HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'
+
+import * as api from 'products/event_definitions/frontend/generated/api'
import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'
import { productSetupStatusLogic } from './productSetupStatusLogic'
-import { ProductSetupProbe, statusFromProbeCounts } from './setupProbes'
+import { ProductSetupProbe, statusFromProbeDefinitions } from './setupProbes'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productSetupPreloadLogicValues {
@@ -30,16 +30,8 @@ export type productSetupPreloadLogicType = MakeLogicType<
>
/**
- * Only count events this recent when approximating setup status. Keeps the probe
- * query prunable to recent partitions instead of scanning the team's full history;
- * a product whose newest event is older than this briefly shows its empty state
- * until the in-scene detection (which owns the real semantics) answers.
- */
-export const PRELOAD_LOOKBACK_DAYS = 90
-
-/**
- * Resolves every registered product's setup status as early as possible — one
- * combined event-count query on idle after the team loads — and seeds
+ * Resolves every registered product's setup status as early as possible with one
+ * event-definition request after the team loads and seeds
* `productSetupStatusLogic` with the results. By the time a user first opens a
* gated product scene, the status is usually already known, so the gate renders
* the empty state (or the scene) directly instead of a loading spinner.
@@ -78,20 +70,17 @@ export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([
return
}
- // Event names are static internal literals from the probe registry, so
- // inlining them is safe. The timestamp bound keeps the scan to recent
- // partitions - without it this would touch every partition the team has
- // ever written; a cached result is fine for seeding.
- const events = [
+ const eventNames = [
...new Set(probes.flatMap((probe) => [...probe.hasDataEvents, ...(probe.waitingEvents ?? [])])),
]
- const query = `SELECT event, count() FROM events WHERE event IN (${events
- .map((event) => `'${event}'`)
- .join(', ')}) AND timestamp > now() - INTERVAL ${PRELOAD_LOOKBACK_DAYS} DAY GROUP BY event`
- let response: HogQLQueryResponse
+ let existingEventNames: Set<string>
try {
- response = (await api.query({ kind: NodeKind.HogQLQuery, query })) as HogQLQueryResponse
+ const response = await api.eventDefinitionsList(String(teamId), {
+ names: eventNames,
+ limit: eventNames.length,
+ })
+ existingEventNames = new Set(response.results.map(({ name }) => name))
} catch (error) {
if (error instanceof Error && isBreakpoint(error)) {
throw error
@@ -105,15 +94,9 @@ export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([
return
}
- const countsByEvent: Record<string, number> = {}
- for (const row of response?.results ?? []) {
- const [event, count] = row as [string, unknown]
- countsByEvent[event] = Number(count) || 0
- }
-
for (const probe of probes) {
seeded.add(`${teamId}:${probe.productKey}`)
- seedProbeStatus(probe, countsByEvent, cache)
+ seedProbeStatus(probe, existingEventNames, cache)
}
},
// Covers login and project switches that happen after mount.
@@ -143,11 +126,7 @@ export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([
}),
])
-function seedProbeStatus(
- probe: ProductSetupProbe,
- countsByEvent: Record<string, number>,
- cache: Record<string, any>
-): void {
+function seedProbeStatus(probe: ProductSetupProbe, eventNames: Set<string>, cache: Record<string, any>): void {
const instance = productSetupStatusLogic.build({ productKey: probe.productKey })
if (!instance.isMounted()) {
// Keep the instance alive for the app's lifetime so the seeded status is
@@ -166,6 +145,6 @@ function seedProbeStatus(
// Seed only unknown statuses - a product logic that already answered
// (fresh, uncached) always beats this cached approximation.
if (instance.values.status === 'loading') {
- instance.actions.setDetectedStatus(statusFromProbeCounts(probe, countsByEvent))
+ instance.actions.setDetectedStatus(statusFromProbeDefinitions(probe, eventNames))
}
}
diff --git a/frontend/src/lib/components/ProductEmptyState/setupProbes.test.ts b/frontend/src/lib/components/ProductEmptyState/setupProbes.test.ts
index 175530035c23..2c4a486d2cfc 100644
--- a/frontend/src/lib/components/ProductEmptyState/setupProbes.test.ts
+++ b/frontend/src/lib/components/ProductEmptyState/setupProbes.test.ts
@@ -1,8 +1,8 @@
import { ProductKey } from '~/queries/schema/schema-general'
-import { statusFromProbeCounts, type ProductSetupProbe } from './setupProbes'
+import { statusFromProbeDefinitions, type ProductSetupProbe } from './setupProbes'
-describe('statusFromProbeCounts', () => {
+describe('statusFromProbeDefinitions', () => {
const probe: ProductSetupProbe = {
productKey: ProductKey.MCP_ANALYTICS,
hasDataEvents: ['$mcp_tool_call'],
@@ -13,16 +13,18 @@ describe('statusFromProbeCounts', () => {
// (waiting beating has-data) or a crash on missing counts would either hide
// the empty state or show it to fully onboarded projects app-wide.
it.each([
- [{ $mcp_tool_call: 5, $mcp_initialize: 2 }, 'has-data'],
- [{ $mcp_initialize: 2 }, 'waiting-for-data'],
- [{}, 'needs-setup'],
- [{ $mcp_tool_call: 0, $mcp_initialize: 0 }, 'needs-setup'],
- ] as const)('maps counts %j to %s', (counts, expected) => {
- expect(statusFromProbeCounts(probe, counts as Record<string, number>)).toBe(expected)
+ [['$mcp_tool_call', '$mcp_initialize'], 'has-data'],
+ [['$mcp_initialize'], 'waiting-for-data'],
+ [[], 'needs-setup'],
+ ] as const)('maps definitions %j to %s', (definitions, expected) => {
+ expect(statusFromProbeDefinitions(probe, new Set(definitions))).toBe(expected)
})
it('never reports waiting-for-data for probes without waitingEvents', () => {
- const binaryProbe: ProductSetupProbe = { productKey: ProductKey.MCP_ANALYTICS, hasDataEvents: ['$exception'] }
- expect(statusFromProbeCounts(binaryProbe, { $mcp_initialize: 10 })).toBe('needs-setup')
+ const binaryProbe: ProductSetupProbe = {
+ productKey: ProductKey.MCP_ANALYTICS,
+ hasDataEvents: ['$exception'],
+ }
+ expect(statusFromProbeDefinitions(binaryProbe, new Set(['$mcp_initialize']))).toBe('needs-setup')
})
})
diff --git a/frontend/src/lib/components/ProductEmptyState/setupProbes.ts b/frontend/src/lib/components/ProductEmptyState/setupProbes.ts
index b09125c6e9a5..f7b6fa67975d 100644
--- a/frontend/src/lib/components/ProductEmptyState/setupProbes.ts
+++ b/frontend/src/lib/components/ProductEmptyState/setupProbes.ts
@@ -6,10 +6,10 @@ import type { ProductSetupStatus } from './types'
/**
* A cheap, declarative approximation of a product's setup status, resolvable at
- * app boot from event counts alone. A product declares its probe as `setupProbe`
+ * app boot from event definitions. A product declares its probe as `setupProbe`
* in its manifest; `build-products.mjs` aggregates them into `productSetupProbes`
- * (see `~/products`), and all of them are answered by ONE combined ClickHouse
- * count query (see `productSetupPreloadLogic`), so statuses are known before the
+ * (see `~/products`), and each one is answered by a Postgres-backed API call
+ * (see `productSetupPreloadLogic`), so statuses are known before the
* user first opens the product and the loading spinner rarely shows.
*
* Keep each probe's semantics in sync with the product's own detection logic
@@ -18,7 +18,7 @@ import type { ProductSetupStatus } from './types'
*/
export interface ProductSetupProbe {
productKey: ProductKey
- /** Any of these events existing (within the preload lookback window) means the product has real data. */
+ /** Any of these event definitions existing means the product has real data. */
hasDataEvents: string[]
/** Any of these existing (without `hasDataEvents`) means instrumented but no traffic yet. */
waitingEvents?: string[]
@@ -26,15 +26,12 @@ export interface ProductSetupProbe {
featureFlag?: FeatureFlagKey
}
-export function statusFromProbeCounts(
- probe: ProductSetupProbe,
- countsByEvent: Record<string, number>
-): ProductSetupStatus {
- if (probe.hasDataEvents.some((event) => (countsByEvent[event] ?? 0) > 0)) {
+export function statusFromProbeDefinitions(probe: ProductSetupProbe, eventNames: Set<string>): ProductSetupStatus {
+ if (probe.hasDataEvents.some((event) => eventNames.has(event))) {
return 'has-data'
}
- if (probe.waitingEvents?.some((event) => (countsByEvent[event] ?? 0) > 0)) {
+ if (probe.waitingEvents?.some((event) => eventNames.has(event))) {
return 'waiting-for-data'
}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 6eb769c49557..c6728e318620 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -7604,8 +7604,8 @@ export interface ProductManifest {
treeItemsMetadata?: FileSystemImport[]
/**
* Boot-time setup-status probe for this product's empty state. Aggregated across
- * manifests into `productSetupProbes` and answered by one combined event-count
- * query at app boot (see `productSetupPreloadLogic`).
+ * manifests into `productSetupProbes` and answered by one property-definition
+ * request at app boot (see `productSetupPreloadLogic`).
*/
setupProbe?: ProductSetupProbe
}
diff --git a/posthog/api/event_definition.py b/posthog/api/event_definition.py
index c0e858a1ba15..9bfd577b2525 100644
--- a/posthog/api/event_definition.py
+++ b/posthog/api/event_definition.py
@@ -310,6 +310,11 @@ class EventDefinitionViewSet(
search_query = search_query + " AND NOT name = ANY(%(excluded_list)s)"
params["excluded_list"] = excluded_list
+ names = [name for value in self.request.query_params.getlist("names") for name in value.split(",") if name]
+ if names:
+ search_query = search_query + " AND posthog_eventdefinition.name = ANY(%(names)s)"
+ params["names"] = list(set(names))
+
sql = create_event_definitions_sql(
event_type,
is_enterprise=EE_AVAILABLE,
@@ -387,7 +392,16 @@ class EventDefinitionViewSet(
required=False,
description="When true, omit events that have been explicitly hidden by a team admin (Enterprise only).",
),
+ OpenApiParameter(
+ "names",
+ OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ many=True,
+ description="Return exact matches for these event names. Pass names as repeated or comma-separated values.",
+ ),
],
+ extensions={"x-product": "event_definitions"},
)
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
diff --git a/posthog/api/test/test_event_definition.py b/posthog/api/test/test_event_definition.py
index f190f23b2c4c..4d0b018cbb75 100644
--- a/posthog/api/test/test_event_definition.py
+++ b/posthog/api/test/test_event_definition.py
@@ -77,6 +77,18 @@ class TestEventDefinitionAPI(APIBaseTest):
assert "installed_app" not in result_names
assert "purchase" not in result_names
+ @parameterized.expand(
+ [
+ ("repeated", "names=installed_app&names=purchase&names=missing_event"),
+ ("comma_separated", "names=installed_app,purchase,missing_event"),
+ ]
+ )
+ def test_list_event_definitions_with_exact_names(self, _name, query_string):
+ response = self.client.get(f"/api/projects/@current/event_definitions/?{query_string}")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert {result["name"] for result in response.json()["results"]} == {"installed_app", "purchase"}
+
@parameterized.expand(
[
(
diff --git a/products/event_definitions/frontend/generated/api.schemas.ts b/products/event_definitions/frontend/generated/api.schemas.ts
index 4c30ddd26ad3..dd900e54a23c 100644
--- a/products/event_definitions/frontend/generated/api.schemas.ts
+++ b/products/event_definitions/frontend/generated/api.schemas.ts
@@ -270,6 +270,10 @@ export type EventDefinitionsListParams = {
* Number of results to return per page.
*/
limit?: number
+ /**
+ * Return exact matches for these event names. Pass names as repeated or comma-separated values.
+ */
+ names?: string[]
/**
* The initial index from which to return the results.
*/
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8e4d1416f3ac..5e286082ad35 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -75437,6 +75437,10 @@ export namespace Schemas {
* Number of results to return per page.
*/
limit?: number;
+ /**
+ * Return exact matches for these event names. Pass names as repeated or comma-separated values.
+ */
+ names?: string[];
/**
* The initial index from which to return the results.
*/