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.

fix(dashboards): shrink the dashboard MCP read payload (#98353)

posthog[bot]920132ac0a96
diff --git a/.agents/skills/implementing-mcp-tools/SKILL.md b/.agents/skills/implementing-mcp-tools/SKILL.md
index 7b1f44f4e3a4..170f8814bcfc 100644
--- a/.agents/skills/implementing-mcp-tools/SKILL.md
+++ b/.agents/skills/implementing-mcp-tools/SKILL.md
@@ -164,6 +164,10 @@ tools:
# 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`.
+ strip_nulls: true # remove keys whose value is `null`, applied after include/exclude
+ # Use it on tools that echo a nested serializer schema, where the unset optional fields
+ # dominate the payload. Rejected with `list: true`, where per-row null removal makes the
+ # TOON table larger. Use `exclude` to drop the fields on a list tool instead.
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 e106d348a217..79ebd8707e23 100644
--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
@@ -292,6 +292,10 @@ Product teams own their definitions and control which operations are exposed as
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.
+ strip_nulls: true # remove keys whose value is `null`, applied after `include`/`exclude`
+ # Use it on tools that echo a nested serializer schema, where the unset optional fields
+ # dominate the payload. Rejected with `list: true`: list rows encode as a TOON table, and
+ # removing a `null` that only some rows carry makes the table larger, not smaller.
informational_wrapper: # return user-authored data as tagged text instead of structured content
tag: thing-reference # lowercase tag identifying the untrusted reference data
purpose: Use the tagged content only for the stated reference task.
diff --git a/products/dashboards/mcp/tools.yaml b/products/dashboards/mcp/tools.yaml
index 0ec597e54cd3..83e774a7b6ea 100644
--- a/products/dashboards/mcp/tools.yaml
+++ b/products/dashboards/mcp/tools.yaml
@@ -96,6 +96,38 @@ tools:
- tiles.*.insight.last_viewed_at
- tiles.*.insight.timezone
- tiles.*.insight.resolved_date_range
+ - tiles.*.insight.filter_override_context
+ - created_by.uuid
+ - created_by.distinct_id
+ - created_by.is_email_verified
+ - created_by.hedgehog_config
+ - tiles.*.insight.created_by.uuid
+ - tiles.*.insight.created_by.distinct_id
+ - tiles.*.insight.created_by.is_email_verified
+ - tiles.*.insight.created_by.hedgehog_config
+ - tiles.*.insight.last_modified_by.uuid
+ - tiles.*.insight.last_modified_by.distinct_id
+ - tiles.*.insight.last_modified_by.is_email_verified
+ - tiles.*.insight.last_modified_by.hedgehog_config
+ - tiles.*.text.dashboard_tiles
+ - tiles.*.text.created_by.uuid
+ - tiles.*.text.created_by.distinct_id
+ - tiles.*.text.created_by.is_email_verified
+ - tiles.*.text.created_by.hedgehog_config
+ - tiles.*.text.last_modified_by.uuid
+ - tiles.*.text.last_modified_by.distinct_id
+ - tiles.*.text.last_modified_by.is_email_verified
+ - tiles.*.text.last_modified_by.hedgehog_config
+ - tiles.*.widget.dashboard_tiles
+ - tiles.*.widget.created_by.uuid
+ - tiles.*.widget.created_by.distinct_id
+ - tiles.*.widget.created_by.is_email_verified
+ - tiles.*.widget.created_by.hedgehog_config
+ - tiles.*.widget.last_modified_by.uuid
+ - tiles.*.widget.last_modified_by.distinct_id
+ - tiles.*.widget.last_modified_by.is_email_verified
+ - tiles.*.widget.last_modified_by.hedgehog_config
+ strip_nulls: true
dashboard-create-tile:
operation: dashboards_create_text_tile_create
enabled: true
@@ -212,6 +244,38 @@ tools:
- tiles.*.insight.alerts
- tiles.*.insight.timezone
- tiles.*.insight.resolved_date_range
+ - tiles.*.insight.filter_override_context
+ - created_by.uuid
+ - created_by.distinct_id
+ - created_by.is_email_verified
+ - created_by.hedgehog_config
+ - tiles.*.insight.created_by.uuid
+ - tiles.*.insight.created_by.distinct_id
+ - tiles.*.insight.created_by.is_email_verified
+ - tiles.*.insight.created_by.hedgehog_config
+ - tiles.*.insight.last_modified_by.uuid
+ - tiles.*.insight.last_modified_by.distinct_id
+ - tiles.*.insight.last_modified_by.is_email_verified
+ - tiles.*.insight.last_modified_by.hedgehog_config
+ - tiles.*.text.dashboard_tiles
+ - tiles.*.text.created_by.uuid
+ - tiles.*.text.created_by.distinct_id
+ - tiles.*.text.created_by.is_email_verified
+ - tiles.*.text.created_by.hedgehog_config
+ - tiles.*.text.last_modified_by.uuid
+ - tiles.*.text.last_modified_by.distinct_id
+ - tiles.*.text.last_modified_by.is_email_verified
+ - tiles.*.text.last_modified_by.hedgehog_config
+ - tiles.*.widget.dashboard_tiles
+ - tiles.*.widget.created_by.uuid
+ - tiles.*.widget.created_by.distinct_id
+ - tiles.*.widget.created_by.is_email_verified
+ - tiles.*.widget.created_by.hedgehog_config
+ - tiles.*.widget.last_modified_by.uuid
+ - tiles.*.widget.last_modified_by.distinct_id
+ - tiles.*.widget.last_modified_by.is_email_verified
+ - tiles.*.widget.last_modified_by.hedgehog_config
+ strip_nulls: true
dashboard-insights-run:
operation: dashboards_run_insights_retrieve
enabled: true
@@ -415,6 +479,38 @@ tools:
- tiles.*.insight.alerts
- tiles.*.insight.timezone
- tiles.*.insight.resolved_date_range
+ - tiles.*.insight.filter_override_context
+ - created_by.uuid
+ - created_by.distinct_id
+ - created_by.is_email_verified
+ - created_by.hedgehog_config
+ - tiles.*.insight.created_by.uuid
+ - tiles.*.insight.created_by.distinct_id
+ - tiles.*.insight.created_by.is_email_verified
+ - tiles.*.insight.created_by.hedgehog_config
+ - tiles.*.insight.last_modified_by.uuid
+ - tiles.*.insight.last_modified_by.distinct_id
+ - tiles.*.insight.last_modified_by.is_email_verified
+ - tiles.*.insight.last_modified_by.hedgehog_config
+ - tiles.*.text.dashboard_tiles
+ - tiles.*.text.created_by.uuid
+ - tiles.*.text.created_by.distinct_id
+ - tiles.*.text.created_by.is_email_verified
+ - tiles.*.text.created_by.hedgehog_config
+ - tiles.*.text.last_modified_by.uuid
+ - tiles.*.text.last_modified_by.distinct_id
+ - tiles.*.text.last_modified_by.is_email_verified
+ - tiles.*.text.last_modified_by.hedgehog_config
+ - tiles.*.widget.dashboard_tiles
+ - tiles.*.widget.created_by.uuid
+ - tiles.*.widget.created_by.distinct_id
+ - tiles.*.widget.created_by.is_email_verified
+ - tiles.*.widget.created_by.hedgehog_config
+ - tiles.*.widget.last_modified_by.uuid
+ - tiles.*.widget.last_modified_by.distinct_id
+ - tiles.*.widget.last_modified_by.is_email_verified
+ - tiles.*.widget.last_modified_by.hedgehog_config
+ strip_nulls: true
dashboard-update-text-tile:
operation: dashboards_update_text_tile_create
enabled: true
diff --git a/services/mcp/definitions/README.md b/services/mcp/definitions/README.md
index 5acb3ad73554..63c5c98220f9 100644
--- a/services/mcp/definitions/README.md
+++ b/services/mcp/definitions/README.md
@@ -115,6 +115,10 @@ 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
+ strip_nulls: true # remove keys whose value is `null`, applied after include/exclude
+ # Use it on tools that echo a nested serializer schema, where the unset optional fields
+ # dominate the payload. Rejected with `list: true`, where per-row null removal makes the
+ # TOON table larger. Use `exclude` to drop the fields on a list tool instead.
requires_ai_consent: true # gate behind org AI data processing consent
param_overrides: # override individual param descriptions or schemas
name:
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index 48a097e3671f..9cb508d1bb9b 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -893,44 +893,54 @@ function buildPathExpr(
// Response filtering templates
// ------------------------------------------------------------------
+type ResponseFilterHelper = 'pickResponseFields' | 'omitResponseFields' | 'stripNullFields'
+
function buildResponseFilter(config: ToolConfig): {
code: string
- helperImport: 'pickResponseFields' | 'omitResponseFields' | null
+ helperImports: ResponseFilterHelper[]
} {
+ const helperImports: ResponseFilterHelper[] = []
+ // Builds the expression that shapes one item — the whole result for a detail tool, each
+ // `results` entry for a list tool. Starts as identity, so each configured step wraps it.
+ let shapeItem = (target: string): string => target
+
if (config.response?.include?.length) {
- const paths = config.response?.include.map((f) => `'${f}'`).join(', ')
+ 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
+ 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, ${pathsExpr})) } as typeof result\n`,
- helperImport: 'pickResponseFields',
- }
- }
- return {
- code: ` const filtered = pickResponseFields(result, ${pathsExpr}) as typeof result\n`,
- helperImport: 'pickResponseFields',
- }
+ helperImports.push('pickResponseFields')
+ shapeItem = (target) => `pickResponseFields(${target}, ${pathsExpr})`
+ } else if (config.response?.exclude?.length) {
+ const paths = config.response.exclude.map((f) => `'${f}'`).join(', ')
+ helperImports.push('omitResponseFields')
+ shapeItem = (target) => `omitResponseFields(${target}, [${paths}])`
}
- if (config.response?.exclude?.length) {
- const paths = config.response?.exclude.map((f) => `'${f}'`).join(', ')
- if (config.list) {
- return {
- code: ` const filtered = { ...result, results: (result.results ?? []).map((item: any) => omitResponseFields(item, [${paths}])) } as typeof result\n`,
- helperImport: 'omitResponseFields',
- }
- }
+
+ if (config.response?.strip_nulls) {
+ const inner = shapeItem
+ helperImports.push('stripNullFields')
+ shapeItem = (target) => `stripNullFields(${inner(target)})`
+ }
+
+ if (helperImports.length === 0) {
+ return { code: '', helperImports: [] }
+ }
+
+ if (config.list) {
return {
- code: ` const filtered = omitResponseFields(result, [${paths}]) as typeof result\n`,
- helperImport: 'omitResponseFields',
+ code: ` const filtered = { ...result, results: (result.results ?? []).map((item: any) => ${shapeItem('item')}) } as typeof result\n`,
+ helperImports,
}
}
- return { code: '', helperImport: null }
+ return {
+ code: ` const filtered = ${shapeItem('result')} as typeof result\n`,
+ helperImports,
+ }
}
/**
@@ -1279,7 +1289,7 @@ function generateToolCode(
needsWithInformationalResponse,
toolUtilsValueImports: new Set(
[
- responseFilter.helperImport,
+ ...responseFilter.helperImports,
config.response?.informational_wrapper && 'withInformationalResponse',
].filter((value): value is string => !!value)
),
@@ -1314,9 +1324,10 @@ const ${factoryName} = (): ToolBase<ReturnType<typeof ${schemaName}>, ${resultTy
hasAgentNote,
needsWithInformationalResponse,
toolUtilsValueImports: new Set(
- [responseFilter.helperImport, config.response?.informational_wrapper && 'withInformationalResponse'].filter(
- (value): value is string => !!value
- )
+ [
+ ...responseFilter.helperImports,
+ config.response?.informational_wrapper && 'withInformationalResponse',
+ ].filter((value): value is string => !!value)
),
}
}
@@ -1619,9 +1630,10 @@ ${handlerBody} },
hasAgentNote,
needsWithInformationalResponse,
toolUtilsValueImports: new Set(
- [responseFilter.helperImport, config.response?.informational_wrapper && 'withInformationalResponse'].filter(
- (value): value is string => !!value
- )
+ [
+ ...responseFilter.helperImports,
+ config.response?.informational_wrapper && 'withInformationalResponse',
+ ].filter((value): value is string => !!value)
),
}
}
diff --git a/services/mcp/scripts/yaml-config-schema.ts b/services/mcp/scripts/yaml-config-schema.ts
index d153cec64d9d..15fde016f081 100644
--- a/services/mcp/scripts/yaml-config-schema.ts
+++ b/services/mcp/scripts/yaml-config-schema.ts
@@ -206,6 +206,12 @@ export const ToolConfigSchema = z
* returns the full `include` set. Requires `include`; incompatible with `exclude`.
*/
selectable: z.boolean().optional(),
+ /**
+ * Remove keys whose value is `null` from the response, after `include`/`exclude`.
+ * Use it on tools that echo a nested serializer schema, where the unset optional
+ * fields dominate the payload.
+ */
+ strip_nulls: z.boolean().optional(),
/** Wrap user-authored response data in an explicit informational-only tag boundary. */
informational_wrapper: z
.object({
@@ -283,6 +289,14 @@ export const ToolConfigSchema = z
message: '`feature_flag_variant` requires `feature_flag` to be set',
path: ['feature_flag_variant'],
})
+ // A list response encodes as a TOON table: one header of shared keys, then one row per
+ // item. Dropping a `null` that only some rows carry breaks that uniformity and forces the
+ // expanded per-key form, so the response grows instead of shrinking.
+ .refine((data) => !(data.response?.strip_nulls && data.list), {
+ message:
+ '`response.strip_nulls` cannot be combined with `list: true` — rows encode as a TOON table, and per-item null removal makes a ragged table larger. Use `response.exclude` to drop the fields instead.',
+ path: ['response', 'strip_nulls'],
+ })
// confirmed_action emits two factories (`-prepare`, `-execute`) via a
// codegen path that doesn't currently wrap either with `withUiApp`.
// Reject the combination at YAML time rather than silently drop the
diff --git a/services/mcp/src/tools/generated/dashboards.ts b/services/mcp/src/tools/generated/dashboards.ts
index deb95e7a11ec..5ac0c0d814ed 100644
--- a/services/mcp/src/tools/generated/dashboards.ts
+++ b/services/mcp/src/tools/generated/dashboards.ts
@@ -9,6 +9,7 @@ import {
withPostHogUrl,
withAgentNote,
omitResponseFields,
+ stripNullFields,
withInformationalResponse,
type WithPostHogUrl,
type WithAgentNote,
@@ -78,45 +79,78 @@ const dashboardCreate = (): ToolBase<
include_dashboards: params.include_dashboards,
},
})
- const filtered = omitResponseFields(result, [
- 'effective_restriction_level',
- 'effective_privilege_level',
- 'user_access_level',
- 'access_control_version',
- 'restriction_level',
- 'creation_mode',
- 'deleted',
- 'breakdown_colors',
- 'data_color_theme_id',
- 'quick_filter_ids',
- 'tiles.*.color',
- 'tiles.*.transparent_background',
- 'tiles.*.show_description',
- 'tiles.*.button_tile',
- 'tiles.*.insight.result',
- 'tiles.*.insight.hasMore',
- 'tiles.*.insight.columns',
- 'tiles.*.insight.hogql',
- 'tiles.*.insight.types',
- 'tiles.*.insight.query_status',
- 'tiles.*.insight.cache_target_age',
- 'tiles.*.insight.next_allowed_client_refresh',
- 'tiles.*.insight.filters_hash',
- 'tiles.*.insight.dashboards',
- 'tiles.*.insight.dashboard_tiles',
- 'tiles.*.insight.effective_restriction_level',
- 'tiles.*.insight.effective_privilege_level',
- 'tiles.*.insight.user_access_level',
- 'tiles.*.insight.filters',
- 'tiles.*.insight.is_sample',
- 'tiles.*.insight.saved',
- 'tiles.*.insight.order',
- 'tiles.*.insight.deleted',
- 'tiles.*.insight.alerts',
- 'tiles.*.insight.last_viewed_at',
- 'tiles.*.insight.timezone',
- 'tiles.*.insight.resolved_date_range',
- ]) as typeof result
+ const filtered = stripNullFields(
+ omitResponseFields(result, [
+ 'effective_restriction_level',
+ 'effective_privilege_level',
+ 'user_access_level',
+ 'access_control_version',
+ 'restriction_level',
+ 'creation_mode',
+ 'deleted',
+ 'breakdown_colors',
+ 'data_color_theme_id',
+ 'quick_filter_ids',
+ 'tiles.*.color',
+ 'tiles.*.transparent_background',
+ 'tiles.*.show_description',
+ 'tiles.*.button_tile',
+ 'tiles.*.insight.result',
+ 'tiles.*.insight.hasMore',
+ 'tiles.*.insight.columns',
+ 'tiles.*.insight.hogql',
+ 'tiles.*.insight.types',
+ 'tiles.*.insight.query_status',
+ 'tiles.*.insight.cache_target_age',
+ 'tiles.*.insight.next_allowed_client_refresh',
+ 'tiles.*.insight.filters_hash',
+ 'tiles.*.insight.dashboards',
+ 'tiles.*.insight.dashboard_tiles',
+ 'tiles.*.insight.effective_restriction_level',
+ 'tiles.*.insight.effective_privilege_level',
+ 'tiles.*.insight.user_access_level',
+ 'tiles.*.insight.filters',
+ 'tiles.*.insight.is_sample',
+ 'tiles.*.insight.saved',
+ 'tiles.*.insight.order',
+ 'tiles.*.insight.deleted',
+ 'tiles.*.insight.alerts',
+ 'tiles.*.insight.last_viewed_at',
+ 'tiles.*.insight.timezone',
+ 'tiles.*.insight.resolved_date_range',
+ 'tiles.*.insight.filter_override_context',
+ 'created_by.uuid',
+ 'created_by.distinct_id',
+ 'created_by.is_email_verified',
+ 'created_by.hedgehog_config',
+ 'tiles.*.insight.created_by.uuid',
+ 'tiles.*.insight.created_by.distinct_id',
+ 'tiles.*.insight.created_by.is_email_verified',
+ 'tiles.*.insight.created_by.hedgehog_config',
+ 'tiles.*.insight.last_modified_by.uuid',
+ 'tiles.*.insight.last_modified_by.distinct_id',
+ 'tiles.*.insight.last_modified_by.is_email_verified',
+ 'tiles.*.insight.last_modified_by.hedgehog_config',
+ 'tiles.*.text.dashboard_tiles',
+ 'tiles.*.text.created_by.uuid',
+ 'tiles.*.text.created_by.distinct_id',
+ 'tiles.*.text.created_by.is_email_verified',
+ 'tiles.*.text.created_by.hedgehog_config',
+ 'tiles.*.text.last_modified_by.uuid',
+ 'tiles.*.text.last_modified_by.distinct_id',
+ 'tiles.*.text.last_modified_by.is_email_verified',
+ 'tiles.*.text.last_modified_by.hedgehog_config',
+ 'tiles.*.widget.dashboard_tiles',
+ 'tiles.*.widget.created_by.uuid',
+ 'tiles.*.widget.created_by.distinct_id',
+ 'tiles.*.widget.created_by.is_email_verified',
+ 'tiles.*.widget.created_by.hedgehog_config',
+ 'tiles.*.widget.last_modified_by.uuid',
+ 'tiles.*.widget.last_modified_by.distinct_id',
+ 'tiles.*.widget.last_modified_by.is_email_verified',
+ 'tiles.*.widget.last_modified_by.hedgehog_config',
+ ])
+ ) as typeof result
return withAgentNote(
await withPostHogUrl(context, filtered, `/dashboard/${filtered.id}`),
"Consider offering the user a recurring delivery of this dashboard as a next step, but only when the dashboard in this response has tiles on it. Creating from a template (`use_template`) or duplicating another dashboard (`use_dashboard`) usually starts with tiles, though duplicating an empty dashboard does not. A dashboard with no tiles has nothing to deliver, and subscriptions-create needs at least one chart, so say nothing about subscriptions until it has some. Describe it the way a person would recognize it, for example a weekly email every Monday morning with these charts attached, or the same thing posted to a Slack channel. To create it, use subscriptions-create. It needs `dashboard` set to the dashboard's id, `dashboard_export_insights` listing up to 10 charts, `target_type` of `email` or `slack`, and `target_value`, `frequency`, `interval` and `start_date`. For a Slack delivery, also set `integration_id`. Find the connected Slack workspace with integrations-list (filter kind=slack) and the channel for `target_value` with integrations-channels-retrieve. Ask the user for the recipients and the cadence rather than choosing them, since this creates a recurring outbound delivery. If either subscriptions-create or subscriptions-list is not available to you in this session, say nothing about subscriptions. If the user already declined a subscription earlier in this conversation, do not offer again."
@@ -225,43 +259,76 @@ const dashboardGet = (): ToolBase<ReturnType<typeof DashboardGetSchema>, WithPos
variables_override: params.variables_override,
},
})
- const filtered = omitResponseFields(result, [
- 'effective_restriction_level',
- 'effective_privilege_level',
- 'user_access_level',
- 'access_control_version',
- 'restriction_level',
- 'creation_mode',
- 'deleted',
- 'breakdown_colors',
- 'data_color_theme_id',
- 'quick_filter_ids',
- 'tiles.*.color',
- 'tiles.*.transparent_background',
- 'tiles.*.show_description',
- 'tiles.*.button_tile',
- 'tiles.*.insight.result',
- 'tiles.*.insight.hasMore',
- 'tiles.*.insight.columns',
- 'tiles.*.insight.hogql',
- 'tiles.*.insight.types',
- 'tiles.*.insight.query_status',
- 'tiles.*.insight.cache_target_age',
- 'tiles.*.insight.next_allowed_client_refresh',
- 'tiles.*.insight.filters_hash',
- 'tiles.*.insight.dashboards',
- 'tiles.*.insight.dashboard_tiles',
- 'tiles.*.insight.effective_restriction_level',
- 'tiles.*.insight.effective_privilege_level',
- 'tiles.*.insight.user_access_level',
- 'tiles.*.insight.filters',
- 'tiles.*.insight.is_sample',
- 'tiles.*.insight.order',
- 'tiles.*.insight.deleted',
- 'tiles.*.insight.alerts',
- 'tiles.*.insight.timezone',
- 'tiles.*.insight.resolved_date_range',
- ]) as typeof result
+ const filtered = stripNullFields(
+ omitResponseFields(result, [
+ 'effective_restriction_level',
+ 'effective_privilege_level',
+ 'user_access_level',
+ 'access_control_version',
+ 'restriction_level',
+ 'creation_mode',
+ 'deleted',
+ 'breakdown_colors',
+ 'data_color_theme_id',
+ 'quick_filter_ids',
+ 'tiles.*.color',
+ 'tiles.*.transparent_background',
+ 'tiles.*.show_description',
+ 'tiles.*.button_tile',
+ 'tiles.*.insight.result',
+ 'tiles.*.insight.hasMore',
+ 'tiles.*.insight.columns',
+ 'tiles.*.insight.hogql',
+ 'tiles.*.insight.types',
+ 'tiles.*.insight.query_status',
+ 'tiles.*.insight.cache_target_age',
+ 'tiles.*.insight.next_allowed_client_refresh',
+ 'tiles.*.insight.filters_hash',
+ 'tiles.*.insight.dashboards',
+ 'tiles.*.insight.dashboard_tiles',
+ 'tiles.*.insight.effective_restriction_level',
+ 'tiles.*.insight.effective_privilege_level',
+ 'tiles.*.insight.user_access_level',
+ 'tiles.*.insight.filters',
+ 'tiles.*.insight.is_sample',
+ 'tiles.*.insight.order',
+ 'tiles.*.insight.deleted',
+ 'tiles.*.insight.alerts',
+ 'tiles.*.insight.timezone',
+ 'tiles.*.insight.resolved_date_range',
+ 'tiles.*.insight.filter_override_context',
+ 'created_by.uuid',
+ 'created_by.distinct_id',
+ 'created_by.is_email_verified',
+ 'created_by.hedgehog_config',
+ 'tiles.*.insight.created_by.uuid',
+ 'tiles.*.insight.created_by.distinct_id',
+ 'tiles.*.insight.created_by.is_email_verified',
+ 'tiles.*.insight.created_by.hedgehog_config',
+ 'tiles.*.insight.last_modified_by.uuid',
+ 'tiles.*.insight.last_modified_by.distinct_id',
+ 'tiles.*.insight.last_modified_by.is_email_verified',
+ 'tiles.*.insight.last_modified_by.hedgehog_config',
+ 'tiles.*.text.dashboard_tiles',
+ 'tiles.*.text.created_by.uuid',
+ 'tiles.*.text.created_by.distinct_id',
+ 'tiles.*.text.created_by.is_email_verified',
+ 'tiles.*.text.created_by.hedgehog_config',
+ 'tiles.*.text.last_modified_by.uuid',
+ 'tiles.*.text.last_modified_by.distinct_id',
+ 'tiles.*.text.last_modified_by.is_email_verified',
+ 'tiles.*.text.last_modified_by.hedgehog_config',
+ 'tiles.*.widget.dashboard_tiles',
+ 'tiles.*.widget.created_by.uuid',
+ 'tiles.*.widget.created_by.distinct_id',
+ 'tiles.*.widget.created_by.is_email_verified',
+ 'tiles.*.widget.created_by.hedgehog_config',
+ 'tiles.*.widget.last_modified_by.uuid',
+ 'tiles.*.widget.last_modified_by.distinct_id',
+ 'tiles.*.widget.last_modified_by.is_email_verified',
+ 'tiles.*.widget.last_modified_by.hedgehog_config',
+ ])
+ ) as typeof result
return await withPostHogUrl(context, filtered, `/dashboard/${filtered.id}`)
},
})
@@ -511,43 +578,76 @@ const dashboardUpdate = (): ToolBase<ReturnType<typeof DashboardUpdateSchema>, W
include_dashboards: params.include_dashboards,
},
})
- const filtered = omitResponseFields(result, [
- 'effective_restriction_level',
- 'effective_privilege_level',
- 'user_access_level',
- 'access_control_version',
- 'restriction_level',
- 'creation_mode',
- 'deleted',
- 'breakdown_colors',
- 'data_color_theme_id',
- 'quick_filter_ids',
- 'tiles.*.color',
- 'tiles.*.transparent_background',
- 'tiles.*.show_description',
- 'tiles.*.button_tile',
- 'tiles.*.insight.result',
- 'tiles.*.insight.hasMore',
- 'tiles.*.insight.columns',
- 'tiles.*.insight.hogql',
- 'tiles.*.insight.types',
- 'tiles.*.insight.query_status',
- 'tiles.*.insight.cache_target_age',
- 'tiles.*.insight.next_allowed_client_refresh',
- 'tiles.*.insight.filters_hash',
- 'tiles.*.insight.dashboards',
- 'tiles.*.insight.dashboard_tiles',
- 'tiles.*.insight.effective_restriction_level',
- 'tiles.*.insight.effective_privilege_level',
- 'tiles.*.insight.user_access_level',
- 'tiles.*.insight.filters',
- 'tiles.*.insight.is_sample',
- 'tiles.*.insight.order',
- 'tiles.*.insight.deleted',
- 'tiles.*.insight.alerts',
- 'tiles.*.insight.timezone',
- 'tiles.*.insight.resolved_date_range',
- ]) as typeof result
+ const filtered = stripNullFields(
+ omitResponseFields(result, [
+ 'effective_restriction_level',
+ 'effective_privilege_level',
+ 'user_access_level',
+ 'access_control_version',
+ 'restriction_level',
+ 'creation_mode',
+ 'deleted',
+ 'breakdown_colors',
+ 'data_color_theme_id',
+ 'quick_filter_ids',
+ 'tiles.*.color',
+ 'tiles.*.transparent_background',
+ 'tiles.*.show_description',
+ 'tiles.*.button_tile',
+ 'tiles.*.insight.result',
+ 'tiles.*.insight.hasMore',
+ 'tiles.*.insight.columns',
+ 'tiles.*.insight.hogql',
+ 'tiles.*.insight.types',
+ 'tiles.*.insight.query_status',
+ 'tiles.*.insight.cache_target_age',
+ 'tiles.*.insight.next_allowed_client_refresh',
+ 'tiles.*.insight.filters_hash',
+ 'tiles.*.insight.dashboards',
+ 'tiles.*.insight.dashboard_tiles',
+ 'tiles.*.insight.effective_restriction_level',
+ 'tiles.*.insight.effective_privilege_level',
+ 'tiles.*.insight.user_access_level',
+ 'tiles.*.insight.filters',
+ 'tiles.*.insight.is_sample',
+ 'tiles.*.insight.order',
+ 'tiles.*.insight.deleted',
+ 'tiles.*.insight.alerts',
+ 'tiles.*.insight.timezone',
+ 'tiles.*.insight.resolved_date_range',
+ 'tiles.*.insight.filter_override_context',
+ 'created_by.uuid',
+ 'created_by.distinct_id',
+ 'created_by.is_email_verified',
+ 'created_by.hedgehog_config',
+ 'tiles.*.insight.created_by.uuid',
+ 'tiles.*.insight.created_by.distinct_id',
+ 'tiles.*.insight.created_by.is_email_verified',
+ 'tiles.*.insight.created_by.hedgehog_config',
+ 'tiles.*.insight.last_modified_by.uuid',
+ 'tiles.*.insight.last_modified_by.distinct_id',
+ 'tiles.*.insight.last_modified_by.is_email_verified',
+ 'tiles.*.insight.last_modified_by.hedgehog_config',
+ 'tiles.*.text.dashboard_tiles',
+ 'tiles.*.text.created_by.uuid',
+ 'tiles.*.text.created_by.distinct_id',
+ 'tiles.*.text.created_by.is_email_verified',
+ 'tiles.*.text.created_by.hedgehog_config',
+ 'tiles.*.text.last_modified_by.uuid',
+ 'tiles.*.text.last_modified_by.distinct_id',
+ 'tiles.*.text.last_modified_by.is_email_verified',
+ 'tiles.*.text.last_modified_by.hedgehog_config',
+ 'tiles.*.widget.dashboard_tiles',
+ 'tiles.*.widget.created_by.uuid',
+ 'tiles.*.widget.created_by.distinct_id',
+ 'tiles.*.widget.created_by.is_email_verified',
+ 'tiles.*.widget.created_by.hedgehog_config',
+ 'tiles.*.widget.last_modified_by.uuid',
+ 'tiles.*.widget.last_modified_by.distinct_id',
+ 'tiles.*.widget.last_modified_by.is_email_verified',
+ 'tiles.*.widget.last_modified_by.hedgehog_config',
+ ])
+ ) as typeof result
return await withPostHogUrl(context, filtered, `/dashboard/${filtered.id}`)
},
})
diff --git a/services/mcp/src/tools/tool-utils.ts b/services/mcp/src/tools/tool-utils.ts
index 15f54b4bf869..1c8b7e3f52d7 100644
--- a/services/mcp/src/tools/tool-utils.ts
+++ b/services/mcp/src/tools/tool-utils.ts
@@ -181,3 +181,32 @@ function removeAtPath(obj: unknown, segments: string[]): void {
removeAtPath(record[head], rest)
}
}
+
+/**
+ * Remove keys whose value is `null`, recursing through objects and arrays. Array element
+ * positions are kept.
+ *
+ * PostHog serializers write every unset optional field as an explicit `null`, so a response
+ * that echoes a nested schema (a dashboard tile's query, for example) spends most of its size
+ * on keys that carry no information. An absent key and a `null` key read the same to an agent,
+ * which makes the removal lossless.
+ */
+export function stripNullFields<T>(obj: T): T {
+ return stripNulls(obj) as T
+}
+
+function stripNulls(value: unknown): unknown {
+ if (Array.isArray(value)) {
+ return value.map(stripNulls)
+ }
+ if (value === null || typeof value !== 'object') {
+ return value
+ }
+ const result: Record<string, unknown> = {}
+ for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
+ if (item !== null) {
+ result[key] = stripNulls(item)
+ }
+ }
+ return result
+}
diff --git a/services/mcp/tests/unit/dashboard-get-response-budget.test.ts b/services/mcp/tests/unit/dashboard-get-response-budget.test.ts
new file mode 100644
index 000000000000..4d8c76905089
--- /dev/null
+++ b/services/mcp/tests/unit/dashboard-get-response-budget.test.ts
@@ -0,0 +1,343 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { estimateTokens } from '@/lib/estimate-tokens'
+import { formatResponse } from '@/lib/response'
+import { GENERATED_TOOLS } from '@/tools/generated/dashboards'
+import type { Context } from '@/tools/types'
+
+/**
+ * An agent that reads a dashboard over MCP has to fit the whole response in one tool result.
+ * A dashboard of this size is ordinary, so the ceiling here is the size that keeps the
+ * list-to-detail flow usable — not the size the payload happens to be today.
+ */
+const TOKEN_BUDGET = 10_000
+
+const TILE_COUNT = 11
+
+/** The `UserBasic` keys an agent cannot act on. Name and email stay. */
+const STRIPPED_USER_FIELDS = ['uuid', 'distinct_id', 'is_email_verified', 'hedgehog_config']
+
+function createUser(id: number, firstName: string, lastName: string): Record<string, unknown> {
+ return {
+ id,
+ uuid: `00000000-0000-4000-8000-0000000000${id}`,
+ distinct_id: `distinct-id-for-user-${id}`,
+ first_name: firstName,
+ last_name: lastName,
+ email: `${firstName.toLowerCase()}@example.com`,
+ is_email_verified: true,
+ hedgehog_config: {
+ use_as_profile: false,
+ color: 'invert-hue',
+ accessories: ['flag', 'sunglasses', 'parrot'],
+ skin: 'default',
+ },
+ role_at_organization: null,
+ }
+}
+
+/**
+ * A trends query with every optional field the serializer emits. The explicit `null`s are the
+ * point of the fixture: they are what the response used to spend most of its size on.
+ */
+function createTileQuery(): Record<string, unknown> {
+ return {
+ kind: 'InsightVizNode',
+ source: {
+ kind: 'TrendsQuery',
+ aggregation_group_type_index: null,
+ breakdownFilter: {
+ breakdown: 'tool',
+ breakdown_group_type_index: null,
+ breakdown_hide_other_aggregation: null,
+ breakdown_histogram_bin_count: null,
+ breakdown_limit: 10,
+ breakdown_normalize_url: null,
+ breakdown_path_cleaning: null,
+ breakdown_type: 'event',
+ breakdowns: null,
+ },
+ calendarHeatmapFilter: null,
+ compareFilter: null,
+ conversionGoal: null,
+ dataColorTheme: null,
+ dateRange: {
+ date_from: '-90d',
+ date_to: null,
+ daysOfWeek: null,
+ excludeIncompletePeriods: false,
+ explicitDate: false,
+ },
+ filterTestAccounts: false,
+ interval: 'week',
+ modifiers: null,
+ properties: { type: 'AND', values: [] },
+ response: null,
+ samplingFactor: null,
+ series: [
+ {
+ kind: 'EventsNode',
+ custom_name: 'Calls',
+ event: 'widget opened',
+ fixedProperties: null,
+ limit: null,
+ math: 'total',
+ math_group_type_index: null,
+ math_hogql: null,
+ math_multiplier: null,
+ math_property: null,
+ math_property_revenue_currency: null,
+ math_property_type: null,
+ name: null,
+ optionalInFunnel: null,
+ orderBy: null,
+ properties: null,
+ response: null,
+ version: null,
+ },
+ ],
+ tags: null,
+ trendsFilter: {
+ aggregationAxisFormat: 'numeric',
+ aggregationAxisPostfix: null,
+ aggregationAxisPrefix: null,
+ breakdown_histogram_bin_count: null,
+ chartStyle: null,
+ confidenceLevel: null,
+ decimalPlaces: null,
+ detailedResultsAggregationType: null,
+ display: 'ActionsLineGraph',
+ excludeBoxPlotOutliers: true,
+ formula: null,
+ formulaNodes: null,
+ formulas: null,
+ goalLines: null,
+ hiddenLegendIndexes: null,
+ hideWeekends: false,
+ legendPosition: 'bottom',
+ metricChangeDecreaseColor: null,
+ metricChangeIncreaseColor: null,
+ metricColorByDirection: false,
+ metricLineDecreaseColor: null,
+ metricLineIncreaseColor: null,
+ metricShowChange: true,
+ metricSummary: 'total',
+ minDecimalPlaces: null,
+ movingAverageIntervals: null,
+ resultCustomizationBy: 'value',
+ resultCustomizations: null,
+ showAlertThresholdLines: false,
+ showAnnotations: true,
+ showConfidenceIntervals: null,
+ showLabelsOnSeries: null,
+ showLegend: true,
+ showMovingAverage: null,
+ showMultipleYAxes: false,
+ showPercentStackView: false,
+ showTrendLines: null,
+ showValuesOnSeries: false,
+ smoothingIntervals: 1,
+ stackBreakdownValues: false,
+ xAxisLabel: null,
+ yAxisLabel: null,
+ yAxisMax: null,
+ yAxisMin: null,
+ yAxisScaleType: 'linear',
+ yAxisStartAtZero: true,
+ },
+ version: 4,
+ },
+ }
+}
+
+function createDashboardResponse(): Record<string, unknown> {
+ const dashboardFilters = {
+ properties: [{ key: 'client_name', type: 'event', value: 'is_set', operator: 'is_set' }],
+ }
+ return {
+ id: 42,
+ name: 'Widget adoption',
+ description: 'Widget usage over time',
+ pinned: true,
+ created_at: '2026-02-18T18:28:34.858807Z',
+ created_by: createUser(1, 'Ada', 'Lovelace'),
+ last_accessed_at: '2026-09-10T12:41:12.137521Z',
+ last_viewed_at: null,
+ filters: dashboardFilters,
+ variables: {},
+ team_id: 7,
+ tags: ['widgets'],
+ tiles: Array.from({ length: TILE_COUNT }, (_, index) => ({
+ id: 1000 + index,
+ insight: {
+ id: 2000 + index,
+ short_id: `short${index}`,
+ name: `Widget metric ${index}`,
+ derived_name: null,
+ query: createTileQuery(),
+ description: `What widget metric ${index} measures`,
+ created_at: '2026-02-18T18:28:57.827410Z',
+ created_by: createUser(1, 'Ada', 'Lovelace'),
+ updated_at: '2026-06-19T07:10:12.182364Z',
+ favorited: false,
+ saved: true,
+ last_modified_at: '2026-06-19T07:10:12.181366Z',
+ last_modified_by: createUser(2, 'Grace', 'Hopper'),
+ last_refresh: null,
+ is_cached: false,
+ filter_override_context: {
+ dashboard: dashboardFilters,
+ tile: null,
+ overridden_dashboard: null,
+ },
+ last_viewed_at: null,
+ tags: ['widgets'],
+ },
+ text: null,
+ widget: null,
+ layouts: { sm: { h: 5, i: `${1000 + index}`, w: 6, x: 0, y: index * 5, minH: 2, minW: 2 } },
+ filters_overrides: {},
+ order: index,
+ last_refresh: null,
+ is_cached: false,
+ })),
+ }
+}
+
+type TileContent = Record<string, unknown> & {
+ created_by: Record<string, unknown>
+ last_modified_by: Record<string, unknown>
+}
+
+/**
+ * A dashboard that mixes tile types. The all-insight fixture leaves `text` and `widget` null on
+ * every tile, and `strip_nulls` then removes both keys, so it never reaches what they nest.
+ */
+function createMixedDashboardResponse(): Record<string, unknown> {
+ const base = createDashboardResponse()
+ const tileBackReference = [{ id: 1100, dashboard_id: 42, deleted: false }]
+ return {
+ ...base,
+ tiles: [
+ (base.tiles as Record<string, unknown>[])[0]!,
+ {
+ id: 1100,
+ insight: null,
+ text: {
+ id: 300,
+ body: '## Adoption\n\nThe charts below track the widgets released this quarter.',
+ created_by: createUser(1, 'Ada', 'Lovelace'),
+ last_modified_at: '2026-06-19T07:10:12.181366Z',
+ last_modified_by: createUser(2, 'Grace', 'Hopper'),
+ team: 7,
+ dashboard_tiles: tileBackReference,
+ },
+ widget: null,
+ layouts: { sm: { h: 2, i: '1100', w: 6, x: 0, y: 55, minH: 2, minW: 2 } },
+ filters_overrides: {},
+ order: TILE_COUNT,
+ last_refresh: null,
+ is_cached: false,
+ },
+ {
+ id: 1101,
+ insight: null,
+ text: null,
+ widget: {
+ id: '00000000-0000-4000-8000-000000000abc',
+ widget_type: 'error_tracking_list',
+ name: 'Widget errors',
+ description: 'Open issues raised by the widget surface',
+ config: { limit: 5, order_by: null },
+ created_by: createUser(1, 'Ada', 'Lovelace'),
+ last_modified_at: '2026-06-19T07:10:12.181366Z',
+ last_modified_by: createUser(2, 'Grace', 'Hopper'),
+ team: 7,
+ dashboard_tiles: tileBackReference,
+ },
+ layouts: { sm: { h: 5, i: '1101', w: 6, x: 0, y: 57, minH: 2, minW: 2 } },
+ filters_overrides: {},
+ order: TILE_COUNT + 1,
+ last_refresh: null,
+ is_cached: false,
+ },
+ ],
+ }
+}
+
+function createMockContext(result: Record<string, unknown>): Context {
+ return {
+ api: {
+ request: vi.fn().mockResolvedValue(result),
+ getProjectBaseUrl: () => 'https://us.posthog.com/project/7',
+ },
+ stateManager: { getProjectId: async () => 7 },
+ getDistinctId: async () => 'test-distinct-id',
+ trackEvent: async () => {},
+ } as unknown as Context
+}
+
+describe('dashboard-get response budget', () => {
+ const tool = GENERATED_TOOLS['dashboard-get']!()
+
+ async function shapeDashboard(): Promise<Record<string, unknown>> {
+ return (await tool.handler(createMockContext(createDashboardResponse()), {
+ id: 42,
+ })) as unknown as Record<string, unknown>
+ }
+
+ it(`keeps a ${TILE_COUNT}-tile dashboard within the response budget`, async () => {
+ const shaped = await shapeDashboard()
+
+ expect(estimateTokens(formatResponse(shaped))).toBeLessThan(TOKEN_BUDGET)
+ })
+
+ it('keeps the tiles, queries and creators an agent needs', async () => {
+ const shaped = await shapeDashboard()
+ const tiles = shaped.tiles as { id: number; insight: Record<string, unknown> }[]
+
+ expect(tiles).toHaveLength(TILE_COUNT)
+ for (const tile of tiles) {
+ expect(tile.insight.short_id).toBeTruthy()
+ expect((tile.insight.query as { source: { kind: string } }).source.kind).toBe('TrendsQuery')
+ }
+
+ const creator = tiles[0]!.insight.created_by as Record<string, unknown>
+ expect(creator.email).toBe('[email protected]')
+ for (const field of STRIPPED_USER_FIELDS) {
+ expect(creator).not.toHaveProperty(field)
+ }
+ // The dashboard's own `filters` already carries what this per-tile copy repeated.
+ expect(tiles[0]!.insight).not.toHaveProperty('filter_override_context')
+ expect(shaped.filters).toBeTruthy()
+ })
+
+ it('strips the same creator metadata from text and widget tiles', async () => {
+ const shaped = (await tool.handler(createMockContext(createMixedDashboardResponse()), {
+ id: 42,
+ })) as unknown as Record<string, unknown>
+ const tiles = shaped.tiles as { text?: TileContent; widget?: TileContent }[]
+ const textTile = tiles[1]!.text!
+ const widgetTile = tiles[2]!.widget!
+
+ expect(textTile.body as string).toContain('The charts below track')
+ expect(widgetTile.name).toBe('Widget errors')
+ expect(widgetTile.config).toEqual({ limit: 5 })
+
+ for (const tile of [textTile, widgetTile]) {
+ expect(tile.created_by.email).toBe('[email protected]')
+ expect(tile.last_modified_by.first_name).toBe('Grace')
+ for (const field of STRIPPED_USER_FIELDS) {
+ expect(tile.created_by).not.toHaveProperty(field)
+ expect(tile.last_modified_by).not.toHaveProperty(field)
+ }
+ expect(tile).not.toHaveProperty('dashboard_tiles')
+ }
+ })
+
+ it('carries no null-valued keys, which the serializer emits for every unset field', async () => {
+ const shaped = await shapeDashboard()
+
+ expect(JSON.stringify(shaped)).not.toContain(':null')
+ })
+})
diff --git a/services/mcp/tests/unit/generate-tools.test.ts b/services/mcp/tests/unit/generate-tools.test.ts
index 2a642106ada0..4d30076695dd 100644
--- a/services/mcp/tests/unit/generate-tools.test.ts
+++ b/services/mcp/tests/unit/generate-tools.test.ts
@@ -1503,6 +1503,16 @@ describe('ToolConfigSchema validation', () => {
expect(result.success).toBe(true)
})
+ it('rejects response.strip_nulls on a list tool', () => {
+ const result = ToolConfigSchema.safeParse({
+ operation: 'things_list',
+ enabled: true,
+ list: true,
+ response: { strip_nulls: true },
+ })
+ expect(result.success).toBe(false)
+ })
+
it('accepts response.exclude alone', () => {
const result = ToolConfigSchema.safeParse({
operation: 'things_list',
@@ -1522,7 +1532,7 @@ describe('buildResponseFilter', () => {
const config: ToolConfig = { operation: 'things_list', enabled: true }
const result = buildResponseFilter(config)
expect(result.code).toBe('')
- expect(result.helperImport).toBeNull()
+ expect(result.helperImports).toEqual([])
})
it('generates pickResponseFields for detail endpoint with response.include', () => {
@@ -1534,7 +1544,7 @@ describe('buildResponseFilter', () => {
const result = buildResponseFilter(config)
expect(result.code).toContain('pickResponseFields(result, ')
expect(result.code).toContain("'id', 'name', 'status'")
- expect(result.helperImport).toBe('pickResponseFields')
+ expect(result.helperImports).toEqual(['pickResponseFields'])
})
it('generates omitResponseFields for detail endpoint with response.exclude', () => {
@@ -1546,7 +1556,7 @@ describe('buildResponseFilter', () => {
const result = buildResponseFilter(config)
expect(result.code).toContain('omitResponseFields(result, ')
expect(result.code).toContain("'filters', 'created_by'")
- expect(result.helperImport).toBe('omitResponseFields')
+ expect(result.helperImports).toEqual(['omitResponseFields'])
})
it('maps pickResponseFields over results for list endpoint with response.include', () => {
@@ -1559,7 +1569,7 @@ describe('buildResponseFilter', () => {
const result = buildResponseFilter(config)
expect(result.code).toContain('(result.results ?? []).map')
expect(result.code).toContain('pickResponseFields(item, ')
- expect(result.helperImport).toBe('pickResponseFields')
+ expect(result.helperImports).toEqual(['pickResponseFields'])
})
it('maps omitResponseFields over results for list endpoint with response.exclude', () => {
@@ -1572,7 +1582,29 @@ describe('buildResponseFilter', () => {
const result = buildResponseFilter(config)
expect(result.code).toContain('(result.results ?? []).map')
expect(result.code).toContain('omitResponseFields(item, ')
- expect(result.helperImport).toBe('omitResponseFields')
+ expect(result.helperImports).toEqual(['omitResponseFields'])
+ })
+
+ it('wraps the exclude expression in stripNullFields for response.strip_nulls', () => {
+ const config: ToolConfig = {
+ operation: 'things_retrieve',
+ enabled: true,
+ response: { exclude: ['filters'], strip_nulls: true },
+ }
+ const result = buildResponseFilter(config)
+ expect(result.code).toContain("stripNullFields(omitResponseFields(result, ['filters']))")
+ expect(result.helperImports).toEqual(['omitResponseFields', 'stripNullFields'])
+ })
+
+ it('generates stripNullFields alone when no include or exclude is configured', () => {
+ const config: ToolConfig = {
+ operation: 'things_retrieve',
+ enabled: true,
+ response: { strip_nulls: true },
+ }
+ const result = buildResponseFilter(config)
+ expect(result.code).toContain('stripNullFields(result)')
+ expect(result.helperImports).toEqual(['stripNullFields'])
})
it('preserves wildcard dot-path patterns in generated code', () => {
diff --git a/services/mcp/tests/unit/utils.test.ts b/services/mcp/tests/unit/utils.test.ts
index 59a82620a82d..a71c57f0f301 100644
--- a/services/mcp/tests/unit/utils.test.ts
+++ b/services/mcp/tests/unit/utils.test.ts
@@ -2,7 +2,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { env } from '@/lib/env'
import { extractBearerToken, formatPrompt, redactToken, sanitizeHeaderValue } from '@/lib/utils'
-import { omitResponseFields, pickResponseFields, withInformationalResponse, withPostHogUrl } from '@/tools/tool-utils'
+import {
+ omitResponseFields,
+ pickResponseFields,
+ stripNullFields,
+ withInformationalResponse,
+ withPostHogUrl,
+} from '@/tools/tool-utils'
import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, type Context } from '@/tools/types'
// Mock the env proxy that the production code reads through, rather than poking
@@ -263,6 +269,34 @@ describe('utils', () => {
})
})
+ describe('stripNullFields', () => {
+ it('removes null-valued keys and keeps the other falsy values', () => {
+ const obj = { id: 1, name: null, saved: false, count: 0, label: '' }
+ expect(stripNullFields(obj)).toEqual({ id: 1, saved: false, count: 0, label: '' })
+ })
+
+ it('recurses through objects nested in arrays', () => {
+ const obj = {
+ series: [
+ { event: 'signup', math_property: null },
+ { event: 'login', limit: null },
+ ],
+ }
+ expect(stripNullFields(obj)).toEqual({ series: [{ event: 'signup' }, { event: 'login' }] })
+ })
+
+ it('keeps array element positions when an element is null', () => {
+ const obj = { values: [1, null, 3] }
+ expect(stripNullFields(obj)).toEqual({ values: [1, null, 3] })
+ })
+
+ it('does not mutate the original object', () => {
+ const obj = { id: 1, nested: { keep: true, drop: null } }
+ stripNullFields(obj)
+ expect(obj.nested.drop).toBeNull()
+ })
+ })
+
describe('omitResponseFields', () => {
it('removes specified top-level fields', () => {
const obj = { id: 1, name: 'test', filters: { a: 1 }, created_by: 'user' }