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(mcp): type and name dashboard tile selectors (#121463)

Matt Pua2648fb4241c6
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
index a860a8dd40e9..fb56a8b4755e 100644
--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
@@ -635,7 +635,11 @@ Product teams own their definitions and control which operations are exposed as
The two overrides above reshape a generated tool's schema.
Neither can change what happens around the request.
`validators` runs as a synchronous `superRefine`, so it cannot await anything;
- `inject_body` supplies static values; `rename_params` only renames.
+ `inject_body` supplies static values; `rename_params` renames body or query parameters.
+ Query aliases retain the original HTTP parameter name. For example, `dashboard-insights-run` exposes
+ `dashboard_tile_ids` as an integer array and sends it as the API's comma-separated `tile_ids` parameter.
+ The tool also accepts `tile_ids` as a legacy alias, with either an array or a comma-separated string.
+ Its `id` parameter accepts `dashboard_id` and `dashboardId` aliases.
When a tool has to read current state before writing, or handle a specific error, set `hooks:` on the tool.
The value is a module path relative to `src/tools/`, without the extension:
diff --git a/products/dashboards/mcp/tools.yaml b/products/dashboards/mcp/tools.yaml
index 478e3cb3a527..28d5c2ca7af7 100644
--- a/products/dashboards/mcp/tools.yaml
+++ b/products/dashboards/mcp/tools.yaml
@@ -299,15 +299,24 @@ tools:
'json' for raw query results. 'optimized' output is bounded so a wide dashboard fits in context: a tile's
table is held to max_result_chars characters by keeping its header and both ends and dropping rows from the
middle, held down further by whatever the response has left of its overall budget, and tiles past that
- budget are not run. To fit more of what you need into that budget, in order: pass tile_ids to run only the
- tiles you care about; pass filters_override={"interval": "day"} (or "week"/"month") to turn a long run of
- hourly buckets into fewer, wider rows, which also cuts the query cost; raise max_result_chars (200 or more),
- or pass 0 for a tile's whole table. 'json' is unbounded, so pair it with tile_ids. Supports
+ budget are not run. To fit more of what you need into that budget, in order: pass dashboard_tile_ids to run
+ only the tiles you care about; pass filters_override={"interval": "day"} (or "week"/"month") to turn a long
+ run of hourly buckets into fewer, wider rows, which also cuts the query cost; raise max_result_chars (200 or
+ more), or pass 0 for a tile's whole table. 'json' is unbounded, so pair it with dashboard_tile_ids. Supports
variables_override and filters_override query params to run insights with one-off overrides without
persisting; see the parameter descriptions for the exact JSON shape required.
param_overrides:
+ tile_ids:
+ input_schema: DashboardInsightTileIdsSchema
+ aliases:
+ - tile_ids
id:
cast: string-int
+ aliases:
+ - dashboard_id
+ - dashboardId
+ rename_params:
+ tile_ids: dashboard_tile_ids
reads_ingested_data: events
dashboard-reorder-tiles:
operation: dashboards_reorder_tiles_create
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 3c418a8fe177..1b7b674c584e 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -3811,7 +3811,7 @@
}
},
"dashboard-insights-run": {
- "description": "Run all insights on a dashboard and return their results. Uses cached results by default (may be stale); set refresh to 'blocking' for fresh results. Set format to 'optimized' (default) for LLM-friendly text tables or 'json' for raw query results. 'optimized' output is bounded so a wide dashboard fits in context: a tile's table is held to max_result_chars characters by keeping its header and both ends and dropping rows from the middle, held down further by whatever the response has left of its overall budget, and tiles past that budget are not run. To fit more of what you need into that budget, in order: pass tile_ids to run only the tiles you care about; pass filters_override={\"interval\": \"day\"} (or \"week\"/\"month\") to turn a long run of hourly buckets into fewer, wider rows, which also cuts the query cost; raise max_result_chars (200 or more), or pass 0 for a tile's whole table. 'json' is unbounded, so pair it with tile_ids. Supports variables_override and filters_override query params to run insights with one-off overrides without persisting; see the parameter descriptions for the exact JSON shape required.",
+ "description": "Run all insights on a dashboard and return their results. Uses cached results by default (may be stale); set refresh to 'blocking' for fresh results. Set format to 'optimized' (default) for LLM-friendly text tables or 'json' for raw query results. 'optimized' output is bounded so a wide dashboard fits in context: a tile's table is held to max_result_chars characters by keeping its header and both ends and dropping rows from the middle, held down further by whatever the response has left of its overall budget, and tiles past that budget are not run. To fit more of what you need into that budget, in order: pass dashboard_tile_ids to run only the tiles you care about; pass filters_override={\"interval\": \"day\"} (or \"week\"/\"month\") to turn a long run of hourly buckets into fewer, wider rows, which also cuts the query cost; raise max_result_chars (200 or more), or pass 0 for a tile's whole table. 'json' is unbounded, so pair it with dashboard_tile_ids. Supports variables_override and filters_override query params to run insights with one-off overrides without persisting; see the parameter descriptions for the exact JSON shape required.",
"category": "Dashboards",
"feature": "dashboards",
"summary": "Run dashboard insights",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index ebfdadd9367d..65a737504591 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3826,7 +3826,7 @@
}
},
"dashboard-insights-run": {
- "description": "Run all insights on a dashboard and return their results. Uses cached results by default (may be stale); set refresh to 'blocking' for fresh results. Set format to 'optimized' (default) for LLM-friendly text tables or 'json' for raw query results. 'optimized' output is bounded so a wide dashboard fits in context: a tile's table is held to max_result_chars characters by keeping its header and both ends and dropping rows from the middle, held down further by whatever the response has left of its overall budget, and tiles past that budget are not run. To fit more of what you need into that budget, in order: pass tile_ids to run only the tiles you care about; pass filters_override={\"interval\": \"day\"} (or \"week\"/\"month\") to turn a long run of hourly buckets into fewer, wider rows, which also cuts the query cost; raise max_result_chars (200 or more), or pass 0 for a tile's whole table. 'json' is unbounded, so pair it with tile_ids. Supports variables_override and filters_override query params to run insights with one-off overrides without persisting; see the parameter descriptions for the exact JSON shape required.",
+ "description": "Run all insights on a dashboard and return their results. Uses cached results by default (may be stale); set refresh to 'blocking' for fresh results. Set format to 'optimized' (default) for LLM-friendly text tables or 'json' for raw query results. 'optimized' output is bounded so a wide dashboard fits in context: a tile's table is held to max_result_chars characters by keeping its header and both ends and dropping rows from the middle, held down further by whatever the response has left of its overall budget, and tiles past that budget are not run. To fit more of what you need into that budget, in order: pass dashboard_tile_ids to run only the tiles you care about; pass filters_override={\"interval\": \"day\"} (or \"week\"/\"month\") to turn a long run of hourly buckets into fewer, wider rows, which also cuts the query cost; raise max_result_chars (200 or more), or pass 0 for a tile's whole table. 'json' is unbounded, so pair it with dashboard_tile_ids. Supports variables_override and filters_override query params to run insights with one-off overrides without persisting; see the parameter descriptions for the exact JSON shape required.",
"category": "Dashboards",
"feature": "dashboards",
"summary": "Run dashboard insights",
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index a6e83fd63e29..b75efdb6ae12 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -126,6 +126,16 @@
"maximum": 9007199254740991,
"description": "Version returned by channel-instructions-retrieve. Use 0 when the channel has no instructions."
},
+ "DashboardInsightTileIdsSchema": {
+ "description": "IDs from tiles[].id in dashboard-get. Omit to run all insight tiles. Text and widget tiles produce no insight result.",
+ "minItems": 1,
+ "type": "array",
+ "items": {
+ "type": "integer",
+ "exclusiveMinimum": 0,
+ "maximum": 9007199254740991
+ }
+ },
"DashboardTileCreateSchema": {
"type": "object",
"properties": {
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index 6d705403b1e0..98cb30127fd2 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -717,7 +717,7 @@ function composeToolSchema(
}
if (override.aliases?.length) {
- paramAliases[paramName] = override.aliases
+ paramAliases[renameMap.get(paramName) ?? paramName] = override.aliases
}
// An `optional` override must also surface as optional in the agent-facing
@@ -812,10 +812,13 @@ function composeToolSchema(
// When the original is also a path param, the body copy was already dropped above
// and the surviving key addresses the resource, so omitting it here would leave the
// handler with no value for the URL.
+ const fieldSource = queryParamNames.includes(original)
+ ? `(${schemaExpr}).shape['${original}']`
+ : `${bodyImport}.shape['${original}']`
if (!pathParamNames.includes(original)) {
schemaExpr += `\n .omit({ '${original}': true })`
}
- schemaExpr += `\n .extend({ ${alias}: ${bodyImport}.shape['${original}'] })`
+ schemaExpr += `\n .extend({ ${alias}: ${fieldSource} })`
}
}
@@ -854,7 +857,11 @@ function composeToolSchema(
// param, so an alias that is also a real parameter of this operation, or an alias
// two params both claim, would silently drop a value. Checked after every override
// has run, because input_schema overrides add body fields inside the loop above.
- const declaredParamNames = new Set([...pathParamNames, ...queryParamNames, ...bodyFieldNames])
+ const declaredParamNames = new Set([
+ ...pathParamNames,
+ ...queryParamNames.map((name) => renameMap.get(name) ?? name),
+ ...bodyFieldNames,
+ ])
const aliasOwners = new Map<string, string>()
for (const [paramName, aliases] of Object.entries(paramAliases)) {
for (const alias of aliases) {
@@ -882,8 +889,8 @@ function composeToolSchema(
schemaRefBlocks,
schemaExpr,
pathParamNames,
- queryParamNames,
- csvQueryParamNames,
+ queryParamNames: queryParamNames.map((name) => renameMap.get(name) ?? name),
+ csvQueryParamNames: new Set([...csvQueryParamNames].map((name) => renameMap.get(name) ?? name)),
bodyFieldNames,
variantSpecificBodyFieldNames,
renamedFields,
@@ -1255,15 +1262,16 @@ function generateToolCode(
if (hasQuery) {
const queryAssignments = composition.queryParamNames
.map((qn) => {
+ const queryKey = composition.renamedFields[qn] ?? qn
// explode: false params are comma-joined here because
// ApiClient.request() JSON-stringifies raw arrays (the
// json.loads()-style contract), which DRF CSV filters can't parse.
// Callers may pass either the array shape or a single string, so
// only join when it's actually an array; an empty array is omitted.
if (composition.csvQueryParamNames.has(qn)) {
- return ` ${qn}: Array.isArray(params.${qn}) ? params.${qn}.join(',') || undefined : params.${qn},`
+ return ` ${queryKey}: Array.isArray(params.${qn}) ? params.${qn}.join(',') || undefined : params.${qn},`
}
- return ` ${qn}: params.${qn},`
+ return ` ${queryKey}: params.${qn},`
})
.join('\n')
handlerBody += ` query: {\n${queryAssignments}\n },\n`
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 18bfd3f6fa38..ec104e232b84 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -45,6 +45,21 @@ export const ChannelInstructionsBaseVersionSchema = z
.max(9007199254740991)
.describe('Version returned by channel-instructions-retrieve. Use 0 when the channel has no instructions.')
+function normalizeDashboardTileIds(value: unknown): unknown {
+ if (typeof value === 'string' && /^\s*\d+(?:\s*,\s*\d+)*\s*$/.test(value)) {
+ return value.split(',').map(Number)
+ }
+ return value
+}
+
+export const DashboardInsightTileIdsSchema = z
+ .preprocess(normalizeDashboardTileIds, z.array(z.number().int().positive()).min(1))
+ .optional()
+ .describe(
+ 'IDs from tiles[].id in dashboard-get. Omit to run all insight tiles. Text and widget tiles produce no insight result.'
+ )
+ .transform((ids): string | undefined => ids?.join(','))
+
const DashboardTileLayoutSchema = z.object({
x: z.number().int().min(0).optional().describe('Column position in the dashboard grid (0-indexed).'),
y: z.number().int().min(0).optional().describe('Row position in the dashboard grid (0-indexed).'),
diff --git a/services/mcp/src/tools/generated/dashboards.ts b/services/mcp/src/tools/generated/dashboards.ts
index 15390ad609ca..d73fc5159926 100644
--- a/services/mcp/src/tools/generated/dashboards.ts
+++ b/services/mcp/src/tools/generated/dashboards.ts
@@ -3,8 +3,8 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/dashboards/api'
-import { DashboardTileCreateSchema } from '@/schema/tool-inputs'
-import { castStringToInt } from '@/tools/cast-helpers'
+import { DashboardInsightTileIdsSchema, DashboardTileCreateSchema } from '@/schema/tool-inputs'
+import { castStringToInt, normalizeParamAliases } from '@/tools/cast-helpers'
import {
withPostHogUrl,
withAgentNote,
@@ -335,23 +335,38 @@ const dashboardGet = (): ToolBase<
const DashboardInsightsRunSchema = () => {
const DashboardsRunInsightsRetrieveParams = orvalSchemas.DashboardsRunInsightsRetrieveParams()
const DashboardsRunInsightsRetrieveQueryParams = orvalSchemas.DashboardsRunInsightsRetrieveQueryParams()
- return DashboardsRunInsightsRetrieveParams.omit({ project_id: true })
- .extend(DashboardsRunInsightsRetrieveQueryParams.omit({ format: true }).shape)
- .extend({ id: z.preprocess(castStringToInt, DashboardsRunInsightsRetrieveParams.shape['id']) })
- .extend({
- filters_override: z
- .union([z.string(), z.record(z.string(), z.unknown())])
- .optional()
- .describe(
- 'Object (or pre-encoded JSON string) to override dashboard filters for this request only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token.'
- ),
- variables_override: z
- .union([z.string(), z.record(z.string(), z.unknown())])
- .optional()
- .describe(
- 'Object (or pre-encoded JSON string) to override dashboard variables for this request only (not persisted). Format: {"<variable_id>": {"code_name": "<code_name>", "variableId": "<variable_id>", "value": <new_value>}}. Each entry must include `code_name` — partial entries are silently dropped. The simplest workflow is to call `dashboard-get` first, copy the matching entry from the response, and mutate `value`. Top-level keys replace; nested values are not deep-merged. Ignored when accessed via a sharing token.'
- ),
- })
+ return z.preprocess(
+ normalizeParamAliases({ dashboard_tile_ids: ['tile_ids'], id: ['dashboard_id', 'dashboardId'] }),
+ DashboardsRunInsightsRetrieveParams.omit({ project_id: true })
+ .extend(DashboardsRunInsightsRetrieveQueryParams.omit({ format: true }).shape)
+ .extend({
+ tile_ids: DashboardInsightTileIdsSchema,
+ id: z.preprocess(castStringToInt, DashboardsRunInsightsRetrieveParams.shape['id']),
+ })
+ .omit({ tile_ids: true })
+ .extend({
+ dashboard_tile_ids: DashboardsRunInsightsRetrieveParams.omit({ project_id: true })
+ .extend(DashboardsRunInsightsRetrieveQueryParams.omit({ format: true }).shape)
+ .extend({
+ tile_ids: DashboardInsightTileIdsSchema,
+ id: z.preprocess(castStringToInt, DashboardsRunInsightsRetrieveParams.shape['id']),
+ }).shape['tile_ids'],
+ })
+ .extend({
+ filters_override: z
+ .union([z.string(), z.record(z.string(), z.unknown())])
+ .optional()
+ .describe(
+ 'Object (or pre-encoded JSON string) to override dashboard filters for this request only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token.'
+ ),
+ variables_override: z
+ .union([z.string(), z.record(z.string(), z.unknown())])
+ .optional()
+ .describe(
+ 'Object (or pre-encoded JSON string) to override dashboard variables for this request only (not persisted). Format: {"<variable_id>": {"code_name": "<code_name>", "variableId": "<variable_id>", "value": <new_value>}}. Each entry must include `code_name` — partial entries are silently dropped. The simplest workflow is to call `dashboard-get` first, copy the matching entry from the response, and mutate `value`. Top-level keys replace; nested values are not deep-merged. Ignored when accessed via a sharing token.'
+ ),
+ })
+ )
}
const dashboardInsightsRun = (): ToolBase<
@@ -370,7 +385,7 @@ const dashboardInsightsRun = (): ToolBase<
max_result_chars: params.max_result_chars,
output_format: params.output_format,
refresh: params.refresh,
- tile_ids: params.tile_ids,
+ tile_ids: params.dashboard_tile_ids,
variables_override: params.variables_override,
},
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-insights-run.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-insights-run.json
index 2378a0195344..c03b1e0d6392 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-insights-run.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-insights-run.json
@@ -1,6 +1,16 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
+ "dashboard_tile_ids": {
+ "description": "IDs from tiles[].id in dashboard-get. Omit to run all insight tiles. Text and widget tiles produce no insight result.",
+ "items": {
+ "exclusiveMinimum": 0,
+ "maximum": 9007199254740991,
+ "type": "integer"
+ },
+ "minItems": 1,
+ "type": "array"
+ },
"filters_override": {
"anyOf": [
{
@@ -34,10 +44,6 @@
"enum": ["blocking", "force_blocking", "force_cache"],
"type": "string"
},
- "tile_ids": {
- "description": "Comma-separated dashboard tile IDs to run. Defaults to every insight tile on the dashboard. Use it to read one tile without receiving the others. An ID that is not on this dashboard is rejected.",
- "type": "string"
- },
"variables_override": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/dashboard-insights-run.test.ts b/services/mcp/tests/unit/dashboard-insights-run.test.ts
new file mode 100644
index 000000000000..0e9264617ab3
--- /dev/null
+++ b/services/mcp/tests/unit/dashboard-insights-run.test.ts
@@ -0,0 +1,124 @@
+import { createServer } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import { describe, expect, it, vi } from 'vitest'
+import { z } from 'zod'
+
+import { ApiClient } from '@/api/client'
+import { DashboardsRunInsightsRetrieveQueryParams } from '@/generated/dashboards/api'
+import { createExecTool } from '@/tools/exec'
+import { GENERATED_TOOLS } from '@/tools/generated/dashboards'
+import type { Context } from '@/tools/types'
+
+describe('dashboard-insights-run', () => {
+ const tool = GENERATED_TOOLS['dashboard-insights-run']!()
+
+ it.each([
+ [{ dashboard_tile_ids: [101, 102] }, '101,102'],
+ [{ tile_ids: [101, 102] }, '101,102'],
+ [{ tile_ids: '101,102' }, '101,102'],
+ [{ tile_ids: ' 101, 102 ' }, '101,102'],
+ [{ dashboard_tile_ids: [101], tile_ids: [102] }, '101'],
+ [{}, undefined],
+ ])('sends the selected dashboard tiles to the API: %j', async (selector, expected) => {
+ const request = vi.fn().mockResolvedValue({ results: [] })
+ const context = {
+ api: { request, getProjectBaseUrl: () => 'https://example.com/project/42' },
+ stateManager: { getProjectId: async () => '42' },
+ } as unknown as Context
+
+ const params = tool.schema.parse({ id: 7, ...selector, output_format: 'json' })
+ await tool.handler(context, params)
+
+ expect(request).toHaveBeenCalledWith(
+ expect.objectContaining({
+ path: '/api/projects/42/dashboards/7/run_insights/',
+ query: expect.objectContaining({ tile_ids: expected, output_format: 'json' }),
+ })
+ )
+ expect(request.mock.calls[0]![0].query).not.toHaveProperty('dashboard_tile_ids')
+ })
+
+ it.each(['direct', 'exec'])('preserves the tile selection through %s and real HTTP transport', async (mode) => {
+ const urls: string[] = []
+ const server = createServer((request, response) => {
+ urls.push(request.url!)
+ response.setHeader('Content-Type', 'application/json')
+ response.end(JSON.stringify({ results: [] }))
+ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ const baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
+ const context = {
+ api: new ApiClient({ apiToken: 'test-token', baseUrl }),
+ stateManager: { getProjectId: async () => '42' },
+ } as unknown as Context
+ const exec = createExecTool(
+ [
+ {
+ ...tool,
+ title: 'Run dashboard insights',
+ description: '',
+ scopes: [],
+ annotations: {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: true,
+ },
+ },
+ ],
+ context,
+ '',
+ '',
+ undefined
+ )
+ try {
+ for (const input of [
+ { id: 7, dashboard_tile_ids: [101, 102] },
+ { dashboard_id: '7', tile_ids: [101, 102] },
+ { dashboardId: 7, tile_ids: '101,102' },
+ ]) {
+ if (mode === 'exec') {
+ await exec.handler(context, {
+ command: `call --json dashboard-insights-run ${JSON.stringify(input)}`,
+ })
+ } else {
+ await tool.handler(context, tool.schema.parse(input))
+ }
+ }
+ const invalid = { id: 7, tile_ids: 'insight-short-id' }
+ if (mode === 'exec') {
+ await expect(
+ exec.handler(context, {
+ command: `call --json dashboard-insights-run ${JSON.stringify(invalid)}`,
+ })
+ ).rejects.toThrow('dashboard_tile_ids')
+ } else {
+ expect(tool.schema.safeParse(invalid).success).toBe(false)
+ }
+ expect(urls).toHaveLength(3)
+ for (const url of urls) {
+ const request = new URL(url, baseUrl)
+ expect(request.pathname).toBe('/api/projects/42/dashboards/7/run_insights/')
+ expect(request.searchParams.get('tile_ids')).toBe('101,102')
+ expect(request.searchParams.has('dashboard_tile_ids')).toBe(false)
+ }
+ } finally {
+ await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())))
+ }
+ })
+
+ it('advertises an array while the HTTP API keeps its string contract', () => {
+ expect(DashboardsRunInsightsRetrieveQueryParams().shape.tile_ids.safeParse([101, 102]).success).toBe(false)
+ expect(DashboardsRunInsightsRetrieveQueryParams().shape.tile_ids.safeParse('101,102').success).toBe(true)
+ const schema = z.toJSONSchema(tool.schema, { io: 'input' })
+ expect(schema.properties?.dashboard_tile_ids).toMatchObject({ type: 'array', items: { type: 'integer' } })
+ expect(schema.properties).not.toHaveProperty('tile_ids')
+ })
+
+ it.each(['abc123', '101,abc123', ['abc123'], [0], [-1], [1.5], []].map((ids) => ({ ids })))(
+ 'rejects an invalid dashboard tile selector: %j',
+ ({ ids }) => {
+ expect(tool.schema.safeParse({ id: 7, dashboard_tile_ids: ids }).success).toBe(false)
+ }
+ )
+})
diff --git a/services/mcp/tests/unit/generate-tools.test.ts b/services/mcp/tests/unit/generate-tools.test.ts
index f87bb4d6265d..2be13dcc15e7 100644
--- a/services/mcp/tests/unit/generate-tools.test.ts
+++ b/services/mcp/tests/unit/generate-tools.test.ts
@@ -988,6 +988,36 @@ describe('anyOf / oneOf body schemas (discriminated unions)', () => {
})
describe('rename_params', () => {
+ it('maps a query alias to the original HTTP key and preserves its schema override', () => {
+ const config: ToolConfig = {
+ operation: 'things_list',
+ enabled: true,
+ rename_params: { tile_ids: 'dashboard_tile_ids' },
+ param_overrides: { tile_ids: { input_schema: 'DashboardInsightTileIdsSchema', aliases: ['tile_ids'] } },
+ }
+ const resolved = makeResolved({
+ operation: {
+ operationId: 'things_list',
+ parameters: [{ in: 'query', name: 'tile_ids', schema: { type: 'string' } }],
+ },
+ })
+ const result = generateToolCode(
+ 'things-list',
+ config,
+ resolved,
+ defaultCategory,
+ makeSpec(),
+ new Set<string>(),
+ stubGetQuerySchema
+ )
+
+ expect(result.code).toContain('dashboard_tile_ids:')
+ expect(result.code).toContain('DashboardInsightTileIdsSchema')
+ expect(result.code).toContain('tile_ids: params.dashboard_tile_ids')
+ expect(result.code).not.toContain('ThingsListBody')
+ expect(result.code).toContain("normalizeParamAliases({ dashboard_tile_ids: ['tile_ids'] })")
+ })
+
it('swaps field names in schema expression and tracks renames', () => {
const config: ToolConfig = {
operation: 'things_create',