: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
refactor(growth): rename SDK Doctor to SDK Health everywhere (#60574)
Rafael Audibert6ec6efa35164
diff --git a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsxindex a564248d8229..2fad6c5f1c49 100644--- a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx@@ -314,7 +314,7 @@ const iconTypes: Record<FileSystemIconType, { icon: JSX.Element; iconColor?: Filinbox: {icon: <IconNotification />,},- sdk_doctor: {+ sdk_health: {icon: <IconCode />,},pipeline_status: {diff --git a/frontend/src/lib/components/Search/searchLogic.tsx b/frontend/src/lib/components/Search/searchLogic.tsxindex 184330c51f54..b98a14c84554 100644--- a/frontend/src/lib/components/Search/searchLogic.tsx+++ b/frontend/src/lib/components/Search/searchLogic.tsx@@ -600,14 +600,14 @@ export const searchLogic = kea<searchLogicType>([record: { type: 'pipeline_status', iconType: 'pipeline_status' },},{- id: 'health-sdk-doctor',- name: 'SDK doctor',- displayName: 'SDK doctor',+ id: 'health-sdk-health',+ name: 'SDK health',+ displayName: 'SDK health',category: 'health',- href: urls.sdkDoctor(),- itemType: 'sdk_doctor',- lastViewedAt: sceneLogViewsByRef['SdkDoctor'] ?? null,- record: { type: 'sdk_doctor', iconType: 'sdk_doctor' },+ href: urls.sdkHealth(),+ itemType: 'sdk_health',+ lastViewedAt: sceneLogViewsByRef['SdkHealth'] ?? null,+ record: { type: 'sdk_health', iconType: 'sdk_health' },},],],diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex b19e082fbc90..07caf65782b5 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -20659,7 +20659,7 @@"settings","health","inbox",- "sdk_doctor",+ "sdk_health","pipeline_status","llm_evaluations","llm_tags",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex b2ec9655a5ba..898a2e32ab04 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -3400,7 +3400,7 @@ export type FileSystemIconType =| 'settings'| 'health'| 'inbox'- | 'sdk_doctor'+ | 'sdk_health'| 'pipeline_status'| 'llm_evaluations'| 'llm_tags'diff --git a/frontend/src/scenes/appScenes.ts b/frontend/src/scenes/appScenes.tsindex 3422871e4725..15c8c6919571 100644--- a/frontend/src/scenes/appScenes.ts+++ b/frontend/src/scenes/appScenes.ts@@ -107,7 +107,7 @@ export const appScenes: Record<Scene | string, () => any> = {[Scene.HealthCategoryDetail]: () => import('./health/categoryDetail/HealthCategoryDetailScene'),[Scene.HealthAlerts]: () => import('./health-alerts/HealthAlertsScene'),[Scene.PipelineStatus]: () => import('./health/pipelineStatus/PipelineStatusScene'),- [Scene.SdkDoctor]: () => import('./onboarding/sdks/SdkDoctorScene'),+ [Scene.SdkHealth]: () => import('./onboarding/sdks/SdkHealthScene'),[Scene.Exports]: () => import('./exports/ExportsScene'),[Scene.Subscriptions]: () => import('./subscriptions/SubscriptionsScene'),[Scene.Subscription]: () => import('./subscriptions/SubscriptionScene'),diff --git a/frontend/src/scenes/health-alerts/HealthAlertsEntryPoint.tsx b/frontend/src/scenes/health-alerts/HealthAlertsEntryPoint.tsxindex 4adbdfcd6ea2..97e9f3ad2322 100644--- a/frontend/src/scenes/health-alerts/HealthAlertsEntryPoint.tsx+++ b/frontend/src/scenes/health-alerts/HealthAlertsEntryPoint.tsx@@ -31,7 +31,7 @@ export interface HealthAlertsEntryPointProps {logicKey?: string// Restricts the resulting HogFunction's filter to a `kind IN (...)` set.// The central scene reads this from the `preset_kinds` URL search param so- // per-page entry points (SDK Doctor, Pipeline Status) can deep-link in with+ // per-page entry points (SDK Health, Pipeline Status) can deep-link in with// a scoped wizard. Omit (or pass an empty array) to leave filters// unrestricted (every kind).presetKinds?: string[]diff --git a/frontend/src/scenes/health/categoryDetail/categoryDetailConfig.ts b/frontend/src/scenes/health/categoryDetail/categoryDetailConfig.tsindex 7fc154814796..f7caaaef669d 100644--- a/frontend/src/scenes/health/categoryDetail/categoryDetailConfig.ts+++ b/frontend/src/scenes/health/categoryDetail/categoryDetailConfig.ts@@ -29,10 +29,10 @@ export const CATEGORY_DETAIL_CONFIG: Partial<Record<HealthIssueCategory, Categor},sdk: {docsUrl: 'https://posthog.com/docs/libraries',- deepDiveUrl: urls.sdkDoctor(),- deepDiveLabel: 'Open SDK doctor',+ deepDiveUrl: urls.sdkHealth(),+ deepDiveLabel: 'Open SDK health',guidance: 'Outdated SDKs miss bug fixes and new features. Update to the latest version for best results.',- redirectUrl: urls.sdkDoctor(),+ redirectUrl: urls.sdkHealth(),},web_analytics: {docsUrl: 'https://posthog.com/docs/web-analytics',diff --git a/frontend/src/scenes/health/renderers/SdkOutdatedRenderer.tsx b/frontend/src/scenes/health/renderers/SdkOutdatedRenderer.tsxindex 7b7b8cb97422..daf454859237 100644--- a/frontend/src/scenes/health/renderers/SdkOutdatedRenderer.tsx+++ b/frontend/src/scenes/health/renderers/SdkOutdatedRenderer.tsx@@ -2,7 +2,7 @@ import { LemonTag, Link, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { SDK_DOCS_LINKS, SDK_TYPE_READABLE_NAME } from 'scenes/onboarding/sdks/sdkConstants'-import type { SdkType } from 'scenes/onboarding/sdks/sdkDoctorLogic'+import type { SdkType } from 'scenes/onboarding/sdks/sdkHealthLogic'import type { HealthIssue } from '../types'diff --git a/frontend/src/scenes/hog-functions/AlertWizard/alertWizardLogic.ts b/frontend/src/scenes/hog-functions/AlertWizard/alertWizardLogic.tsindex dcb4c1c5357a..7cd83883928c 100644--- a/frontend/src/scenes/hog-functions/AlertWizard/alertWizardLogic.ts+++ b/frontend/src/scenes/hog-functions/AlertWizard/alertWizardLogic.ts@@ -59,7 +59,7 @@ export interface AlertWizardLogicProps {presetTriggerKey?: HogFunctionSubTemplateIdType// When set, the wizard pre-applies a `kind IN (...)` property filter on the// first event of the created HogFunction. Used by the health-alerts family- // so a per-page entry point (e.g. the SDK Doctor scene) can scope the alert+ // so a per-page entry point (e.g. the SDK Health scene) can scope the alert// to one or more health-check kinds. Pass an empty array to mean "all kinds"// explicitly; omit the prop to leave filters untouched.presetTriggerKinds?: string[]diff --git a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsxindex 07534b2f8132..cb3f2bb59a5f 100644--- a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx+++ b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx@@ -882,7 +882,7 @@ export const hogFunctionConfigurationLogic = kea<hogFunctionConfigurationLogicTyissue_id: '00000000-0000-0000-0000-000000000000',title: 'posthog-python SDK is outdated',summary: 'posthog-python is on 7.0.0, latest is 7.14.0',- link: '/health/sdk-doctor',+ link: '/health/sdk-health',payload: {sdk_name: 'posthog-python',latest_version: '7.14.0',diff --git a/frontend/src/scenes/hog-functions/list/HogFunctionsList.test.ts b/frontend/src/scenes/hog-functions/list/HogFunctionsList.test.tsindex 125fe83445e6..5b94f7e9bad9 100644--- a/frontend/src/scenes/hog-functions/list/HogFunctionsList.test.ts+++ b/frontend/src/scenes/hog-functions/list/HogFunctionsList.test.ts@@ -10,16 +10,16 @@ describe('urlForHogFunction', () => {})it('appends returnTo as a query param for a hog function id', () => {- expect(urlForHogFunction(makeFn('abc123'), '/health/sdk-doctor')).toBe(- '/functions/abc123?returnTo=%2Fhealth%2Fsdk-doctor'+ expect(urlForHogFunction(makeFn('abc123'), '/health/sdk-health')).toBe(+ '/functions/abc123?returnTo=%2Fhealth%2Fsdk-health')})it('does not append returnTo for plugin- prefix IDs', () => {- expect(urlForHogFunction(makeFn('plugin-7'), '/health/sdk-doctor')).toBe('/pipeline/plugins/7')+ expect(urlForHogFunction(makeFn('plugin-7'), '/health/sdk-health')).toBe('/pipeline/plugins/7')})it('does not append returnTo for batch-export- prefix IDs', () => {- expect(urlForHogFunction(makeFn('batch-export-9'), '/health/sdk-doctor')).toBe('/pipeline/batch-exports/9')+ expect(urlForHogFunction(makeFn('batch-export-9'), '/health/sdk-health')).toBe('/pipeline/batch-exports/9')})})diff --git a/frontend/src/scenes/onboarding/sdks/SdkDoctorComponents.tsx b/frontend/src/scenes/onboarding/sdks/SdkHealthComponents.tsxsimilarity index 96%rename from frontend/src/scenes/onboarding/sdks/SdkDoctorComponents.tsxrename to frontend/src/scenes/onboarding/sdks/SdkHealthComponents.tsxindex a97137077751..77424ef4ad62 100644--- a/frontend/src/scenes/onboarding/sdks/SdkDoctorComponents.tsx+++ b/frontend/src/scenes/onboarding/sdks/SdkHealthComponents.tsx@@ -9,10 +9,10 @@ import { newInternalTab } from 'lib/utils/newInternalTab'import { urls } from 'scenes/urls'import { SDK_DOCS_LINKS, SDK_TYPE_READABLE_NAME } from './sdkConstants'-import { AugmentedTeamSdkVersionsInfoRelease, type SdkType, sdkDoctorLogic } from './sdkDoctorLogic'+import { AugmentedTeamSdkVersionsInfoRelease, type SdkType, sdkHealthLogic } from './sdkHealthLogic'// The version drill-in SQL and Activity page URL are computed by the backend (sql_query /-// activity_page_url on each release) so the UI and the SDK Doctor MCP tool stay in lockstep.+// activity_page_url on each release) so the UI and the SDK Health MCP tool stay in lockstep.const COLUMNS: LemonTableColumns<AugmentedTeamSdkVersionsInfoRelease> = [{title: (@@ -112,7 +112,7 @@ const COLUMNS: LemonTableColumns<AugmentedTeamSdkVersionsInfoRelease> = []export function SdkSection({ sdkType }: { sdkType: SdkType }): JSX.Element {- const { augmentedData, reportLoading: loading } = useValues(sdkDoctorLogic)+ const { augmentedData, reportLoading: loading } = useValues(sdkHealthLogic)const sdk = augmentedData[sdkType]!const links = SDK_DOCS_LINKS[sdkType]diff --git a/frontend/src/scenes/onboarding/sdks/SdkDoctorScene.tsx b/frontend/src/scenes/onboarding/sdks/SdkHealthScene.tsxsimilarity index 92%rename from frontend/src/scenes/onboarding/sdks/SdkDoctorScene.tsxrename to frontend/src/scenes/onboarding/sdks/SdkHealthScene.tsxindex 06cc7e644cf0..539989032ec2 100644--- a/frontend/src/scenes/onboarding/sdks/SdkDoctorScene.tsx+++ b/frontend/src/scenes/onboarding/sdks/SdkHealthScene.tsx@@ -15,28 +15,28 @@ import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'-import { SdkSection } from './SdkDoctorComponents'-import { SdkType, sdkDoctorLogic } from './sdkDoctorLogic'-import { sdkDoctorSceneLogic } from './sdkDoctorSceneLogic'+import { SdkSection } from './SdkHealthComponents'+import { SdkType, sdkHealthLogic } from './sdkHealthLogic'+import { sdkHealthSceneLogic } from './sdkHealthSceneLogic'export const scene: SceneExport = {- component: SdkDoctorScene,- logic: sdkDoctorSceneLogic,+ component: SdkHealthScene,+ logic: sdkHealthSceneLogic,}-export function SdkDoctorScene(): JSX.Element {+export function SdkHealthScene(): JSX.Element {const {augmentedData,reportLoading: loading,needsUpdatingCount,hasErrors,snoozedUntil,- } = useValues(sdkDoctorLogic)+ } = useValues(sdkHealthLogic)const { isDev } = useValues(preflightLogic)const { featureFlags } = useValues(featureFlagLogic)const healthAlertsEnabled = !!featureFlags[FEATURE_FLAGS.HEALTH_ALERTS]- const { loadReport, snoozeSdkDoctor } = useActions(sdkDoctorLogic)+ const { loadReport, snoozeSdkHealth } = useActions(sdkHealthLogic)useOnMountEffect(() => {posthog.capture('sdk doctor loaded', { needsUpdatingCount })@@ -49,17 +49,17 @@ export function SdkDoctorScene(): JSX.Element {const snoozeWarning = (): void => {posthog.capture('sdk doctor snooze warning')- snoozeSdkDoctor()+ snoozeSdkHealth()}return (<SceneContent><SceneTitleSection- name="SDK Doctor"+ name="SDK Health"description="Monitor and maintain your PostHog SDK integrations by automatically detecting version issues, configuration problems, and implementation patterns across your applications."resourceType={{to: undefined,- type: 'sdk_doctor',+ type: 'sdk_health',}}actions={<>@@ -69,7 +69,7 @@ export function SdkDoctorScene(): JSX.Element {type="secondary"to={urls.healthAlerts(['sdk_outdated'])}onClick={() => {- posthog.capture('health_alerts_entry_point_clicked', { source: 'sdk_doctor' })+ posthog.capture('health_alerts_entry_point_clicked', { source: 'sdk_health' })}}icon={<IconBell className="size-4" />}tooltip="Subscribe to alerts when SDKs go outdated"@@ -102,7 +102,7 @@ export function SdkDoctorScene(): JSX.Element {{/* Beta feedback banner */}<LemonBanner type="info">- <strong>SDK Doctor is in Beta!</strong> Help us improve by sharing your feedback?{' '}+ <strong>SDK Health is in Beta!</strong> Help us improve by sharing your feedback?{' '}<Link to="#panel=support%3Asupport%3Asdk%3Alow%3Atrue">Send feedback</Link></LemonBanner>diff --git a/frontend/src/scenes/onboarding/sdks/sdkConstants.ts b/frontend/src/scenes/onboarding/sdks/sdkConstants.tsindex 13118b6d356d..110c984e4f01 100644--- a/frontend/src/scenes/onboarding/sdks/sdkConstants.ts+++ b/frontend/src/scenes/onboarding/sdks/sdkConstants.ts@@ -1,4 +1,4 @@-import type { SdkType } from './sdkDoctorLogic'+import type { SdkType } from './sdkHealthLogic'export const SDK_TYPE_READABLE_NAME: Record<SdkType, string> = {web: 'Web',diff --git a/frontend/src/scenes/onboarding/sdks/sdkDoctorLogic.tsx b/frontend/src/scenes/onboarding/sdks/sdkHealthLogic.tsxsimilarity index 94%rename from frontend/src/scenes/onboarding/sdks/sdkDoctorLogic.tsxrename to frontend/src/scenes/onboarding/sdks/sdkHealthLogic.tsxindex f03331633d5a..39cc246bd036 100644--- a/frontend/src/scenes/onboarding/sdks/sdkDoctorLogic.tsx+++ b/frontend/src/scenes/onboarding/sdks/sdkHealthLogic.tsx@@ -8,7 +8,7 @@ import api from 'lib/api'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { teamLogic } from 'scenes/teamLogic'-import type { sdkDoctorLogicType } from './sdkDoctorLogicType'+import type { sdkHealthLogicType } from './sdkHealthLogicType'// Supported SDK types for version detection and health monitoringexport type SdkType =@@ -33,7 +33,7 @@ export type SdkVersion = `${string}.${string}.${string}`*/export type SdkHealthStatus = 'danger' | 'warning' | 'success'-// --- Backend report shape (mirrors SdkHealthReportSerializer in posthog/api/sdk_doctor.py) ---+// --- Backend report shape (mirrors SdkHealthReportSerializer in posthog/api/sdk_health.py) ---//// All outdatedness heuristics (device thresholds, grace periods, traffic-share rules, severity// escalation) live in products/growth/backend/sdk_health.py and are surfaced pre-computed here.@@ -116,7 +116,7 @@ export type AugmentedTeamSdkVersionsInfo = {}/**- * SDK Doctor - PostHog SDK Health Monitoring+ * SDK Health - PostHog SDK Health Monitoring** Detects installed SDKs and their versions across a team's events and surfaces a pre-digested* health report computed entirely by the backend (see products/growth/backend/sdk_health.py).@@ -127,15 +127,15 @@ export type AugmentedTeamSdkVersionsInfo = {* - The `report` endpoint applies the outdatedness heuristics and returns the assessment below.*/-export const sdkDoctorLogic = kea<sdkDoctorLogicType>([- path(['scenes', 'onboarding', 'sdks', 'sdkDoctorLogic']),+export const sdkHealthLogic = kea<sdkHealthLogicType>([+ path(['scenes', 'onboarding', 'sdks', 'sdkHealthLogic']),connect(() => ({values: [preflightLogic, ['isCloudOrDev'], teamLogic, ['currentTeamId']],})),actions({- snoozeSdkDoctor: true,+ snoozeSdkHealth: true,unsnooze: true,}),@@ -144,7 +144,7 @@ export const sdkDoctorLogic = kea<sdkDoctorLogicType>([null as string | null,{ persist: true },{- snoozeSdkDoctor: () => new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),+ snoozeSdkHealth: () => new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),unsnooze: () => null,},],@@ -161,11 +161,11 @@ export const sdkDoctorLogic = kea<sdkDoctorLogicType>([return null}try {- const base = `api/projects/${values.currentTeamId}/sdk_doctor/report/`+ const base = `api/projects/${values.currentTeamId}/sdk_health/report/`const endpoint = options?.forceRefresh === true ? `${base}?force_refresh=true` : basereturn await api.get<SdkHealthReportResponse>(endpoint)} catch (error) {- console.error('Error loading SDK doctor report', error)+ console.error('Error loading SDK health report', error)return null}},@@ -249,8 +249,8 @@ export const sdkDoctorLogic = kea<sdkDoctorLogicType>([}),listeners({- snoozeSdkDoctor: () => {- lemonToast.success('SDK Doctor snoozed for 30 days')+ snoozeSdkHealth: () => {+ lemonToast.success('SDK Health snoozed for 30 days')},}),diff --git a/frontend/src/scenes/onboarding/sdks/sdkDoctorSceneLogic.tsx b/frontend/src/scenes/onboarding/sdks/sdkHealthSceneLogic.tsxsimilarity index 59%rename from frontend/src/scenes/onboarding/sdks/sdkDoctorSceneLogic.tsxrename to frontend/src/scenes/onboarding/sdks/sdkHealthSceneLogic.tsxindex eb673bbc1d7f..963fbdc8f005 100644--- a/frontend/src/scenes/onboarding/sdks/sdkDoctorSceneLogic.tsx+++ b/frontend/src/scenes/onboarding/sdks/sdkHealthSceneLogic.tsx@@ -6,10 +6,10 @@ import { urls } from 'scenes/urls'import { Breadcrumb } from '~/types'-import type { sdkDoctorSceneLogicType } from './sdkDoctorSceneLogicType'+import type { sdkHealthSceneLogicType } from './sdkHealthSceneLogicType'-export const sdkDoctorSceneLogic = kea<sdkDoctorSceneLogicType>([- path(['scenes', 'onboarding', 'sdks', 'sdkDoctorSceneLogic']),+export const sdkHealthSceneLogic = kea<sdkHealthSceneLogicType>([+ path(['scenes', 'onboarding', 'sdks', 'sdkHealthSceneLogic']),selectors({breadcrumbs: [() => [],@@ -20,9 +20,9 @@ export const sdkDoctorSceneLogic = kea<sdkDoctorSceneLogicType>([path: urls.health(),},{- key: Scene.SdkDoctor,- name: sceneConfigurations[Scene.SdkDoctor].name,- iconType: sceneConfigurations[Scene.SdkDoctor].iconType || 'default_icon_type',+ key: Scene.SdkHealth,+ name: sceneConfigurations[Scene.SdkHealth].name,+ iconType: sceneConfigurations[Scene.SdkHealth].iconType || 'default_icon_type',},],],diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex cf01eea9d5f4..c274ed86c766 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -142,7 +142,7 @@ export enum Scene {Health = 'Health',HealthCategoryDetail = 'HealthCategoryDetail',HealthAlerts = 'HealthAlerts',- SdkDoctor = 'SdkDoctor',+ SdkHealth = 'SdkHealth',SessionAttributionExplorer = 'SessionAttributionExplorer',SessionGroupSummariesTable = 'SessionGroupSummariesTable',SessionGroupSummary = 'SessionGroupSummary',diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.tsindex f1646330b801..dd67d26ca98b 100644--- a/frontend/src/scenes/scenes.ts+++ b/frontend/src/scenes/scenes.ts@@ -500,10 +500,10 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {description: 'Monitor the status of your data pipelines.',iconType: 'pipeline_status',},- [Scene.SdkDoctor]: {+ [Scene.SdkHealth]: {projectBased: true,- name: 'SDK doctor',- iconType: 'sdk_doctor',+ name: 'SDK health',+ iconType: 'sdk_health',description:'Monitor and maintain your PostHog SDK integrations by automatically detecting version issues, configuration problems, and implementation patterns across your applications.',},@@ -923,7 +923,7 @@ export const routes: Record<string, [Scene | string, string]> = {[urls.inbox()]: [Scene.Inbox, 'inbox'],[urls.inbox(':reportId')]: [Scene.Inbox, 'inbox'],[urls.pipelineStatus()]: [Scene.PipelineStatus, 'pipelineStatus'],- [urls.sdkDoctor()]: [Scene.SdkDoctor, 'sdkDoctor'],+ [urls.sdkHealth()]: [Scene.SdkHealth, 'sdkHealth'],[urls.healthAlerts()]: [Scene.HealthAlerts, 'healthAlerts'],// Parameterized route must come after static /health/* routes[urls.healthCategory(':category')]: [Scene.HealthCategoryDetail, 'healthCategoryDetail'],diff --git a/frontend/src/scenes/settings/environment/replayTriggersLogic.ts b/frontend/src/scenes/settings/environment/replayTriggersLogic.tsindex 1160ea50b35d..245f4fd58cfb 100644--- a/frontend/src/scenes/settings/environment/replayTriggersLogic.ts+++ b/frontend/src/scenes/settings/environment/replayTriggersLogic.ts@@ -5,7 +5,7 @@ import { subscriptions } from 'kea-subscriptions'import { UrlTriggerConfig } from 'lib/components/IngestionControls/types'import { compareVersion } from 'lib/utils/semver'-import { sdkDoctorLogic } from 'scenes/onboarding/sdks/sdkDoctorLogic'+import { sdkHealthLogic } from 'scenes/onboarding/sdks/sdkHealthLogic'import { teamLogic } from 'scenes/teamLogic'import { TeamPublicType, TeamType } from '~/types'@@ -88,7 +88,7 @@ export const replayTriggersLogic = kea<replayTriggersLogicType>([validateUrlInput: (url: string, type: 'trigger' | 'blocklist') => ({ url, type }),}),connect(() => ({- values: [teamLogic, ['currentTeam'], sdkDoctorLogic, ['augmentedData']],+ values: [teamLogic, ['currentTeam'], sdkHealthLogic, ['augmentedData']],actions: [teamLogic, ['updateCurrentTeam']],})),reducers({diff --git a/frontend/src/scenes/surveys/surveysSdkLogic.ts b/frontend/src/scenes/surveys/surveysSdkLogic.tsindex 0eb94e229a3a..253de1631206 100644--- a/frontend/src/scenes/surveys/surveysSdkLogic.ts+++ b/frontend/src/scenes/surveys/surveysSdkLogic.ts@@ -1,6 +1,6 @@import { connect, kea, path, selectors } from 'kea'-import { sdkDoctorLogic } from '~/scenes/onboarding/sdks/sdkDoctorLogic'+import { sdkHealthLogic } from '~/scenes/onboarding/sdks/sdkHealthLogic'import type { surveysSdkLogicType } from './surveysSdkLogicType'import { TeamSdkVersions } from './surveyVersionRequirements'@@ -8,17 +8,17 @@ import { TeamSdkVersions } from './surveyVersionRequirements'export const surveysSdkLogic = kea<surveysSdkLogicType>([path(['scenes', 'surveys', 'surveysSdkLogic']),connect(() => ({- values: [sdkDoctorLogic, ['augmentedData as sdkDoctorData']],+ values: [sdkHealthLogic, ['augmentedData as sdkHealthData']],})),selectors({teamSdkVersions: [- (s) => [s.sdkDoctorData],- (sdkDoctorData): TeamSdkVersions => {+ (s) => [s.sdkHealthData],+ (sdkHealthData): TeamSdkVersions => {const versions: TeamSdkVersions = {}- for (const [sdkType, sdkInfo] of Object.entries(sdkDoctorData ?? {})) {+ for (const [sdkType, sdkInfo] of Object.entries(sdkHealthData ?? {})) {if (sdkInfo?.allReleases?.length) {- // sdk doctor uses 'web' but we use 'posthog-js' in SURVEY_SDK_REQUIREMENTS+ // sdk health uses 'web' but we use 'posthog-js' in SURVEY_SDK_REQUIREMENTSconst key = sdkType === 'web' ? 'posthog-js' : sdkTypeversions[key as keyof TeamSdkVersions] = sdkInfo.allReleases[0]?.version ?? null}diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.tsindex a9c6258700db..4579fec0d120 100644--- a/frontend/src/scenes/urls.ts+++ b/frontend/src/scenes/urls.ts@@ -296,7 +296,7 @@ export const urls = {webAnalyticsBotAnalytics: (): string => '/web/bots',webAnalyticsHealth: (): string => '/web/health',pipelineStatus: (): string => '/health/pipeline-status',- sdkDoctor: (): string => '/health/sdk-doctor',+ sdkHealth: (): string => '/health/sdk-health',exports: (): string => '/exports',subscriptions: (): string => '/subscriptions',subscription: (id: string | number): string => `/subscriptions/${id}`,diff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex 80f471195259..48b7626dfc48 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -13,7 +13,7 @@ from posthog.api.csp_reporting import CSPReportingViewSetfrom posthog.api.js_snippet import JsSnippetViewSetfrom posthog.api.query_performance_proxy import QueryPerformanceProxyViewSetfrom posthog.api.routing import DefaultRouterPlusPlus, RouterRegistry-from posthog.api.sdk_doctor import SdkDoctorViewSet+from posthog.api.sdk_health import SdkHealthViewSetfrom posthog.api.wizard import http as wizardfrom posthog.approvals import api as approval_apifrom posthog.settings import EE_AVAILABLE@@ -157,7 +157,7 @@ def register_legacy_dual_route_team_nested_viewset(projects_router.register(r"annotations", annotation.AnnotationsViewSet, "project_annotations", ["project_id"])-projects_router.register(r"sdk_doctor", SdkDoctorViewSet, "project_sdk_doctor", ["project_id"])+projects_router.register(r"sdk_health", SdkHealthViewSet, "project_sdk_health", ["project_id"])projects_router.register(r"activity_log",advanced_activity_logs.ActivityLogViewSet,diff --git a/posthog/api/sdk_doctor.py b/posthog/api/sdk_health.pysimilarity index 92%rename from posthog/api/sdk_doctor.pyrename to posthog/api/sdk_health.pyindex 92b0d9e11ab9..df0deeda9f34 100644--- a/posthog/api/sdk_doctor.py+++ b/posthog/api/sdk_health.py@@ -62,7 +62,7 @@ class SdkReleaseAssessmentSerializer(serializers.Serializer):)status_reason = serializers.CharField(help_text=(- "Per-version badge tooltip text matching the SDK Doctor UI exactly. Quote verbatim when "+ "Per-version badge tooltip text matching the SDK Health UI exactly. Quote verbatim when ""reporting to users. Varies by state: 'Released X ago. Upgrade recommended.' for outdated ""versions, 'You have the latest available.' for current versions, or 'Released X ago. ""Upgrading is a good idea, but it's not urgent yet.' for recent-but-behind versions."@@ -95,7 +95,7 @@ class SdkAssessmentSerializer(serializers.Serializer):help_text="SDK identifier, e.g. 'web', 'posthog-python', 'posthog-node', 'posthog-ios'.")readable_name = serializers.CharField(- help_text="Human-readable SDK name matching the SDK Doctor UI (e.g. 'Python', 'Node.js', 'Web', 'iOS')."+ help_text="Human-readable SDK name matching the SDK Health UI (e.g. 'Python', 'Node.js', 'Web', 'iOS').")latest_version = serializers.CharField(help_text="Most recent published version of this SDK.")needs_updating = serializers.BooleanField(help_text="True if this SDK needs attention (is_outdated OR is_old).")@@ -115,7 +115,7 @@ class SdkAssessmentSerializer(serializers.Serializer):banners = serializers.ListField(child=serializers.CharField(),help_text=(- "Top-level alert sentences matching the SDK Doctor UI's 'Time for an update!' banner — "+ "Top-level alert sentences matching the SDK Health UI's 'Time for an update!' banner — ""one per outdated version with significant traffic. Quote verbatim when surfacing the ""headline to users."),@@ -148,9 +148,9 @@ class SdkHealthReportSerializer(serializers.Serializer):# --- ViewSet (MCP-accessible, project-scoped) -------------------------------@extend_schema(tags=["sdk_doctor"])-class SdkDoctorViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):- """Project-scoped SDK Doctor report for MCP and agent consumption."""+@extend_schema(tags=["sdk_health"])+class SdkHealthViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):+ """Project-scoped SDK Health report for MCP and agent consumption."""scope_object = "project"@@ -218,7 +218,7 @@ class SdkDoctorViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):@api_view(["GET"])@permission_classes([IsAuthenticated])-def sdk_doctor(request: Request) -> Response:+def sdk_health(request: Request) -> Response:"""Serve team SDK versions. Data is cached by the Temporal sdk_outdated health check.Supports force_refresh=true for on-demand detection.@@ -234,7 +234,7 @@ def sdk_doctor(request: Request) -> Response:return Response({"error": "Failed to get SDK versions. Please try again later."}, status=500)if not team_data:# Empty dict: brand-new team, deleted team, or no SDK traffic in the last 7 days.- # Match SdkDoctorViewSet.report's empty-report behavior — never 500 here.+ # Match SdkHealthViewSet.report's empty-report behavior — never 500 here.return Response({}, status=200)sdk_data = get_github_sdk_data()@@ -274,24 +274,24 @@ def get_team_data(team_id: int, force_refresh: bool) -> dict[str, list[SdkVersiosdk_versions = json.loads(cached_data.decode("utf-8") if isinstance(cached_data, bytes) else cached_data)- logger.info("sdk_doctor_team_cache_hit", team_id=team_id)+ logger.info("sdk_health_team_cache_hit", team_id=team_id)return sdk_versionsexcept (json.JSONDecodeError, AttributeError) as e:- logger.warning("sdk_doctor_team_cache_corrupted", team_id=team_id, error=str(e))+ logger.warning("sdk_health_team_cache_corrupted", team_id=team_id, error=str(e))capture_exception(e)else:- logger.info("sdk_doctor_team_force_refresh", team_id=team_id)+ logger.info("sdk_health_team_force_refresh", team_id=team_id)- logger.info("sdk_doctor_team_cache_miss", team_id=team_id)+ logger.info("sdk_health_team_cache_miss", team_id=team_id)try:sdk_versions = get_and_cache_team_sdk_versions(team_id, redis_client)if sdk_versions is not None:- logger.info("sdk_doctor_team_cache_populated", team_id=team_id)+ logger.info("sdk_health_team_cache_populated", team_id=team_id)return sdk_versionselse:- logger.error("sdk_doctor_team_clickhouse_empty", team_id=team_id)+ logger.error("sdk_health_team_clickhouse_empty", team_id=team_id)except Exception as e:- logger.exception("sdk_doctor_team_fetch_failed", team_id=team_id)+ logger.exception("sdk_health_team_fetch_failed", team_id=team_id)capture_exception(e)return None@@ -309,9 +309,9 @@ def get_github_sdk_data() -> dict[str, Any]:parsed = json.loads(cached_data.decode("utf-8") if isinstance(cached_data, bytes) else cached_data)data[sdk_type] = parsedexcept (json.JSONDecodeError, AttributeError) as e:- logger.warning("sdk_doctor_github_cache_corrupted", sdk_type=sdk_type, error=str(e))+ logger.warning("sdk_health_github_cache_corrupted", sdk_type=sdk_type, error=str(e))capture_exception(e, {"sdk_type": sdk_type, "cache_key": cache_key})else:- logger.warning("sdk_doctor_github_cache_miss", sdk_type=sdk_type)+ logger.warning("sdk_health_github_cache_miss", sdk_type=sdk_type)return datadiff --git a/posthog/api/test/test_sdk_doctor.py b/posthog/api/test/test_sdk_health.pysimilarity index 85%rename from posthog/api/test/test_sdk_doctor.pyrename to posthog/api/test/test_sdk_health.pyindex 280b37f1c5cf..e3d1ff9337ec 100644--- a/posthog/api/test/test_sdk_doctor.py+++ b/posthog/api/test/test_sdk_health.py@@ -4,19 +4,19 @@ from unittest.mock import patchfrom rest_framework import status-class TestSdkDoctorViewSet(APIBaseTest):- """Tests for the /api/projects/{team_id}/sdk_doctor/report/ MCP-accessible endpoint."""+class TestSdkHealthViewSet(APIBaseTest):+ """Tests for the /api/projects/{team_id}/sdk_health/report/ MCP-accessible endpoint."""def _url(self) -> str:- return f"/api/projects/{self.team.pk}/sdk_doctor/report/"+ return f"/api/projects/{self.team.pk}/sdk_health/report/"def test_requires_authentication(self) -> None:self.client.logout()response = self.client.get(self._url())assert response.status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)- @patch("posthog.api.sdk_doctor.get_team_data")- @patch("posthog.api.sdk_doctor.get_github_sdk_data")+ @patch("posthog.api.sdk_health.get_team_data")+ @patch("posthog.api.sdk_health.get_github_sdk_data")def test_cold_cache_returns_empty_healthy_report(self, mock_github, mock_team) -> None:# Both caches cold → endpoint must still respond 200 with a healthy (but empty) report# rather than a 500 — agents should see "nothing to report" not a service error.@@ -32,8 +32,8 @@ class TestSdkDoctorViewSet(APIBaseTest):assert data["team_sdk_count"] == 0assert data["sdks"] == []- @patch("posthog.api.sdk_doctor.get_team_data")- @patch("posthog.api.sdk_doctor.get_github_sdk_data")+ @patch("posthog.api.sdk_health.get_team_data")+ @patch("posthog.api.sdk_health.get_github_sdk_data")def test_happy_path_returns_digested_report(self, mock_github, mock_team) -> None:mock_team.return_value = {"posthog-node": [@@ -67,8 +67,8 @@ class TestSdkDoctorViewSet(APIBaseTest):assert "posthog-node" in release["sql_query"]assert release["activity_page_url"].startswith(f"/project/{self.team.pk}/")- @patch("posthog.api.sdk_doctor.get_team_data")- @patch("posthog.api.sdk_doctor.get_github_sdk_data")+ @patch("posthog.api.sdk_health.get_team_data")+ @patch("posthog.api.sdk_health.get_github_sdk_data")def test_force_refresh_param_threaded_to_fetcher(self, mock_github, mock_team) -> None:mock_team.return_value = Nonemock_github.return_value = {}@@ -80,11 +80,11 @@ class TestSdkDoctorViewSet(APIBaseTest):force_refresh = kwargs.get("force_refresh", args[1] if len(args) > 1 else None)assert force_refresh is True- @patch("posthog.api.sdk_doctor.get_team_data")- @patch("posthog.api.sdk_doctor.get_github_sdk_data")+ @patch("posthog.api.sdk_health.get_team_data")+ @patch("posthog.api.sdk_health.get_github_sdk_data")def test_partial_cache_missing_sdk_in_github_data_is_skipped(self, mock_github, mock_team) -> None:# team_data has two SDKs, but github cache only knows about one.- # The defensive `.get(lib, {})` in SdkDoctorViewSet.report is what makes this safe —+ # The defensive `.get(lib, {})` in SdkHealthViewSet.report is what makes this safe —# compute_sdk_health skips SDKs with no latest_version rather than KeyError.# If someone ever swaps `.get(lib, {})` back to `sdk_data[lib]` (like the legacy# flat endpoint does), this test will catch it.@@ -110,13 +110,13 @@ class TestSdkDoctorViewSet(APIBaseTest):assert "posthog-python" not in sdk_libs-class TestSdkDoctorLegacyEndpoint(APIBaseTest):- """Tests for the legacy /api/sdk_doctor/ endpoint consumed by the onboarding scene."""+class TestSdkHealthLegacyEndpoint(APIBaseTest):+ """Tests for the legacy /api/sdk_health/ endpoint consumed by the onboarding scene."""def _url(self) -> str:- return "/api/sdk_doctor/"+ return "/api/sdk_health/"- @patch("posthog.api.sdk_doctor.get_team_data")+ @patch("posthog.api.sdk_health.get_team_data")def test_cold_cache_returns_empty_200(self, mock_team) -> None:mock_team.return_value = {}@@ -124,7 +124,7 @@ class TestSdkDoctorLegacyEndpoint(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json() == {}- @patch("posthog.api.sdk_doctor.get_team_data")+ @patch("posthog.api.sdk_health.get_team_data")def test_genuine_failure_returns_500(self, mock_team) -> None:mock_team.return_value = None@@ -132,8 +132,8 @@ class TestSdkDoctorLegacyEndpoint(APIBaseTest):assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERRORassert response.json() == {"error": "Failed to get SDK versions. Please try again later."}- @patch("posthog.api.sdk_doctor.get_team_data")- @patch("posthog.api.sdk_doctor.get_github_sdk_data")+ @patch("posthog.api.sdk_health.get_team_data")+ @patch("posthog.api.sdk_health.get_github_sdk_data")def test_missing_github_data_returns_500(self, mock_github, mock_team) -> None:mock_team.return_value = {"posthog-node": [{"lib_version": "1.0.0", "count": 100, "max_timestamp": "2026-04-21T00:00:00Z"}]@@ -144,8 +144,8 @@ class TestSdkDoctorLegacyEndpoint(APIBaseTest):assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERRORassert response.json() == {"error": "Failed to get GitHub SDK data. Please try again later."}- @patch("posthog.api.sdk_doctor.get_team_data")- @patch("posthog.api.sdk_doctor.get_github_sdk_data")+ @patch("posthog.api.sdk_health.get_team_data")+ @patch("posthog.api.sdk_health.get_github_sdk_data")def test_happy_path_returns_combined_data(self, mock_github, mock_team) -> None:mock_team.return_value = {"posthog-node": [diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 50d5b9a2f53b..b5f51219a701 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -56,7 +56,7 @@ class Product(StrEnum):REPLAY = "replay"REPLAY_VISION = "replay_vision"REVENUE_ANALYTICS = "revenue_analytics"- SDK_DOCTOR = "sdk_doctor"+ SDK_HEALTH = "sdk_health"SESSION_SUMMARY = "session_summary"SIGNALS = "signals"SURVEYS = "surveys"diff --git a/posthog/schema.py b/posthog/schema.pyindex 6f36de355a3f..e66699bf2a59 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -2396,7 +2396,7 @@ class FileSystemIconType(StrEnum):SETTINGS = "settings"HEALTH = "health"INBOX = "inbox"- SDK_DOCTOR = "sdk_doctor"+ SDK_HEALTH = "sdk_health"PIPELINE_STATUS = "pipeline_status"LLM_EVALUATIONS = "llm_evaluations"LLM_TAGS = "llm_tags"diff --git a/posthog/temporal/health_checks/framework.py b/posthog/temporal/health_checks/framework.pyindex 9c2466626a4d..3684cdf1d9e5 100644--- a/posthog/temporal/health_checks/framework.py+++ b/posthog/temporal/health_checks/framework.py@@ -25,7 +25,7 @@ class AlertContent:title: strsummary: str- # Relative path inside the PostHog app (e.g. "/health/sdk-doctor").+ # Relative path inside the PostHog app (e.g. "/health/sdk-health").# HogFunction templates concatenate this onto {project.url}.link: strdiff --git a/posthog/urls.py b/posthog/urls.pyindex 0eece2913db3..68718ae0ac2b 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -34,7 +34,7 @@ from posthog.api.id_jag import IdJagViewSetfrom posthog.api.oauth.connected_apps import ConnectedAppsViewSetfrom posthog.api.oauth.wizard_metadata import WIZARD_METADATA_PATH, WizardClientMetadataViewfrom posthog.api.query import progress-from posthog.api.sdk_doctor import sdk_doctor+from posthog.api.sdk_health import sdk_healthfrom posthog.api.two_factor_qrcode import CacheAwareQRGeneratorViewfrom posthog.api.utils import hostname_in_allowed_url_listfrom posthog.api.web_experiment import web_experiments@@ -271,7 +271,7 @@ urlpatterns = [csrf_exempt(user_interviews_start_call),name="user_interviews_start_call",),- path("api/sdk_doctor/", sdk_doctor),+ path("api/sdk_health/", sdk_health),path("api/conversations/", include("products.conversations.backend.api.urls")),path("api/environments/<int:parent_lookup_team_id>/mcp_analytics/",diff --git a/products/growth/backend/constants.py b/products/growth/backend/constants.pyindex 03035e9585ca..4151d16d5d93 100644--- a/products/growth/backend/constants.py+++ b/products/growth/backend/constants.py@@ -7,13 +7,13 @@ SDK_CACHE_EXPIRY = 60 * 60 * 24 * 7 # 7 days — used by the GitHub `latestVers# previous day's write for any given team can be timestamped meaningfully later. A 26h TTL gives# ~2h headroom relative to cron *start*, and less for teams late in the batch queue. That's# deliberate: when a team's TTL expires before its next batch slot, the next user request hits-# the cache-miss fallback in posthog/api/sdk_doctor.py:get_team_data, which runs one fresh+# the cache-miss fallback in posthog/api/sdk_health.py:get_team_data, which runs one fresh# single-team HogQL query and repopulates Redis. Steady-state load is unchanged; the trade-off# prevents days-long stale snapshots when a team's batch is skipped or times out.TEAM_SDK_CACHE_EXPIRY = 60 * 60 * 26 # 26 hours-# Canonical list of the SDK identifiers SDK Doctor tracks. Lives here (rather than in+# Canonical list of the SDK identifiers SDK Health tracks. Lives here (rather than in# products/growth/dags/github_sdk_versions.py) so non-Dagster consumers — the Temporal# health check, the API view, and tests — don't need to import from a Dagster module.SdkTypes = Literal[diff --git a/products/growth/backend/sdk_health.py b/products/growth/backend/sdk_health.pyindex 44021abb417d..b95254ca8ea0 100644--- a/products/growth/backend/sdk_health.py+++ b/products/growth/backend/sdk_health.py@@ -1,10 +1,10 @@"""-SDK Doctor health assessment.+SDK Health health assessment.The single source of truth for SDK outdatedness detection. Consumed by:- the `sdk_outdated` Temporal health check (alerts / HealthIssue rows),- - the SDK Doctor report endpoint (posthog/api/sdk_doctor.py), which the SDK Doctor UI and the- SDK Doctor MCP tool both read.+ - the SDK Health report endpoint (posthog/api/sdk_health.py), which the SDK Health UI and the+ SDK Health MCP tool both read.The frontend renders these pre-computed values."""@@ -332,7 +332,7 @@ def _released_ago(release_date_iso: Optional[str], now: Optional[datetime] = Non# --- UI-facing string/URL builders ---------#-# The SDK Doctor UI (frontend/src/scenes/onboarding/sdks/) renders these strings/URLs verbatim+# The SDK Health UI (frontend/src/scenes/onboarding/sdks/) renders these strings/URLs verbatim# from the report endpoint, so this is the single place the copy and Activity/SQL links are built.@@ -368,7 +368,7 @@ def _is_safe_for_interpolation(value: str) -> bool:def _build_sql_query(sdk_type: str, version: str) -> str:"""- SQL drill-in for an SDK version, rendered as-is by the SDK Doctor UI and MCP tool.+ SQL drill-in for an SDK version, rendered as-is by the SDK Health UI and MCP tool.Returns an empty string when either `sdk_type` or `version` fails validation —the skill instructs agents to surface the unexpected empty value rather than retry@@ -390,7 +390,7 @@ def _build_sql_query(sdk_type: str, version: str) -> str:def _build_activity_page_url(project_id: Optional[int], sdk_type: str, version: str) -> str:"""- Activity > Explore drill-in URL for an SDK version, rendered as-is by the SDK Doctor UI and MCP tool.+ Activity > Explore drill-in URL for an SDK version, rendered as-is by the SDK Health UI and MCP tool.Returns a relative path (no host) including /project/<id>/ prefix so MCP agentscan combine it with the user's known PostHog host (e.g. us.posthog.com).@@ -473,7 +473,7 @@ def _build_activity_page_url(project_id: Optional[int], sdk_type: str, version:def _build_banner(sdk_type: str, alert: OutdatedTrafficAlert) -> str:"""- Top-level alert text mirroring SdkDoctorScene.tsx's "Time for an update!" banner:+ Top-level alert text mirroring SdkHealthScene.tsx's "Time for an update!" banner:"Version {ver} of the {Readable} SDK has captured more than {N}% of events in the last 7 days."Version is routed through `_safe_version_display` as defense in depth — the primary@@ -644,7 +644,7 @@ def _build_reason(The single source of truth for "why is this flagged?": it always names the currentin-use version and, when older versions still taking significant traffic are what drovethe alert, the specific versions that triggered it. This keeps the string self-contained- for every consumer (SDK Doctor UI, MCP agents, alert destinations) — including the case+ for every consumer (SDK Health UI, MCP agents, alert destinations) — including the casewhere the latest in-use version already matches latest but an older one is still served."""name = SDK_READABLE_NAME.get(sdk_type, sdk_type)@@ -751,7 +751,7 @@ def compute_sdk_health() -> SdkHealthReport:"""Top-level entry point. Takes the combined data structure returned by the existing- /api/sdk_doctor/ view:+ /api/sdk_health/ view:{"web": {diff --git a/products/growth/backend/team_sdk_versions.py b/products/growth/backend/team_sdk_versions.pyindex bde4bad499fb..a0eb8884785f 100644--- a/products/growth/backend/team_sdk_versions.py+++ b/products/growth/backend/team_sdk_versions.py@@ -43,7 +43,7 @@ QUERY = parse_select("""def run_query(team: Team) -> HogQLQueryResponse:query_type = "sdk_versions_for_team"with tags_context(- product=Product.SDK_DOCTOR,+ product=Product.SDK_HEALTH,feature=Feature.HEALTH_CHECK,team_id=team.pk,org_id=team.organization_id,@@ -79,10 +79,10 @@ def get_sdk_versions_for_team(return dict(output)except Team.DoesNotExist:- logger.exception(f"[SDK Doctor] Team {team_id} not found")+ logger.exception(f"[SDK Health] Team {team_id} not found")return {} # Safe to return empty dict, this is not an errorexcept Exception as e:- logger.exception(f"[SDK Doctor] Error querying events for team {team_id}")+ logger.exception(f"[SDK Health] Error querying events for team {team_id}")capture_exception(e, {"team_id": team_id})return None@@ -95,7 +95,7 @@ def get_and_cache_team_sdk_versions() -> dict[str, list[SdkVersionEntry]] | None:"""Query ClickHouse for team SDK versions and cache the result.- Used by the SDK Doctor API for on-demand cache-miss fallback.+ Used by the SDK Health API for on-demand cache-miss fallback.Returns the response data dict or None if failed."""try:@@ -104,13 +104,13 @@ def get_and_cache_team_sdk_versions(payload = json.dumps(sdk_versions)cache_key = team_sdk_versions_key(team_id)redis_client.setex(cache_key, TEAM_SDK_CACHE_EXPIRY, payload)- logger.info(f"[SDK Doctor] Team {team_id} SDK versions cached successfully")+ logger.info(f"[SDK Health] Team {team_id} SDK versions cached successfully")return sdk_versionselse:- logger.error(f"[SDK Doctor] No data received from ClickHouse for team {team_id}")+ logger.error(f"[SDK Health] No data received from ClickHouse for team {team_id}")return Noneexcept Exception as e:- logger.exception(f"[SDK Doctor] Failed to get and cache SDK versions for team {team_id}")+ logger.exception(f"[SDK Health] Failed to get and cache SDK versions for team {team_id}")capture_exception(e)return Nonediff --git a/products/growth/backend/temporal/health_checks/sdk_outdated.py b/products/growth/backend/temporal/health_checks/sdk_outdated.pyindex b2388fe7cd74..2fc6705e10ee 100644--- a/products/growth/backend/temporal/health_checks/sdk_outdated.py+++ b/products/growth/backend/temporal/health_checks/sdk_outdated.py@@ -21,7 +21,7 @@ from products.growth.backend.constants import ()from products.growth.backend.sdk_health import SdkAssessment, _is_safe_for_interpolation, compute_sdk_health-# Issue severity follows the SDK Doctor assessment severity: a single outdated SDK is a warning,+# Issue severity follows the SDK Health assessment severity: a single outdated SDK is a warning,# but when the bulk of a team's SDKs are outdated the assessment escalates to "danger"._SEVERITY_BY_ASSESSMENT: dict[str, HealthIssue.Severity] = {"danger": HealthIssue.Severity.CRITICAL,@@ -75,7 +75,7 @@ def _load_github_sdk_data() -> dict[str, dict]:def _cache_team_sdk_data(team_sdk_data: dict[int, dict[str, list[SdkVersionEntry]]]) -> None:- """Cache team SDK version data in Redis for the SDK Doctor API."""+ """Cache team SDK version data in Redis for the SDK Health API."""if not team_sdk_data:return@@ -100,7 +100,7 @@ class SdkOutdatedCheck(HealthCheck):sdk_name = issue.payload.get("sdk_name", "an SDK")# `reason` is the assessment's single source of truth (compute_sdk_health → _build_reason).# It already names the current in-use version and the specific older versions driving the- # alert, and routes every version through SDK Doctor's allowlist before interpolation — so+ # alert, and routes every version through SDK Health's allowlist before interpolation — so# it's both complete and safe to forward to alert destinations (Slack, email, webhooks).summary = issue.payload.get("reason")if not summary:@@ -116,7 +116,7 @@ class SdkOutdatedCheck(HealthCheck):return AlertContent(title=f"{sdk_name} SDK is outdated",summary=summary,- link="/health/sdk-doctor",+ link="/health/sdk-health",)def detect(self, team_ids: list[int]) -> dict[int, list[HealthCheckResult]]:diff --git a/products/growth/backend/tests/test_sdk_health.py b/products/growth/backend/tests/test_sdk_health.pyindex a6a832999e11..2b6981f51138 100644--- a/products/growth/backend/tests/test_sdk_health.py+++ b/products/growth/backend/tests/test_sdk_health.py@@ -479,8 +479,7 @@ class TestUiParityStrings(SimpleTestCase):def test_sql_query_matches_ui_template_exact(self):# Exact-string match (not substring containment) so any whitespace / punctuation- # drift against queryForSdkVersion() in SdkDoctorComponents.tsx breaks this test.- # If you change one side, change the other — the comment in the TS file points here.+ # drift in the generated SQL is caught. The SDK Health UI renders this string as-is.sql = _build_sql_query("posthog-node", "1.230.1")expected = ("SELECT * FROM events WHERE timestamp >= NOW() - INTERVAL 7 DAY "diff --git a/products/growth/dags/github_sdk_versions.py b/products/growth/dags/github_sdk_versions.pyindex 422f04b12b70..805516006be5 100644--- a/products/growth/dags/github_sdk_versions.py+++ b/products/growth/dags/github_sdk_versions.py@@ -123,7 +123,7 @@ def fetch_releases_from_repo(repo: str, skip_cache: bool = False) -> list[Any]:skip_cache = Trueif repo in local_releases_cache and not skip_cache:- logger.info(f"[SDK Doctor] Returning cached releases for {repo}")+ logger.info(f"[SDK Health] Returning cached releases for {repo}")return local_releases_cache[repo]releases = []@@ -132,21 +132,21 @@ def fetch_releases_from_repo(repo: str, skip_cache: bool = False) -> list[Any]:while page <= 10: # Github only permits us to list the first 1000 items, so that's 100 items * 10 pagestry:url = f"https://api.github.com/repos/{repo}/releases?per_page=100&page={page}"- logger.info(f"[SDK Doctor] Fetching releases from {url}")+ logger.info(f"[SDK Health] Fetching releases from {url}")response = requests.get(url, timeout=10)if not response.ok:- logger.error(f"[SDK Doctor] Failed to fetch releases for {repo}", status_code=response.status_code)+ logger.error(f"[SDK Health] Failed to fetch releases for {repo}", status_code=response.status_code)breakreleases_json = response.json()if releases_json is None:- logger.error(f"[SDK Doctor] Expected list of releases, got empty response", repo=repo)+ logger.error(f"[SDK Health] Expected list of releases, got empty response", repo=repo)breakif not isinstance(releases_json, list):- logger.error(f"[SDK Doctor] Expected list of releases, got {type(releases_json)}", repo=repo)+ logger.error(f"[SDK Health] Expected list of releases, got {type(releases_json)}", repo=repo)breakif len(releases_json) == 0:@@ -155,7 +155,7 @@ def fetch_releases_from_repo(repo: str, skip_cache: bool = False) -> list[Any]:releases.extend(releases_json)page += 1except Exception as e:- logger.exception(f"[SDK Doctor] Failed to fetch releases for {repo}", repo=repo)+ logger.exception(f"[SDK Health] Failed to fetch releases for {repo}", repo=repo)capture_exception(e, additional_properties={"repo": repo, "page": page, "url": url})breakdiff --git a/products/growth/skills/diagnosing-sdk-health/SKILL.md b/products/growth/skills/diagnosing-sdk-health/SKILL.mdindex d0a4fb78f513..ae3a72e77be5 100644--- a/products/growth/skills/diagnosing-sdk-health/SKILL.md+++ b/products/growth/skills/diagnosing-sdk-health/SKILL.md@@ -3,23 +3,23 @@ name: diagnosing-sdk-healthdescription: >Diagnoses the health of a project's PostHog SDK integrations — which SDKs are up todate, which are outdated, and what to do about it. Use when a user asks about PostHog- SDK versions, outdated SDKs, upgrade recommendations, "SDK health", "SDK doctor", or- when events or features seem off and it might be due to using an old SDK.+ SDK versions, outdated SDKs, upgrade recommendations, "SDK health", "SDK doctor" (the+ former name), or when events or features seem off and it might be due to using an old SDK.---# Diagnosing SDK healthWhen a user asks about PostHog SDK versions, outdated SDKs, or whether they should-upgrade, use the pre-digested SDK Doctor report rather than reasoning about versions+upgrade, use the pre-digested SDK Health report rather than reasoning about versionsyourself. The backend applies smart-semver rules (grace periods, minor-count thresholds,age-based detection), traffic-percentage thresholds, and provides user-facing copy that-matches the SDK Doctor UI exactly.+matches the SDK Health UI exactly.## Available tools| Tool | Purpose || ------------------------ | ---------------------------------------------------------------------------------------------------- |-| `posthog:sdk-doctor-get` | Returns a structured health report plus UI-matching copy and drill-in URLs per SDK/version. |+| `posthog:sdk-health-get` | Returns a structured health report plus UI-matching copy and drill-in URLs per SDK/version. || `posthog:execute-sql` | (Optional) Run a `sql_query` from the report to show events captured by a specific outdated version. |## Workflow@@ -27,7 +27,7 @@ matches the SDK Doctor UI exactly.### Step 1 — Invoke the tool```json-posthog:sdk-doctor-get+posthog:sdk-health-get{}```@@ -55,7 +55,7 @@ Lead with the headline:### Step 3 — Surface the banner text(s) verbatim-Each SDK's `banners` array contains zero or more sentences that match the SDK Doctor UI's+Each SDK's `banners` array contains zero or more sentences that match the SDK Health UI's"Time for an update!" alert exactly, e.g.:> Version 7.0.0 of the Python SDK has captured more than 10% of events in the last 7 days.@@ -99,7 +99,7 @@ ready-to-use links:### Step 6 — Link to the UI-Always close with a link to the SDK Doctor page: `/project/<project_id>/health/sdk-doctor`.+Always close with a link to the SDK Health page: `/project/<project_id>/health/sdk-health`.The UI shows per-row event counts, last-event timestamps, release notes, and SDK docslinks — more than the tool response includes.@@ -148,7 +148,7 @@ interpolate (e.g. it contained quote characters or whitespace). When this happenSimilarly, if you pass `sql_query` to `posthog:execute-sql` and it errors, surface theerror verbatim rather than rewriting the query. The query template is a verbatim mirror-of what the SDK Doctor UI uses — if the UI's SQL wouldn't run, something else is wrong.+of what the SDK Health UI uses — if the UI's SQL wouldn't run, something else is wrong.**Do not wrap, truncate, or modify `sql_query` in any way before passing to`posthog:execute-sql`.** No `SELECT * FROM (<sql_query>) LIMIT 10`, no adding `WHERE`diff --git a/services/mcp/definitions/sdk_doctor.yaml b/services/mcp/definitions/sdk_health.yamlsimilarity index 91%rename from services/mcp/definitions/sdk_doctor.yamlrename to services/mcp/definitions/sdk_health.yamlindex cd188773cf05..e603c8853fdf 100644--- a/services/mcp/definitions/sdk_doctor.yaml+++ b/services/mcp/definitions/sdk_health.yaml@@ -4,13 +4,13 @@## To enable a tool, set enabled: true and add required scopes + annotations.# All other fields (title, description, enrich_url, etc.) are yours to configure.-category: SDK Doctor-feature: sdk_doctor-url_prefix: /health/sdk-doctor+category: SDK Health+feature: sdk_health+url_prefix: /health/sdk-healthui_apps: {}tools:- sdk-doctor-get:- operation: sdk_doctor_report_retrieve+ sdk-health-get:+ operation: sdk_health_report_retrieveenabled: truescopes:- project:readdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 8d283b4b737f..a56a42988a60 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -4823,10 +4823,10 @@"readOnlyHint": false}},- "sdk-doctor-get": {+ "sdk-health-get": {"description": "Returns a pre-digested health report for the PostHog SDKs this project is using. Covers which SDKs are current vs outdated (smart-semver rules with grace periods and traffic-percentage thresholds), per-version breakdowns, and a human-readable reason for each assessment. Use when the user asks about PostHog SDK versions, outdated SDKs, SDK health, version upgrade recommendations, or why events may not be captured due to SDK issues.",- "category": "SDK Doctor",- "feature": "sdk_doctor",+ "category": "SDK Health",+ "feature": "sdk_health","summary": "Get SDK health report","title": "Get SDK health report","required_scopes": ["project:read"],diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex e70a3752da0d..c520f8781e9d 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5134,10 +5134,10 @@"readOnlyHint": false}},- "sdk-doctor-get": {+ "sdk-health-get": {"description": "Returns a pre-digested health report for the PostHog SDKs this project is using. Covers which SDKs are current vs outdated (smart-semver rules with grace periods and traffic-percentage thresholds), per-version breakdowns, and a human-readable reason for each assessment. Use when the user asks about PostHog SDK versions, outdated SDKs, SDK health, version upgrade recommendations, or why events may not be captured due to SDK issues.",- "category": "SDK Doctor",- "feature": "sdk_doctor",+ "category": "SDK Health",+ "feature": "sdk_health","summary": "Get SDK health report","title": "Get SDK health report","required_scopes": ["project:read"],diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9fb1007afe6f..3e66bff5d644 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -38241,7 +38241,7 @@ export namespace Schemas {needs_updating: boolean;/** True when this version equals or exceeds the latest known published version. */is_current_or_newer: boolean;- /** Per-version badge tooltip text matching the SDK Doctor UI exactly. Quote verbatim when reporting to users. Varies by state: 'Released X ago. Upgrade recommended.' for outdated versions, 'You have the latest available.' for current versions, or 'Released X ago. Upgrading is a good idea, but it's not urgent yet.' for recent-but-behind versions. */+ /** Per-version badge tooltip text matching the SDK Health UI exactly. Quote verbatim when reporting to users. Varies by state: 'Released X ago. Upgrade recommended.' for outdated versions, 'You have the latest available.' for current versions, or 'Released X ago. Upgrading is a good idea, but it's not urgent yet.' for recent-but-behind versions. */status_reason: string;/** SQL SELECT statement for drilling into events for this SDK version over the last 7 days. Suitable to pass to the execute-sql tool or to display as a copy-paste snippet. */sql_query: string;@@ -38252,7 +38252,7 @@ export namespace Schemas {export interface SdkAssessment {/** SDK identifier, e.g. 'web', 'posthog-python', 'posthog-node', 'posthog-ios'. */lib: string;- /** Human-readable SDK name matching the SDK Doctor UI (e.g. 'Python', 'Node.js', 'Web', 'iOS'). */+ /** Human-readable SDK name matching the SDK Health UI (e.g. 'Python', 'Node.js', 'Web', 'iOS'). */readable_name: string;/** Most recent published version of this SDK. */latest_version: string;@@ -38270,7 +38270,7 @@ export namespace Schemas {severity: SdkAssessmentSeverityEnum;/** Per-SDK programmatic summary (used for ranking/filtering). For user-facing copy, prefer releases[].status_reason (badge tooltip) and banners (top-level alert text) — those match the UI exactly. */reason: string;- /** Top-level alert sentences matching the SDK Doctor UI's 'Time for an update!' banner — one per outdated version with significant traffic. Quote verbatim when surfacing the headline to users. */+ /** Top-level alert sentences matching the SDK Health UI's 'Time for an update!' banner — one per outdated version with significant traffic. Quote verbatim when surfacing the headline to users. */banners: string[];/** Per-version assessment for all versions seen in the last 7 days. */releases: SdkReleaseAssessment[];@@ -51396,7 +51396,7 @@ export namespace Schemas {offset?: number;};- export type SdkDoctorReportRetrieveParams = {+ export type SdkHealthReportRetrieveParams = {/*** When true, bypasses the Redis cache and re-queries ClickHouse for SDK usage. Use sparingly — data is refreshed every 12 hours by a background job.*/diff --git a/services/mcp/src/generated/sdk_doctor/api.ts b/services/mcp/src/generated/sdk_health/api.tssimilarity index 90%rename from services/mcp/src/generated/sdk_doctor/api.tsrename to services/mcp/src/generated/sdk_health/api.tsindex 56bedb3bc16c..621571fee945 100644--- a/services/mcp/src/generated/sdk_doctor/api.ts+++ b/services/mcp/src/generated/sdk_health/api.ts@@ -12,7 +12,7 @@ import * as zod from 'zod'* Returns a pre-digested health assessment of the PostHog SDKs the project is using. Covers which SDKs are current vs outdated (smart-semver rules with grace periods and traffic-percentage thresholds), per-version breakdown, and a human-readable reason for each assessment. Use this to diagnose SDK version issues, surface upgrade recommendations, or check overall SDK health.* @summary Get SDK health report for a project*/-export const SdkDoctorReportRetrieveParams = /* @__PURE__ */ zod.object({+export const SdkHealthReportRetrieveParams = /* @__PURE__ */ zod.object({project_id: zod.string().describe(@@ -20,7 +20,7 @@ export const SdkDoctorReportRetrieveParams = /* @__PURE__ */ zod.object({),})-export const SdkDoctorReportRetrieveQueryParams = /* @__PURE__ */ zod.object({+export const SdkHealthReportRetrieveQueryParams = /* @__PURE__ */ zod.object({force_refresh: zod.boolean().optional()diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.tsindex e7689b8bbb30..6ece761878b5 100644--- a/services/mcp/src/tools/generated/index.ts+++ b/services/mcp/src/tools/generated/index.ts@@ -31,7 +31,7 @@ import { GENERATED_TOOLS as proxyRecords } from './proxy-records'import { GENERATED_TOOLS as queryWrappers } from './query-wrappers'import { GENERATED_TOOLS as replay } from './replay'import { GENERATED_TOOLS as replay_vision } from './replay_vision'-import { GENERATED_TOOLS as sdk_doctor } from './sdk_doctor'+import { GENERATED_TOOLS as sdk_health } from './sdk_health'import { GENERATED_TOOLS as signals } from './signals'import { GENERATED_TOOLS as surveys } from './surveys'import { GENERATED_TOOLS as tasks } from './tasks'@@ -72,7 +72,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =...queryWrappers,...replay,...replay_vision,- ...sdk_doctor,+ ...sdk_health,...signals,...surveys,...tasks,diff --git a/services/mcp/src/tools/generated/sdk_doctor.ts b/services/mcp/src/tools/generated/sdk_health.tssimilarity index 66%rename from services/mcp/src/tools/generated/sdk_doctor.tsrename to services/mcp/src/tools/generated/sdk_health.tsindex cac72952869a..5793cea330a6 100644--- a/services/mcp/src/tools/generated/sdk_doctor.ts+++ b/services/mcp/src/tools/generated/sdk_health.ts@@ -1,24 +1,24 @@-// AUTO-GENERATED from services/mcp/definitions/sdk_doctor.yaml + OpenAPI — do not edit+// AUTO-GENERATED from services/mcp/definitions/sdk_health.yaml + OpenAPI — do not editimport { z } from 'zod'import type { Schemas } from '@/api/generated'-import { SdkDoctorReportRetrieveQueryParams } from '@/generated/sdk_doctor/api'+import { SdkHealthReportRetrieveQueryParams } from '@/generated/sdk_health/api'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'-const SdkDoctorGetSchema = SdkDoctorReportRetrieveQueryParams.extend({- force_refresh: SdkDoctorReportRetrieveQueryParams.shape['force_refresh'].describe(+const SdkHealthGetSchema = SdkHealthReportRetrieveQueryParams.extend({+ force_refresh: SdkHealthReportRetrieveQueryParams.shape['force_refresh'].describe('Set to true to bypass the Redis cache and re-query ClickHouse for SDK usage. Use sparingly — data is refreshed every 12 hours by a background job, so the cached answer is usually fine.'),})-const sdkDoctorGet = (): ToolBase<typeof SdkDoctorGetSchema, Schemas.SdkHealthReport> => ({- name: 'sdk-doctor-get',- schema: SdkDoctorGetSchema,- handler: async (context: Context, params: z.infer<typeof SdkDoctorGetSchema>) => {+const sdkHealthGet = (): ToolBase<typeof SdkHealthGetSchema, Schemas.SdkHealthReport> => ({+ name: 'sdk-health-get',+ schema: SdkHealthGetSchema,+ handler: async (context: Context, params: z.infer<typeof SdkHealthGetSchema>) => {const projectId = await context.stateManager.getProjectId()const result = await context.api.request<Schemas.SdkHealthReport>({method: 'GET',- path: `/api/projects/${encodeURIComponent(String(projectId))}/sdk_doctor/report/`,+ path: `/api/projects/${encodeURIComponent(String(projectId))}/sdk_health/report/`,query: {force_refresh: params.force_refresh,},@@ -28,5 +28,5 @@ const sdkDoctorGet = (): ToolBase<typeof SdkDoctorGetSchema, Schemas.SdkHealthRe})export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {- 'sdk-doctor-get': sdkDoctorGet,+ 'sdk-health-get': sdkHealthGet,}diff --git a/services/mcp/tests/unit/__snapshots__/exec-tool.json b/services/mcp/tests/unit/__snapshots__/exec-tool.jsondeleted file mode 100644index 262393e2fd51..000000000000--- a/services/mcp/tests/unit/__snapshots__/exec-tool.json+++ /dev/null@@ -1,23 +0,0 @@-{- "name": "exec",- "title": "Execute PostHog command",- "description": "### Using the `posthog` tool\n\nPass CLI-style commands in the `command` parameter for all PostHog interactions.\n\n**MANDATORY — HARD REQUIREMENTS**\n\n1. Discover tools first with `search` or `tools`.\n2. Run `info <tool_name>` BEFORE every `call <tool_name> <json>`.\n\nBLOCKING, like reading a file before editing it. Tool names and schemas are NOT predictable — never assume.\n\n**Commands (in order):**\n\n```text\n# 1. Discover (preferred: focused regex over name/title/description)\nposthog:exec({ \"command\": \"search <regex>\" })\nposthog:exec({ \"command\": \"tools\" }) # fallback: list all\n\n# 2. Check description + top-level schema (REQUIRED before call)\nposthog:exec({ \"command\": \"info <tool_name>\" })\n\n# 3. Drill into complex fields — REQUIRED for any field with a `hint`\nposthog:exec({ \"command\": \"schema <tool_name> <field_path>\" })\n\n# 4. Call the tool\nposthog:exec({ \"command\": \"call <tool_name> <json_input>\" })\nposthog:exec({ \"command\": \"call --json <tool_name> <json_input>\" })\n```\n\n**Schema drill-down:**\n\n- `info` returns the full schema if it fits the token budget; otherwise it auto-summarizes (names, types, required, enums, defaults) and attaches `hint` entries pointing to `schema <tool> <path>` for complex fields.\n- `schema <tool>` (no path) returns the summarized top-level schema.\n- `schema <tool> <path>` resolves a dot path, descending through:\n - object `properties` (e.g. `query.source`)\n - array `items` — numeric segments step into items (`events.0.properties`), or jump to a property on the item type (`events.id`)\n - `anyOf`/`oneOf` — numeric segment picks a variant by index, or a property name matches any object variant defining it\n- Oversized sub-schemas are also summarized with a `note` to drill further.\n- Unknown paths return an error listing available child paths.\n\n**Not supported:**\n\n- `search` matches tool metadata only, not input schemas.\n- No pattern-based field projection — drill one path at a time.",- "annotations": {- "destructiveHint": false,- "idempotentHint": false,- "openWorldHint": true,- "readOnlyHint": false- },- "scopes": [],- "inputSchema": {- "$schema": "https://json-schema.org/draft/2020-12/schema",- "type": "object",- "properties": {- "command": {- "type": "string",- "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary with drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), call `schema <tool_name> <field_name>` for each field you need to populate BEFORE constructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large), drill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> series.properties` — to see property filter structure of series\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"DO NOT GUESS – run `schema query-trends series` before populating this field\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval\n- batch-export\n- cdp-function\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- data-warehouse-data\n- desktop-file-system\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data\n- feature-flag\n- file-download-batch\n- hog-flows\n- inbox\n- insight\n- integration\n- llm-total-costs\n- llma-clustering\n- llma-evaluation\n- llma-personal\n- llma-prompt\n- llma-review\n- llma-score\n- llma-sentiment\n- llma-skill\n- llma-summarization\n- llma-tagger\n- llma-trace\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- query\n- read-data\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- signals-scout\n- sql-variables\n- subscriptions\n- survey\n- switch\n- usage-metrics\n- user\n- view\n- web-analytics-weekly\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.\n\n#### Searching for existing entities\n\n\"find / which / do we have / what's our X chart\" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.\n\nRequired order on every run, no shortcuts:\n\n1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.\n2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.\n3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.\n4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.\n\n<bad-example>\nUser: rename / find / list … (any `system.*` question)\nAssistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]\nWRONG — the rule is \"schema first, every run, no shortcuts.\" Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-lifecycle-actors` — List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-paths-actors` — List persons who traversed the paths defined by a paths insight\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nPostHog app links must be full URLs (origin + path) — bare paths aren't clickable in MCP clients like Cursor or Claude Desktop. Use Markdown with descriptive anchor text, e.g. `[Cohorts](https://us.posthog.com/project/1/cohorts)`. Never include `/-/`.\n\n- If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.\n- Otherwise build the link from the Base URL in the active-environment block (don't double-prefix):\n - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`, and most pages.\n - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"- }- },- "required": ["command"]- }-}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/sdk-doctor-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/sdk-health-get.jsonsimilarity index 100%rename from services/mcp/tests/unit/__snapshots__/tool-schemas/sdk-doctor-get.jsonrename to services/mcp/tests/unit/__snapshots__/tool-schemas/common/sdk-health-get.jsondiff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/sdk-health-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/sdk-health-get.jsonnew file mode 100644index 000000000000..f37c4528fbc2--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/sdk-health-get.json@@ -0,0 +1,10 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "force_refresh": {+ "description": "Set to true to bypass the Redis cache and re-query ClickHouse for SDK usage. Use sparingly — data is refreshed every 12 hours by a background job, so the cached answer is usually fine.",+ "type": "boolean"+ }+ },+ "type": "object"+}diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 6c2c530e511d..bccfcb300f1d 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -1,11 +1,9 @@import guidelines from '@shared/guidelines.md'-import path from 'node:path'-import { fileURLToPath } from 'node:url'-import { format } from 'oxfmt'import { describe, expect, it } from 'vitest'import { parse as parseYaml } from 'yaml'import { z } from 'zod'+import { buildQueryToolsBlock, buildToolDomainsBlock } from '@/lib/instructions'import { InstructionsFormatter } from '@/lib/instructions-formatter'import { SessionManager } from '@/lib/SessionManager'import { getToolsFromContext } from '@/tools'@@ -676,8 +674,8 @@ describe('exec tool', () => {})})- describe('schema snapshot', () => {- function createSnapshotContext(): Context {+ describe('exec tool description', () => {+ function createExecContext(): Context {return {api: {} as any,cache: {} as any,@@ -704,7 +702,7 @@ describe('exec tool', () => {// exec tool's description must fit within that budget or clients will// silently drop the tail of the instructions.it('keeps the tool description within 2048 characters', async () => {- const context = createSnapshotContext()+ const context = createExecContext()const v2Tools = await getToolsFromContext(context)const toolInfos = v2Tools.map((t) => ({name: t.name,@@ -736,68 +734,41 @@ describe('exec tool', () => {expect(execTool.description.length).toBeLessThanOrEqual(2048)})- // Snapshots the full exec tool definition built from the real v2 tool set:- // description (the `exec-tool-blurb` subprompt), annotations, and input schema- // including the `command` field description — which embeds the generated- // `tool_domains` block. Because `buildToolDomainsBlock` relies on tool-name conventions- // (CRUD suffixes, prefix actions, plural collapsing), this snapshot is the- // canary for any drift in naming or in the domain-extraction logic.- //- // Snapshots the Codex (`supportsInstructions: false`) wiring, where every- // placeholder is filled. That's the only path where `{tool_domains}` and- // `{query_tools}` actually appear in the `command` parameter description,- // so the snapshot has to follow it to keep catching drift in those blocks.- it('matches the full exec tool schema', async () => {- const context = createSnapshotContext()- const v2Tools = [...(await getToolsFromContext(context))].sort((a, b) => a.name.localeCompare(b.name))- const toolInfos = v2Tools.map((t) => ({- name: t.name,- category: getToolDefinition(t.name).category,- }))- const queryToolInfos = v2Tools- .filter((t) => t.name.startsWith('query-'))- .map((t) => {- const def = getToolDefinition(t.name)- return {- name: t.name,- title: def.title,- ...(def.system_prompt_hint ? { systemPromptHint: def.system_prompt_hint } : {}),- }- })+ // The `{tool_domains}` and `{query_tools}` placeholders in the exec+ // tool's `command` description are filled from the passed tool set. A+ // fixed fake set keeps this hermetic — adding or renaming a real tool+ // can't flip it.+ it('interpolates the tool-domain and query-tool blocks into the command description', () => {+ const toolInfos = [+ { name: 'experiment-create', category: 'Experiments' },+ { name: 'experiment-delete', category: 'Experiments' },+ { name: 'query-trends', category: 'Query' },+ ]+ const queryToolInfos = [{ name: 'query-trends', title: 'Trends', systemPromptHint: 'time series' }]+const formatter = new InstructionsFormatter()const commandReference = formatter.buildExecCommandReference({ guidelines, tools: toolInfos, queryTools: queryToolInfos },{ stripEnvContext: false })const execTool = createExecTool(- v2Tools,- context,+ [],+ createExecContext(),formatter.buildExecToolDescription(),commandReference,undefined)+ const commandDescription = execTool.schema.shape.command.description ?? ''- const snapshot = {- name: execTool.name,- title: execTool.title,- description: execTool.description,- annotations: execTool.annotations,- scopes: execTool.scopes,- inputSchema: z.toJSONSchema(execTool.schema, { io: 'input', reused: 'inline' }),- }+ expect(commandDescription).not.toContain('{tool_domains}')+ expect(commandDescription).not.toContain('{query_tools}')- const __dirname = path.dirname(fileURLToPath(import.meta.url))- const snapshotPath = path.resolve(__dirname, '__snapshots__', 'exec-tool.json')- // Format via oxfmt so the snapshot matches repo-wide formatting rules- // (lint-staged reformats *.json and would otherwise flip this file on save).- const content = `${JSON.stringify(snapshot, null, 4)}\n`- const result = await format(snapshotPath, content, { tabWidth: 4, printWidth: 120 })- if (result.errors.length > 0) {- throw new Error(- `Failed formatting snapshot: ${result.errors.map((e) => e.message ?? 'unknown').join('; ')}`- )- }- await expect(result.code).toMatchFileSnapshot(snapshotPath)+ const domainsBlock = buildToolDomainsBlock(toolInfos)+ const queryToolsBlock = buildQueryToolsBlock(queryToolInfos)+ expect(domainsBlock).toContain('experiment')+ expect(domainsBlock).toContain('query')+ expect(commandDescription).toContain(domainsBlock)+ expect(commandDescription).toContain(queryToolsBlock)})})})