: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): respect project test account filter default in query tools (#69576)
Thomas Obermüllerb876bd975285
diff --git a/services/mcp/src/lib/instructions.ts b/services/mcp/src/lib/instructions.tsindex e18c444bebc7..1c746442ae38 100644--- a/services/mcp/src/lib/instructions.ts+++ b/services/mcp/src/lib/instructions.ts@@ -43,6 +43,11 @@ export function buildActiveEnvironmentContextPrompt(}if (project) {lines.push(`Project timezone: ${project.timezone ?? 'UTC'}.`)+ if (project.test_account_filters_default_checked) {+ lines.push(+ 'This project filters out internal and test users by default. `query-*` tools apply this automatically when `filterTestAccounts` is omitted; when composing queries for other tools (e.g. insight-create), set `filterTestAccounts: true` unless the user asks to include internal/test data.'+ )+ }const poeValue = project.person_on_events_querying_enabled as string | boolean | null | undefinedif (poeValue === true || poeValue === 'true') {lines.push(diff --git a/services/mcp/src/schema/query.ts b/services/mcp/src/schema/query.tsindex 15595045e28c..2b4526f7d7b1 100644--- a/services/mcp/src/schema/query.ts+++ b/services/mcp/src/schema/query.ts@@ -167,7 +167,9 @@ const AnyEntityNode = EventsNode// Base query interfaceconst InsightsQueryBase = z.object({dateRange: DateRange.optional(),- filterTestAccounts: z.boolean().optional().default(false),+ // No hard default: omission lets the project's "Filter out internal and test+ // users" default setting apply, matching UI behavior for new insights.+ filterTestAccounts: z.boolean().optional(),properties: z.union([z.array(AnyPropertyFilter), PropertyGroupFilter]).optional()diff --git a/services/mcp/src/tools/query-wrapper-factory.ts b/services/mcp/src/tools/query-wrapper-factory.tsindex ef2a8f3bdd36..409d0a5aa942 100644--- a/services/mcp/src/tools/query-wrapper-factory.ts+++ b/services/mcp/src/tools/query-wrapper-factory.ts@@ -23,6 +23,47 @@ interface QueryWrapperConfig<T extends ZodObjectAny> {urlPrefix?: string}+const TEST_ACCOUNT_FILTER_FIELD = 'filterTestAccounts'++function hasTestAccountFilterField(schema: ZodObjectAny): schema is z.ZodObject<z.ZodRawShape> {+ return schema instanceof z.ZodObject && TEST_ACCOUNT_FILTER_FIELD in schema.shape+}++/**+ * Most generated query schemas hard-default `filterTestAccounts` to `false`, which+ * silently ignores the project's "Filter out internal and test users" default+ * (`test_account_filters_default_checked`) that the UI applies to every new+ * insight. Stripping the schema default lets an omitted value survive validation+ * as `undefined`, so the handler can fill in the project default instead. An+ * explicit `filterTestAccounts` from the caller always wins.+ *+ * Only a `false` default is stripped: a schema that defaults the field to `true`+ * (e.g. AssistantTracesQuery) is an intentional stricter product default, and+ * replacing it would flip its queries to unfiltered on projects where the+ * setting is unchecked.+ */+function withoutTestAccountFilterDefault<T extends ZodObjectAny>(schema: T): T {+ if (!hasTestAccountFilterField(schema)) {+ return schema+ }+ // `ZodRawShape` values are typed as core `$ZodType`, which hides `safeParse`.+ const field = schema.shape[TEST_ACCOUNT_FILTER_FIELD] as z.ZodType+ const omittedValue = field.safeParse(undefined)+ if (!omittedValue.success || omittedValue.data !== false) {+ return schema+ }+ return schema.extend({+ // Strict boolean, not `z.coerce.boolean()`: coercion turns the string+ // `"false"` into `true`, which would silently flip query semantics.+ [TEST_ACCOUNT_FILTER_FIELD]: z+ .boolean()+ .optional()+ .describe(+ 'Exclude internal and test users by applying the respective filters. When omitted, follows the project\'s "Filter out internal and test users" default setting.'+ ),+ }) as unknown as T+}+function buildInsightUrl(kind: 'InsightVizNode' | 'DataTableNode',query: Record<string, unknown>,@@ -37,12 +78,16 @@ function buildInsightUrl(}export function createQueryWrapper<T extends ZodObjectAny>(config: QueryWrapperConfig<T>): () => ToolBase<T> {+ // Both the advertised tool schema and the handler's re-parse must use the+ // stripped schema — parsing with the original would re-apply the `false`+ // default and make omission indistinguishable from an explicit `false`.+ const schema = withoutTestAccountFilterDefault(config.schema)return () => ({name: config.name,- schema: config.schema,+ schema,handler: async (context: Context, rawParams: z.infer<T>) => {const projectId = await context.stateManager.getProjectId()- const params = config.schema.parse(rawParams)+ const params = schema.parse(rawParams)// `output_format` is a tool-level control, not part of the query body. Strip it before// POSTing so it doesn't leak into the backend `kind: ...Query` payload.const { output_format: callerOutputFormat, ...queryParams } = params as typeof params & {@@ -52,6 +97,14 @@ export function createQueryWrapper<T extends ZodObjectAny>(config: QueryWrapperC...queryParams,kind: config.kind,}+ if (hasTestAccountFilterField(schema) && query[TEST_ACCOUNT_FILTER_FIELD] === undefined) {+ const project = await context.stateManager.getCachedOrFetchProject().catch(() => undefined)+ // Only inject `true`: when the project default is unchecked the field+ // stays omitted and the backend's own `false` default applies.+ if (project?.test_account_filters_default_checked) {+ query[TEST_ACCOUNT_FILTER_FIELD] = true+ }+ }const baseUrl = context.api.getProjectBaseUrl(projectId)const effectiveOutputFormat = callerOutputFormat ?? config.outputFormatdiff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-funnel.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-funnel.jsonindex a98b29e24853..7fb8b474722c 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-funnel.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-funnel.json@@ -81,8 +81,7 @@"description": "Date range for the query"},"filterTestAccounts": {- "default": false,- "description": "Exclude internal and test users by applying the respective filters",+ "description": "Exclude internal and test users by applying the respective filters. When omitted, follows the project's \"Filter out internal and test users\" default setting.","type": "boolean"},"funnelsFilter": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-lifecycle.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-lifecycle.jsonindex 2405216b84b1..4dd4272f3752 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-lifecycle.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-lifecycle.json@@ -51,8 +51,7 @@"description": "Date range for the query"},"filterTestAccounts": {- "default": false,- "description": "Exclude internal and test users by applying the respective filters",+ "description": "Exclude internal and test users by applying the respective filters. When omitted, follows the project's \"Filter out internal and test users\" default setting.","type": "boolean"},"interval": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-paths.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-paths.jsonindex dd976a240bd2..29e2a9e19bc1 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-paths.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-paths.json@@ -51,8 +51,7 @@"description": "Date range for the query"},"filterTestAccounts": {- "default": false,- "description": "Exclude internal and test users by applying the respective filters",+ "description": "Exclude internal and test users by applying the respective filters. When omitted, follows the project's \"Filter out internal and test users\" default setting.","type": "boolean"},"kind": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-retention.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-retention.jsonindex 581a2975cf83..25b6d6d22291 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-retention.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-retention.json@@ -51,8 +51,7 @@"description": "Date range for the query"},"filterTestAccounts": {- "default": false,- "description": "Exclude internal and test users by applying the respective filters",+ "description": "Exclude internal and test users by applying the respective filters. When omitted, follows the project's \"Filter out internal and test users\" default setting.","type": "boolean"},"kind": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-stickiness.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-stickiness.jsonindex 6738f5ec9b30..730288df853d 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-stickiness.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-stickiness.json@@ -66,8 +66,7 @@"description": "Date range for the query"},"filterTestAccounts": {- "default": false,- "description": "Exclude internal and test users by applying the respective filters",+ "description": "Exclude internal and test users by applying the respective filters. When omitted, follows the project's \"Filter out internal and test users\" default setting.","type": "boolean"},"interval": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.jsonindex a5f31e1ae4c0..a9487a4d8b2b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json@@ -145,8 +145,7 @@"description": "Date range for the query"},"filterTestAccounts": {- "default": false,- "description": "Exclude internal and test users by applying the respective filters",+ "description": "Exclude internal and test users by applying the respective filters. When omitted, follows the project's \"Filter out internal and test users\" default setting.","type": "boolean"},"interval": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-overview.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-overview.jsonindex ede39df21a7a..6be9beb46fd0 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-overview.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-overview.json@@ -90,8 +90,7 @@"type": "boolean"},"filterTestAccounts": {- "default": false,- "description": "Exclude internal and test users by applying the team's test-account filter.",+ "description": "Exclude internal and test users by applying the respective filters. When omitted, follows the project's \"Filter out internal and test users\" default setting.","type": "boolean"},"kind": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-stats.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-stats.jsonindex faf5d61e3635..e6ee7d5d1a9a 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-stats.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-web-stats.json@@ -121,8 +121,7 @@"type": "boolean"},"filterTestAccounts": {- "default": false,- "description": "Exclude internal and test users by applying the team's test-account filter.",+ "description": "Exclude internal and test users by applying the respective filters. When omitted, follows the project's \"Filter out internal and test users\" default setting.","type": "boolean"},"includeAvgTimeOnPage": {diff --git a/services/mcp/tests/unit/instructions.test.ts b/services/mcp/tests/unit/instructions.test.tsindex 9a494989b8c5..1f94bfa2d980 100644--- a/services/mcp/tests/unit/instructions.test.ts+++ b/services/mcp/tests/unit/instructions.test.ts@@ -296,6 +296,18 @@ describe('buildActiveEnvironmentContextPrompt', () => {expect(buildActiveEnvironmentContextPrompt(undefined, undefined, undefined)).toBeUndefined()})+ it.each([+ ['checked', true, true],+ ['unchecked', false, false],+ ['unset', undefined, false],+ ])('surfaces the test account filter default only when %s', (_name, testAccountFiltersDefaultChecked, expected) => {+ const result = buildActiveEnvironmentContextPrompt(user, org, {+ ...project,+ test_account_filters_default_checked: testAccountFiltersDefaultChecked,+ } as CachedProject)+ expect((result ?? '').includes('filters out internal and test users by default')).toBe(expected)+ })+it('still renders an "Unknown" project when org is present but project is missing', () => {// The org branch is unchanged — only the no-org branch was added.const result = buildActiveEnvironmentContextPrompt(user, org, undefined)diff --git a/services/mcp/tests/unit/query-wrapper-factory.test.ts b/services/mcp/tests/unit/query-wrapper-factory.test.tsindex 3add14e4a249..83ff30a7edc0 100644--- a/services/mcp/tests/unit/query-wrapper-factory.test.ts+++ b/services/mcp/tests/unit/query-wrapper-factory.test.ts@@ -306,6 +306,92 @@ describe('createQueryWrapper output_format handling', () => {})})+describe('createQueryWrapper filterTestAccounts project default', () => {+ // Mirrors the generated wrapper schemas: most default `filterTestAccounts`+ // to false (which the factory must strip so omission can follow the project+ // setting), AssistantTracesQuery to true (an intentional stricter default+ // the factory must keep).+ function makeSchema(schemaDefault: boolean): z.ZodObject<z.ZodRawShape> {+ return z.object({+ series: z.array(z.object({ kind: z.string(), event: z.string() })),+ filterTestAccounts: z.coerce+ .boolean()+ .describe('Exclude internal and test users by applying the respective filters')+ .default(schemaDefault)+ .optional(),+ })+ }+ const series = [{ kind: 'EventsNode', event: '$pageview' }]++ function createMockContext(+ runQuery: ReturnType<typeof vi.fn>,+ testAccountFiltersDefaultChecked: boolean | undefined+ ): Context {+ return {+ api: {+ query: vi.fn().mockReturnValue({ runQuery }),+ getProjectBaseUrl: vi.fn().mockReturnValue('http://localhost:8010/project/1'),+ },+ stateManager: {+ getProjectId: vi.fn().mockResolvedValue('1'),+ getCachedOrFetchProject: vi+ .fn()+ .mockResolvedValue({ test_account_filters_default_checked: testAccountFiltersDefaultChecked }),+ },+ } as unknown as Context+ }++ it.each([+ ['omitted follows a checked project default', false, {}, true, true],+ ['omitted stays unset when the project default is unchecked', false, {}, false, undefined],+ ['explicit false wins over a checked project default', false, { filterTestAccounts: false }, true, false],+ ['explicit true wins over an unchecked project default', false, { filterTestAccounts: true }, false, true],+ ['an intentional true schema default survives an unchecked project default', true, {}, false, true],+ [+ 'explicit false wins over an intentional true schema default',+ true,+ { filterTestAccounts: false },+ true,+ false,+ ],+ ] as const)('%s', async (_name, schemaDefault, inputExtra, projectDefault, expected) => {+ const runQuery = vi.fn().mockResolvedValue({ results: [] })+ const context = createMockContext(runQuery, projectDefault)+ const tool = createQueryWrapper({ name: 'test', schema: makeSchema(schemaDefault), kind: 'TrendsQuery' })()++ // Validate through the tool's advertised schema first, exactly like the+ // executor does — this is where a hard default would clobber omission.+ await tool.handler(context, tool.schema.parse({ series, ...inputExtra }))++ expect(runQuery.mock.calls[0]![0].query.filterTestAccounts).toBe(expected)+ })++ it.each(['false', 'true'])(+ 'rejects the string %j rather than coercing it to a boolean',+ (stringValue) => {+ const tool = createQueryWrapper({ name: 'test', schema: makeSchema(false), kind: 'TrendsQuery' })()++ // The generated schemas use z.coerce.boolean(), which would turn "false"+ // into true; the stripped replacement must be a strict boolean so a+ // malformed value is rejected instead of silently flipping filtering.+ expect(tool.schema.safeParse({ series, filterTestAccounts: stringValue }).success).toBe(false)+ }+ )++ it('does not inject the field into schemas that lack it', async () => {+ const runQuery = vi.fn().mockResolvedValue({ results: [] })+ const context = createMockContext(runQuery, true)+ const schemaWithoutFilter = z.object({+ series: z.array(z.object({ kind: z.string(), event: z.string() })),+ })+ const tool = createQueryWrapper({ name: 'test', schema: schemaWithoutFilter, kind: 'WebOverviewQuery' })()++ await tool.handler(context, tool.schema.parse({ series }))++ expect(runQuery.mock.calls[0]![0].query).not.toHaveProperty('filterTestAccounts')+ })+})+describe('createQueryWrapper actors dispatch', () => {function createMockContext(): Context {return {