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): add `cast` capability to tools.yaml and apply for experiments (#57806)

Marcel Poelker057a41a9a64f
diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yaml
index a7e44c205ef1..c236768bfa53 100644
--- a/products/experiments/mcp/tools.yaml
+++ b/products/experiments/mcp/tools.yaml
@@ -44,6 +44,9 @@ tools:
No request body needed. Can be restored later via the unarchive tool.
+ param_overrides:
+ id:
+ cast: string-int
ui_app: experiment
experiment-create:
operation: experiments_create
@@ -117,6 +120,9 @@ tools:
description: >
Delete an experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the
user's reference first. Always confirm by name before deleting.
+ param_overrides:
+ id:
+ cast: string-int
soft_delete: true
response:
include:
@@ -147,6 +153,9 @@ tools:
meaning changes to one experiment's flag (e.g. shipping a variant, pausing) will affect both experiments.
Always confirm the new flag key with the user before duplicating. Optionally provide a custom name (defaults
to "Original Name (Copy)").
+ param_overrides:
+ id:
+ cast: string-int
experiment-end:
operation: experiments_end_create
enabled: true
@@ -178,6 +187,9 @@ tools:
Other options: use ship_variant to end AND roll out a winner. Use pause to temporarily deactivate the flag
without ending.
+ param_overrides:
+ id:
+ cast: string-int
ui_app: experiment
experiment-get:
operation: experiments_retrieve
@@ -200,6 +212,9 @@ tools:
end_date, linked feature_flag (with variants, filters, active state), metrics and metrics_secondary arrays,
conclusion and conclusion_comment if ended, parameters (including feature_flag_variants and
recommended_running_time), stats_config, and type (web/product).
+ param_overrides:
+ id:
+ cast: string-int
ui_app: experiment
experiment-holdouts-create:
operation: experiment_holdouts_create
@@ -245,6 +260,9 @@ tools:
No request body needed.
+ param_overrides:
+ id:
+ cast: string-int
ui_app: experiment
experiment-list:
operation: experiments_list
@@ -274,6 +292,14 @@ tools:
Filter by experiment status. Values: "draft" (not yet launched), "running" (launched, flag active),
"paused" (launched, flag deactivated — mutually exclusive with running), "stopped" or "complete"
(both mean ended), "all" (no filter). Defaults to all non-archived experiments.
+ limit:
+ cast: string-int
+ offset:
+ cast: string-int
+ created_by_id:
+ cast: string-int
+ feature_flag_id:
+ cast: string-int
ui_app: experiment-list
response:
include:
@@ -316,6 +342,9 @@ tools:
No request body needed. Use resume to reactivate.
+ param_overrides:
+ id:
+ cast: string-int
ui_app: experiment
experiment-reset:
operation: experiments_reset_create
@@ -346,6 +375,9 @@ tools:
No request body needed.
+ param_overrides:
+ id:
+ cast: string-int
ui_app: experiment
experiment-resume:
operation: experiments_resume_create
@@ -374,6 +406,9 @@ tools:
No request body needed.
+ param_overrides:
+ id:
+ cast: string-int
ui_app: experiment
experiment-saved-metrics-create:
operation: experiment_saved_metrics_create
@@ -431,6 +466,9 @@ tools:
Returns 400 if: experiment is in draft ("Experiment has not been launched yet."), variant_key not found on
the flag, or no linked feature flag. Returns 409 if an approval policy requires review before the flag
change takes effect — includes a change_request_id in the response.
+ param_overrides:
+ id:
+ cast: string-int
ui_app: experiment
experiment-stats:
operation: experiments_stats_retrieve
@@ -466,6 +504,9 @@ tools:
Returns a timeseries object keyed by date (YYYY-MM-DD) with per-variant statistical results for each day,
overall status ("pending", "completed", "partial", "failed"), computed_at timestamp, and
recalculation_status if a recalculation is in progress.
+ param_overrides:
+ id:
+ cast: string-int
ui_app: experiment-results
experiment-unarchive:
operation: experiments_unarchive_create
@@ -490,6 +531,9 @@ tools:
No request body needed.
+ param_overrides:
+ id:
+ cast: string-int
ui_app: experiment
experiment-update:
operation: experiments_partial_update
@@ -550,6 +594,9 @@ tools:
- archived
- allow_unknown_events
- update_feature_flag_params
+ param_overrides:
+ id:
+ cast: string-int
ui_app: experiment
experiments-copy-to-project-create:
operation: experiments_copy_to_project_create
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index 39f9dea0a50e..cf5ac7dacd30 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -317,6 +317,8 @@ function operationIdToPascal(operationId: string): string {
interface SchemaComposition {
orvalImports: string[]
toolInputsImports: string[]
+ /** Names of helpers imported from `@/tools/cast-helpers` (e.g. `castStringToInt`). */
+ castHelperImports: Set<string>
/** Inline Zod declarations generated from schema_ref (emitted before the schema declaration) */
schemaRefBlocks: string[]
schemaExpr: string
@@ -341,6 +343,14 @@ function composeToolSchema(
const pathParamNames: string[] = []
const queryParamNames: string[] = []
const bodyFieldNames: string[] = []
+ /**
+ * Params whose underlying Orval shape is `.optional()` (or `.nullish()`).
+ * Used by the cast branch in `param_overrides`: `z.preprocess(fn, source)`
+ * does not propagate optionality to the JSON Schema output, so we re-apply
+ * `.optional()` after the wrapper for fields that were optional at source.
+ * Path params are omitted (always required).
+ */
+ const optionalParamNames = new Set<string>()
const excludeSet = new Set(config.exclude_params ?? [])
const includeSet = config.include_params ? new Set(config.include_params) : undefined
@@ -404,6 +414,9 @@ function composeToolSchema(
}
for (const p of usefulQueryParams) {
queryParamNames.push(p.name)
+ if (!p.required) {
+ optionalParamNames.add(p.name)
+ }
}
}
}
@@ -417,6 +430,10 @@ function composeToolSchema(
const bodyOmitFields = new Set<string>()
const bodySchema = resolveSchema(spec, bodySchemaRef)
+ // PATCH bodies are partial — Orval emits every field as `.optional()`.
+ // For POST/PUT, optionality follows the body schema's `required` list.
+ const bodyRequiredSet = new Set(bodySchema?.required ?? [])
+ const bodyAllOptional = resolved.method === 'PATCH'
if (bodySchema?.properties) {
for (const [name, prop] of Object.entries(bodySchema.properties)) {
@@ -448,7 +465,11 @@ function composeToolSchema(
// handler references params.<alias>. The original→alias
// mapping is tracked in renamedFields for body-building.
const alias = renameMap.get(name)
- bodyFieldNames.push(alias ?? name)
+ const fieldKey = alias ?? name
+ bodyFieldNames.push(fieldKey)
+ if (bodyAllOptional || !bodyRequiredSet.has(name)) {
+ optionalParamNames.add(fieldKey)
+ }
}
}
@@ -479,7 +500,9 @@ function composeToolSchema(
// - schema_ref → generate inline Zod from schema.json and use that
// - description → wrap the existing Orval-derived field with .describe(...)
// - optional+fallback → make param optional and resolve from state when omitted
+ // - cast → wrap with z.preprocess(...) from @/tools/cast-helpers
const toolInputsImports: string[] = []
+ const castHelperImports = new Set<string>()
const schemaRefBlocks: string[] = []
const paramFallbacks: Record<string, string> = {}
// Fields added via param_overrides (input_schema/schema_ref) need to participate in
@@ -497,6 +520,22 @@ function composeToolSchema(
paramFallbacks[paramName] = override.fallback
}
+ const castHelper = override.cast === 'string-int' ? 'castStringToInt' : null
+ if (castHelper) {
+ castHelperImports.add(castHelper)
+ }
+ // `z.preprocess(fn, source)` does not propagate inner `.optional()` to
+ // the JSON Schema output (zod 4 marks the wrapped field as required).
+ // Re-apply `.optional()` after the preprocess for fields whose source
+ // was optional, so the agent-facing tool schema stays accurate.
+ const wrapWithCast = (inner: string): string => {
+ if (!castHelper) {
+ return inner
+ }
+ const wrapped = `z.preprocess(${castHelper}, ${inner})`
+ return optionalParamNames.has(paramName) ? `${wrapped}.optional()` : wrapped
+ }
+
if (override.input_schema) {
toolInputsImports.push(override.input_schema)
schemaOverrides.push(`${paramName}: ${override.input_schema}${optionalSuffix}`)
@@ -512,9 +551,9 @@ function composeToolSchema(
if (isWriteOp && !bodyFieldNames.includes(paramName)) {
bodyFieldNames.push(paramName)
}
- } else if (override.description || override.default !== undefined || override.optional) {
+ } else if (override.description || override.default !== undefined || override.optional || castHelper) {
// Locate the Orval source schema this param came from, so we can reference
- // its original field type via .shape and wrap it with .describe(...) / .default(...) / .optional().
+ // its original field type via .shape and wrap it with .describe(...) / .default(...) / .optional() / cast.
let sourceImport: string | null = null
if (bodyFieldNames.includes(paramName)) {
sourceImport = `${pascal}Body`
@@ -534,7 +573,7 @@ function composeToolSchema(
if (override.optional) {
expr += '.optional()'
}
- schemaOverrides.push(`${paramName}: ${expr}`)
+ schemaOverrides.push(`${paramName}: ${wrapWithCast(expr)}`)
}
}
}
@@ -590,6 +629,7 @@ function composeToolSchema(
return {
orvalImports,
toolInputsImports,
+ castHelperImports,
schemaRefBlocks,
schemaExpr,
pathParamNames,
@@ -720,6 +760,7 @@ function generateToolCode(
code: string
orvalImports: string[]
toolInputsImports: string[]
+ castHelperImports: Set<string>
schemaRefBlocks: string[]
responseType: string | undefined
needsWithPostHogUrl: boolean
@@ -893,6 +934,7 @@ const ${factoryName} = (): ToolBase<typeof ${schemaName}, ${resultType}> => ${fa
code,
orvalImports: composition.orvalImports,
toolInputsImports: composition.toolInputsImports,
+ castHelperImports: composition.castHelperImports,
schemaRefBlocks: composition.schemaRefBlocks,
responseType,
needsWithPostHogUrl,
@@ -913,6 +955,7 @@ function generateCustomSchemaToolCode(
code: string
orvalImports: string[]
toolInputsImports: string[]
+ castHelperImports: Set<string>
schemaRefBlocks: string[]
responseType: string | undefined
needsWithPostHogUrl: boolean
@@ -988,6 +1031,7 @@ ${handlerBody} },
code,
orvalImports: [],
toolInputsImports: config.input_schema ? [config.input_schema] : [],
+ castHelperImports: new Set(),
schemaRefBlocks: [],
responseType,
needsWithPostHogUrl: false,
@@ -1064,6 +1108,7 @@ function generateCategoryFile(
const allOrvalImports = new Set<string>()
const allToolInputsImports = new Set<string>()
+ const allCastHelperImports = new Set<string>()
const allSchemaRefBlocks: string[] = []
const emittedSchemaRefDefs = new Set<string>()
const toolCodes: string[] = []
@@ -1083,6 +1128,9 @@ function generateCategoryFile(
for (const imp of result.toolInputsImports) {
allToolInputsImports.add(imp)
}
+ for (const imp of result.castHelperImports) {
+ allCastHelperImports.add(imp)
+ }
// Collect schema_ref blocks, deduplicating by const name
for (const block of result.schemaRefBlocks) {
for (const decl of block.split('\n\nconst ')) {
@@ -1214,6 +1262,11 @@ function generateCategoryFile(
? `import { ${[...allToolInputsImports].sort().join(', ')} } from '@/schema/tool-inputs'\n`
: ''
+ const castHelpersImportLine =
+ allCastHelperImports.size > 0
+ ? `import { ${[...allCastHelperImports].sort().join(', ')} } from '@/tools/cast-helpers'\n`
+ : ''
+
// Build tool-utils import (WithPostHogUrl type + withPostHogUrl runtime helper)
const toolUtilsTypeImports: string[] = []
const toolUtilsValueImports: string[] = []
@@ -1244,7 +1297,7 @@ function generateCategoryFile(
import { z } from 'zod'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
-${toolUtilsImportLine ? `${toolUtilsImportLine}` : ''}${schemasImportLine}${withUiAppImportLine}${toolInputsImportLine}${wrapperImportLine}${orvalImportLine}${schemaRefCode}${toolCodes.join('')}${wrapperSchemasCode}
+${toolUtilsImportLine ? `${toolUtilsImportLine}` : ''}${schemasImportLine}${withUiAppImportLine}${toolInputsImportLine}${castHelpersImportLine}${wrapperImportLine}${orvalImportLine}${schemaRefCode}${toolCodes.join('')}${wrapperSchemasCode}
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
${mapEntries}
}
diff --git a/services/mcp/scripts/yaml-config-schema.ts b/services/mcp/scripts/yaml-config-schema.ts
index f17dfa5a0850..e50eb79158c7 100644
--- a/services/mcp/scripts/yaml-config-schema.ts
+++ b/services/mcp/scripts/yaml-config-schema.ts
@@ -69,6 +69,20 @@ export const ToolConfigSchema = z
* Supported keys: 'orgId' (→ getOrgID()), 'projectId' (→ getProjectId()).
*/
fallback: z.enum(['orgId', 'projectId']).optional(),
+ /**
+ * Apply a narrow input cast to the parameter. Wraps the original
+ * Orval-derived schema with `z.preprocess(...)` so the field's
+ * description, integer/min/max constraints, etc. are preserved.
+ *
+ * Currently supported:
+ * - `'string-int'` — casts strings that look like a base-10 integer
+ * (e.g. `"123"`, `"-7"`) to a number. Anything else passes through
+ * unchanged so zod still rejects with its honest error.
+ *
+ * Mutually exclusive with `input_schema` and `schema_ref` (those
+ * fully replace the schema; cast composes with the existing one).
+ */
+ cast: z.enum(['string-int']).optional(),
})
.strict()
.refine((data) => !(data.input_schema && data.schema_ref), {
@@ -77,6 +91,10 @@ export const ToolConfigSchema = z
.refine((data) => !(data.optional && !data.fallback), {
message: 'optional requires a fallback key to resolve the value from state',
})
+ .refine((data) => !(data.cast && (data.input_schema || data.schema_ref)), {
+ message:
+ 'cast wraps the existing field schema and cannot be combined with input_schema or schema_ref (which replace it)',
+ })
)
.optional(),
mcp_version: z.number().int().positive().optional(),
diff --git a/services/mcp/src/tools/cast-helpers.ts b/services/mcp/src/tools/cast-helpers.ts
new file mode 100644
index 000000000000..c2ce5a50289d
--- /dev/null
+++ b/services/mcp/src/tools/cast-helpers.ts
@@ -0,0 +1,31 @@
+/**
+ * Input casts for permissive zod schemas at the MCP tool boundary.
+ *
+ * MCP clients — especially LLM agents — sometimes send numeric primitives
+ * as strings (e.g. `id: "123"` instead of `id: 123`). Production traces
+ * showed this consistently across experiment tools and a handful of others
+ * (`project-get`, `dashboard-get`, etc.). Rather than globally relaxing
+ * every numeric field via `z.coerce.number()` — which would also accept
+ * surprising inputs like `true → 1` and `null → 0` — these casts apply a
+ * narrow, opt-in conversion that only touches strings whose contents are
+ * unambiguously a base-10 integer. Leading zeros (e.g. `"007"`) are
+ * accepted and parse to the obvious value (7).
+ *
+ * Compose via `z.preprocess(castStringToInt, originalSchema)` so the
+ * field's existing description, integer constraint, and bounds are
+ * preserved. Anything that isn't a stringified integer passes through
+ * unchanged so zod can still reject true type mismatches with its honest
+ * error message.
+ *
+ * Wired up declaratively via `param_overrides: { id: { cast: 'string-int' } }`
+ * in product `tools.yaml` files — see services/mcp/scripts/generate-tools.ts.
+ */
+
+/** Cast strings that look like a base-10 integer (e.g. "123", "-7", "007") to a number; pass everything else through. */
+export const castStringToInt = (v: unknown): unknown => {
+ // Regex: optional minus sign followed by one or more digits
+ if (typeof v === 'string' && /^-?\d+$/.test(v)) {
+ return Number(v)
+ }
+ return v
+}
diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.ts
index 9428fe8f146e..39cc87d0e386 100644
--- a/services/mcp/src/tools/generated/experiments.ts
+++ b/services/mcp/src/tools/generated/experiments.ts
@@ -25,10 +25,13 @@ import {
ExperimentsUnarchiveCreateParams,
} from '@/generated/experiments/api'
import { withUiApp } from '@/resources/ui-apps'
+import { castStringToInt } from '@/tools/cast-helpers'
import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
-const ExperimentArchiveSchema = ExperimentsArchiveCreateParams.omit({ project_id: true })
+const ExperimentArchiveSchema = ExperimentsArchiveCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsArchiveCreateParams.shape['id']),
+})
const experimentArchive = (): ToolBase<typeof ExperimentArchiveSchema, WithPostHogUrl<Schemas.Experiment>> =>
withUiApp('experiment', {
@@ -109,7 +112,9 @@ const experimentCreate = (): ToolBase<typeof ExperimentCreateSchema, WithPostHog
},
})
-const ExperimentDeleteSchema = ExperimentsDestroyParams.omit({ project_id: true })
+const ExperimentDeleteSchema = ExperimentsDestroyParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsDestroyParams.shape['id']),
+})
const experimentDelete = (): ToolBase<typeof ExperimentDeleteSchema, Schemas.Experiment> => ({
name: 'experiment-delete',
@@ -126,9 +131,9 @@ const experimentDelete = (): ToolBase<typeof ExperimentDeleteSchema, Schemas.Exp
},
})
-const ExperimentDuplicateSchema = ExperimentsDuplicateCreateParams.omit({ project_id: true }).extend(
- ExperimentsDuplicateCreateBody.omit({ _create_in_folder: true }).shape
-)
+const ExperimentDuplicateSchema = ExperimentsDuplicateCreateParams.omit({ project_id: true })
+ .extend(ExperimentsDuplicateCreateBody.omit({ _create_in_folder: true }).shape)
+ .extend({ id: z.preprocess(castStringToInt, ExperimentsDuplicateCreateParams.shape['id']) })
const experimentDuplicate = (): ToolBase<typeof ExperimentDuplicateSchema, unknown> => ({
name: 'experiment-duplicate',
@@ -220,7 +225,9 @@ const experimentDuplicate = (): ToolBase<typeof ExperimentDuplicateSchema, unkno
},
})
-const ExperimentEndSchema = ExperimentsEndCreateParams.omit({ project_id: true }).extend(ExperimentsEndCreateBody.shape)
+const ExperimentEndSchema = ExperimentsEndCreateParams.omit({ project_id: true })
+ .extend(ExperimentsEndCreateBody.shape)
+ .extend({ id: z.preprocess(castStringToInt, ExperimentsEndCreateParams.shape['id']) })
const experimentEnd = (): ToolBase<typeof ExperimentEndSchema, WithPostHogUrl<Schemas.Experiment>> =>
withUiApp('experiment', {
@@ -244,7 +251,9 @@ const experimentEnd = (): ToolBase<typeof ExperimentEndSchema, WithPostHogUrl<Sc
},
})
-const ExperimentGetSchema = ExperimentsRetrieveParams.omit({ project_id: true })
+const ExperimentGetSchema = ExperimentsRetrieveParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsRetrieveParams.shape['id']),
+})
const experimentGet = (): ToolBase<typeof ExperimentGetSchema, WithPostHogUrl<Schemas.Experiment>> =>
withUiApp('experiment', {
@@ -260,7 +269,9 @@ const experimentGet = (): ToolBase<typeof ExperimentGetSchema, WithPostHogUrl<Sc
},
})
-const ExperimentLaunchSchema = ExperimentsLaunchCreateParams.omit({ project_id: true })
+const ExperimentLaunchSchema = ExperimentsLaunchCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsLaunchCreateParams.shape['id']),
+})
const experimentLaunch = (): ToolBase<typeof ExperimentLaunchSchema, WithPostHogUrl<Schemas.Experiment>> =>
withUiApp('experiment', {
@@ -280,6 +291,10 @@ const ExperimentListSchema = ExperimentsListQueryParams.extend({
status: ExperimentsListQueryParams.shape['status'].describe(
'Filter by experiment status. Values: "draft" (not yet launched), "running" (launched, flag active), "paused" (launched, flag deactivated — mutually exclusive with running), "stopped" or "complete" (both mean ended), "all" (no filter). Defaults to all non-archived experiments.'
),
+ limit: z.preprocess(castStringToInt, ExperimentsListQueryParams.shape['limit']).optional(),
+ offset: z.preprocess(castStringToInt, ExperimentsListQueryParams.shape['offset']).optional(),
+ created_by_id: z.preprocess(castStringToInt, ExperimentsListQueryParams.shape['created_by_id']).optional(),
+ feature_flag_id: z.preprocess(castStringToInt, ExperimentsListQueryParams.shape['feature_flag_id']).optional(),
})
const experimentList = (): ToolBase<typeof ExperimentListSchema, WithPostHogUrl<Schemas.PaginatedExperimentList>> =>
@@ -333,7 +348,9 @@ const experimentList = (): ToolBase<typeof ExperimentListSchema, WithPostHogUrl<
},
})
-const ExperimentPauseSchema = ExperimentsPauseCreateParams.omit({ project_id: true })
+const ExperimentPauseSchema = ExperimentsPauseCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsPauseCreateParams.shape['id']),
+})
const experimentPause = (): ToolBase<typeof ExperimentPauseSchema, WithPostHogUrl<Schemas.Experiment>> =>
withUiApp('experiment', {
@@ -349,7 +366,9 @@ const experimentPause = (): ToolBase<typeof ExperimentPauseSchema, WithPostHogUr
},
})
-const ExperimentResetSchema = ExperimentsResetCreateParams.omit({ project_id: true })
+const ExperimentResetSchema = ExperimentsResetCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsResetCreateParams.shape['id']),
+})
const experimentReset = (): ToolBase<typeof ExperimentResetSchema, WithPostHogUrl<Schemas.Experiment>> =>
withUiApp('experiment', {
@@ -365,7 +384,9 @@ const experimentReset = (): ToolBase<typeof ExperimentResetSchema, WithPostHogUr
},
})
-const ExperimentResumeSchema = ExperimentsResumeCreateParams.omit({ project_id: true })
+const ExperimentResumeSchema = ExperimentsResumeCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsResumeCreateParams.shape['id']),
+})
const experimentResume = (): ToolBase<typeof ExperimentResumeSchema, WithPostHogUrl<Schemas.Experiment>> =>
withUiApp('experiment', {
@@ -381,9 +402,9 @@ const experimentResume = (): ToolBase<typeof ExperimentResumeSchema, WithPostHog
},
})
-const ExperimentShipVariantSchema = ExperimentsShipVariantCreateParams.omit({ project_id: true }).extend(
- ExperimentsShipVariantCreateBody.shape
-)
+const ExperimentShipVariantSchema = ExperimentsShipVariantCreateParams.omit({ project_id: true })
+ .extend(ExperimentsShipVariantCreateBody.shape)
+ .extend({ id: z.preprocess(castStringToInt, ExperimentsShipVariantCreateParams.shape['id']) })
const experimentShipVariant = (): ToolBase<typeof ExperimentShipVariantSchema, WithPostHogUrl<Schemas.Experiment>> =>
withUiApp('experiment', {
@@ -426,9 +447,9 @@ const experimentStats = (): ToolBase<typeof ExperimentStatsSchema, unknown> => (
},
})
-const ExperimentTimeseriesResultsSchema = ExperimentsTimeseriesResultsRetrieveParams.omit({ project_id: true }).extend(
- ExperimentsTimeseriesResultsRetrieveQueryParams.shape
-)
+const ExperimentTimeseriesResultsSchema = ExperimentsTimeseriesResultsRetrieveParams.omit({ project_id: true })
+ .extend(ExperimentsTimeseriesResultsRetrieveQueryParams.shape)
+ .extend({ id: z.preprocess(castStringToInt, ExperimentsTimeseriesResultsRetrieveParams.shape['id']) })
const experimentTimeseriesResults = (): ToolBase<typeof ExperimentTimeseriesResultsSchema, unknown> =>
withUiApp('experiment-results', {
@@ -448,7 +469,9 @@ const experimentTimeseriesResults = (): ToolBase<typeof ExperimentTimeseriesResu
},
})
-const ExperimentUnarchiveSchema = ExperimentsUnarchiveCreateParams.omit({ project_id: true })
+const ExperimentUnarchiveSchema = ExperimentsUnarchiveCreateParams.omit({ project_id: true }).extend({
+ id: z.preprocess(castStringToInt, ExperimentsUnarchiveCreateParams.shape['id']),
+})
const experimentUnarchive = (): ToolBase<typeof ExperimentUnarchiveSchema, WithPostHogUrl<Schemas.Experiment>> =>
withUiApp('experiment', {
@@ -464,24 +487,26 @@ const experimentUnarchive = (): ToolBase<typeof ExperimentUnarchiveSchema, WithP
},
})
-const ExperimentUpdateSchema = ExperimentsPartialUpdateParams.omit({ project_id: true }).extend(
- ExperimentsPartialUpdateBody.omit({
- start_date: true,
- end_date: true,
- feature_flag_key: true,
- secondary_metrics: true,
- saved_metrics_ids: true,
- filters: true,
- deleted: true,
- type: true,
- exposure_criteria: true,
- scheduling_config: true,
- _create_in_folder: true,
- primary_metrics_ordered_uuids: true,
- secondary_metrics_ordered_uuids: true,
- only_count_matured_users: true,
- }).shape
-)
+const ExperimentUpdateSchema = ExperimentsPartialUpdateParams.omit({ project_id: true })
+ .extend(
+ ExperimentsPartialUpdateBody.omit({
+ start_date: true,
+ end_date: true,
+ feature_flag_key: true,
+ secondary_metrics: true,
+ saved_metrics_ids: true,
+ filters: true,
+ deleted: true,
+ type: true,
+ exposure_criteria: true,
+ scheduling_config: true,
+ _create_in_folder: true,
+ primary_metrics_ordered_uuids: true,
+ secondary_metrics_ordered_uuids: true,
+ only_count_matured_users: true,
+ }).shape
+ )
+ .extend({ id: z.preprocess(castStringToInt, ExperimentsPartialUpdateParams.shape['id']) })
const experimentUpdate = (): ToolBase<typeof ExperimentUpdateSchema, WithPostHogUrl<Schemas.Experiment>> =>
withUiApp('experiment', {
diff --git a/services/mcp/tests/unit/cast-helpers.test.ts b/services/mcp/tests/unit/cast-helpers.test.ts
new file mode 100644
index 000000000000..ef908bb894ac
--- /dev/null
+++ b/services/mcp/tests/unit/cast-helpers.test.ts
@@ -0,0 +1,58 @@
+/**
+ * Unit tests for the narrow string→primitive casts used by
+ * `param_overrides: { ...: { cast: '...' } }` in tools.yaml.
+ *
+ * The intent is to be permissive about the *one* shape LLM agents
+ * commonly mis-emit (stringified integer ids) and strict about
+ * everything else, so genuine type mismatches still surface as
+ * honest zod rejections instead of silently casting to 0/1.
+ */
+import { describe, expect, it } from 'vitest'
+import { z } from 'zod'
+
+import { castStringToInt } from '../../src/tools/cast-helpers'
+
+describe('castStringToInt', () => {
+ const schema = z.preprocess(castStringToInt, z.number().int())
+
+ it('casts a stringified positive integer', () => {
+ expect(schema.parse('123')).toBe(123)
+ })
+
+ it('casts a stringified negative integer', () => {
+ expect(schema.parse('-7')).toBe(-7)
+ })
+
+ it('casts a string with leading zeros', () => {
+ // Documented behavior: "007" → 7. Agents may include leading zeros
+ // when extracting an id from text; we accept the obvious value.
+ expect(schema.parse('007')).toBe(7)
+ })
+
+ it('passes through plain numbers untouched', () => {
+ expect(schema.parse(42)).toBe(42)
+ })
+
+ it.each([
+ ['boolean true', true],
+ ['boolean false', false],
+ ['null', null],
+ ['empty array', []],
+ ['empty string', ''],
+ ['decimal string', '1.5'],
+ ['hex string', '0x10'],
+ ['non-numeric string', 'abc'],
+ ['string with whitespace', ' 12 '],
+ ] as const)('rejects non-int input: %s', (_label, input) => {
+ // Anything that isn't a strict base-10 integer string passes through
+ // to zod unchanged, which then rejects it with its honest type error.
+ expect(() => schema.parse(input)).toThrow()
+ })
+
+ it('preserves the wrapped schema description and constraints', () => {
+ const wrapped = z.preprocess(castStringToInt, z.number().int().min(1).describe('Experiment id.'))
+ // Min constraint still applies after the cast runs.
+ expect(() => wrapped.parse('0')).toThrow()
+ expect(wrapped.parse('1')).toBe(1)
+ })
+})
diff --git a/services/mcp/tests/unit/experiments-schema-cast.test.ts b/services/mcp/tests/unit/experiments-schema-cast.test.ts
new file mode 100644
index 000000000000..8666314fb837
--- /dev/null
+++ b/services/mcp/tests/unit/experiments-schema-cast.test.ts
@@ -0,0 +1,108 @@
+/**
+ * Regression tests for narrow string→int casts on experiment tool schemas.
+ *
+ * Production traces showed agents intermittently sending stringified ids
+ * (`"123"` instead of `123`) on `experiment-get` / `-update` / `-list` /
+ * `-duplicate` and friends, which the MCP layer then rejected with
+ * `MCP error -32602: Invalid input: expected number, received string`.
+ * (`experiment-results-get` sees the same shape but is handwritten via
+ * `services/mcp/src/schema/tool-inputs.ts` and not covered by this PR.)
+ *
+ * The fix is declarative — `param_overrides: { id: { cast: 'string-int' } }`
+ * in `products/experiments/mcp/tools.yaml` — wired through the codegen to
+ * wrap the field's existing zod schema with `z.preprocess(castStringToInt, ...)`.
+ *
+ * These tests pin the runtime behavior end-to-end so the override can't
+ * silently regress when the codegen, the YAML, or the schema source changes.
+ * They also assert the safety properties: no surprising `true → 1` /
+ * `null → 0` behavior, only true stringified-int casts.
+ */
+import { describe, expect, it } from 'vitest'
+import { z } from 'zod'
+
+import { GENERATED_TOOLS } from '@/tools/generated/experiments'
+import type { ToolBase, ZodObjectAny } from '@/tools/types'
+
+const PROJECT_ID = '2'
+
+/** Resolve a generated tool's input schema. Cast through `unknown` so individual
+ * test cases can assert on parsed fields without TypeScript widening to `unknown`. */
+function getToolSchema(toolName: keyof typeof GENERATED_TOOLS): z.ZodTypeAny {
+ const factory = GENERATED_TOOLS[toolName] as () => ToolBase<ZodObjectAny>
+ return factory().schema as z.ZodTypeAny
+}
+
+/** Wrapper around `schema.parse` that returns a record so tests don't have to
+ * cast on every access. The underlying schema runtime guarantees an object
+ * shape for each generated tool's params. */
+function parseWith(schema: z.ZodTypeAny, input: unknown): Record<string, unknown> {
+ return schema.parse(input) as Record<string, unknown>
+}
+
+/**
+ * One row per lifecycle tool that has `param_overrides: { id: { cast: 'string-int' } }`
+ * in tools.yaml. The `extras` map captures each tool's *additional* required-input
+ * fields beyond `id`/`project_id`, so the parameterised assertion can build a minimal
+ * valid input for every shape. Adding a new cast'd lifecycle tool means appending
+ * one row here — the test will then cover it automatically.
+ */
+const LIFECYCLE_TOOLS_WITH_ID_CAST = [
+ ['experiment-archive', {}],
+ ['experiment-delete', {}],
+ ['experiment-duplicate', { name: 'A duplicate', feature_flag_key: 'duplicated-flag' }],
+ ['experiment-end', {}],
+ ['experiment-get', {}],
+ ['experiment-launch', {}],
+ ['experiment-pause', {}],
+ ['experiment-reset', {}],
+ ['experiment-resume', {}],
+ ['experiment-ship-variant', { variant_key: 'test' }],
+ ['experiment-timeseries-results', { metric_uuid: 'metric-uuid', fingerprint: 'fp' }],
+ ['experiment-unarchive', {}],
+ ['experiment-update', {}],
+] as const satisfies ReadonlyArray<readonly [keyof typeof GENERATED_TOOLS, Record<string, unknown>]>
+
+describe('experiment lifecycle tools — id cast', () => {
+ it.each(LIFECYCLE_TOOLS_WITH_ID_CAST)('%s accepts a stringified id', (toolName, extras) => {
+ const parsed = parseWith(getToolSchema(toolName), { id: '123', project_id: PROJECT_ID, ...extras })
+ expect(parsed.id).toBe(123)
+ expect(typeof parsed.id).toBe('number')
+ })
+
+ it.each(LIFECYCLE_TOOLS_WITH_ID_CAST)('%s still accepts a plain numeric id', (toolName, extras) => {
+ const parsed = parseWith(getToolSchema(toolName), { id: 123, project_id: PROJECT_ID, ...extras })
+ expect(parsed.id).toBe(123)
+ })
+})
+
+describe('experiment-get — safety: must still reject non-int input', () => {
+ // We explicitly DO NOT want `z.coerce.number()` semantics, where `true → 1`,
+ // `null → 0`, etc. These should still reject so genuine type errors surface
+ // honestly instead of silently 404-ing the API. Asserted on `experiment-get`
+ // since the cast helper is shared, so one tool's safety contract covers all.
+ const schema = getToolSchema('experiment-get')
+ it.each([
+ ['boolean true', true],
+ ['null', null],
+ ['empty string', ''],
+ ['decimal string', '1.5'],
+ ['non-numeric string', 'abc'],
+ ] as const)('rejects unsafe input: %s', (_label, badId) => {
+ expect(() => schema.parse({ id: badId, project_id: PROJECT_ID })).toThrow()
+ })
+})
+
+describe('experiment-list — query-param casts', () => {
+ const schema = getToolSchema('experiment-list')
+
+ it.each([
+ ['limit', '50', 50],
+ ['offset', '100', 100],
+ ['created_by_id', '42', 42],
+ ['feature_flag_id', '7', 7],
+ ] as const)('casts stringified %s', (field, raw, expected) => {
+ const parsed = parseWith(schema, { [field]: raw })
+ expect(parsed[field]).toBe(expected)
+ expect(typeof parsed[field]).toBe('number')
+ })
+})