:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): keep project-switch calls on the project their flags were evaluated for (#123244)
posthog[bot]d9ea6ca2d6d2
diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.tsindex 7a099a5e88d9..8b23146ed948 100644--- a/services/mcp/src/hono/analytics.ts+++ b/services/mcp/src/hono/analytics.ts@@ -173,7 +173,7 @@ export async function trackToolCall(return}try {- const analyticsContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)+ const analyticsContext = state.analyticsContext ?? (await state.reqCtx.safelyGetAnalyticsContext(state.context))const requestContext = state.requestContextconst sessionUuid = await state.reqCtx.getEffectiveSessionUuid(requestContext)diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex 0a593fc25c21..39f51c59b186 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -5,7 +5,7 @@ import { env } from '@/lib/env'import { McpSessionResetRequiredError } from '@/lib/errors'import { EVENT_SOURCE, resolveEventSource } from '@/lib/event-source'import { MCP_NO_DATA_INSTALL_NOTICE_FLAG, type NoDataAction } from '@/lib/no-data-guard'-import { buildMCPAnalyticsGroups } from '@/lib/posthog/analytics'+import { buildMCPAnalyticsGroups, type MCPAnalyticsContext } from '@/lib/posthog/analytics'import {type EvaluatedFlags,evaluateFeatureFlags,@@ -63,6 +63,12 @@ export interface ResolvedState {isImpersonated?: booleansuppressAnalytics?: booleanprojectHasData?: boolean | undefined+ /**+ * The workspace context that the flags and `projectHasData` were resolved against.+ * A handler such as `switch-project` changes the live context, so tool-call analytics+ * read this snapshot to keep the project group consistent with the variant.+ */+ analyticsContext?: MCPAnalyticsContext | undefined/** Set on the per-call state when the no-data notice blocked or warned this call. */noDataAction?: NoDataAction | undefinedoauthClientId: string | undefined@@ -345,6 +351,7 @@ export class RequestStateResolver {isImpersonated: _apiKey?.is_impersonated === true,suppressAnalytics: props.suppressAnalytics,projectHasData: flagAnalyticsContext?.projectHasData,+ analyticsContext: flagAnalyticsContext,oauthClientId: oauthClientId || undefined,clientProfile,requestContext,diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.tsindex 5d4a9d80ef78..9db3b58c0af5 100644--- a/services/mcp/tests/hono/request-state-resolver.test.ts+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -609,12 +609,13 @@ describe('RequestStateResolver MCP client contexts', () => {[{ projectHasData: false }, false],[{ projectHasData: true }, true],[undefined, undefined],- ])('carries the project ingestion state from analytics context %j', async (analyticsContext, expectedHasData) => {+ ])('carries the analytics context and its ingestion state %j', async (analyticsContext, expectedHasData) => {mockAnalyticsContext.current = analyticsContextconst result = await makeResolver().resolve(makeProps())expect(result.projectHasData).toBe(expectedHasData)+ expect(result.analyticsContext).toBe(mockAnalyticsContext.current)})it.each([diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.tsindex 5e5a2b87741d..1a5313df8e01 100644--- a/services/mcp/tests/hono/tool-executor-intent.test.ts+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts@@ -34,6 +34,7 @@ import { toolCallsTotal } from '@/hono/metrics'import type { ResolvedState } from '@/hono/request-state-resolver'import { ToolCatalog } from '@/hono/tool-catalog'import { ToolExecutor } from '@/hono/tool-executor'+import { MCP_NO_DATA_INSTALL_NOTICE_FLAG } from '@/lib/no-data-guard'import { getPostHogClient } from '@/lib/posthog'import { MAX_CAPTURED_DESCRIPTION_LENGTH } from '@/tools/toolDefinitions'@@ -197,6 +198,68 @@ describe('ToolExecutor analytics capture', () => {expect(state.context.api.config.onPrivateResponse).toBeUndefined()})+ it.each(['direct', 'exec'])(+ 'keeps a %s switch-project call on the project its variant was evaluated for',+ async (mode) => {+ const capture = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})+ const source = { organizationId: 'org-1', projectId: '1', projectUuid: 'uuid-1', projectHasData: false }+ const destination = {+ organizationId: 'org-1',+ projectId: '2',+ projectUuid: 'uuid-2',+ projectHasData: false,+ }+ let active = source+ const tool = {+ name: 'switch-project',+ title: 'Switch project',+ description: 'Synthetic switch',+ scopes: [],+ annotations: { readOnlyHint: false },+ schema: z.object({ projectId: z.number() }),+ handler: async () => {+ active = destination+ return 'Switched to project 2'+ },+ }+ vi.spyOn(catalog, 'getToolByName').mockReturnValue({+ build: () => tool,+ meta: undefined,+ rawInputSchema: undefined,+ definition: undefined,+ })+ const baseState = makeToolExecutorState([tool], { suppressAnalytics: false })+ const state = makeToolExecutorState([tool], {+ useSingleExec: mode === 'exec',+ suppressAnalytics: false,+ analyticsContext: source,+ projectHasData: source.projectHasData,+ toolFeatureFlags: { [MCP_NO_DATA_INSTALL_NOTICE_FLAG]: 'warn' },+ reqCtx: { ...baseState.reqCtx, safelyGetAnalyticsContext: vi.fn(async () => active) } as any,+ })++ await executor.handleToolCall(+ mode === 'exec'+ ? { name: 'exec', arguments: { command: 'call switch-project {"projectId": 2}' } }+ : { name: tool.name, arguments: { projectId: 2 } },+ state+ )+ await new Promise((resolve) => setImmediate(resolve))++ expect(active).toBe(destination)+ expect(capture).toHaveBeenCalledOnce()+ const event = capture.mock.calls[0]![0]+ expect(event.toolName).toBe('switch-project')+ expect(event.groups).toEqual({ organization: 'org-1', project: 'uuid-1' })+ expect(event.properties).toMatchObject({+ $mcp_project_id: '1',+ mcp_project_has_data: false,+ mcp_no_data_action: 'none',+ [`$feature/${MCP_NO_DATA_INSTALL_NOTICE_FLAG}`]: 'warn',+ })+ }+ )+it.each([true, false])('isolates intent descriptions with single exec=%s', async (useSingleExec) => {const tool = catalog.getFilteredTools({ scopes: ['*'] }).find((entry) => entry.name === 'projects-get')!const state = makeToolExecutorState([tool], { useSingleExec })