: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 { createHash, randomUUID } from 'node:crypto'
import { ApiClient } from '@/api/client'
import { MemoryCache } from '@/lib/cache/MemoryCache'
import { getPostHogClient } from '@/lib/posthog'
import { buildMCPAnalyticsGroups, buildMCPContextProperties } from '@/lib/posthog/analytics'
import type { AnalyticsEvent } from '@/lib/posthog/analytics'
import { resolveScopePreset } from '@/lib/scope-preset'
import { SessionManager } from '@/lib/SessionManager'
import { StateManager } from '@/lib/StateManager'
import { sanitizeHeaderValue } from '@/lib/utils'
import type { Context, Env, PinnedActiveContext, State } from '@/tools/types'
import type { CliConfig } from './config'
function cliIdentityKey(apiKey: string | undefined): string {
if (!apiKey) {
return 'anonymous'
}
return createHash('sha256').update(apiKey).digest('hex').slice(0, 16)
}
const pendingAnalytics = new Set<Promise<void>>()
/**
* Flush queued analytics before the process exits. `process.exit()` does not
* wait for in-flight requests, so the error path must call this explicitly —
* without it, errored `$mcp_tool_call` events are enqueued but never sent.
*/
export async function flushAnalytics(timeoutMs = 2000): Promise<void> {
try {
await Promise.race([
Promise.allSettled(pendingAnalytics),
new Promise((resolve) => setTimeout(resolve, timeoutMs).unref()),
])
await getPostHogClient().shutdown(timeoutMs)
} catch {
// Analytics must never fail or block the CLI.
}
}
/** Which CLI runs the tools. The default is posthog-cli; the hog CLI passes its own. */
export interface CliIdentity {
clientName: string
userAgent: string
source: string
}
const POSTHOG_CLI_IDENTITY: CliIdentity = {
clientName: 'posthog-cli',
userAgent: 'posthog-cli api',
source: 'posthog_cli',
}
export async function buildCliContext(
config: CliConfig,
identity: CliIdentity = POSTHOG_CLI_IDENTITY
): Promise<Context> {
const identityKey = cliIdentityKey(config.apiKey)
const fallbackDistinctId = `${identity.clientName}:${identityKey}`
// Set by the Rust wrapper; joins these events to its telemetry for the same run.
const cliInvocationId = process.env.POSTHOG_CLI_INVOCATION_ID
const sessionId = randomUUID()
const cache = new MemoryCache<State>(`cli:${identityKey}:${config.host}:${sessionId}`)
const pinned: PinnedActiveContext | undefined =
config.organizationId || config.projectId
? {
pin: { organizationId: config.organizationId, projectId: config.projectId },
sessionScoped: false,
orgId: config.organizationId,
projectId: config.projectId,
}
: undefined
let privateResponse = false
const api = new ApiClient({
apiToken: config.apiKey ?? '',
baseUrl: config.host.replace(/\/+$/, ''),
clientUserAgent: identity.userAgent,
mcpClientName: identity.clientName,
mcpClientVersion: sanitizeHeaderValue(process.env.POSTHOG_CLI_VERSION),
mcpConsumer: identity.clientName,
onPrivateResponse: () => {
privateResponse = true
},
})
const stateManager = new StateManager(cache, api, pinned)
const sessionManager = new SessionManager(cache)
const context: Context = {
api,
cache,
env: process.env as Env,
stateManager,
sessionManager,
getDistinctId: () => stateManager.getDistinctId(),
trackEvent: (event: AnalyticsEvent, properties: Record<string, unknown> = {}) => {
const capture = (async (): Promise<void> => {
try {
const [distinctId, analyticsContext, apiKey] = await Promise.all([
stateManager.getDistinctId().catch(() => undefined),
stateManager.getAnalyticsContext().catch(() => undefined),
stateManager.getApiKey().catch(() => undefined),
])
const groups = analyticsContext ? buildMCPAnalyticsGroups(analyticsContext) : {}
getPostHogClient().capture({
distinctId: distinctId ?? fallbackDistinctId,
event,
...(Object.keys(groups).length > 0 ? { groups } : {}),
properties: {
$ai_product: 'mcp',
$mcp_source: identity.source,
$mcp_client_name: identity.clientName,
$mcp_consumer: identity.clientName,
$mcp_mode: 'cli',
$mcp_scope_preset: resolveScopePreset(apiKey?.scopes),
$mcp_version: config.version,
...(cliInvocationId ? { cli_invocation_id: cliInvocationId } : {}),
...(analyticsContext ? buildMCPContextProperties(analyticsContext) : {}),
$session_id: await sessionManager.getSessionUuid(sessionId),
...properties,
is_impersonated: apiKey?.is_impersonated === true,
suppress_analytics: privateResponse || apiKey?.suppress_analytics === true,
},
})
} catch {}
})()
pendingAnalytics.add(capture)
void capture.finally(() => pendingAnalytics.delete(capture))
return capture
},
}
return context
}