Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(mcp): remove dead initMcpAnalytics / old-SDK analytics code (#63279)

Lucas Faria5bf158bd32e6
diff --git a/services/mcp/src/lib/posthog/analytics.ts b/services/mcp/src/lib/posthog/analytics.ts
index 0a345fdfa183..d53a03c1b5e8 100644
--- a/services/mcp/src/lib/posthog/analytics.ts
+++ b/services/mcp/src/lib/posthog/analytics.ts
@@ -1,9 +1,3 @@
-import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
-
-import { env } from '@/lib/env'
-
-import { getPostHogClient } from './client'
-
export enum AnalyticsEvent {
MCP_INIT = 'mcp init',
MCP_PROJECT_SWITCHED = 'mcp project switched',
@@ -55,221 +49,3 @@ export const buildMCPContextProperties = (
...(ctx.projectUuid ? { [`${prefix}project_uuid`]: ctx.projectUuid } : {}),
...(ctx.projectName ? { [`${prefix}project_name`]: ctx.projectName } : {}),
})
-
-// Provider interface for resolving user/session identity and workspace context.
-export type IdentityProvider = {
- getDistinctId: () => Promise<string>
- getMcpClientName: () => Promise<string | undefined>
- getMcpClientVersion: () => Promise<string | undefined>
- getMcpProtocolVersion: () => Promise<string | undefined>
- // Per-request `x-anthropic-client` value. Distinct from `mcpClientName`:
- // tracks the live inner client on pooled MCP transports.
- getMcpVendorClient: () => Promise<string | undefined>
- getRegion: () => Promise<string | undefined>
- getAnalyticsContext: () => Promise<MCPAnalyticsContext | undefined>
- getClientUserAgent: () => Promise<string | undefined>
- getOAuthClientName: () => Promise<string | undefined>
- getReadOnly: () => Promise<boolean | undefined>
- getTransport: () => Promise<string | undefined>
- getMcpConsumer: () => Promise<string | undefined>
- getMcpMode: () => Promise<string | undefined>
- // PostHog-side session UUID. Resolved from the wrapper-app `?sessionId=`
- // query hint via `SessionManager.getSessionUuid()` and used as `$session_id`
- // / `$ai_session_id` to drive Session Replay and AI observability grouping.
- // Only set when a wrapping consumer app supplied the hint.
- getSessionUuid: () => Promise<string | undefined>
- // Streamable-HTTP transport session id from the inbound `Mcp-Session-Id`
- // header. Distinct from `getSessionUuid()` above: this one is minted by
- // the MCP server per the protocol spec and is available on (almost) every
- // request, whereas `getSessionUuid()` only resolves when a wrapper app
- // also supplied a `?sessionId=` hint. Emitted on events as `mcp_session_id`.
- getMcpSessionId: () => Promise<string | undefined>
- // Agent-echoed conversation id from `@posthog/mcp-analytics` PR #14
- // (`enableConversationId: true`). Persists across transport reconnects.
- // Sourced from tool-call arguments by the SDK; we scaffold the property
- // here so it lands on events once the SDK is bumped. Returns undefined
- // until that wiring is in place.
- getMcpConversationId: () => Promise<string | undefined>
-}
-
-type McpAnalyticsOptions = {
- contextEnabled: boolean
- // Gate `get_more_tools` registration on non-single-exec mode. With the full
- // tool roster registered, a missing-tool report maps to a real gap in the
- // catalog. In single-exec mode the wrapper handles every call, so the
- // signal has nothing to map to and the extra slot is just noise.
- reportMissingEnabled: boolean
- // In single-exec mode, every event's `$mcp_tool_name` is `exec` — the real
- // tool the LLM was invoking lives inside `arguments.command`. This callback
- // lets the caller resolve that inner tool's name + description from the
- // request so they can be surfaced as `$mcp_exec_tool_call_name` /
- // `$mcp_exec_tool_call_description`. Returns undefined when the request
- // isn't an exec call or the inner tool isn't recognized. Type accepts
- // `| undefined` explicitly so callers can pass the value through
- // unconditionally under `exactOptionalPropertyTypes: true`.
- resolveExecInnerToolCall?: ((request: unknown) => { name: string; description: string } | undefined) | undefined
- // In single-exec mode the SDK's $mcp_listed_tool_names on mcp_tools_list
- // collapses to just the dispatcher's name (`exec`) because that's the
- // only tool the server actually advertises over MCP. Passing the full
- // inner-tool catalog here lets us attach the inner names on tools/list
- // events as $mcp_exec_inner_tool_names so dashboards can compute the
- // "advertised but never called" diff against $mcp_exec_tool_call_name
- // from mcp_tool_call events.
- execInnerToolNames?: readonly string[] | undefined
-}
-
-export type McpAnalyticsInitResult =
- | {
- action: 'initialized'
- }
- | {
- action: 'skipped'
- reason: 'missing_config'
- hasApiKey: boolean
- hasHost: boolean
- }
- | {
- action: 'failed'
- errorName: string
- errorMessage: string
- }
-
-async function buildEventTags(identity: IdentityProvider): Promise<Record<string, string>> {
- const sessionUuid = await identity.getSessionUuid()
- if (!sessionUuid) {
- return {}
- }
-
- return {
- $session_id: sessionUuid,
- $ai_session_id: sessionUuid,
- }
-}
-
-export async function buildEventProperties(identity: IdentityProvider): Promise<Record<string, unknown>> {
- const [
- clientUserAgent,
- mcpClientName,
- mcpClientVersion,
- mcpProtocolVersion,
- mcpVendorClient,
- mcpRegion,
- analyticsContext,
- oauthClientName,
- readOnly,
- transport,
- mcpConsumer,
- mcpMode,
- mcpSessionId,
- mcpConversationId,
- ] = await Promise.all([
- identity.getClientUserAgent(),
- identity.getMcpClientName(),
- identity.getMcpClientVersion(),
- identity.getMcpProtocolVersion(),
- identity.getMcpVendorClient(),
- identity.getRegion(),
- identity.getAnalyticsContext(),
- identity.getOAuthClientName(),
- identity.getReadOnly(),
- identity.getTransport(),
- identity.getMcpConsumer(),
- identity.getMcpMode(),
- identity.getMcpSessionId(),
- identity.getMcpConversationId(),
- ])
-
- const groups = {
- ...(analyticsContext?.organizationId ? { organization: analyticsContext.organizationId } : {}),
- ...(analyticsContext?.projectUuid ? { project: analyticsContext.projectUuid } : {}),
- }
-
- return {
- $ai_product: 'mcp',
- $mcp_version: MCP_ANALYTICS_VERSION,
- $mcp_client_user_agent: clientUserAgent,
- $mcp_client_name: mcpClientName,
- $mcp_client_version: mcpClientVersion,
- mcp_vendor_client: mcpVendorClient,
- $mcp_protocol_version: mcpProtocolVersion,
- $mcp_region: mcpRegion,
- $mcp_organization_id: analyticsContext?.organizationId,
- $mcp_project_id: analyticsContext?.projectId,
- $mcp_project_uuid: analyticsContext?.projectUuid,
- $mcp_project_name: analyticsContext?.projectName,
- $mcp_oauth_client_name: oauthClientName,
- $mcp_read_only: readOnly,
- $mcp_transport: transport,
- $mcp_consumer: mcpConsumer,
- $mcp_mode: mcpMode,
- $mcp_session_id: mcpSessionId,
- $mcp_conversation_id: mcpConversationId,
- ...(Object.keys(groups).length > 0 ? { $groups: groups } : {}),
- }
-}
-
-export function redactSensitiveInformation(text: string): string {
- return text.replace(/Bearer\s?[\w\-.]+/g, '<redacted>')
-}
-
-export async function initMcpAnalytics(
- server: McpServer,
- identity: IdentityProvider,
- options: McpAnalyticsOptions = { contextEnabled: false, reportMissingEnabled: false }
-): Promise<McpAnalyticsInitResult> {
- const { POSTHOG_ANALYTICS_API_KEY: posthogApiKey, POSTHOG_ANALYTICS_HOST: posthogHost } = env
- if (!posthogApiKey || !posthogHost) {
- return {
- action: 'skipped',
- reason: 'missing_config',
- hasApiKey: !!posthogApiKey,
- hasHost: !!posthogHost,
- }
- }
-
- try {
- const { track } = await import('@posthog/mcp-analytics') // Import only if needed
- const distinctId = await identity.getDistinctId()
-
- track(server, {
- posthogClient: getPostHogClient(),
- context: options.contextEnabled,
- enableAITracing: true,
- enableConversationId: false,
- enableTracing: true,
- identify: { userId: distinctId },
- reportMissing: options.reportMissingEnabled,
- eventTags: () => buildEventTags(identity),
- eventProperties: async (request) => {
- const base = await buildEventProperties(identity)
- const innerToolCall = options.resolveExecInnerToolCall?.(request)
- const isListToolsRequest =
- (request as { method?: unknown })?.method === 'tools/list' &&
- !!options.execInnerToolNames &&
- options.execInnerToolNames.length > 0
-
- return {
- ...base,
- ...(innerToolCall
- ? {
- $mcp_exec_tool_call_name: innerToolCall.name,
- $mcp_exec_tool_call_description: innerToolCall.description,
- }
- : {}),
- ...(isListToolsRequest
- ? { $mcp_exec_inner_tool_names: [...(options.execInnerToolNames ?? [])] }
- : {}),
- }
- },
- redactSensitiveInformation: (text) => Promise.resolve(redactSensitiveInformation(text)),
- })
-
- return { action: 'initialized' }
- } catch (error) {
- return {
- action: 'failed',
- errorName: error instanceof Error ? error.name : 'UnknownError',
- errorMessage: error instanceof Error ? error.message : String(error),
- }
- }
-}
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index af58700ed12f..89a5f7e6e840 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -65,11 +65,10 @@ export function parseExecCallInnerToolName(command: string): string | undefined
return innerName || undefined
}
-// Builds the resolver mcp.ts hands to initMcpAnalytics in single-exec
-// mode: given a request, return the inner tool's { name, description } when
-// the agent invoked it via `call <tool> ...`, or undefined otherwise. Lives
-// here (alongside parseExecCallInnerToolName) so tests can import the exact
-// same factory the production code uses — no copy-pasted resolver lambda.
+// Resolves the inner tool an `exec` call targets: given a request, return the
+// inner tool's { name, description } when the agent invoked it via
+// `call <tool> ...`, or undefined otherwise. Lives here (alongside
+// parseExecCallInnerToolName) so callers and tests share one factory.
export function createExecInnerToolCallResolver(
allTools: ReadonlyArray<Tool<ZodObjectAny>>
): (request: unknown) => { name: string; description: string } | undefined {
diff --git a/services/mcp/tests/unit/exec-description-emission.test.ts b/services/mcp/tests/unit/exec-description-emission.test.ts
deleted file mode 100644
index 07748313c48a..000000000000
--- a/services/mcp/tests/unit/exec-description-emission.test.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-// Real end-to-end check that $mcp_exec_tool_call_name and
-// $mcp_exec_tool_call_description actually land on the captured PostHog event
-// when an agent runs `exec("call <tool> {}")`. Bypasses the global
-// @posthog/mcp-analytics mock (set in tests/setup.ts) and drives the real SDK
-// with a stub posthog-node client to capture events.
-import { vi } from 'vitest'
-vi.unmock('@posthog/mcp-analytics')
-
-import { Client } from '@modelcontextprotocol/sdk/client/index.js'
-import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
-import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
-import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js'
-import { track } from '@posthog/mcp-analytics'
-import { describe, expect, it } from 'vitest'
-import { z } from 'zod'
-
-import { createExecInnerToolCallResolver, createExecTool } from '@/tools/exec'
-import type { Context, Tool, ZodObjectAny } from '@/tools/types'
-
-type CapturedEvent = { event: string; properties: Record<string, unknown> }
-
-type StubPostHogClient = {
- capture: (msg: { event: string; properties?: Record<string, unknown> }) => void
- flush: () => Promise<void>
- shutdown: () => Promise<void>
-}
-
-function makeStubPostHogClient(events: CapturedEvent[]): StubPostHogClient {
- return {
- capture: ({ event, properties }) => {
- events.push({ event, properties: properties ?? {} })
- },
- flush: async () => {},
- shutdown: async () => {},
- }
-}
-
-function makeTool(overrides: Partial<Tool<ZodObjectAny>>): Tool<ZodObjectAny> {
- return {
- name: 'mock-tool',
- title: 'Mock tool',
- description: 'A mock tool for testing',
- schema: z.object({}),
- scopes: [],
- annotations: {
- destructiveHint: false,
- idempotentHint: true,
- openWorldHint: false,
- readOnlyHint: true,
- },
- handler: async () => 'ok',
- ...overrides,
- }
-}
-
-const mockContext = { getDistinctId: async () => 'distinct-1' } as unknown as Context
-
-type ExecHarness = {
- client: Client
- events: CapturedEvent[]
- cleanup: () => Promise<void>
-}
-
-async function buildExecHarness(allTools: Tool<ZodObjectAny>[]): Promise<ExecHarness> {
- const events: CapturedEvent[] = []
- const server = new McpServer({ name: 'test-mcp', version: '1.0.0' })
-
- const execTool = createExecTool(allTools, mockContext, 'exec tool', 'command reference', undefined)
- server.registerTool(
- execTool.name,
- { title: execTool.title, description: execTool.description, inputSchema: execTool.schema.shape },
- (async (params: { command: string }) => {
- const result = await execTool.handler(mockContext, params)
- return { content: [{ type: 'text' as const, text: String(result) }] }
- }) as Parameters<typeof server.registerTool>[2]
- )
-
- const resolveExecInnerToolCall = createExecInnerToolCallResolver(allTools)
-
- track(server, {
- apiKey: 'phc_test',
- posthogClient: makeStubPostHogClient(events),
- posthogOptions: { flushAt: 1, flushInterval: 0, host: 'https://test.posthog.com' },
- enableTracing: true,
- eventProperties: (request) => {
- const innerCall = resolveExecInnerToolCall(request)
- return innerCall
- ? {
- $mcp_exec_tool_call_name: innerCall.name,
- $mcp_exec_tool_call_description: innerCall.description,
- }
- : {}
- },
- })
-
- const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: {} })
- const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair()
- await Promise.all([client.connect(clientTransport), server.server.connect(serverTransport)])
-
- return {
- client,
- events,
- cleanup: async () => {
- await clientTransport.close?.()
- await serverTransport.close?.()
- },
- }
-}
-
-// Poll the captured events for a matching record instead of sleeping a fixed
-// duration — flushAt:1 makes capture effectively immediate, but timer-based
-// waits are flake-prone under CI load.
-async function waitForEvent(
- events: CapturedEvent[],
- predicate: (event: CapturedEvent) => boolean,
- timeoutMs = 1000
-): Promise<CapturedEvent | undefined> {
- const deadline = Date.now() + timeoutMs
- while (Date.now() < deadline) {
- const match = events.find(predicate)
- if (match) {
- return match
- }
- await new Promise((resolve) => setTimeout(resolve, 5))
- }
- return events.find(predicate)
-}
-
-describe('$mcp_exec_tool_call_* end-to-end', () => {
- it('lands on the mcp_tool_call event when exec invokes a known inner tool', async () => {
- const allTools = [
- makeTool({ name: 'execute-sql', description: 'Run a HogQL/SQL query against PostHog.' }),
- makeTool({ name: 'feature-flag-get-all', description: 'List feature flags in the project.' }),
- ]
- const { client, events, cleanup } = await buildExecHarness(allTools)
-
- try {
- await client.request(
- {
- method: 'tools/call',
- params: { name: 'exec', arguments: { command: 'call execute-sql {}' } },
- },
- CallToolResultSchema
- )
-
- const toolCallEvent = await waitForEvent(events, (e) => e.event === 'mcp_tool_call')
-
- expect(toolCallEvent, 'mcp_tool_call event should be captured').not.toBeUndefined()
- expect(toolCallEvent?.properties.$mcp_tool_name).toBe('exec')
- // The SDK property reports the *outer* tool's description (exec) — which is
- // exactly the uninformative case the dotcom properties exist to fix.
- expect(toolCallEvent?.properties.$mcp_tool_description).toBe('exec tool')
- // The dotcom-side properties carry the real inner-tool name + description.
- expect(toolCallEvent?.properties.$mcp_exec_tool_call_name).toBe('execute-sql')
- expect(toolCallEvent?.properties.$mcp_exec_tool_call_description).toBe(
- 'Run a HogQL/SQL query against PostHog.'
- )
- } finally {
- await cleanup()
- }
- })
-
- it('omits $mcp_exec_tool_call_* for non-call verbs', async () => {
- const allTools = [makeTool({ name: 'execute-sql', description: 'Run a HogQL/SQL query against PostHog.' })]
- const { client, events, cleanup } = await buildExecHarness(allTools)
-
- try {
- // `info` verb references a tool but doesn't invoke it — should NOT
- // emit the inner-call name or description.
- await client.request(
- {
- method: 'tools/call',
- params: { name: 'exec', arguments: { command: 'info execute-sql' } },
- },
- CallToolResultSchema
- )
-
- const toolCallEvent = await waitForEvent(events, (e) => e.event === 'mcp_tool_call')
-
- expect(toolCallEvent).not.toBeUndefined()
- expect(toolCallEvent?.properties).not.toHaveProperty('$mcp_exec_tool_call_name')
- expect(toolCallEvent?.properties).not.toHaveProperty('$mcp_exec_tool_call_description')
- } finally {
- await cleanup()
- }
- })
-})
diff --git a/services/mcp/tests/unit/posthog/analytics.test.ts b/services/mcp/tests/unit/posthog/analytics.test.ts
index 554c1f450f9f..72e8fb608927 100644
--- a/services/mcp/tests/unit/posthog/analytics.test.ts
+++ b/services/mcp/tests/unit/posthog/analytics.test.ts
@@ -1,14 +1,6 @@
-import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
-import { env } from 'cloudflare:workers'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-
-import { track } from '@posthog/mcp-analytics'
+import { describe, expect, it } from 'vitest'
import { buildMCPAnalyticsGroups, buildMCPContextProperties, type MCPAnalyticsContext } from '@/lib/posthog/analytics'
-import { initMcpAnalytics, type IdentityProvider } from '@/lib/posthog/analytics'
-
-const TEST_API_KEY = 'test-api-key'
-const TEST_HOST = 'https://test.posthog.com'
describe('buildMCPAnalyticsGroups', () => {
it.each<[string, MCPAnalyticsContext, Record<string, string>]>([
@@ -61,338 +53,3 @@ describe('buildMCPContextProperties', () => {
expect(buildMCPContextProperties(input, options)).toEqual(expected)
})
})
-
-describe('initMcpAnalytics', () => {
- beforeEach(() => {
- vi.mocked(track).mockClear()
- env.POSTHOG_ANALYTICS_API_KEY = TEST_API_KEY
- env.POSTHOG_ANALYTICS_HOST = TEST_HOST
- })
-
- function createMockIdentity(overrides: Partial<IdentityProvider> = {}): IdentityProvider {
- return {
- getDistinctId: vi.fn().mockResolvedValue('user-123'),
- getSessionUuid: vi.fn().mockResolvedValue('session-uuid-456'),
- getMcpClientName: vi.fn().mockResolvedValue('claude-code'),
- getMcpClientVersion: vi.fn().mockResolvedValue('1.2.3'),
- getMcpProtocolVersion: vi.fn().mockResolvedValue('2024-11-05'),
- getMcpVendorClient: vi.fn().mockResolvedValue('ClaudeCode'),
- getRegion: vi.fn().mockResolvedValue('us'),
- getAnalyticsContext: vi.fn().mockResolvedValue({
- organizationId: 'org-789',
- projectId: 'proj-101',
- projectUuid: 'proj-uuid-101',
- projectName: 'Project 101',
- }),
- getClientUserAgent: vi.fn().mockResolvedValue('test-agent/1.0'),
- getOAuthClientName: vi.fn().mockResolvedValue('PostHog Code'),
- getReadOnly: vi.fn().mockResolvedValue(true),
- getTransport: vi.fn().mockResolvedValue('streamable-http'),
- getMcpConsumer: vi.fn().mockResolvedValue('posthog-code'),
- getMcpMode: vi.fn().mockResolvedValue('cli'),
- getMcpSessionId: vi.fn().mockResolvedValue('mcp-session-abc'),
- getMcpConversationId: vi.fn().mockResolvedValue('mcp-conversation-xyz'),
- ...overrides,
- }
- }
-
- function getTrackOptions(): {
- identify: { userId: string }
- eventTags: () => Promise<Record<string, string>>
- eventProperties: (request?: unknown) => Promise<Record<string, unknown>>
- } {
- const call = vi.mocked(track).mock.calls[0]!
- return call[1] as {
- identify: { userId: string }
- eventTags: () => Promise<Record<string, string>>
- eventProperties: (request?: unknown) => Promise<Record<string, unknown>>
- }
- }
-
- it('calls PostHog MCP analytics track with safe defaults', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- const result = await initMcpAnalytics(server, identity)
-
- expect(track).toHaveBeenCalledWith(
- server,
- expect.objectContaining({
- posthogClient: expect.any(Object),
- context: false,
- enableAITracing: true,
- enableTracing: true,
- identify: expect.objectContaining({ userId: expect.any(String) }),
- eventTags: expect.any(Function),
- eventProperties: expect.any(Function),
- reportMissing: false,
- })
- )
- expect(result).toMatchObject({ action: 'initialized' })
- })
-
- it('enables required context only when explicitly requested', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- const result = await initMcpAnalytics(server, identity, {
- contextEnabled: true,
- reportMissingEnabled: false,
- })
-
- expect(track).toHaveBeenCalledWith(
- server,
- expect.objectContaining({
- context: true,
- enableAITracing: true,
- reportMissing: false,
- })
- )
- expect(result).toMatchObject({ action: 'initialized' })
- })
-
- it('enables get_more_tools (reportMissing) only when explicitly requested', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- const result = await initMcpAnalytics(server, identity, {
- contextEnabled: false,
- reportMissingEnabled: true,
- })
-
- expect(track).toHaveBeenCalledWith(
- server,
- expect.objectContaining({
- reportMissing: true,
- })
- )
- expect(result).toMatchObject({ action: 'initialized' })
- })
-
- it.each(['POSTHOG_ANALYTICS_API_KEY', 'POSTHOG_ANALYTICS_HOST'] as const)(
- 'skips initialization when %s is not set',
- async (envKey) => {
- env[envKey] = undefined as unknown as string
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- const result = await initMcpAnalytics(server, identity)
-
- expect(track).not.toHaveBeenCalled()
- expect(result).toMatchObject({ action: 'skipped', reason: 'missing_config' })
- }
- )
-
- it('identify callback resolves identity from provider', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- await initMcpAnalytics(server, identity)
-
- expect(getTrackOptions().identify).toEqual({ userId: 'user-123' })
- })
-
- it('eventTags callback returns $session_id and $ai_session_id when available', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- await initMcpAnalytics(server, identity)
-
- expect(await getTrackOptions().eventTags()).toEqual({
- $session_id: 'session-uuid-456',
- $ai_session_id: 'session-uuid-456',
- })
- })
-
- it('eventTags callback returns empty when session uuid is undefined', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity({
- getSessionUuid: vi.fn().mockResolvedValue(undefined),
- })
-
- await initMcpAnalytics(server, identity)
-
- expect(await getTrackOptions().eventTags()).toEqual({})
- })
-
- it('eventProperties callback returns PostHog MCP context properties', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- await initMcpAnalytics(server, identity)
-
- expect(await getTrackOptions().eventProperties()).toEqual({
- $ai_product: 'mcp',
- $mcp_version: 2,
- $mcp_client_user_agent: 'test-agent/1.0',
- $mcp_client_name: 'claude-code',
- $mcp_client_version: '1.2.3',
- mcp_vendor_client: 'ClaudeCode',
- $mcp_protocol_version: '2024-11-05',
- $mcp_region: 'us',
- $mcp_organization_id: 'org-789',
- $mcp_project_id: 'proj-101',
- $mcp_project_uuid: 'proj-uuid-101',
- $mcp_project_name: 'Project 101',
- $mcp_oauth_client_name: 'PostHog Code',
- $mcp_read_only: true,
- $mcp_transport: 'streamable-http',
- $mcp_consumer: 'posthog-code',
- $mcp_mode: 'cli',
- $mcp_session_id: 'mcp-session-abc',
- $mcp_conversation_id: 'mcp-conversation-xyz',
- $groups: {
- organization: 'org-789',
- project: 'proj-uuid-101',
- },
- })
- })
-
- it.each<{
- scenario: string
- resolverReturn: { name: string; description: string } | undefined
- expectedProperties: Record<string, unknown>
- absentProperties: string[]
- }>([
- {
- scenario: 'adds name + description when the resolver returns an inner tool',
- resolverReturn: { name: 'execute-sql', description: 'Run a HogQL/SQL query.' },
- expectedProperties: {
- $mcp_exec_tool_call_name: 'execute-sql',
- $mcp_exec_tool_call_description: 'Run a HogQL/SQL query.',
- },
- absentProperties: [],
- },
- {
- scenario: 'omits both properties when the resolver returns undefined',
- resolverReturn: undefined,
- expectedProperties: {},
- absentProperties: ['$mcp_exec_tool_call_name', '$mcp_exec_tool_call_description'],
- },
- ])('eventProperties $scenario', async ({ resolverReturn, expectedProperties, absentProperties }) => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
- const resolveExecInnerToolCall = vi.fn().mockReturnValue(resolverReturn)
-
- await initMcpAnalytics(server, identity, {
- contextEnabled: false,
- reportMissingEnabled: false,
- resolveExecInnerToolCall,
- })
-
- const fakeRequest = { params: { name: 'exec', arguments: { command: 'call execute-sql {}' } } }
- const properties = await getTrackOptions().eventProperties(fakeRequest)
-
- expect(resolveExecInnerToolCall).toHaveBeenCalledWith(fakeRequest)
- for (const [key, value] of Object.entries(expectedProperties)) {
- expect(properties[key]).toBe(value)
- }
- for (const key of absentProperties) {
- expect(properties).not.toHaveProperty(key)
- }
- // Identity-derived properties should always be there regardless of resolver outcome.
- expect(properties.$mcp_organization_id).toBe('org-789')
- })
-
- it('eventProperties does not call the resolver when none is configured', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- await initMcpAnalytics(server, identity)
-
- const properties = await getTrackOptions().eventProperties({
- params: { name: 'exec', arguments: { command: 'call execute-sql {}' } },
- })
-
- expect(properties).not.toHaveProperty('$mcp_exec_tool_call_name')
- expect(properties).not.toHaveProperty('$mcp_exec_tool_call_description')
- })
-
- it('eventProperties attaches $mcp_exec_inner_tool_names on tools/list when execInnerToolNames is configured', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
- const execInnerToolNames = ['execute-sql', 'feature-flag-get-all', 'insight-get']
-
- await initMcpAnalytics(server, identity, {
- contextEnabled: false,
- reportMissingEnabled: false,
- execInnerToolNames,
- })
-
- const listRequest = { method: 'tools/list', params: {} }
- const properties = await getTrackOptions().eventProperties(listRequest)
-
- expect(properties.$mcp_exec_inner_tool_names).toEqual(execInnerToolNames)
- // Other inner-call properties should be absent since this isn't a `call` request.
- expect(properties).not.toHaveProperty('$mcp_exec_tool_call_name')
- })
-
- it('eventProperties does not attach $mcp_exec_inner_tool_names on non-list methods', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- await initMcpAnalytics(server, identity, {
- contextEnabled: false,
- reportMissingEnabled: false,
- execInnerToolNames: ['execute-sql'],
- })
-
- const callRequest = {
- method: 'tools/call',
- params: { name: 'exec', arguments: { command: 'call execute-sql {}' } },
- }
- const properties = await getTrackOptions().eventProperties(callRequest)
-
- expect(properties).not.toHaveProperty('$mcp_exec_inner_tool_names')
- })
-
- it('eventProperties does not attach $mcp_exec_inner_tool_names when execInnerToolNames is empty', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- await initMcpAnalytics(server, identity, {
- contextEnabled: false,
- reportMissingEnabled: false,
- execInnerToolNames: [],
- })
-
- const properties = await getTrackOptions().eventProperties({ method: 'tools/list', params: {} })
-
- expect(properties).not.toHaveProperty('$mcp_exec_inner_tool_names')
- })
-
- it('eventProperties callback omits $groups when analytics context is unavailable', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity({
- getAnalyticsContext: vi.fn().mockResolvedValue(undefined),
- })
-
- await initMcpAnalytics(server, identity)
-
- const properties = await getTrackOptions().eventProperties()
- expect(properties.$groups).toBeUndefined()
- expect(properties.$mcp_organization_id).toBeUndefined()
- expect(properties.$mcp_project_uuid).toBeUndefined()
- })
-
- it('swallows errors if PostHog MCP analytics track throws', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- vi.mocked(track).mockImplementationOnce(() => {
- throw new Error('PostHog MCP analytics init failed')
- })
-
- await expect(initMcpAnalytics(server, identity)).resolves.toMatchObject({ action: 'failed' })
- })
-
- it('swallows errors if analytics identity resolution throws', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity({
- getDistinctId: vi.fn().mockRejectedValue(new Error('identity unavailable')),
- })
-
- await expect(initMcpAnalytics(server, identity)).resolves.toMatchObject({ action: 'failed' })
- expect(track).not.toHaveBeenCalled()
- })
-})