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.

refactor: move to @posthog/mcp-analytics 0.0.9 (#58920)

Rafael Audibert5148a53aa1ad
diff --git a/.oxlintrc.json b/.oxlintrc.json
index 0ffbf72fa378..98cef8e0d2bc 100644
--- a/.oxlintrc.json
+++ b/.oxlintrc.json
@@ -41,7 +41,9 @@
"error",
{
"ignoreRestSiblings": true,
- "destructuredArrayIgnorePattern": "^_$"
+ "argsIgnorePattern": "^_",
+ "varsIgnorePattern": "^_",
+ "destructuredArrayIgnorePattern": "^_"
}
],
"no-useless-spread": "error",
@@ -190,10 +192,7 @@
}
},
{
- "files": [
- "services/mcp/src/ui-apps/**/*.{ts,tsx}",
- "products/**/mcp/apps/**/*.{ts,tsx}"
- ],
+ "files": ["services/mcp/src/ui-apps/**/*.{ts,tsx}", "products/**/mcp/apps/**/*.{ts,tsx}"],
"rules": {
"react/forbid-elements": "off"
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 171404755127..adf501379b55 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3519,8 +3519,8 @@ importers:
specifier: ^1.29.0
version: 1.29.0(@cfworker/[email protected])([email protected])
'@posthog/mcp-analytics':
- specifier: npm:@posthog/[email protected]
- version: '@posthog/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])'
+ specifier: npm:@posthog/[email protected]
+ version: '@posthog/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])'
'@posthog/quill':
specifier: workspace:*
version: link:../../packages/quill/packages/quill
@@ -3551,9 +3551,6 @@ importers:
lucide-react:
specifier: ^0.577.0
version: 0.577.0([email protected])
- mcpcat:
- specifier: 0.1.15
- version: 0.1.15(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))
posthog-js-lite:
specifier: 4.2.2
version: 4.2.2
@@ -8991,8 +8988,8 @@ packages:
react: 18.3.1
react-dom: 18.3.1
- '@posthog/[email protected]':
- resolution: {integrity: sha512-pB5oyt6WrhYJVauIwZbQSmsoVNAPxYRulKVfpRCNJNCN6tUycDYtdvox8jqqfwHoJHOmYUjRVJPCmyTVNQYlNg==}
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-Tcz5fGpG0ZCtA94jDhmQigHA49K4UVhkbBGgn+w7pZXiXPkDCPO0ZXtuRXdPgyO/l1WW9RB27D9pR2fvLmT+Mg==}
engines: {node: '>=22.22.0'}
peerDependencies:
'@modelcontextprotocol/sdk': ^1.29.0
@@ -18393,14 +18390,6 @@ packages:
resolution: {integrity: sha512-tJDrKbUzN6PSA88tWgg0L2R4Ln00XwecYQJPFI+RvlF2k1sx6VQYtuQ1SVxm8+bw5tF7GWV4xyb+3/KyzEpPUw==}
engines: {node: '>=12', npm: '>=6'}
- resolution: {integrity: sha512-HhKa4HidN5swb6k+YOKNfv3MyVfTxxvhR7VPnQBxy/lBw3arVOfWzX9FTt0uYc4NrMjWJeTUtpbS8ENR0F44iQ==}
-
- resolution: {integrity: sha512-rc5a/sWhrJvnU9k1a9xjVNC6apQykUQvlJ60h/6IHgCSsHGHS9kFsTmC7aMufitcPbDo9Kq2cy8vUbHtveEj5Q==}
- peerDependencies:
- '@modelcontextprotocol/sdk': ^1.29.0
-
resolution: {integrity: sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==}
@@ -32008,7 +31997,7 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
dependencies:
'@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])
posthog-node: 5.33.3([email protected])
@@ -44077,13 +44066,6 @@ snapshots:
mmdb-lib: 2.0.2
tiny-lru: 11.0.1
-
- dependencies:
- '@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])
- mcpcat-api: 0.1.8
-
dependencies:
hash-base: 3.1.0
diff --git a/services/mcp/.dev.vars.example b/services/mcp/.dev.vars.example
index 65540076a0b8..dbf3ac8b9791 100644
--- a/services/mcp/.dev.vars.example
+++ b/services/mcp/.dev.vars.example
@@ -10,9 +10,6 @@ MCP_APPS_BASE_URL=http://localhost:8787
POSTHOG_MCP_APPS_ANALYTICS_BASE_URL=http://localhost:8010
POSTHOG_UI_APPS_TOKEN=your_posthog_ui_apps_token_here
-# MCPCat project ID for analytics (optional, disables MCPCat if not set)
-MCP_CAT_PROJECT_ID=
-
# PostHog API key for dev/self-hosted analytics
# If not set, simply won't capture any analytics
POSTHOG_ANALYTICS_API_KEY=local_api_key
diff --git a/services/mcp/package.json b/services/mcp/package.json
index 0cfe505f5e73..b7e15e2eec4c 100644
--- a/services/mcp/package.json
+++ b/services/mcp/package.json
@@ -41,7 +41,7 @@
"@hono/node-server": "^2.0.2",
"@modelcontextprotocol/ext-apps": "^1.5.0",
"@modelcontextprotocol/sdk": "^1.29.0",
- "@posthog/mcp-analytics": "npm:@posthog/[email protected]",
+ "@posthog/mcp-analytics": "npm:@posthog/[email protected]",
"@posthog/quill": "workspace:*",
"@toon-format/toon": "^2.1.0",
"agents": "0.10.2",
@@ -52,7 +52,6 @@
"hono": "^4.12.18",
"ioredis": "^4.28.5",
"lucide-react": "^0.577.0",
- "mcpcat": "0.1.15",
"posthog-js-lite": "4.2.2",
"posthog-node": "^5.25.0",
"prom-client": "^14.2.0",
diff --git a/services/mcp/src/hono/mcp-server.ts b/services/mcp/src/hono/mcp-server.ts
index 2847140be090..68b0c7f26a8b 100644
--- a/services/mcp/src/hono/mcp-server.ts
+++ b/services/mcp/src/hono/mcp-server.ts
@@ -3,22 +3,21 @@ import { McpServer, type ToolCallback } from '@modelcontextprotocol/sdk/server/m
import type { z } from 'zod'
import { ApiClient } from '@/api/client'
-import {
- AnalyticsEvent,
- buildMCPAnalyticsGroups,
- buildMCPContextProperties,
- evaluateFeatureFlags,
- getPostHogClient,
- isFeatureFlagEnabled,
- type MCPAnalyticsContext,
-} from '@/lib/analytics'
import { hasScope } from '@/lib/api'
import { buildToolResultPayload, isToolCallPayload } from '@/lib/build-tool-result'
import { MCPClientProfile } from '@/lib/client-detection'
import { handleToolError, wrapError } from '@/lib/errors'
import { type QueryToolInfo } from '@/lib/instructions'
import { InstructionsFormatter } from '@/lib/instructions-formatter'
-import { initMcpCatObservability } from '@/lib/mcpcat'
+import { getPostHogClient } from '@/lib/posthog'
+import {
+ AnalyticsEvent,
+ buildMCPAnalyticsGroups,
+ buildMCPContextProperties,
+ initMcpAnalytics,
+ type MCPAnalyticsContext,
+} from '@/lib/posthog/analytics'
+import { evaluateFeatureFlags, isFeatureFlagEnabled } from '@/lib/posthog/flags'
import { type RequestProperties } from '@/lib/request-properties'
import { SessionManager } from '@/lib/SessionManager'
import { StateManager } from '@/lib/StateManager'
@@ -27,7 +26,7 @@ import { registerPrompts } from '@/prompts'
import { registerResources } from '@/resources'
import { registerUiAppResources } from '@/resources/ui-apps'
import EXECUTE_SQL_PROMPT from '@/templates/execute-sql-prompt.md'
-import { createExecTool, type ExecInnerCallTracker } from '@/tools/exec'
+import { createExecInnerToolCallResolver, createExecTool, type ExecInnerCallTracker } from '@/tools/exec'
import { getToolDefinition } from '@/tools/toolDefinitions'
import { type CloudRegion, type Context, type Env, type State, type Tool } from '@/tools/types'
@@ -45,24 +44,12 @@ import { initDurationSeconds, toolCallDurationSeconds, toolCallsTotal } from './
export type { RequestProperties }
const instructionsFormatter = new InstructionsFormatter()
-const POSTHOG_MCP_ANALYTICS_FLAG = 'mcp-posthog-analytics-sdk'
-type McpAnalyticsProvider = 'posthog_mcp_analytics' | 'mcpcat'
-type PostHogMcpAnalyticsFlagResult = {
- enabled: boolean
- errorName?: string
- errorMessage?: string
-}
type HonoRequestProperties = RequestProperties & {
- mcpAnalyticsProvider?: McpAnalyticsProvider | undefined
- mcpAnalyticsFlagKey?: string | undefined
- mcpAnalyticsFlagEnabled?: boolean | undefined
- mcpAnalyticsFlagErrorName?: string | undefined
- mcpAnalyticsFlagErrorMessage?: string | undefined
- posthogMcpAnalyticsInitAction?: 'initialized' | 'skipped' | 'failed' | undefined
- posthogMcpAnalyticsInitReason?: string | undefined
- posthogMcpAnalyticsInitErrorName?: string | undefined
- posthogMcpAnalyticsInitErrorMessage?: string | undefined
+ mcpAnalyticsInitAction?: 'initialized' | 'skipped' | 'failed' | undefined
+ mcpAnalyticsInitReason?: string | undefined
+ mcpAnalyticsInitErrorName?: string | undefined
+ mcpAnalyticsInitErrorMessage?: string | undefined
}
// Guidelines are generated at build time; optional import so tests and
@@ -232,8 +219,6 @@ export class HonoMcpServer {
try {
const distinctId = await this.getDistinctId()
- const client = getPostHogClient()
-
await this.resolveClientInfo()
const clientName = await this.cache.get('clientName')
@@ -244,6 +229,7 @@ export class HonoMcpServer {
: {}
const groups = options?.context ? buildMCPAnalyticsGroups(options.context) : {}
+ const client = getPostHogClient()
client.capture({
distinctId,
event,
@@ -426,7 +412,6 @@ export class HonoMcpServer {
const flagPromise = this.resolveVersionFlag()
const toolFlagsPromise = this.resolveToolFeatureFlags(clientVersion)
const singleExecPromise = this.resolveSingleExecFlag()
- const posthogMcpAnalyticsFlagPromise = this.resolvePostHogMcpAnalyticsFlag()
// Seed cache with header-provided IDs before any fetches
if (organizationId) {
@@ -455,11 +440,10 @@ export class HonoMcpServer {
await context.stateManager.setDefaultOrganizationAndProject()
}
- const [flagVersion, toolFeatureFlags, singleExecFlagOn, posthogMcpAnalyticsFlag] = await Promise.all([
+ const [flagVersion, toolFeatureFlags, singleExecFlagOn, _apiKey] = await Promise.all([
flagPromise,
toolFlagsPromise,
singleExecPromise,
- posthogMcpAnalyticsFlagPromise,
// Trigger OAuth introspection so the OAuth client name is cached before the useSingleExec decision below
context.stateManager.getApiKey(),
])
@@ -639,22 +623,42 @@ export class HonoMcpServer {
getMcpConversationId: async () => this.props.mcpConversationId,
}
- Object.assign(this.props, {
- mcpAnalyticsProvider: 'mcpcat' satisfies McpAnalyticsProvider,
- mcpAnalyticsFlagKey: POSTHOG_MCP_ANALYTICS_FLAG,
- mcpAnalyticsFlagEnabled: posthogMcpAnalyticsFlag.enabled,
- ...(posthogMcpAnalyticsFlag.errorName
- ? { mcpAnalyticsFlagErrorName: posthogMcpAnalyticsFlag.errorName }
- : {}),
- ...(posthogMcpAnalyticsFlag.errorMessage
- ? { mcpAnalyticsFlagErrorMessage: posthogMcpAnalyticsFlag.errorMessage }
- : {}),
+ // In single-exec mode every event's `$mcp_tool_name` is `exec`, so the
+ // SDK's `$mcp_tool_description` would be the dispatcher's static text on
+ // every call. Resolve the inner tool the agent was actually invoking
+ // from the command and surface its name + description as
+ // `$mcp_exec_tool_call_name` / `$mcp_exec_tool_call_description`.
+ const resolveExecInnerToolCall = useSingleExec ? createExecInnerToolCallResolver(allTools) : undefined
+
+ // In single-exec mode the SDK's $mcp_listed_tool_names collapses to
+ // just `exec`, so we can't compute "advertised but never called"
+ // (zombie tools) from SDK data alone. Pass the inner-tool catalog
+ // here so analytics can attach it as $mcp_exec_inner_tool_names on
+ // mcp_tools_list events. Dashboards can then diff it against
+ // $mcp_exec_tool_call_name from mcp_tool_call.
+ const execInnerToolNames = useSingleExec ? allTools.map((t) => t.name) : undefined
+
+ const initResult = await initMcpAnalytics(this.server, mcpAnalyticsIdentity, {
+ contextEnabled: true,
+ resolveExecInnerToolCall,
+ execInnerToolNames,
+ // `get_more_tools` only earns its keep outside single-exec mode — there
+ // it lets the model report a gap in our discrete tool catalog. In
+ // single-exec mode the wrapper handles every call, so the missing-tool
+ // signal has nothing to map to and the extra slot is pure noise.
+ reportMissingEnabled: !useSingleExec,
})
- // The Hono runtime always uses mcpcat for observability. The
- // @posthog/mcp-analytics SDK depends on cloudflare:workers env and is
- // skipped here — its flag is still resolved above for analytics parity.
- await initMcpCatObservability(this.server, mcpAnalyticsIdentity)
+ Object.assign(this.props, {
+ mcpAnalyticsInitAction: initResult.action,
+ ...(initResult.action === 'skipped' ? { mcpAnalyticsInitReason: initResult.reason } : {}),
+ ...(initResult.action === 'failed'
+ ? {
+ mcpAnalyticsInitErrorName: initResult.errorName,
+ mcpAnalyticsInitErrorMessage: initResult.errorMessage,
+ }
+ : {}),
+ } as HonoRequestProperties)
const initDurationMs = this.props.requestStartTime ? Date.now() - this.props.requestStartTime : undefined
@@ -724,19 +728,6 @@ export class HonoMcpServer {
}
}
- private async resolvePostHogMcpAnalyticsFlag(): Promise<PostHogMcpAnalyticsFlagResult> {
- try {
- const distinctId = await this.getDistinctId()
- return { enabled: !!(await isFeatureFlagEnabled(POSTHOG_MCP_ANALYTICS_FLAG, distinctId)) }
- } catch (error) {
- return {
- enabled: false,
- errorName: error instanceof Error ? error.name : 'UnknownError',
- errorMessage: error instanceof Error ? error.message : String(error),
- }
- }
- }
-
private async resolveToolFeatureFlags(version?: number): Promise<Record<string, boolean> | undefined> {
try {
const { getRequiredFeatureFlags } = await import('@/tools/toolDefinitions')
diff --git a/services/mcp/src/hono/request-utils.ts b/services/mcp/src/hono/request-utils.ts
index 401cafc3acc5..6951df204b91 100644
--- a/services/mcp/src/hono/request-utils.ts
+++ b/services/mcp/src/hono/request-utils.ts
@@ -1,7 +1,7 @@
import { z } from 'zod'
-import { getPostHogClient } from '@/lib/analytics'
import { mapErrorToAuthResponse, mapKnownErrorMessage, validateBearerToken } from '@/lib/auth-errors'
+import { getPostHogClient } from '@/lib/posthog'
import {
type ClientInfo,
parseRequestProperties,
diff --git a/services/mcp/src/index.ts b/services/mcp/src/index.ts
index b24a1415a8e0..24837a1b38a3 100644
--- a/services/mcp/src/index.ts
+++ b/services/mcp/src/index.ts
@@ -1,4 +1,3 @@
-import { getPostHogClient } from '@/lib/analytics'
import { MCP_DOCS_URL, OAUTH_SCOPES_SUPPORTED, getAuthorizationServerUrl } from '@/lib/constants'
import {
buildInsufficientScopeChallenge,
@@ -8,6 +7,7 @@ import {
} from '@/lib/errors'
import { RequestLogger, withLogging } from '@/lib/logging'
import { extractClientInfoFromBody } from '@/lib/mcp-client-info'
+import { getPostHogClient } from '@/lib/posthog'
import { buildRedirectUrl, matchAuthServerRedirect } from '@/lib/routing'
import { hash, parseMcpMode, sanitizeHeaderValue } from '@/lib/utils'
import type { CloudRegion } from '@/tools/types'
@@ -16,26 +16,11 @@ import { MCP, RequestProperties } from './mcp'
function extendMcpServerLog(log: RequestLogger, props: RequestProperties): void {
const mcpServerLog: Record<string, unknown> = {
- ...(props.mcpAnalyticsProvider ? { mcpAnalyticsProvider: props.mcpAnalyticsProvider } : {}),
- ...(props.mcpAnalyticsFlagKey ? { mcpAnalyticsFlagKey: props.mcpAnalyticsFlagKey } : {}),
- ...(props.mcpAnalyticsFlagEnabled !== undefined
- ? { mcpAnalyticsFlagEnabled: props.mcpAnalyticsFlagEnabled }
- : {}),
- ...(props.mcpAnalyticsFlagErrorName ? { mcpAnalyticsFlagErrorName: props.mcpAnalyticsFlagErrorName } : {}),
- ...(props.mcpAnalyticsFlagErrorMessage
- ? { mcpAnalyticsFlagErrorMessage: props.mcpAnalyticsFlagErrorMessage }
- : {}),
- ...(props.posthogMcpAnalyticsInitAction
- ? { posthogMcpAnalyticsInitAction: props.posthogMcpAnalyticsInitAction }
- : {}),
- ...(props.posthogMcpAnalyticsInitReason
- ? { posthogMcpAnalyticsInitReason: props.posthogMcpAnalyticsInitReason }
- : {}),
- ...(props.posthogMcpAnalyticsInitErrorName
- ? { posthogMcpAnalyticsInitErrorName: props.posthogMcpAnalyticsInitErrorName }
- : {}),
- ...(props.posthogMcpAnalyticsInitErrorMessage
- ? { posthogMcpAnalyticsInitErrorMessage: props.posthogMcpAnalyticsInitErrorMessage }
+ ...(props.mcpAnalyticsInitAction ? { mcpAnalyticsInitAction: props.mcpAnalyticsInitAction } : {}),
+ ...(props.mcpAnalyticsInitReason ? { mcpAnalyticsInitReason: props.mcpAnalyticsInitReason } : {}),
+ ...(props.mcpAnalyticsInitErrorName ? { mcpAnalyticsInitErrorName: props.mcpAnalyticsInitErrorName } : {}),
+ ...(props.mcpAnalyticsInitErrorMessage
+ ? { mcpAnalyticsInitErrorMessage: props.mcpAnalyticsInitErrorMessage }
: {}),
}
diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.ts
index 3cf507adc77d..fd1bc668cf7a 100644
--- a/services/mcp/src/lib/StateManager.ts
+++ b/services/mcp/src/lib/StateManager.ts
@@ -1,14 +1,13 @@
import type { ApiClient, GroupType } from '@/api/client'
import { hasScope } from '@/lib/api'
-import { getPostHogClient } from '@/lib/analytics'
+import type { ScopedCache } from '@/lib/cache/ScopedCache'
import { ErrorCode, MissingOrganizationContextError, MissingProjectContextError, wrapError } from '@/lib/errors'
import { buildActiveEnvironmentContextPrompt } from '@/lib/instructions'
+import { getPostHogClient } from '@/lib/posthog'
import { sanitizeHeaderValue } from '@/lib/utils'
import type { ApiUser } from '@/schema/api'
import type { CachedOrg, CachedProject, CachedUser, State } from '@/tools/types'
-import type { ScopedCache } from './cache/ScopedCache'
-
const CACHE_TTL_MS = 10 * 60 * 1000 // 10 minutes
export class StateManager {
diff --git a/services/mcp/src/lib/analytics.ts b/services/mcp/src/lib/analytics.ts
deleted file mode 100644
index 541b9b77a4d6..000000000000
--- a/services/mcp/src/lib/analytics.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { PostHog } from 'posthog-node'
-
-import { env } from '@/lib/env'
-
-let _client: PostHog | undefined
-
-export enum AnalyticsEvent {
- MCP_INIT = 'mcp init',
- MCP_PROJECT_SWITCHED = 'mcp project switched',
- MCP_ORGANIZATION_SWITCHED = 'mcp organization switched',
- MCP_TOOL_CALL = 'mcp_tool_call', // matching mcpcat
- MCP_FEEDBACK_SUBMITTED = 'mcp feedback submitted',
-}
-
-export type MCPAnalyticsContext = {
- organizationId?: string
- projectId?: string
- projectUuid?: string
- projectName?: string
-}
-
-/**
- * Build PostHog `$groups` from resolved workspace context. Uses `projectUuid`
- * (not the numeric team id) as the `project` group key to match the convention
- * in `posthog/event_usage.py` so MCP events join with the rest of the product
- * in group-level analytics.
- */
-export const buildMCPAnalyticsGroups = ({
- organizationId,
- projectUuid,
-}: MCPAnalyticsContext): Record<string, string> => ({
- ...(organizationId ? { organization: organizationId } : {}),
- ...(projectUuid ? { project: projectUuid } : {}),
-})
-
-/**
- * Convert the workspace context (camelCase) into snake_case event properties.
- * Single source of truth for this mapping — every callsite that would otherwise
- * hand-roll `{ organization_id, project_id, project_uuid, project_name }` should
- * go through this helper so adding a field is a one-touch change.
- *
- * `prefix` is used to emit `previous_*` properties on context-switch events.
- */
-export const buildMCPContextProperties = (
- ctx: MCPAnalyticsContext,
- { prefix = '' }: { prefix?: string } = {}
-): Record<string, string> => ({
- ...(ctx.organizationId ? { [`${prefix}organization_id`]: ctx.organizationId } : {}),
- ...(ctx.projectId ? { [`${prefix}project_id`]: ctx.projectId } : {}),
- ...(ctx.projectUuid ? { [`${prefix}project_uuid`]: ctx.projectUuid } : {}),
- ...(ctx.projectName ? { [`${prefix}project_name`]: ctx.projectName } : {}),
-})
-
-export const getPostHogClient = (): PostHog => {
- if (!_client) {
- _client = new PostHog(env.POSTHOG_ANALYTICS_API_KEY ?? '', {
- disabled: !env.POSTHOG_ANALYTICS_API_KEY || !env.POSTHOG_ANALYTICS_HOST, // Disable if the API key or host is not set
- ...(env.POSTHOG_ANALYTICS_HOST ? { host: env.POSTHOG_ANALYTICS_HOST } : {}),
- flushAt: 1,
- flushInterval: 0,
- })
- }
-
- return _client
-}
-
-export async function isFeatureFlagEnabled(flagKey: string, distinctId: string): Promise<boolean> {
- try {
- const client = getPostHogClient()
- const result = await client.isFeatureEnabled(flagKey, distinctId)
- return result === true
- } catch {
- return false
- }
-}
-
-/**
- * Evaluate multiple feature flags in parallel for the given user.
- * Returns a map of flag key → boolean.
- */
-export async function evaluateFeatureFlags(flagKeys: string[], distinctId: string): Promise<Record<string, boolean>> {
- if (flagKeys.length === 0) {
- return {}
- }
-
- const results = await Promise.all(
- flagKeys.map(async (key) => {
- const enabled = await isFeatureFlagEnabled(key, distinctId)
- return [key, enabled] as const
- })
- )
-
- return Object.fromEntries(results)
-}
diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.ts
index 1395b8865565..fbe4a9fb8288 100644
--- a/services/mcp/src/lib/errors.ts
+++ b/services/mcp/src/lib/errors.ts
@@ -1,6 +1,6 @@
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
-import { getPostHogClient } from '@/lib/analytics'
+import { getPostHogClient } from '@/lib/posthog'
import { sanitizeHeaderValue } from '@/lib/utils'
export enum ErrorCode {
diff --git a/services/mcp/src/lib/mcpcat.ts b/services/mcp/src/lib/mcpcat.ts
deleted file mode 100644
index 36eb98224181..000000000000
--- a/services/mcp/src/lib/mcpcat.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
-import { track } from 'mcpcat'
-
-import type { MCPAnalyticsContext } from '@/lib/analytics'
-import { env } from '@/lib/env'
-
-/** Provider interface for resolving user/session identity and workspace context. */
-export type McpCatIdentityProvider = {
- getDistinctId: () => Promise<string>
- // 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 LLM Analytics grouping.
- // Only set when a wrapping consumer app supplied the hint.
- getSessionUuid: () => Promise<string | undefined>
- getMcpClientName: () => Promise<string | undefined>
- getMcpClientVersion: () => Promise<string | undefined>
- getMcpProtocolVersion: () => Promise<string | undefined>
- getRegion: () => Promise<string | undefined>
- getAnalyticsContext: () => Promise<MCPAnalyticsContext | undefined>
- getClientUserAgent: () => Promise<string | undefined>
- getMcpVersion: () => Promise<number | undefined>
- getOAuthClientName: () => Promise<string | undefined>
- getReadOnly: () => Promise<boolean | undefined>
- getTransport: () => Promise<string | undefined>
- getMcpConsumer: () => Promise<string | undefined>
- getMcpMode: () => 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>
-}
-
-export function redactSensitiveInformation(text: string): string {
- return text.replace(/Bearer\s?[\w\-.]+/g, '<redacted>')
-}
-
-export async function initMcpCatObservability(server: McpServer, identity: McpCatIdentityProvider): Promise<void> {
- // MCPCat initialization must never block MCP server startup
- // and we don't even need to do anything if the API key or host is not set
- // This is properly set in production where we care about analytics
- const posthogApiKey = env.POSTHOG_ANALYTICS_API_KEY
- const posthogHost = env.POSTHOG_ANALYTICS_HOST
- if (!posthogApiKey || !posthogHost) {
- return
- }
-
- // Compute the distinct ID only once and include with every single event
- const distinctId = await identity.getDistinctId()
- const identifyResult = { userId: distinctId }
-
- try {
- // If the MCP_CAT_PROJECT_ID is not set, use null. This will disable sending events to MCPcat.
- // For production, we'll set this to the correct project ID.
- track(server, env.MCP_CAT_PROJECT_ID ?? null, {
- enableReportMissing: false,
- enableToolCallContext: false,
- enableTracing: true, // Tracks tools and usage patterns
- identify: async () => identifyResult,
- // For tags, we need to override MCPcat's default $session_id and $ai_session_id with our
- // own PostHog session UUID. $session_id drives Session Replay; $ai_session_id is what
- // LLM Analytics groups traces by — without overriding it, MCPcat's exporter falls back
- // to `mcpcat_<ksuid>`. Recomputed per event so a late-bound session UUID is picked up.
- eventTags: async () => {
- const sessionUuid = await identity.getSessionUuid()
- if (!sessionUuid) {
- return {}
- }
-
- return {
- $session_id: sessionUuid,
- $ai_session_id: sessionUuid,
- }
- },
- // Recomputed per event so workspace switches (via `switch-project` / `switch-organization`)
- // are reflected on subsequent events without a reinit.
- eventProperties: async () => {
- const [
- mcpVersion,
- clientUserAgent,
- mcpClientName,
- mcpClientVersion,
- mcpProtocolVersion,
- mcpRegion,
- analyticsContext,
- oauthClientName,
- readOnly,
- transport,
- mcpConsumer,
- mcpMode,
- mcpSessionId,
- mcpConversationId,
- ] = await Promise.all([
- identity.getMcpVersion(),
- identity.getClientUserAgent(),
- identity.getMcpClientName(),
- identity.getMcpClientVersion(),
- identity.getMcpProtocolVersion(),
- identity.getRegion(),
- identity.getAnalyticsContext(),
- identity.getOAuthClientName(),
- identity.getReadOnly(),
- identity.getTransport(),
- identity.getMcpConsumer(),
- identity.getMcpMode(),
- identity.getMcpSessionId(),
- identity.getMcpConversationId(),
- ])
-
- // `$groups` is the raw event-payload key; mcpcat doesn't expose a typed
- // `groups` option, so we set it directly alongside the other properties.
- const groups = {
- ...(analyticsContext?.organizationId ? { organization: analyticsContext.organizationId } : {}),
- ...(analyticsContext?.projectUuid ? { project: analyticsContext.projectUuid } : {}),
- }
-
- return {
- ai_product: 'mcp',
- mcp_version: mcpVersion,
- client_user_agent: clientUserAgent,
- mcp_client_name: mcpClientName,
- mcp_client_version: mcpClientVersion,
- mcp_protocol_version: mcpProtocolVersion,
- mcp_region: mcpRegion,
- organization_id: analyticsContext?.organizationId,
- project_id: analyticsContext?.projectId,
- project_uuid: analyticsContext?.projectUuid,
- project_name: analyticsContext?.projectName,
- mcp_oauth_client_name: oauthClientName,
- 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 } : {}),
- }
- },
- redactSensitiveInformation: (text) => Promise.resolve(redactSensitiveInformation(text)),
- exporters: {
- posthog: {
- type: 'posthog',
- apiKey: posthogApiKey,
- host: posthogHost,
- enableAITracing: true,
- },
- },
- })
- } catch {
- // MCPCat initialization must never block MCP server startup
- }
-}
diff --git a/services/mcp/src/lib/posthog-mcp-analytics.ts b/services/mcp/src/lib/posthog/analytics.ts
similarity index 56%
rename from services/mcp/src/lib/posthog-mcp-analytics.ts
rename to services/mcp/src/lib/posthog/analytics.ts
index 2b04d08d62f3..f5d587cf5a08 100644
--- a/services/mcp/src/lib/posthog-mcp-analytics.ts
+++ b/services/mcp/src/lib/posthog/analytics.ts
@@ -1,11 +1,91 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { env } from '@/lib/env'
-import { type McpCatIdentityProvider, redactSensitiveInformation } from '@/lib/mcpcat'
-export type PostHogMcpAnalyticsIdentityProvider = McpCatIdentityProvider
+import { getPostHogClient } from './client'
-export type PostHogMcpAnalyticsOptions = {
+export enum AnalyticsEvent {
+ MCP_INIT = 'mcp init',
+ MCP_PROJECT_SWITCHED = 'mcp project switched',
+ MCP_ORGANIZATION_SWITCHED = 'mcp organization switched',
+ MCP_TOOL_CALL = 'mcp_tool_call', // matching @posthog/mcp-analytics
+ MCP_FEEDBACK_SUBMITTED = 'mcp feedback submitted',
+}
+
+export type MCPAnalyticsContext = {
+ organizationId?: string
+ projectId?: string
+ projectUuid?: string
+ projectName?: string
+}
+
+/**
+ * Build PostHog `$groups` from resolved workspace context. Uses `projectUuid`
+ * (not the numeric team id) as the `project` group key to match the convention
+ * in `posthog/event_usage.py` so MCP events join with the rest of the product
+ * in group-level analytics.
+ */
+export const buildMCPAnalyticsGroups = ({
+ organizationId,
+ projectUuid,
+}: MCPAnalyticsContext): Record<string, string> => ({
+ ...(organizationId ? { organization: organizationId } : {}),
+ ...(projectUuid ? { project: projectUuid } : {}),
+})
+
+/**
+ * Convert the workspace context (camelCase) into snake_case event properties.
+ * Single source of truth for this mapping — every callsite that would otherwise
+ * hand-roll `{ organization_id, project_id, project_uuid, project_name }` should
+ * go through this helper so adding a field is a one-touch change.
+ *
+ * `prefix` is used to emit `previous_*` properties on context-switch events.
+ */
+export const buildMCPContextProperties = (
+ ctx: MCPAnalyticsContext,
+ { prefix = '' }: { prefix?: string } = {}
+): Record<string, string> => ({
+ ...(ctx.organizationId ? { [`${prefix}organization_id`]: ctx.organizationId } : {}),
+ ...(ctx.projectId ? { [`${prefix}project_id`]: ctx.projectId } : {}),
+ ...(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>
+ getRegion: () => Promise<string | undefined>
+ getAnalyticsContext: () => Promise<MCPAnalyticsContext | undefined>
+ getClientUserAgent: () => Promise<string | undefined>
+ getMcpVersion: () => Promise<number | 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 LLM Analytics 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
@@ -31,13 +111,9 @@ export type PostHogMcpAnalyticsOptions = {
execInnerToolNames?: readonly string[] | undefined
}
-export type PostHogMcpAnalyticsInitResult =
+export type McpAnalyticsInitResult =
| {
action: 'initialized'
- contextEnabled: boolean
- tracingEnabled: true
- aiTracingEnabled: true
- reportMissingEnabled: boolean
}
| {
action: 'skipped'
@@ -51,7 +127,7 @@ export type PostHogMcpAnalyticsInitResult =
errorMessage: string
}
-async function buildEventTags(identity: PostHogMcpAnalyticsIdentityProvider): Promise<Record<string, string>> {
+async function buildEventTags(identity: IdentityProvider): Promise<Record<string, string>> {
const sessionUuid = await identity.getSessionUuid()
if (!sessionUuid) {
return {}
@@ -63,7 +139,7 @@ async function buildEventTags(identity: PostHogMcpAnalyticsIdentityProvider): Pr
}
}
-async function buildEventProperties(identity: PostHogMcpAnalyticsIdentityProvider): Promise<Record<string, unknown>> {
+async function buildEventProperties(identity: IdentityProvider): Promise<Record<string, unknown>> {
const [
mcpVersion,
clientUserAgent,
@@ -124,13 +200,16 @@ async function buildEventProperties(identity: PostHogMcpAnalyticsIdentityProvide
}
}
-export async function initPostHogMcpAnalytics(
+function redactSensitiveInformation(text: string): string {
+ return text.replace(/Bearer\s?[\w\-.]+/g, '<redacted>')
+}
+
+export async function initMcpAnalytics(
server: McpServer,
- identity: PostHogMcpAnalyticsIdentityProvider,
- options: PostHogMcpAnalyticsOptions = { contextEnabled: false, reportMissingEnabled: false }
-): Promise<PostHogMcpAnalyticsInitResult> {
- const posthogApiKey = env.POSTHOG_ANALYTICS_API_KEY
- const posthogHost = env.POSTHOG_ANALYTICS_HOST
+ 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',
@@ -141,25 +220,18 @@ export async function initPostHogMcpAnalytics(
}
try {
- const { track } = await import('@posthog/mcp-analytics')
+ const { track } = await import('@posthog/mcp-analytics') // Import only if needed
const distinctId = await identity.getDistinctId()
- const identifyResult = { userId: distinctId }
track(server, {
- apiKey: posthogApiKey,
+ posthogClient: getPostHogClient(),
context: options.contextEnabled,
enableAITracing: true,
enableConversationId: true,
enableTracing: true,
- host: posthogHost,
- identify: async () => identifyResult,
- posthogOptions: {
- flushAt: 1,
- flushInterval: 0,
- host: posthogHost,
- },
+ identify: { userId: distinctId },
reportMissing: options.reportMissingEnabled,
- eventTags: async () => buildEventTags(identity),
+ eventTags: () => buildEventTags(identity),
eventProperties: async (request) => {
const base = await buildEventProperties(identity)
const innerToolCall = options.resolveExecInnerToolCall?.(request)
@@ -167,6 +239,7 @@ export async function initPostHogMcpAnalytics(
(request as { method?: unknown })?.method === 'tools/list' &&
!!options.execInnerToolNames &&
options.execInnerToolNames.length > 0
+
return {
...base,
...(innerToolCall
@@ -183,13 +256,7 @@ export async function initPostHogMcpAnalytics(
redactSensitiveInformation: (text) => Promise.resolve(redactSensitiveInformation(text)),
})
- return {
- action: 'initialized',
- contextEnabled: options.contextEnabled,
- tracingEnabled: true,
- aiTracingEnabled: true,
- reportMissingEnabled: options.reportMissingEnabled,
- }
+ return { action: 'initialized' }
} catch (error) {
return {
action: 'failed',
diff --git a/services/mcp/src/lib/posthog/client.ts b/services/mcp/src/lib/posthog/client.ts
new file mode 100644
index 000000000000..c43066984335
--- /dev/null
+++ b/services/mcp/src/lib/posthog/client.ts
@@ -0,0 +1,17 @@
+import { PostHog } from 'posthog-node'
+
+import { env } from '@/lib/env'
+
+let _client: PostHog | undefined
+export const getPostHogClient = (): PostHog => {
+ if (!_client) {
+ _client = new PostHog(env.POSTHOG_ANALYTICS_API_KEY ?? '', {
+ disabled: !env.POSTHOG_ANALYTICS_API_KEY || !env.POSTHOG_ANALYTICS_HOST, // Disable if the API key or host is not set
+ ...(env.POSTHOG_ANALYTICS_HOST ? { host: env.POSTHOG_ANALYTICS_HOST } : {}),
+ flushAt: 1,
+ flushInterval: 0,
+ })
+ }
+
+ return _client
+}
diff --git a/services/mcp/src/lib/posthog/flags.ts b/services/mcp/src/lib/posthog/flags.ts
new file mode 100644
index 000000000000..9ac24609f27a
--- /dev/null
+++ b/services/mcp/src/lib/posthog/flags.ts
@@ -0,0 +1,30 @@
+import { getPostHogClient } from './client'
+
+export async function isFeatureFlagEnabled(flagKey: string, distinctId: string): Promise<boolean> {
+ try {
+ const client = getPostHogClient()
+ const result = await client.isFeatureEnabled(flagKey, distinctId)
+ return result === true
+ } catch {
+ return false
+ }
+}
+
+/**
+ * Evaluate multiple feature flags in parallel for the given user.
+ * Returns a map of flag key → boolean.
+ */
+export async function evaluateFeatureFlags(flagKeys: string[], distinctId: string): Promise<Record<string, boolean>> {
+ if (flagKeys.length === 0) {
+ return {}
+ }
+
+ const results = await Promise.all(
+ flagKeys.map(async (key) => {
+ const enabled = await isFeatureFlagEnabled(key, distinctId)
+ return [key, enabled] as const
+ })
+ )
+
+ return Object.fromEntries(results)
+}
diff --git a/services/mcp/src/lib/posthog/index.ts b/services/mcp/src/lib/posthog/index.ts
new file mode 100644
index 000000000000..fb2db0c5f403
--- /dev/null
+++ b/services/mcp/src/lib/posthog/index.ts
@@ -0,0 +1,3 @@
+import { getPostHogClient } from './client'
+
+export { getPostHogClient }
diff --git a/services/mcp/src/mcp.ts b/services/mcp/src/mcp.ts
index 99c61e5755c2..f15d7c13a4a0 100644
--- a/services/mcp/src/mcp.ts
+++ b/services/mcp/src/mcp.ts
@@ -5,15 +5,6 @@ import { McpAgent } from 'agents/mcp'
import type { z } from 'zod'
import { ApiClient } from '@/api/client'
-import {
- AnalyticsEvent,
- buildMCPAnalyticsGroups,
- buildMCPContextProperties,
- evaluateFeatureFlags,
- getPostHogClient,
- isFeatureFlagEnabled,
- type MCPAnalyticsContext,
-} from '@/lib/analytics'
import { hasScope } from '@/lib/api'
import { buildToolResultPayload, isToolCallPayload } from '@/lib/build-tool-result'
import { DurableObjectCache } from '@/lib/cache/DurableObjectCache'
@@ -28,8 +19,16 @@ import {
import { handleToolError, wrapError } from '@/lib/errors'
import { type QueryToolInfo } from '@/lib/instructions'
import { InstructionsFormatter } from '@/lib/instructions-formatter'
-import { initMcpCatObservability } from '@/lib/mcpcat'
-import { initPostHogMcpAnalytics, type PostHogMcpAnalyticsInitResult } from '@/lib/posthog-mcp-analytics'
+import { getPostHogClient } from '@/lib/posthog'
+import {
+ AnalyticsEvent,
+ buildMCPAnalyticsGroups,
+ buildMCPContextProperties,
+ initMcpAnalytics,
+ McpAnalyticsInitResult,
+ type MCPAnalyticsContext,
+} from '@/lib/posthog/analytics'
+import { evaluateFeatureFlags, isFeatureFlagEnabled } from '@/lib/posthog/flags'
import { SessionManager } from '@/lib/SessionManager'
import { StateManager } from '@/lib/StateManager'
import { formatPrompt, type McpMode, sanitizeHeaderValue } from '@/lib/utils'
@@ -42,13 +41,6 @@ import { getToolDefinition } from '@/tools/toolDefinitions'
import { type CloudRegion, type Context, type State, type Tool } from '@/tools/types'
const instructionsFormatter = new InstructionsFormatter()
-const POSTHOG_MCP_ANALYTICS_FLAG = 'mcp-posthog-analytics-sdk'
-type McpAnalyticsProvider = 'posthog_mcp_analytics' | 'mcpcat'
-type PostHogMcpAnalyticsFlagResult = {
- enabled: boolean
- errorName?: string
- errorMessage?: string
-}
export type RequestProperties = {
userHash: string
@@ -86,15 +78,10 @@ export type RequestProperties = {
transport?: 'streamable-http' | 'sse'
viaSseRedirect?: boolean
requestStartTime?: number
- mcpAnalyticsProvider?: McpAnalyticsProvider
- mcpAnalyticsFlagKey?: string
- mcpAnalyticsFlagEnabled?: boolean
- mcpAnalyticsFlagErrorName?: string
- mcpAnalyticsFlagErrorMessage?: string
- posthogMcpAnalyticsInitAction?: PostHogMcpAnalyticsInitResult['action']
- posthogMcpAnalyticsInitReason?: string
- posthogMcpAnalyticsInitErrorName?: string
- posthogMcpAnalyticsInitErrorMessage?: string
+ mcpAnalyticsInitAction?: McpAnalyticsInitResult['action']
+ mcpAnalyticsInitReason?: string
+ mcpAnalyticsInitErrorName?: string
+ mcpAnalyticsInitErrorMessage?: string
}
export class MCP extends McpAgent<Env> {
@@ -540,7 +527,6 @@ export class MCP extends McpAgent<Env> {
const flagPromise = this.resolveVersionFlag()
const toolFlagsPromise = this.resolveToolFeatureFlags(clientVersion)
const singleExecPromise = this.resolveSingleExecFlag()
- const posthogMcpAnalyticsFlagPromise = this.resolvePostHogMcpAnalyticsFlag()
// Seed cache with header-provided IDs before any fetches
if (organizationId) {
@@ -569,15 +555,13 @@ export class MCP extends McpAgent<Env> {
await context.stateManager.setDefaultOrganizationAndProject()
}
- const [flagVersion, toolFeatureFlags, singleExecFlagOn, posthogMcpAnalyticsFlag] = await Promise.all([
+ const [flagVersion, toolFeatureFlags, singleExecFlagOn, _apiKey] = await Promise.all([
flagPromise,
toolFlagsPromise,
singleExecPromise,
- posthogMcpAnalyticsFlagPromise,
// Trigger OAuth introspection so the OAuth client name is cached before the useSingleExec decision below
context.stateManager.getApiKey(),
])
- const isPosthogMCPAnalyticsEnabled = posthogMcpAnalyticsFlag.enabled
const oauthClientName = (await this.cache.get('clientName')) || undefined
@@ -768,61 +752,42 @@ export class MCP extends McpAgent<Env> {
getMcpConversationId: async () => this.requestProperties.mcpConversationId,
}
- Object.assign(this.requestProperties, {
- mcpAnalyticsProvider: isPosthogMCPAnalyticsEnabled ? 'posthog_mcp_analytics' : 'mcpcat',
- mcpAnalyticsFlagKey: POSTHOG_MCP_ANALYTICS_FLAG,
- mcpAnalyticsFlagEnabled: isPosthogMCPAnalyticsEnabled,
- ...(posthogMcpAnalyticsFlag.errorName
- ? { mcpAnalyticsFlagErrorName: posthogMcpAnalyticsFlag.errorName }
- : {}),
- ...(posthogMcpAnalyticsFlag.errorMessage
- ? { mcpAnalyticsFlagErrorMessage: posthogMcpAnalyticsFlag.errorMessage }
- : {}),
+ // In single-exec mode every event's `$mcp_tool_name` is `exec`, so the
+ // SDK's `$mcp_tool_description` would be the dispatcher's static text on
+ // every call. Resolve the inner tool the agent was actually invoking
+ // from the command and surface its name + description as
+ // `$mcp_exec_tool_call_name` / `$mcp_exec_tool_call_description`.
+ const resolveExecInnerToolCall = useSingleExec ? createExecInnerToolCallResolver(allTools) : undefined
+
+ // In single-exec mode the SDK's $mcp_listed_tool_names collapses to
+ // just `exec`, so we can't compute "advertised but never called"
+ // (zombie tools) from SDK data alone. Pass the inner-tool catalog
+ // here so analytics can attach it as $mcp_exec_inner_tool_names on
+ // mcp_tools_list events. Dashboards can then diff it against
+ // $mcp_exec_tool_call_name from mcp_tool_call.
+ const execInnerToolNames = useSingleExec ? allTools.map((t) => t.name) : undefined
+
+ const initResult = await initMcpAnalytics(this.server, mcpAnalyticsIdentity, {
+ contextEnabled: true,
+ resolveExecInnerToolCall,
+ execInnerToolNames,
+ // `get_more_tools` only earns its keep outside single-exec mode — there
+ // it lets the model report a gap in our discrete tool catalog. In
+ // single-exec mode the wrapper handles every call, so the missing-tool
+ // signal has nothing to map to and the extra slot is pure noise.
+ reportMissingEnabled: !useSingleExec,
})
- // @posthog/mcp is based on the MCP Cat wrapper and keeps tool tracing,
- // AI spans, context capture, and get_more_tools for flagged sessions.
- // Avoid initializing both wrappers because both patch tool handlers and
- // would double-capture every call.
- // `get_more_tools` only earns its keep outside single-exec mode — there
- // it lets the model report a gap in our discrete tool catalog. In
- // single-exec mode the wrapper handles every call, so the missing-tool
- // signal has nothing to map to and the extra slot is pure noise.
- if (isPosthogMCPAnalyticsEnabled) {
- // In single-exec mode every event's `$mcp_tool_name` is `exec`, so the
- // SDK's `$mcp_tool_description` would be the dispatcher's static text on
- // every call. Resolve the inner tool the agent was actually invoking
- // from the command and surface its name + description as
- // `$mcp_exec_tool_call_name` / `$mcp_exec_tool_call_description`.
- const resolveExecInnerToolCall = useSingleExec ? createExecInnerToolCallResolver(allTools) : undefined
-
- // In single-exec mode the SDK's $mcp_listed_tool_names collapses to
- // just `exec`, so we can't compute "advertised but never called"
- // (zombie tools) from SDK data alone. Pass the inner-tool catalog
- // here so analytics can attach it as $mcp_exec_inner_tool_names on
- // mcp_tools_list events. Dashboards can then diff it against
- // $mcp_exec_tool_call_name from mcp_tool_call.
- const execInnerToolNames = useSingleExec ? allTools.map((t) => t.name) : undefined
-
- const initResult = await initPostHogMcpAnalytics(this.server, mcpAnalyticsIdentity, {
- contextEnabled: true,
- reportMissingEnabled: !useSingleExec,
- resolveExecInnerToolCall,
- execInnerToolNames,
- })
- Object.assign(this.requestProperties, {
- posthogMcpAnalyticsInitAction: initResult.action,
- ...(initResult.action === 'skipped' ? { posthogMcpAnalyticsInitReason: initResult.reason } : {}),
- ...(initResult.action === 'failed'
- ? {
- posthogMcpAnalyticsInitErrorName: initResult.errorName,
- posthogMcpAnalyticsInitErrorMessage: initResult.errorMessage,
- }
- : {}),
- })
- } else {
- await initMcpCatObservability(this.server, mcpAnalyticsIdentity)
- }
+ Object.assign(this.requestProperties, {
+ mcpAnalyticsInitAction: initResult.action,
+ ...(initResult.action === 'skipped' ? { mcpAnalyticsInitReason: initResult.reason } : {}),
+ ...(initResult.action === 'failed'
+ ? {
+ mcpAnalyticsInitErrorName: initResult.errorName,
+ mcpAnalyticsInitErrorMessage: initResult.errorMessage,
+ }
+ : {}),
+ } as RequestProperties)
const initDurationMs = this.requestProperties.requestStartTime
? Date.now() - this.requestProperties.requestStartTime
@@ -906,19 +871,6 @@ export class MCP extends McpAgent<Env> {
}
}
- private async resolvePostHogMcpAnalyticsFlag(): Promise<PostHogMcpAnalyticsFlagResult> {
- try {
- const distinctId = await this.getDistinctId()
- return { enabled: !!(await isFeatureFlagEnabled(POSTHOG_MCP_ANALYTICS_FLAG, distinctId)) }
- } catch (error) {
- return {
- enabled: false,
- errorName: error instanceof Error ? error.name : 'UnknownError',
- errorMessage: error instanceof Error ? error.message : String(error),
- }
- }
- }
-
private async resolveToolFeatureFlags(version?: number): Promise<Record<string, boolean> | undefined> {
try {
const { getRequiredFeatureFlags } = await import('@/tools/toolDefinitions')
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 6948a6ab31d6..71da07e3bd93 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -57,7 +57,7 @@ export function parseExecCallInnerToolName(command: string): string | undefined
return innerName || undefined
}
-// Builds the resolver mcp.ts hands to initPostHogMcpAnalytics in single-exec
+// 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
diff --git a/services/mcp/src/tools/feedback/submit.ts b/services/mcp/src/tools/feedback/submit.ts
index b7aeaf856eb6..c215365aebdc 100644
--- a/services/mcp/src/tools/feedback/submit.ts
+++ b/services/mcp/src/tools/feedback/submit.ts
@@ -1,6 +1,6 @@
import type { z } from 'zod'
-import { AnalyticsEvent } from '@/lib/analytics'
+import { AnalyticsEvent } from '@/lib/posthog/analytics'
import { FeedbackSubmitSchema } from '@/schema/tool-inputs'
import type { Context, ToolBase } from '@/tools/types'
diff --git a/services/mcp/src/tools/types.ts b/services/mcp/src/tools/types.ts
index 0a4b44d6039f..ba9633f78219 100644
--- a/services/mcp/src/tools/types.ts
+++ b/services/mcp/src/tools/types.ts
@@ -2,8 +2,8 @@ import type { z } from 'zod'
import type { ApiClient, GroupType } from '@/api/client'
import type { Schemas } from '@/api/generated'
-import type { AnalyticsEvent } from '@/lib/analytics'
import type { ScopedCache } from '@/lib/cache/ScopedCache'
+import type { AnalyticsEvent } from '@/lib/posthog/analytics'
import type { SessionManager } from '@/lib/SessionManager'
import type { StateManager } from '@/lib/StateManager'
import type { PrefixedString } from '@/lib/types'
diff --git a/services/mcp/tests/hono/mcp-server.test.ts b/services/mcp/tests/hono/mcp-server.test.ts
index 46c60095ce1b..43fc2e06e880 100644
--- a/services/mcp/tests/hono/mcp-server.test.ts
+++ b/services/mcp/tests/hono/mcp-server.test.ts
@@ -76,12 +76,7 @@ describe('HonoMcpServer', () => {
it('should cache region from props', async () => {
const server = new HonoMcpServer(mockRedis, { ...baseProps, region: 'eu' })
await server.getBaseUrl()
- expect(mockRedis.set).toHaveBeenCalledWith(
- 'mcp:user:test-hash:region',
- '"eu"',
- 'EX',
- expect.any(Number)
- )
+ expect(mockRedis.set).toHaveBeenCalledWith('mcp:user:test-hash:region', '"eu"', 'EX', expect.any(Number))
})
it('should use custom API base URL from env', async () => {
@@ -125,7 +120,7 @@ describe('HonoMcpServer', () => {
const server = new HonoMcpServer(mockRedis, baseProps)
vi.spyOn(server, 'getDistinctId').mockRejectedValue(new Error('fail'))
- const { AnalyticsEvent } = await import('@/lib/analytics')
+ const { AnalyticsEvent } = await import('@/lib/posthog/analytics')
await expect(server.trackEvent(AnalyticsEvent.MCP_INIT)).resolves.toBeUndefined()
})
})
diff --git a/services/mcp/tests/hono/setup.ts b/services/mcp/tests/hono/setup.ts
index bbc0d464bee1..2686f60fafd5 100644
--- a/services/mcp/tests/hono/setup.ts
+++ b/services/mcp/tests/hono/setup.ts
@@ -9,7 +9,6 @@ vi.mock('cloudflare:workers', () => ({
POSTHOG_UI_APPS_TOKEN: undefined,
POSTHOG_ANALYTICS_API_KEY: undefined,
POSTHOG_ANALYTICS_HOST: undefined,
- MCP_CAT_PROJECT_ID: undefined,
},
}))
@@ -27,118 +26,48 @@ vi.mock('@/resources/ui-apps.generated', () => ({
UI_APP_REGISTRY: {},
}))
-vi.mock('mcpcat', () => ({
+vi.mock('@posthog/mcp-analytics', () => ({
track: vi.fn(),
}))
-// Mock modules that may not exist on all branches yet (added on master,
-// not yet merged into this feature branch). These mocks allow the hono
-// code to import from master-targeted paths during tests.
-vi.mock('@/lib/build-tool-result', async () => {
+// Mock template imports that may not exist
+vi.mock('@/templates/cli-proxy-command.md', async () => {
try {
- return await vi.importActual('@/lib/build-tool-result')
+ return await vi.importActual('@/templates/cli-proxy-command.md')
} catch {
- return {
- buildToolResultPayload: vi.fn(({ handlerResult }: any) => ({
- content: [{ type: 'text', text: typeof handlerResult === 'string' ? handlerResult : JSON.stringify(handlerResult) }],
- })),
- isToolCallPayload: vi.fn(() => false),
- }
+ return { default: '' }
}
})
-
-vi.mock('@/lib/client-detection', async () => {
+vi.mock('@/templates/cli-proxy-tool.md', async () => {
try {
- return await vi.importActual('@/lib/client-detection')
+ return await vi.importActual('@/templates/cli-proxy-tool.md')
} catch {
- return {
- MCPClientProfile: class MCPClientProfile {
- constructor() {}
- isCodingAgent(): boolean { return false }
- isPostHogCodeConsumer(): boolean { return false }
- isVibeCodingClient(): boolean { return false }
- get capabilities(): { supportsInstructions: boolean } { return { supportsInstructions: true } }
- },
- isCodingAgentClient: vi.fn(() => false),
- CODING_AGENT_CLIENT_NAME_FRAGMENTS: [],
- }
+ return { default: '' }
}
})
-
-vi.mock('@/lib/mcp-client-info', async () => {
+vi.mock('@/templates/execute-sql-prompt.md', async () => {
try {
- return await vi.importActual('@/lib/mcp-client-info')
+ return await vi.importActual('@/templates/execute-sql-prompt.md')
} catch {
- return {
- extractClientInfoFromBody: vi.fn(async () => ({})),
- }
- }
-})
-
-// Mock @/lib/utils additions not present on all branches
-vi.mock('@/lib/utils', async () => {
- const actual = await vi.importActual<Record<string, unknown>>('@/lib/utils')
- return {
- ...actual,
- parseMcpMode: actual.parseMcpMode ?? vi.fn(() => undefined),
- McpMode: actual.McpMode ?? undefined,
+ return { default: '' }
}
})
-
-// Mock @/lib/errors additions not present on all branches
-vi.mock('@/lib/errors', async () => {
- const actual = await vi.importActual<Record<string, unknown>>('@/lib/errors')
- return {
- ...actual,
- wrapError: actual.wrapError ?? vi.fn((msg: string, cause: unknown) => {
- const err = new Error(msg) as Error & { cause?: unknown }
- err.cause = cause
- return err
- }),
- findPostHogPermissionError: actual.findPostHogPermissionError ?? vi.fn(() => undefined),
- formatPermissionErrorMessage: actual.formatPermissionErrorMessage ?? vi.fn((e: any) => e.message),
- buildInsufficientScopeChallenge: actual.buildInsufficientScopeChallenge ?? vi.fn(() => 'Bearer'),
- }
-})
-
-// Mock @/lib/analytics additions not present on all branches
-vi.mock('@/lib/analytics', async () => {
- const actual = await vi.importActual<Record<string, unknown>>('@/lib/analytics')
- return {
- ...actual,
- buildMCPAnalyticsGroups: actual.buildMCPAnalyticsGroups ?? vi.fn(() => ({})),
- buildMCPContextProperties: actual.buildMCPContextProperties ?? vi.fn(() => ({})),
- evaluateFeatureFlags: actual.evaluateFeatureFlags ?? vi.fn(async () => ({})),
- }
-})
-
-// Mock template imports that may not exist
-vi.mock('@/templates/cli-proxy-command.md', async () => {
- try { return await vi.importActual('@/templates/cli-proxy-command.md') } catch { return { default: '' } }
-})
-vi.mock('@/templates/cli-proxy-tool.md', async () => {
- try { return await vi.importActual('@/templates/cli-proxy-tool.md') } catch { return { default: '' } }
-})
-vi.mock('@/templates/execute-sql-prompt.md', async () => {
- try { return await vi.importActual('@/templates/execute-sql-prompt.md') } catch { return { default: '' } }
-})
vi.mock('@/templates/single-exec-instructions.md', async () => {
- try { return await vi.importActual('@/templates/single-exec-instructions.md') } catch { return { default: '' } }
+ try {
+ return await vi.importActual('@/templates/single-exec-instructions.md')
+ } catch {
+ return { default: '' }
+ }
})
// Mock @/tools/exec that may not exist
vi.mock('@/tools/exec', async () => {
- try { return await vi.importActual('@/tools/exec') } catch {
+ try {
+ return await vi.importActual('@/tools/exec')
+ } catch {
return {
createExecTool: vi.fn(() => ({ name: 'posthog', handler: vi.fn() })),
createExecInnerToolCallResolver: vi.fn(() => () => undefined),
}
}
})
-
-// Mock @/lib/mcpcat
-vi.mock('@/lib/mcpcat', async () => {
- try { return await vi.importActual('@/lib/mcpcat') } catch {
- return { initMcpCatObservability: vi.fn() }
- }
-})
diff --git a/services/mcp/tests/integration/harness/cf.ts b/services/mcp/tests/integration/harness/cf.ts
index c7f8d01c0429..157647195905 100644
--- a/services/mcp/tests/integration/harness/cf.ts
+++ b/services/mcp/tests/integration/harness/cf.ts
@@ -51,7 +51,6 @@ export async function startCfHarness(env: IntegrationEnv): Promise<IntegrationHa
POSTHOG_MCP_APPS_ANALYTICS_BASE_URL: '',
POSTHOG_UI_APPS_TOKEN: '',
INKEEP_API_KEY: '',
- MCP_CAT_PROJECT_ID: '',
},
experimental: {
disableExperimentalWarning: true,
diff --git a/services/mcp/tests/setup.ts b/services/mcp/tests/setup.ts
index 6b877f773b31..c5625fc4a0f7 100644
--- a/services/mcp/tests/setup.ts
+++ b/services/mcp/tests/setup.ts
@@ -5,11 +5,6 @@ import { vi } from 'vitest'
// Load .env.test file
config({ path: resolve(process.cwd(), '.env.test') })
-// Mock mcpcat module to not do anything in tests
-vi.mock('mcpcat', () => ({
- track: vi.fn(),
-}))
-
// Mock PostHog MCP analytics module to avoid networked analytics in tests
vi.mock('@posthog/mcp-analytics', () => ({
track: vi.fn(),
@@ -18,7 +13,6 @@ vi.mock('@posthog/mcp-analytics', () => ({
// Mock cloudflare:workers module for Node.js test environment
vi.mock('cloudflare:workers', () => ({
env: {
- MCP_CAT_PROJECT_ID: undefined,
POSTHOG_ANALYTICS_API_KEY: undefined,
POSTHOG_ANALYTICS_HOST: undefined,
POSTHOG_API_BASE_URL: undefined,
diff --git a/services/mcp/tests/unit/analytics.test.ts b/services/mcp/tests/unit/analytics.test.ts
deleted file mode 100644
index 0748078801bc..000000000000
--- a/services/mcp/tests/unit/analytics.test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { describe, expect, it } from 'vitest'
-
-import { buildMCPAnalyticsGroups, buildMCPContextProperties, type MCPAnalyticsContext } from '@/lib/analytics'
-
-describe('buildMCPAnalyticsGroups', () => {
- it.each<[string, MCPAnalyticsContext, Record<string, string>]>([
- [
- 'full context uses UUID as the project group key',
- { organizationId: 'org-1', projectId: '123', projectUuid: 'project-uuid-123' },
- { organization: 'org-1', project: 'project-uuid-123' },
- ],
- ['organization only', { organizationId: 'org-1' }, { organization: 'org-1' }],
- ['project UUID only', { projectUuid: 'project-uuid-123' }, { project: 'project-uuid-123' }],
- ['ignores projectId when projectUuid is absent', { projectId: '123' }, {}],
- ['empty context', {}, {}],
- ])('%s', (_, input, expected) => {
- expect(buildMCPAnalyticsGroups(input)).toEqual(expected)
- })
-})
-
-describe('buildMCPContextProperties', () => {
- it.each<[string, MCPAnalyticsContext, { prefix?: string } | undefined, Record<string, string>]>([
- [
- 'full context → snake_case properties',
- {
- organizationId: 'org-1',
- projectId: '123',
- projectUuid: 'project-uuid-123',
- projectName: 'My Project',
- },
- undefined,
- {
- organization_id: 'org-1',
- project_id: '123',
- project_uuid: 'project-uuid-123',
- project_name: 'My Project',
- },
- ],
- [
- 'prefix applies to every key (used for previous_* on context-switch events)',
- { organizationId: 'org-1', projectUuid: 'project-uuid-123' },
- { prefix: 'previous_' },
- { previous_organization_id: 'org-1', previous_project_uuid: 'project-uuid-123' },
- ],
- ['empty context yields empty object', {}, undefined, {}],
- [
- 'partial context omits absent keys rather than emitting undefined',
- { organizationId: 'org-1' },
- undefined,
- { organization_id: 'org-1' },
- ],
- ])('%s', (_, input, options, expected) => {
- expect(buildMCPContextProperties(input, options)).toEqual(expected)
- })
-})
diff --git a/services/mcp/tests/unit/feature-flag-version.test.ts b/services/mcp/tests/unit/feature-flag-version.test.ts
index 275f1472323a..47bc636e3135 100644
--- a/services/mcp/tests/unit/feature-flag-version.test.ts
+++ b/services/mcp/tests/unit/feature-flag-version.test.ts
@@ -1,7 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const mockIsFeatureEnabled = vi.fn()
-
vi.mock('posthog-node', () => ({
PostHog: vi.fn().mockImplementation(() => ({
isFeatureEnabled: mockIsFeatureEnabled,
@@ -9,7 +8,7 @@ vi.mock('posthog-node', () => ({
}))
// Must import after vi.mock
-import { isFeatureFlagEnabled } from '@/lib/analytics'
+import { isFeatureFlagEnabled } from '@/lib/posthog/flags'
describe('isFeatureFlagEnabled', () => {
beforeEach(() => {
diff --git a/services/mcp/tests/unit/mcp-cache.test.ts b/services/mcp/tests/unit/mcp-cache.test.ts
index 38b005165422..41aaf4ef0cce 100644
--- a/services/mcp/tests/unit/mcp-cache.test.ts
+++ b/services/mcp/tests/unit/mcp-cache.test.ts
@@ -6,13 +6,14 @@ import type { State } from '@/tools/types'
const mockCaptureException = vi.fn()
-vi.mock('@/lib/analytics', () => ({
+vi.mock('@/lib/posthog', () => ({
getPostHogClient: () => ({
captureException: mockCaptureException,
capture: vi.fn(),
}),
+}))
+vi.mock('@/lib/posthog/analytics', () => ({
AnalyticsEvent: {},
- generateId: () => 'test-id',
}))
// Extracted getOrFetchCached logic matching MCP.getOrFetchCached exactly,
@@ -28,7 +29,7 @@ async function getOrFetchCached<D extends keyof State, T extends keyof State>(de
fetcher: () => Promise<State[D]>
}
}): Promise<State[D] | undefined> {
- const { getPostHogClient } = await import('@/lib/analytics')
+ const { getPostHogClient } = await import('@/lib/posthog')
const { cache, waitUntil, cacheTtlMs, opts } = deps
try {
diff --git a/services/mcp/tests/unit/mcpcat.test.ts b/services/mcp/tests/unit/mcpcat.test.ts
deleted file mode 100644
index b94eb47004c4..000000000000
--- a/services/mcp/tests/unit/mcpcat.test.ts
+++ /dev/null
@@ -1,289 +0,0 @@
-import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
-import { env } from 'cloudflare:workers'
-import { track } from 'mcpcat'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-
-import { initMcpCatObservability, redactSensitiveInformation, type McpCatIdentityProvider } from '@/lib/mcpcat'
-
-const TEST_API_KEY = 'test-api-key'
-const TEST_HOST = 'https://test.posthog.com'
-
-describe('redactSensitiveInformation', () => {
- it.each([
- // PostHog project tokens
- ['Bearer phc_1a2b3c4d5e6f', '<redacted>'],
- // PostHog personal API keys
- ['Bearer phx_9z8y7x6w5v4u', '<redacted>'],
- // OAuth access and refresh tokens
- ['Bearer pha_access_token_value', '<redacted>'],
- ['Bearer phr_refresh_token_value', '<redacted>'],
- // Inside JSON strings
- ['"Authorization": "Bearer phc_abc123"', '"Authorization": "<redacted>"'],
- // Tokens with hyphens and dots (just in case we add them)
- ['Bearer phc_abc-123.xyz', '<redacted>'],
- // Multiple tokens
- ['Bearer phc_token1 and Bearer pha_token2', '<redacted> and <redacted>'],
- // No space after Bearer
- ['Bearerphc_no_space', '<redacted>'],
- // No match
- ['no sensitive data here', 'no sensitive data here'],
- ])('redacts %j to %j', (input, expected) => {
- expect(redactSensitiveInformation(input)).toBe(expected)
- })
-})
-
-describe('initMcpCatObservability', () => {
- beforeEach(() => {
- vi.mocked(track).mockClear()
- env.POSTHOG_ANALYTICS_API_KEY = TEST_API_KEY
- env.POSTHOG_ANALYTICS_HOST = TEST_HOST
- })
-
- function createMockIdentity(overrides: Partial<McpCatIdentityProvider> = {}): McpCatIdentityProvider {
- 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'),
- 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'),
- getMcpVersion: vi.fn().mockResolvedValue(2),
- 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 getIdentifyCallback(): () => Promise<unknown> {
- const call = vi.mocked(track).mock.calls[0]!
- const options = call[2] as { identify: () => Promise<unknown> }
- return options.identify
- }
-
- function getEventTagsCallback(): () => Promise<Record<string, string>> {
- const call = vi.mocked(track).mock.calls[0]!
- const options = call[2] as { eventTags: () => Promise<Record<string, string>> }
- return options.eventTags
- }
-
- function getEventPropertiesCallback(): () => Promise<Record<string, unknown>> {
- const call = vi.mocked(track).mock.calls[0]!
- const options = call[2] as { eventProperties: () => Promise<Record<string, unknown>> }
- return options.eventProperties
- }
-
- it('calls mcpcat.track with null projectId and correct options', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- await initMcpCatObservability(server, identity)
-
- expect(track).toHaveBeenCalledWith(
- server,
- null,
- expect.objectContaining({
- enableReportMissing: false,
- enableToolCallContext: false,
- enableTracing: true,
- identify: expect.any(Function),
- eventTags: expect.any(Function),
- eventProperties: expect.any(Function),
- exporters: {
- posthog: {
- type: 'posthog',
- apiKey: TEST_API_KEY,
- host: TEST_HOST,
- enableAITracing: true,
- },
- },
- })
- )
- })
-
- it('skips initialization when POSTHOG_ANALYTICS_API_KEY is not set', async () => {
- env.POSTHOG_ANALYTICS_API_KEY = undefined as unknown as string
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- await initMcpCatObservability(server, identity)
- expect(track).not.toHaveBeenCalled()
- })
-
- it('skips initialization when POSTHOG_ANALYTICS_HOST is not set', async () => {
- env.POSTHOG_ANALYTICS_HOST = undefined as unknown as string
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- await initMcpCatObservability(server, identity)
- expect(track).not.toHaveBeenCalled()
- })
-
- it('identify callback resolves identity from provider', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- await initMcpCatObservability(server, identity)
-
- const result = await getIdentifyCallback()()
- expect(result).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 initMcpCatObservability(server, identity)
-
- const result = await getEventTagsCallback()()
- expect(result).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 initMcpCatObservability(server, identity)
-
- const result = await getEventTagsCallback()()
- expect(result).toEqual({})
- })
-
- type EventPropertiesCase = {
- name: string
- overrides: Partial<McpCatIdentityProvider>
- expected: Record<string, unknown>
- }
-
- it.each<EventPropertiesCase>([
- {
- name: 'full identity + full analytics context emits $groups for org + project',
- overrides: {},
- expected: {
- ai_product: 'mcp',
- mcp_version: 2,
- client_user_agent: 'test-agent/1.0',
- mcp_client_name: 'claude-code',
- mcp_client_version: '1.2.3',
- mcp_protocol_version: '2024-11-05',
- mcp_region: 'us',
- organization_id: 'org-789',
- project_id: 'proj-101',
- project_uuid: 'proj-uuid-101',
- project_name: 'Project 101',
- mcp_oauth_client_name: 'PostHog Code',
- 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',
- },
- },
- },
- {
- name: 'organization-only analytics context emits a single $groups key',
- overrides: {
- getAnalyticsContext: vi.fn().mockResolvedValue({ organizationId: 'org-789' }),
- },
- expected: {
- ai_product: 'mcp',
- mcp_version: 2,
- client_user_agent: 'test-agent/1.0',
- mcp_client_name: 'claude-code',
- mcp_client_version: '1.2.3',
- mcp_protocol_version: '2024-11-05',
- mcp_region: 'us',
- organization_id: 'org-789',
- project_id: undefined,
- project_uuid: undefined,
- project_name: undefined,
- mcp_oauth_client_name: 'PostHog Code',
- 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' },
- },
- },
- {
- name: 'no analytics context omits $groups entirely',
- overrides: {
- getMcpVersion: vi.fn().mockResolvedValue(undefined),
- getClientUserAgent: vi.fn().mockResolvedValue(undefined),
- getMcpClientName: vi.fn().mockResolvedValue(undefined),
- getMcpClientVersion: vi.fn().mockResolvedValue(undefined),
- getMcpProtocolVersion: vi.fn().mockResolvedValue(undefined),
- getRegion: vi.fn().mockResolvedValue(undefined),
- getAnalyticsContext: vi.fn().mockResolvedValue(undefined),
- getOAuthClientName: vi.fn().mockResolvedValue(undefined),
- getReadOnly: vi.fn().mockResolvedValue(undefined),
- getTransport: vi.fn().mockResolvedValue(undefined),
- getMcpConsumer: vi.fn().mockResolvedValue(undefined),
- getMcpMode: vi.fn().mockResolvedValue(undefined),
- getMcpSessionId: vi.fn().mockResolvedValue(undefined),
- getMcpConversationId: vi.fn().mockResolvedValue(undefined),
- },
- expected: {
- ai_product: 'mcp',
- mcp_version: undefined,
- client_user_agent: undefined,
- mcp_client_name: undefined,
- mcp_client_version: undefined,
- mcp_protocol_version: undefined,
- mcp_region: undefined,
- organization_id: undefined,
- project_id: undefined,
- project_uuid: undefined,
- project_name: undefined,
- mcp_oauth_client_name: undefined,
- read_only: undefined,
- mcp_transport: undefined,
- mcp_consumer: undefined,
- mcp_mode: undefined,
- mcp_session_id: undefined,
- mcp_conversation_id: undefined,
- },
- },
- ])('eventProperties: $name', async ({ overrides, expected }) => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity(overrides)
-
- await initMcpCatObservability(server, identity)
-
- const result = await getEventPropertiesCallback()()
- expect(result).toEqual(expected)
- })
-
- it('swallows errors if mcpcat.track throws', async () => {
- const server = new McpServer({ name: 'test', version: '1.0.0' })
- const identity = createMockIdentity()
-
- vi.mocked(track).mockImplementationOnce(() => {
- throw new Error('mcpcat init failed')
- })
-
- await expect(initMcpCatObservability(server, identity)).resolves.toBeUndefined()
- })
-})
diff --git a/services/mcp/tests/unit/permission-errors.test.ts b/services/mcp/tests/unit/permission-errors.test.ts
index 66700ee9aac3..0d6effcb0a59 100644
--- a/services/mcp/tests/unit/permission-errors.test.ts
+++ b/services/mcp/tests/unit/permission-errors.test.ts
@@ -17,11 +17,13 @@ vi.mock('@/api/rate-limiter', () => ({
}))
const captureException = vi.fn()
-vi.mock('@/lib/analytics', () => ({
- getPostHogClient: () => ({
- captureException,
- }),
+vi.mock('@/lib/posthog', () => ({
+ getPostHogClient: () => ({ captureException }),
+}))
+vi.mock('@/lib/posthog/analytics', () => ({
AnalyticsEvent: { MCP_INIT: 'mcp init' },
+}))
+vi.mock('@/lib/posthog/flags', () => ({
isFeatureFlagEnabled: vi.fn().mockResolvedValue(false),
}))
diff --git a/services/mcp/tests/unit/posthog-mcp-analytics.test.ts b/services/mcp/tests/unit/posthog/analytics.test.ts
similarity index 74%
rename from services/mcp/tests/unit/posthog-mcp-analytics.test.ts
rename to services/mcp/tests/unit/posthog/analytics.test.ts
index 00a83de4d502..91f0cba0a2c2 100644
--- a/services/mcp/tests/unit/posthog-mcp-analytics.test.ts
+++ b/services/mcp/tests/unit/posthog/analytics.test.ts
@@ -4,21 +4,72 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { track } from '@posthog/mcp-analytics'
-import { initPostHogMcpAnalytics, type PostHogMcpAnalyticsIdentityProvider } from '@/lib/posthog-mcp-analytics'
+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('initPostHogMcpAnalytics', () => {
+describe('buildMCPAnalyticsGroups', () => {
+ it.each<[string, MCPAnalyticsContext, Record<string, string>]>([
+ [
+ 'full context uses UUID as the project group key',
+ { organizationId: 'org-1', projectId: '123', projectUuid: 'project-uuid-123' },
+ { organization: 'org-1', project: 'project-uuid-123' },
+ ],
+ ['organization only', { organizationId: 'org-1' }, { organization: 'org-1' }],
+ ['project UUID only', { projectUuid: 'project-uuid-123' }, { project: 'project-uuid-123' }],
+ ['ignores projectId when projectUuid is absent', { projectId: '123' }, {}],
+ ['empty context', {}, {}],
+ ])('%s', (_, input, expected) => {
+ expect(buildMCPAnalyticsGroups(input)).toEqual(expected)
+ })
+})
+
+describe('buildMCPContextProperties', () => {
+ it.each<[string, MCPAnalyticsContext, { prefix?: string } | undefined, Record<string, string>]>([
+ [
+ 'full context → snake_case properties',
+ {
+ organizationId: 'org-1',
+ projectId: '123',
+ projectUuid: 'project-uuid-123',
+ projectName: 'My Project',
+ },
+ undefined,
+ {
+ organization_id: 'org-1',
+ project_id: '123',
+ project_uuid: 'project-uuid-123',
+ project_name: 'My Project',
+ },
+ ],
+ [
+ 'prefix applies to every key (used for previous_* on context-switch events)',
+ { organizationId: 'org-1', projectUuid: 'project-uuid-123' },
+ { prefix: 'previous_' },
+ { previous_organization_id: 'org-1', previous_project_uuid: 'project-uuid-123' },
+ ],
+ ['empty context yields empty object', {}, undefined, {}],
+ [
+ 'partial context omits absent keys rather than emitting undefined',
+ { organizationId: 'org-1' },
+ undefined,
+ { organization_id: 'org-1' },
+ ],
+ ])('%s', (_, input, options, expected) => {
+ 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<PostHogMcpAnalyticsIdentityProvider> = {}
- ): PostHogMcpAnalyticsIdentityProvider {
+ function createMockIdentity(overrides: Partial<IdentityProvider> = {}): IdentityProvider {
return {
getDistinctId: vi.fn().mockResolvedValue('user-123'),
getSessionUuid: vi.fn().mockResolvedValue('session-uuid-456'),
@@ -46,13 +97,13 @@ describe('initPostHogMcpAnalytics', () => {
}
function getTrackOptions(): {
- identify: () => Promise<unknown>
+ 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: () => Promise<unknown>
+ identify: { userId: string }
eventTags: () => Promise<Record<string, string>>
eventProperties: (request?: unknown) => Promise<Record<string, unknown>>
}
@@ -62,39 +113,29 @@ describe('initPostHogMcpAnalytics', () => {
const server = new McpServer({ name: 'test', version: '1.0.0' })
const identity = createMockIdentity()
- const result = await initPostHogMcpAnalytics(server, identity)
+ const result = await initMcpAnalytics(server, identity)
expect(track).toHaveBeenCalledWith(
server,
expect.objectContaining({
- apiKey: TEST_API_KEY,
+ posthogClient: expect.any(Object),
context: false,
enableAITracing: true,
enableTracing: true,
- host: TEST_HOST,
- identify: expect.any(Function),
+ identify: expect.objectContaining({ userId: expect.any(String) }),
eventTags: expect.any(Function),
eventProperties: expect.any(Function),
- posthogOptions: {
- flushAt: 1,
- flushInterval: 0,
- host: TEST_HOST,
- },
reportMissing: false,
})
)
- expect(result).toMatchObject({
- action: 'initialized',
- contextEnabled: false,
- reportMissingEnabled: 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 initPostHogMcpAnalytics(server, identity, {
+ const result = await initMcpAnalytics(server, identity, {
contextEnabled: true,
reportMissingEnabled: false,
})
@@ -107,18 +148,14 @@ describe('initPostHogMcpAnalytics', () => {
reportMissing: false,
})
)
- expect(result).toMatchObject({
- action: 'initialized',
- contextEnabled: true,
- reportMissingEnabled: 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 initPostHogMcpAnalytics(server, identity, {
+ const result = await initMcpAnalytics(server, identity, {
contextEnabled: false,
reportMissingEnabled: true,
})
@@ -129,10 +166,7 @@ describe('initPostHogMcpAnalytics', () => {
reportMissing: true,
})
)
- expect(result).toMatchObject({
- action: 'initialized',
- reportMissingEnabled: true,
- })
+ expect(result).toMatchObject({ action: 'initialized' })
})
it.each(['POSTHOG_ANALYTICS_API_KEY', 'POSTHOG_ANALYTICS_HOST'] as const)(
@@ -142,7 +176,7 @@ describe('initPostHogMcpAnalytics', () => {
const server = new McpServer({ name: 'test', version: '1.0.0' })
const identity = createMockIdentity()
- const result = await initPostHogMcpAnalytics(server, identity)
+ const result = await initMcpAnalytics(server, identity)
expect(track).not.toHaveBeenCalled()
expect(result).toMatchObject({ action: 'skipped', reason: 'missing_config' })
@@ -153,16 +187,16 @@ describe('initPostHogMcpAnalytics', () => {
const server = new McpServer({ name: 'test', version: '1.0.0' })
const identity = createMockIdentity()
- await initPostHogMcpAnalytics(server, identity)
+ await initMcpAnalytics(server, identity)
- expect(await getTrackOptions().identify()).toEqual({ userId: 'user-123' })
+ 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 initPostHogMcpAnalytics(server, identity)
+ await initMcpAnalytics(server, identity)
expect(await getTrackOptions().eventTags()).toEqual({
$session_id: 'session-uuid-456',
@@ -176,7 +210,7 @@ describe('initPostHogMcpAnalytics', () => {
getSessionUuid: vi.fn().mockResolvedValue(undefined),
})
- await initPostHogMcpAnalytics(server, identity)
+ await initMcpAnalytics(server, identity)
expect(await getTrackOptions().eventTags()).toEqual({})
})
@@ -185,7 +219,7 @@ describe('initPostHogMcpAnalytics', () => {
const server = new McpServer({ name: 'test', version: '1.0.0' })
const identity = createMockIdentity()
- await initPostHogMcpAnalytics(server, identity)
+ await initMcpAnalytics(server, identity)
expect(await getTrackOptions().eventProperties()).toEqual({
$ai_product: 'mcp',
@@ -239,7 +273,7 @@ describe('initPostHogMcpAnalytics', () => {
const identity = createMockIdentity()
const resolveExecInnerToolCall = vi.fn().mockReturnValue(resolverReturn)
- await initPostHogMcpAnalytics(server, identity, {
+ await initMcpAnalytics(server, identity, {
contextEnabled: false,
reportMissingEnabled: false,
resolveExecInnerToolCall,
@@ -263,7 +297,7 @@ describe('initPostHogMcpAnalytics', () => {
const server = new McpServer({ name: 'test', version: '1.0.0' })
const identity = createMockIdentity()
- await initPostHogMcpAnalytics(server, identity)
+ await initMcpAnalytics(server, identity)
const properties = await getTrackOptions().eventProperties({
params: { name: 'exec', arguments: { command: 'call execute-sql {}' } },
@@ -278,7 +312,7 @@ describe('initPostHogMcpAnalytics', () => {
const identity = createMockIdentity()
const execInnerToolNames = ['execute-sql', 'feature-flag-get-all', 'insight-get']
- await initPostHogMcpAnalytics(server, identity, {
+ await initMcpAnalytics(server, identity, {
contextEnabled: false,
reportMissingEnabled: false,
execInnerToolNames,
@@ -296,13 +330,16 @@ describe('initPostHogMcpAnalytics', () => {
const server = new McpServer({ name: 'test', version: '1.0.0' })
const identity = createMockIdentity()
- await initPostHogMcpAnalytics(server, identity, {
+ 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 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')
@@ -312,7 +349,7 @@ describe('initPostHogMcpAnalytics', () => {
const server = new McpServer({ name: 'test', version: '1.0.0' })
const identity = createMockIdentity()
- await initPostHogMcpAnalytics(server, identity, {
+ await initMcpAnalytics(server, identity, {
contextEnabled: false,
reportMissingEnabled: false,
execInnerToolNames: [],
@@ -329,7 +366,7 @@ describe('initPostHogMcpAnalytics', () => {
getAnalyticsContext: vi.fn().mockResolvedValue(undefined),
})
- await initPostHogMcpAnalytics(server, identity)
+ await initMcpAnalytics(server, identity)
const properties = await getTrackOptions().eventProperties()
expect(properties.$groups).toBeUndefined()
@@ -345,7 +382,7 @@ describe('initPostHogMcpAnalytics', () => {
throw new Error('PostHog MCP analytics init failed')
})
- await expect(initPostHogMcpAnalytics(server, identity)).resolves.toMatchObject({ action: 'failed' })
+ await expect(initMcpAnalytics(server, identity)).resolves.toMatchObject({ action: 'failed' })
})
it('swallows errors if analytics identity resolution throws', async () => {
@@ -354,7 +391,7 @@ describe('initPostHogMcpAnalytics', () => {
getDistinctId: vi.fn().mockRejectedValue(new Error('identity unavailable')),
})
- await expect(initPostHogMcpAnalytics(server, identity)).resolves.toMatchObject({ action: 'failed' })
+ await expect(initMcpAnalytics(server, identity)).resolves.toMatchObject({ action: 'failed' })
expect(track).not.toHaveBeenCalled()
})
})
diff --git a/services/mcp/tests/workers/token-rotation.test.ts b/services/mcp/tests/workers/token-rotation.test.ts
index 9f764b2e6d2c..1c6eeed1e751 100644
--- a/services/mcp/tests/workers/token-rotation.test.ts
+++ b/services/mcp/tests/workers/token-rotation.test.ts
@@ -17,8 +17,8 @@ import type { MCP } from '@/mcp'
// `rotateCachedApiToken` primitive, so warm-setName coverage is handled by the
// unit tests in `tests/unit/mcp-api-caching.test.ts` — attempting to exercise
// it end-to-end here would require full cold-start `init()` to complete, which
-// pulls in every PostHog endpoint + context-mill + MCPCat and is better
-// covered at the HTTP layer in a future test.
+// pulls in every PostHog endpoint + context-mill + PostHog MCP analytics and
+// is better covered at the HTTP layer in a future test.
const propsFor = (apiToken: string): { userHash: string; apiToken: string; clientUserAgent: string } => ({
userHash: 'user-hash',
diff --git a/services/mcp/types.d.ts b/services/mcp/types.d.ts
index e46f54a24b74..59148819c25f 100644
--- a/services/mcp/types.d.ts
+++ b/services/mcp/types.d.ts
@@ -1,10 +1,3 @@
-// Custom optional environment variables not generated by Wrangler
-declare namespace Cloudflare {
- interface Env {
- MCP_CAT_PROJECT_ID: string | undefined
- }
-}
-
// ioredis v4 ships without bundled type declarations. We only use the default
// export (constructor) — typed loosely as `any` so TS can still check call sites
// that interact with it via the local `RedisLike` interface.
diff --git a/services/mcp/vitest.workers.config.mts b/services/mcp/vitest.workers.config.mts
index a562f026754d..e7ff763f88f1 100644
--- a/services/mcp/vitest.workers.config.mts
+++ b/services/mcp/vitest.workers.config.mts
@@ -35,7 +35,6 @@ export default defineWorkersProject({
POSTHOG_ANALYTICS_HOST: '',
POSTHOG_MCP_APPS_ANALYTICS_BASE_URL: '',
POSTHOG_UI_APPS_TOKEN: '',
- MCP_CAT_PROJECT_ID: '',
// Generic test marker. Code can short-circuit features
// that need real network (e.g. context-mill GitHub
// fetch in src/resources/index.ts).