: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
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'
import { toast } from 'react-toastify'
import { IconX } from '@posthog/icons'
import api from 'lib/api'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { userLogic } from 'scenes/userLogic'
import { UserType } from '~/types'
import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'
import type { SurfaceKey } from './prompts'
export type MCPHintPlacement = 'toast' | 'card'
function reportMCPHintDismissed(surfaceKey: string): void {
// pinned: `dismiss_type` stays on the event so existing insights keep matching
posthog.capture('mcp hint dismissed', {
dismiss_type: 'surface',
surface_key: surfaceKey,
})
}
// In production the toast auto-dismisses after a few seconds so it doesn't linger;
// in development we keep it open so it's easier to inspect.
const AUTO_DISMISS_MS = process.env.NODE_ENV === 'development' ? false : 15000
// A full week between hints, regardless of surface — these are promotional,
// so we err heavily on the side of not overloading people.
const COOLDOWN_MS = 7 * 24 * 60 * 60 * 1000
export interface TryShowMCPHintOptions {
/**
* Replaces the generic per-surface toast prompt with one derived from the action the user just took
* (e.g. the actual feature flag they created). Plain string; quoting is handled by the toast component.
*/
derivedPrompt?: string
}
export function tryShowMCPHint(surfaceKey: SurfaceKey, options: TryShowMCPHintOptions = {}): void {
try {
const mounted = mcpHintLogic.findMounted()
mounted?.actions.tryShowHint(surfaceKey, options.derivedPrompt)
} catch (error) {
console.warn('[mcpHint] dispatch failed; host listener will continue', { surfaceKey, error })
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpHintLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
user: UserType | null // userLogic
dismissedSurfaces: Record<string, true>
effectiveOptOut: boolean
lastShownAt: number | null
topEvents: string[]
topEventsLoading: boolean
userRole: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpHintLogicActions {
reportMCPHintShown: (surfaceKey: string) => {
surfaceKey: string
} // eventUsageLogic
updateUser: (
user: Partial<UserType>,
successCallback?: (() => void) | undefined,
failureCallback?: (() => void) | undefined
) => {
failureCallback: (() => void) | undefined
successCallback: (() => void) | undefined
user: Partial<UserType>
} // userLogic
dismissSurface: (surfaceKey: SurfaceKey) => {
surfaceKey:
| 'actions.create'
| 'ai_observability_evaluations.create'
| 'alerts.create'
| 'annotations.create'
| 'cohorts.create'
| 'dashboards.create'
| 'data_warehouse_sources.create'
| 'data_warehouse_sources.update'
| 'early_access_features.create'
| 'error_tracking.assign'
| 'experiments.create'
| 'experiments.launch'
| 'feature_flags.create'
| 'feature_flags.update'
| 'insights.create'
| 'sql.execute'
| 'surveys.create'
| 'workflows.create'
}
keepHintOpen: (toastId: string) => {
toastId: string
}
loadTopEvents: () => any
loadTopEventsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadTopEventsSuccess: (
topEvents: string[],
payload?: any
) => {
topEvents: string[]
payload?: any
}
recordShown: (now: number) => {
now: number
}
reenable: () => {
value: true
}
reportAgentOpened: (
surfaceKey: SurfaceKey,
placement: MCPHintPlacement,
agentKey: string
) => {
agentKey: string
placement: MCPHintPlacement
surfaceKey:
| 'actions.create'
| 'ai_observability_evaluations.create'
| 'alerts.create'
| 'annotations.create'
| 'cohorts.create'
| 'dashboards.create'
| 'data_warehouse_sources.create'
| 'data_warehouse_sources.update'
| 'early_access_features.create'
| 'error_tracking.assign'
| 'experiments.create'
| 'experiments.launch'
| 'feature_flags.create'
| 'feature_flags.update'
| 'insights.create'
| 'sql.execute'
| 'surveys.create'
| 'workflows.create'
}
reportUseCaseCardShown: (surfaceKey: SurfaceKey) => {
surfaceKey:
| 'actions.create'
| 'ai_observability_evaluations.create'
| 'alerts.create'
| 'annotations.create'
| 'cohorts.create'
| 'dashboards.create'
| 'data_warehouse_sources.create'
| 'data_warehouse_sources.update'
| 'early_access_features.create'
| 'error_tracking.assign'
| 'experiments.create'
| 'experiments.launch'
| 'feature_flags.create'
| 'feature_flags.update'
| 'insights.create'
| 'sql.execute'
| 'surveys.create'
| 'workflows.create'
}
tryShowHint: (
surfaceKey: SurfaceKey,
derivedPrompt?: string
) => {
derivedPrompt: string | undefined
surfaceKey:
| 'actions.create'
| 'ai_observability_evaluations.create'
| 'alerts.create'
| 'annotations.create'
| 'cohorts.create'
| 'dashboards.create'
| 'data_warehouse_sources.create'
| 'data_warehouse_sources.update'
| 'early_access_features.create'
| 'error_tracking.assign'
| 'experiments.create'
| 'experiments.launch'
| 'feature_flags.create'
| 'feature_flags.update'
| 'insights.create'
| 'sql.execute'
| 'surveys.create'
| 'workflows.create'
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpHintLogicMeta {
__keaTypeGenInternalSelectorTypes: {
effectiveOptOut: (user: UserType | null) => boolean
userRole: (user: UserType | null) => string | null
}
}
export type mcpHintLogicType = MakeLogicType<
mcpHintLogicValues,
mcpHintLogicActions,
Record<string, any>,
mcpHintLogicMeta
>
export const mcpHintLogic = kea<mcpHintLogicType>([
path(['lib', 'components', 'MCPHint', 'mcpHintLogic']),
connect(() => ({
values: [userLogic, ['user'], featureFlagLogic, ['featureFlags']],
actions: [userLogic, ['updateUser'], eventUsageLogic, ['reportMCPHintShown']],
})),
actions({
tryShowHint: (surfaceKey: SurfaceKey, derivedPrompt?: string) => ({ surfaceKey, derivedPrompt }),
recordShown: (now: number) => ({ now }),
dismissSurface: (surfaceKey: SurfaceKey) => ({ surfaceKey }),
reenable: true,
reportAgentOpened: (surfaceKey: SurfaceKey, placement: MCPHintPlacement, agentKey: string) => ({
surfaceKey,
placement,
agentKey,
}),
reportUseCaseCardShown: (surfaceKey: SurfaceKey) => ({ surfaceKey }),
keepHintOpen: (toastId: string) => ({ toastId }),
}),
reducers({
lastShownAt: [
null as number | null,
{ persist: true },
{
recordShown: (_, { now }) => now,
reenable: () => null,
},
],
dismissedSurfaces: [
{} as Record<string, true>,
{ persist: true },
{
dismissSurface: (state, { surfaceKey }) => ({ ...state, [surfaceKey]: true }),
reenable: () => ({}),
},
],
}),
loaders({
topEvents: [
[] as string[],
{
// Used to weave the team's real event names into the SQL editor's example prompts.
// One-shot per logic mount; if the call fails we silently fall back to default examples.
loadTopEvents: async () => {
try {
// Over-fetch: `buildSqlExamplesFromEvents` drops PostHog-internal (`$`-prefixed)
// events, so a team whose most-recent events are mostly internal could otherwise
// be left with nothing to surface.
const response = await api.eventDefinitions.list({
limit: 30,
ordering: '-last_seen_at',
})
const names = (response.results ?? []).map((d) => d.name).filter((n): n is string => Boolean(n))
return names
} catch {
return []
}
},
},
],
}),
selectors({
effectiveOptOut: [(s) => [s.user], (user: UserType | null): boolean => Boolean(user?.hide_mcp_hints)],
userRole: [(s) => [s.user], (user: UserType | null): string | null => user?.role_at_organization ?? null],
}),
listeners(({ values, actions }) => ({
tryShowHint: async ({ surfaceKey, derivedPrompt }) => {
const now = Date.now()
const sinceLast = values.lastShownAt ? now - values.lastShownAt : Infinity
const cooldownActive = values.lastShownAt !== null && sinceLast < COOLDOWN_MS
if (values.effectiveOptOut || Boolean(values.dismissedSurfaces[surfaceKey]) || cooldownActive) {
return
}
// Record the hint before the toast module loads, so a second action in that gap cannot show a second hint.
actions.recordShown(now)
try {
// Many logics import this one to call tryShowMCPHint, so a static import would load the
// toast and the agent prompt button with every one of them, including in Jest setup.
const { MCPHintToast } = await import('./MCPHintToast')
const toastId = `mcp-hint-${surfaceKey}-${now}`
toast.info(<MCPHintToast surfaceKey={surfaceKey} derivedPrompt={derivedPrompt} toastId={toastId} />, {
toastId,
autoClose: AUTO_DISMISS_MS,
closeOnClick: false,
draggable: false,
hideProgressBar: true,
icon: false,
// Clicking the X is the only way to permanently hide this surface — auto-dismiss
// (timeout) shouldn't count, so we wire dismissSurface here, not in onClose.
// Close first so the toast always dismisses, independent of the bookkeeping action.
closeButton: ({ closeToast }) => (
<LemonButton
type="tertiary"
size="small"
icon={<IconX />}
onClick={(e) => {
closeToast(e)
actions.dismissSurface(surfaceKey)
}}
data-attr="mcp-hint-close"
/>
),
})
actions.reportMCPHintShown(surfaceKey)
} catch (error) {
console.warn('[mcpHint] toast render failed', { surfaceKey, error })
}
},
dismissSurface: ({ surfaceKey }) => {
reportMCPHintDismissed(surfaceKey)
},
reenable: () => {
actions.updateUser({ hide_mcp_hints: false })
},
// pinned: analytics event names and properties
reportAgentOpened: ({ surfaceKey, placement, agentKey }) => {
posthog.capture('mcp hint agent opened', { surface_key: surfaceKey, placement, agent: agentKey })
},
keepHintOpen: ({ toastId }) => {
// The agent menu renders outside the toast, so hovering it does not pause the auto-dismiss timer.
toast.update(toastId, { autoClose: false })
},
reportUseCaseCardShown: ({ surfaceKey }) => {
posthog.capture('mcp use case card shown', { surface_key: surfaceKey })
},
})),
])