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.

feat(mcp): let agents select activity-log response fields (#70340)

Yasen1d13637b4d9f
diff --git a/.agents/skills/implementing-mcp-tools/SKILL.md b/.agents/skills/implementing-mcp-tools/SKILL.md
index 848006795442..a5da2d48ea46 100644
--- a/.agents/skills/implementing-mcp-tools/SKILL.md
+++ b/.agents/skills/implementing-mcp-tools/SKILL.md
@@ -144,6 +144,8 @@ tools:
include: [id, key, name] # keep only these fields (dot-path wildcards supported)
exclude: [filters.groups.*.properties] # remove these fields
# include and exclude are mutually exclusive
+ selectable: true # add optional `fields` param so the agent picks a subset of `include` per call
+ # (constrained to the allowlist); omit `fields` to return the full set. Requires `include`.
feature_flag: my-flag-key # gate this tool behind a PostHog feature flag
feature_flag_behavior: enable # 'enable' (default) or 'disable'
```
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
index f2078c0db21c..7220f7327aee 100644
--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
@@ -240,6 +240,9 @@ Product teams own their definitions and control which operations are exposed as
include: [id, key, name] # keep only these fields (dot-path wildcards supported)
exclude: [filters.groups.*.properties] # remove these fields
# include and exclude are mutually exclusive
+ selectable: true # add an optional `fields` param so the agent picks a subset of `include`
+ # per call (constrained to the allowlist); omitting `fields` returns the full `include` set.
+ # Requires `include`. Use it to keep large responses (e.g. activity logs) small on demand.
input_schema: ActionCreateSchema # use a hand-crafted schema from tool-inputs (optional)
param_overrides: # override Orval-generated param descriptions or schemas
name:
diff --git a/products/platform_features/mcp/tools.yaml b/products/platform_features/mcp/tools.yaml
index e8e36df24e56..8cc666bf9926 100644
--- a/products/platform_features/mcp/tools.yaml
+++ b/products/platform_features/mcp/tools.yaml
@@ -45,7 +45,9 @@ tools:
List activity log entries — who changed what and when (feature flag changes, dashboard edits, experiment
launches, insight edits, etc.), with field-level diffs. Filter by scope, activity type, user, item, date
range, and free-text search. Use this to audit a specific resource's history or to see what changed recently
- across the project.
+ across the project. Responses can be large — pass `fields` to return only what your task needs (e.g.
+ `["user.email", "activity", "scope", "created_at"]` to see who changed what), and only request
+ `detail.changes` when you actually need the field-level diffs.
param_overrides:
page_size:
default: 10
@@ -66,6 +68,7 @@ tools:
- detail.type
- detail.changes
- created_at
+ selectable: true
approval-policies-create:
operation: approval_policies_create
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index c455d5e71008..cf2a56e6acae 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -370,7 +370,7 @@
"feature_entitlement": "audit_logs"
},
"advanced-activity-logs-list": {
- "description": "List activity log entries — who changed what and when (feature flag changes, dashboard edits, experiment launches, insight edits, etc.), with field-level diffs. Filter by scope, activity type, user, item, date range, and free-text search. Use this to audit a specific resource's history or to see what changed recently across the project.",
+ "description": "List activity log entries — who changed what and when (feature flag changes, dashboard edits, experiment launches, insight edits, etc.), with field-level diffs. Filter by scope, activity type, user, item, date range, and free-text search. Use this to audit a specific resource's history or to see what changed recently across the project. Responses can be large — pass `fields` to return only what your task needs (e.g. `[\"user.email\", \"activity\", \"scope\", \"created_at\"]` to see who changed what), and only request `detail.changes` when you actually need the field-level diffs.",
"category": "Platform Features",
"feature": "platform_features",
"summary": "List activity in the project.",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 56368519d9d8..c2c061363a0c 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -370,7 +370,7 @@
"feature_entitlement": "audit_logs"
},
"advanced-activity-logs-list": {
- "description": "List activity log entries — who changed what and when (feature flag changes, dashboard edits, experiment launches, insight edits, etc.), with field-level diffs. Filter by scope, activity type, user, item, date range, and free-text search. Use this to audit a specific resource's history or to see what changed recently across the project.",
+ "description": "List activity log entries — who changed what and when (feature flag changes, dashboard edits, experiment launches, insight edits, etc.), with field-level diffs. Filter by scope, activity type, user, item, date range, and free-text search. Use this to audit a specific resource's history or to see what changed recently across the project. Responses can be large — pass `fields` to return only what your task needs (e.g. `[\"user.email\", \"activity\", \"scope\", \"created_at\"]` to see who changed what), and only request `detail.changes` when you actually need the field-level diffs.",
"category": "Platform Features",
"feature": "platform_features",
"summary": "List activity in the project.",
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index 9b7f7df65834..78f2336e168d 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -853,14 +853,21 @@ function buildResponseFilter(config: ToolConfig): {
} {
if (config.response?.include?.length) {
const paths = config.response?.include.map((f) => `'${f}'`).join(', ')
+ // `selectable` lets the agent pass `fields` to narrow the allowlist per call; the Zod
+ // `z.enum(...).min(1)` on the schema already constrains `fields` to a non-empty subset of
+ // `include`, so an absent `fields` falls back to the full allowlist (an empty array is
+ // rejected at validation) and no separate intersection is needed.
+ const pathsExpr = config.response?.selectable
+ ? `params.fields?.length ? params.fields : [${paths}]`
+ : `[${paths}]`
if (config.list) {
return {
- code: ` const filtered = { ...result, results: (result.results ?? []).map((item: any) => pickResponseFields(item, [${paths}])) } as typeof result\n`,
+ code: ` const filtered = { ...result, results: (result.results ?? []).map((item: any) => pickResponseFields(item, ${pathsExpr})) } as typeof result\n`,
helperImport: 'pickResponseFields',
}
}
return {
- code: ` const filtered = pickResponseFields(result, [${paths}]) as typeof result\n`,
+ code: ` const filtered = pickResponseFields(result, ${pathsExpr}) as typeof result\n`,
helperImport: 'pickResponseFields',
}
}
@@ -880,6 +887,31 @@ function buildResponseFilter(config: ToolConfig): {
return { code: '', helperImport: null }
}
+/**
+ * When `response.selectable` is set, emit a `.extend({ fields: ... })` clause adding an optional
+ * `fields` request param constrained (via `z.enum`) to the `include` allowlist. Returns '' when the
+ * tool doesn't opt in, so the schema expression is left untouched. Throws when `selectable` is set
+ * without an `include` allowlist, since there would be nothing to constrain the `fields` param to.
+ */
+function buildSelectableFieldsExtension(config: ToolConfig): string {
+ if (!config.response?.selectable) {
+ return ''
+ }
+ const include = config.response?.include
+ if (!include?.length) {
+ // selectable has no allowlist to constrain the `fields` param against — fail codegen loudly
+ // rather than silently emitting a tool whose `selectable` flag does nothing.
+ throw new Error(
+ `response.selectable requires a non-empty response.include allowlist — add the fields the tool may return, or remove selectable`
+ )
+ }
+ const enumValues = include.map((f) => `'${f}'`).join(', ')
+ const description =
+ 'Optional subset of response fields to return, each a dot-path from the allowlist. ' +
+ 'Omit to return all fields. Request only the fields your task needs to keep responses small.'
+ return `.extend({ fields: z.array(z.enum([${enumValues}])).min(1).optional().describe(${JSON.stringify(description)}) })`
+}
+
// ------------------------------------------------------------------
// Response enrichment templates
// ------------------------------------------------------------------
@@ -974,6 +1006,12 @@ function generateToolCode(
}
let schemaExpr = composition.schemaExpr
+ // Add the `fields` selection param before any validator wrapping, while schemaExpr is still a
+ // ZodObject that supports `.extend`.
+ const selectableExtension = buildSelectableFieldsExtension(config)
+ if (selectableExtension) {
+ schemaExpr = `${schemaExpr}${selectableExtension}`
+ }
if (config.validators && config.validators.length > 0) {
for (const fn of config.validators) {
schemaExpr = `(${schemaExpr}).superRefine(${fn})`
@@ -1124,7 +1162,11 @@ function generateToolCode(
// `params` is only referenced when a dynamic body/query/path param reads from it; inject_body
// alone doesn't touch params, so don't count it here.
const paramsUsed =
- composition.bodyFieldNames.length > 0 || hasQuery || composition.pathParamNames.length > 0 || enrichUsesParams
+ composition.bodyFieldNames.length > 0 ||
+ hasQuery ||
+ composition.pathParamNames.length > 0 ||
+ enrichUsesParams ||
+ !!selectableExtension
const unusedParamsComment = paramsUsed ? '' : '// eslint-disable-next-line no-unused-vars\n'
// When `confirmed_action` is declared, emit TWO factories instead of
@@ -1358,6 +1400,12 @@ function generateCustomSchemaToolCode(
let baseSchemaExpr = config.input_schema as string
const toolInputsImports: string[] = config.input_schema ? [config.input_schema] : []
+ // Add the `fields` selection param before any validator wrapping, while the custom schema is
+ // still a ZodObject that supports `.extend` — mirrors the Orval-schema path in generateToolCode.
+ const selectableExtension = buildSelectableFieldsExtension(config)
+ if (selectableExtension) {
+ baseSchemaExpr = `${baseSchemaExpr}${selectableExtension}`
+ }
if (config.validators && config.validators.length > 0) {
for (const fn of config.validators) {
baseSchemaExpr = `(${baseSchemaExpr}).superRefine(${fn})`
diff --git a/services/mcp/scripts/yaml-config-schema.ts b/services/mcp/scripts/yaml-config-schema.ts
index 2ff4919387aa..58b7c53b10d6 100644
--- a/services/mcp/scripts/yaml-config-schema.ts
+++ b/services/mcp/scripts/yaml-config-schema.ts
@@ -179,11 +179,20 @@ export const ToolConfigSchema = z
include: z.array(z.string()).optional(),
/** Dot-path patterns of response fields to remove. */
exclude: z.array(z.string()).optional(),
+ /**
+ * Expose an optional `fields` request param so the agent can narrow the response to a
+ * subset of `include` at call time (constrained to the allowlist). Omitting `fields`
+ * returns the full `include` set. Requires `include`; incompatible with `exclude`.
+ */
+ selectable: z.boolean().optional(),
})
.strict()
.refine((data) => !(data.include?.length && data.exclude?.length), {
message: 'response.include and response.exclude are mutually exclusive',
})
+ .refine((data) => !(data.selectable && !data.include?.length), {
+ message: 'response.selectable requires response.include (the allowlist to select from)',
+ })
.optional(),
/**
* Opt the tool into the typed-confirm two-tool paradigm. Codegen
diff --git a/services/mcp/src/tools/generated/platform_features.ts b/services/mcp/src/tools/generated/platform_features.ts
index 3d6eb1dc3c23..c8a56b18f7f7 100644
--- a/services/mcp/src/tools/generated/platform_features.ts
+++ b/services/mcp/src/tools/generated/platform_features.ts
@@ -47,6 +47,30 @@ const advancedActivityLogsFilters = (): ToolBase<
const AdvancedActivityLogsListSchema = AdvancedActivityLogsListQueryParams.extend({
page_size: AdvancedActivityLogsListQueryParams.shape['page_size'].default(10).optional(),
+}).extend({
+ fields: z
+ .array(
+ z.enum([
+ 'id',
+ 'user.id',
+ 'user.first_name',
+ 'user.last_name',
+ 'user.email',
+ 'activity',
+ 'scope',
+ 'item_id',
+ 'detail.name',
+ 'detail.short_id',
+ 'detail.type',
+ 'detail.changes',
+ 'created_at',
+ ])
+ )
+ .min(1)
+ .optional()
+ .describe(
+ 'Optional subset of response fields to return, each a dot-path from the allowlist. Omit to return all fields. Request only the fields your task needs to keep responses small.'
+ ),
})
const advancedActivityLogsList = (): ToolBase<
@@ -82,21 +106,26 @@ const advancedActivityLogsList = (): ToolBase<
const filtered = {
...result,
results: (result.results ?? []).map((item: any) =>
- pickResponseFields(item, [
- 'id',
- 'user.id',
- 'user.first_name',
- 'user.last_name',
- 'user.email',
- 'activity',
- 'scope',
- 'item_id',
- 'detail.name',
- 'detail.short_id',
- 'detail.type',
- 'detail.changes',
- 'created_at',
- ])
+ pickResponseFields(
+ item,
+ params.fields?.length
+ ? params.fields
+ : [
+ 'id',
+ 'user.id',
+ 'user.first_name',
+ 'user.last_name',
+ 'user.email',
+ 'activity',
+ 'scope',
+ 'item_id',
+ 'detail.name',
+ 'detail.short_id',
+ 'detail.type',
+ 'detail.changes',
+ 'created_at',
+ ]
+ )
),
} as typeof result
return await withPostHogUrl(context, filtered, '/activity')
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/advanced-activity-logs-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/advanced-activity-logs-list.json
index 9164a582bef0..a747cf863d53 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/advanced-activity-logs-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/advanced-activity-logs-list.json
@@ -27,6 +27,29 @@
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
"type": "string"
},
+ "fields": {
+ "description": "Optional subset of response fields to return, each a dot-path from the allowlist. Omit to return all fields. Request only the fields your task needs to keep responses small.",
+ "items": {
+ "enum": [
+ "id",
+ "user.id",
+ "user.first_name",
+ "user.last_name",
+ "user.email",
+ "activity",
+ "scope",
+ "item_id",
+ "detail.name",
+ "detail.short_id",
+ "detail.type",
+ "detail.changes",
+ "created_at"
+ ],
+ "type": "string"
+ },
+ "minItems": 1,
+ "type": "array"
+ },
"hogql_filter": {
"description": "Reserved for future HogQL-based filtering.",
"type": "string"
diff --git a/services/mcp/tests/unit/activity-logs-selectable-fields.test.ts b/services/mcp/tests/unit/activity-logs-selectable-fields.test.ts
new file mode 100644
index 000000000000..fb309adb275d
--- /dev/null
+++ b/services/mcp/tests/unit/activity-logs-selectable-fields.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from 'vitest'
+
+import { GENERATED_TOOLS } from '@/tools/generated/platform_features'
+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+
+// One full-fat activity entry carrying every field the tool's `response.include` allowlist keeps,
+// so a narrowing bug (fields ignored -> full payload) is visible.
+const FULL_ENTRY = {
+ id: 'abc',
+ user: { id: 7, first_name: 'Ada', last_name: 'Lovelace', email: '[email protected]' },
+ activity: 'updated',
+ scope: 'FeatureFlag',
+ item_id: '42',
+ detail: {
+ name: 'my-flag',
+ short_id: 'AB12',
+ type: 'boolean',
+ changes: [{ field: 'active', before: false, after: true }],
+ },
+ created_at: '2026-07-13T00:00:00Z',
+ // A field outside the allowlist — must never survive projection.
+ unredacted_ip: '10.0.0.1',
+}
+
+function mockContext(): Context {
+ return {
+ stateManager: { getProjectId: async () => 1 },
+ api: {
+ getProjectBaseUrl: () => 'https://us.posthog.com/project/1',
+ request: async () => ({ count: 1, next: null, previous: null, results: [FULL_ENTRY] }),
+ },
+ } as unknown as Context
+}
+
+describe('advanced-activity-logs-list selectable fields', () => {
+ const listTool = GENERATED_TOOLS['advanced-activity-logs-list'] as () => ToolBase<ZodObjectAny>
+
+ it('narrows each result to the requested fields when `fields` is passed', async () => {
+ const result: any = await listTool().handler(mockContext(), {
+ fields: ['user.email', 'activity', 'created_at'],
+ })
+ const [entry] = result.results
+
+ expect(entry).toEqual({
+ user: { email: '[email protected]' },
+ activity: 'updated',
+ created_at: '2026-07-13T00:00:00Z',
+ })
+ // The heavy diff branch is dropped when not requested.
+ expect(entry).not.toHaveProperty('detail')
+ })
+
+ it('returns the full allowlist (including detail.changes) when `fields` is omitted', async () => {
+ const result: any = await listTool().handler(mockContext(), {})
+ const [entry] = result.results
+
+ expect(entry.detail.changes).toEqual([{ field: 'active', before: false, after: true }])
+ expect(entry.user.email).toBe('[email protected]')
+ // Fields outside the allowlist are still filtered out regardless of `fields`.
+ expect(entry).not.toHaveProperty('unredacted_ip')
+ })
+
+ it('constrains `fields` to the allowlist at the schema level', () => {
+ const schema = listTool().schema
+
+ expect(schema.safeParse({ fields: ['user.email', 'activity'] }).success).toBe(true)
+ // A real response field that is not in the allowlist cannot be requested.
+ expect(schema.safeParse({ fields: ['unredacted_ip'] }).success).toBe(false)
+ // An empty array is rejected rather than silently falling back to the full payload.
+ expect(schema.safeParse({ fields: [] }).success).toBe(false)
+ })
+})
diff --git a/services/mcp/tests/unit/generate-tools.test.ts b/services/mcp/tests/unit/generate-tools.test.ts
index a8b0ae2550dc..2c1b5a0989b2 100644
--- a/services/mcp/tests/unit/generate-tools.test.ts
+++ b/services/mcp/tests/unit/generate-tools.test.ts
@@ -359,6 +359,60 @@ describe('generateToolCode with input_schema', () => {
)
expect(result.code).toMatchSnapshot()
})
+
+ it('extends the custom schema with a selectable `fields` param and narrows the response', () => {
+ const config: ToolConfig = {
+ operation: 'things_list',
+ enabled: true,
+ input_schema: 'ThingListSchema',
+ list: true,
+ response: { include: ['id', 'name'], selectable: true },
+ }
+ const resolved = makeResolved({ method: 'GET' })
+
+ const result = generateToolCode(
+ 'things-list',
+ config,
+ resolved,
+ defaultCategory,
+ makeSpec(),
+ new Set<string>(),
+ stubGetQuerySchema
+ )
+
+ // The `fields` param must be added to the custom schema, constrained to the allowlist,
+ // and reject an empty array so it can't silently fall back to the full payload.
+ expect(result.code).toContain('.extend({ fields: z.array(z.enum([')
+ expect(result.code).toContain("z.enum(['id', 'name'])")
+ expect(result.code).toContain('.min(1)')
+ // And the response filter must honor it, falling back to the full allowlist when omitted.
+ expect(result.code).toContain("params.fields?.length ? params.fields : ['id', 'name']")
+ })
+
+ it('throws when selectable is set without an include allowlist', () => {
+ const config: ToolConfig = {
+ operation: 'things_list',
+ enabled: true,
+ input_schema: 'ThingListSchema',
+ list: true,
+ response: { selectable: true },
+ }
+ const resolved = makeResolved({ method: 'GET' })
+
+ // selectable has no allowlist to constrain `fields` against — codegen must fail loudly rather
+ // than silently emit a tool whose selectable flag does nothing.
+ expect(() =>
+ generateToolCode(
+ 'things-list',
+ config,
+ resolved,
+ defaultCategory,
+ makeSpec(),
+ new Set<string>(),
+ stubGetQuerySchema
+ )
+ ).toThrow(/response\.selectable requires a non-empty response\.include allowlist/)
+ })
})
describe('generateToolCode without input_schema', () => {