:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): validate generated list app tool arguments (#98017)
Lucas Faria661ad0e03f57
diff --git a/.dockerignore b/.dockerignoreindex dfb7ce59bc82..1322e432b1ce 100644--- a/.dockerignore+++ b/.dockerignore@@ -118,6 +118,8 @@ rust/.githubrust/dockerrust/target**/__snapshots__+# generate:ui-apps reads these committed tool input schemas while building the MCP image.+!services/mcp/tests/unit/__snapshots__/tool-schemas!docker-compose.base.yml!docker-compose.dev.yml!dockerdiff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex e41e8bbb34c2..c31cc61acd21 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -316,6 +316,11 @@ Product teams own their definitions and control which operations are exposed asUnknown keys are rejected at build time (Zod `.strict()`) to catch typos early.+ For generated list apps, `generate:ui-apps` also checks `detail_tool` and the+ `detail_args` keys against the tool's input schema snapshot, so a wrong argument+ name fails generation instead of silently dropping the argument at runtime.+ See "UI apps" in `services/mcp/CONTRIBUTING.md` for the rules.+#### Custom input schemasBy default, tool input schemas are auto-derived from OpenAPI via Orval.diff --git a/services/mcp/CONTRIBUTING.md b/services/mcp/CONTRIBUTING.mdindex 9aaa3bb96791..406111e66eae 100644--- a/services/mcp/CONTRIBUTING.md+++ b/services/mcp/CONTRIBUTING.md@@ -296,9 +296,18 @@ Convention defaults (derived from the app key and product directory):Override any field explicitly when the convention doesn't match(e.g. `click_prop: onEntityClick`, `detail_args: "{ entityId: item.id }"`).-`detail_args` must match the target tool's actual parameter names —-mismatching them (e.g. passing `flagId` to a tool that expects `id`) silently-drops the argument instead of failing.+`generate:ui-apps` checks `detail_tool` and the top-level keys of `detail_args`+against the tool's input schema snapshot in `tests/unit/__snapshots__/tool-schemas/`.+Generation fails for a tool without a snapshot, unknown argument names, and missing+required arguments. For example, passing `flagId` to a tool that requires `id` reports+both the unknown key and the missing argument, with the app and tool names.++`detail_args` must be an object literal with explicit keys; spreads and computed keys+are rejected because their names cannot be checked statically. The expression is+parsed, not executed, so dynamic values and nested fields are still validated by the+tool at call time. After adding a tool or changing its input schema, run+`pnpm test tests/unit/tool-schema-snapshots.test.ts -u` to refresh the snapshot, then+regenerate the UI apps.**Link tools to apps** with `ui_app`:diff --git a/services/mcp/scripts/generate-ui-apps.ts b/services/mcp/scripts/generate-ui-apps.tsindex d4bfaa22e0fe..6656e65c5817 100644--- a/services/mcp/scripts/generate-ui-apps.ts+++ b/services/mcp/scripts/generate-ui-apps.ts@@ -20,6 +20,7 @@ import { fileURLToPath } from 'node:url'import { parse as parseYaml } from 'yaml'import { discoverDefinitions, isToolsConfig } from './lib/definitions.mjs'+import { type ToolInputSchema, validateListAppToolCall } from './lib/validate-ui-app-tool-call'import { MCP_ROOT_DIR, ROOT_DIR } from './utils'import {type CategoryConfig,@@ -401,6 +402,18 @@ ${appEntries},// Main// ------------------------------------------------------------------+const TOOL_SCHEMA_SNAPSHOTS_DIR = path.join(MCP_ROOT_DIR, 'tests', 'unit', '__snapshots__', 'tool-schemas')++// The snapshot test writes one JSON schema per registered tool, so the generator+// can read tool inputs without loading the server bundle.+function readToolInputSchema(toolName: string): ToolInputSchema | undefined {+ const snapshotPath = path.join(TOOL_SCHEMA_SNAPSHOTS_DIR, `${toolName}.json`)+ if (!fs.existsSync(snapshotPath)) {+ return undefined+ }+ return JSON.parse(fs.readFileSync(snapshotPath, 'utf-8'))+}+function main(): void {const definitionSources = discoverDefinitions({ definitionsDir: DEFINITIONS_DIR, productsDir: PRODUCTS_DIR })@@ -473,6 +486,7 @@ function main(): void {process.exit(1)}const resolved = resolveListApp(appKey, appConfig, componentImport!)+ validateListAppToolCall(appKey, resolved, readToolInputSchema(resolved.detail_tool))const code = generateListApp(appKey, resolved)const outPath = path.join(GENERATED_APPS_DIR, `${appKey}.tsx`)fs.writeFileSync(outPath, code)diff --git a/services/mcp/scripts/lib/validate-ui-app-tool-call.ts b/services/mcp/scripts/lib/validate-ui-app-tool-call.tsnew file mode 100644index 000000000000..02822977c482--- /dev/null+++ b/services/mcp/scripts/lib/validate-ui-app-tool-call.ts@@ -0,0 +1,70 @@+import ts from 'typescript'++type ListAppCall = { detail_tool: string; detail_args: string }++export type ToolInputSchema = { type?: string; properties?: Record<string, unknown>; required?: string[] }++function argumentKeys(expression: string): string[] {+ const source = `(${expression})`+ const { diagnostics } = ts.transpileModule(source, { reportDiagnostics: true })+ if (diagnostics?.some((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error)) {+ throw new Error('detail_args must be a valid object literal')+ }+ const file = ts.createSourceFile('detail-args.ts', source, ts.ScriptTarget.Latest, true)+ const statement = file.statements[0]+ if (+ file.statements.length !== 1 ||+ !statement ||+ !ts.isExpressionStatement(statement) ||+ !ts.isParenthesizedExpression(statement.expression) ||+ !ts.isObjectLiteralExpression(statement.expression.expression)+ ) {+ throw new Error('detail_args must be an object literal with explicit argument keys')+ }++ return statement.expression.expression.properties.map((property) => {+ if (+ (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property)) ||+ (!ts.isIdentifier(property.name) && !ts.isStringLiteral(property.name))+ ) {+ throw new Error(+ 'detail_args must use explicit argument keys; spreads and computed keys cannot be validated'+ )+ }+ return property.name.text+ })+}++export function validateListAppToolCall(+ appKey: string,+ config: ListAppCall,+ schema: ToolInputSchema | undefined+): void {+ const context = `List app "${appKey}" calling "${config.detail_tool}"`+ if (!schema) {+ throw new Error(+ `${context}: no input schema snapshot for this tool. Check the tool name, or run the tool schema snapshot test to record a new tool.`+ )+ }++ let keys: string[]+ try {+ keys = argumentKeys(config.detail_args)+ } catch (error) {+ throw new Error(`${context}: ${error instanceof Error ? error.message : String(error)}`)+ }++ if (schema.type !== 'object' || !schema.properties) {+ throw new Error(`${context}: the input schema must expose object properties to validate detail_args`)+ }+ const known = new Set(Object.keys(schema.properties))+ const unknown = keys.filter((key) => !known.has(key))+ const missing = (schema.required ?? []).filter((key) => !keys.includes(key))+ if (unknown.length || missing.length) {+ const problems = [+ ...(unknown.length ? [`Unknown arguments: ${unknown.join(', ')}`] : []),+ ...(missing.length ? [`Missing required arguments: ${missing.join(', ')}`] : []),+ ]+ throw new Error(`${context}: ${problems.join('. ')}. Check detail_args against the tool input schema.`)+ }+}diff --git a/services/mcp/tests/unit/ui-app-tool-call-validation.test.ts b/services/mcp/tests/unit/ui-app-tool-call-validation.test.tsnew file mode 100644index 000000000000..9f59a3f053c5--- /dev/null+++ b/services/mcp/tests/unit/ui-app-tool-call-validation.test.ts@@ -0,0 +1,56 @@+import { readFileSync } from 'node:fs'+import path from 'node:path'+import { describe, expect, it } from 'vitest'++import { validateListAppToolCall } from '../../scripts/lib/validate-ui-app-tool-call'++describe('list app tool call validation', () => {+ const schema = { type: 'object', properties: { id: {}, include_details: {} }, required: ['id'] }+ const validate = (detail_args: string): void =>+ validateListAppToolCall('survey-list', { detail_tool: 'survey-get', detail_args }, schema)++ it('rejects the survey list argument mismatch against the committed tool schema snapshot', () => {+ const snapshot = JSON.parse(+ readFileSync(path.join(__dirname, '__snapshots__', 'tool-schemas', 'survey-get.json'), 'utf-8')+ )+ expect(() =>+ validateListAppToolCall(+ 'survey-list',+ { detail_tool: 'survey-get', detail_args: '{ surveyId: item.id }' },+ snapshot+ )+ ).toThrow(/survey-list.*survey-get.*surveyId.*id/)+ })++ it.each(['{ id: item.id }', '{ "id": item.id, include_details: true }', '{ id }'])(+ 'accepts explicit argument keys: %s',+ (args) => expect(() => validate(args)).not.toThrow()+ )++ it('rejects an unknown key even when all required arguments are supplied', () => {+ expect(() => validate('{ id: item.id, typo: true }')).toThrow(/Unknown arguments: typo/)+ })++ it('rejects a missing required argument', () => {+ expect(() => validate('{}')).toThrow(/Missing required arguments: id/)+ })++ it('rejects a tool without a schema snapshot', () => {+ expect(() =>+ validateListAppToolCall(+ 'survey-list',+ { detail_tool: 'surveys-get', detail_args: '{ id: item.id }' },+ undefined+ )+ ).toThrow(/survey-list.*surveys-get.*no input schema snapshot/)+ })++ it.each(['{ ...item }', '{ [field]: item.id }', 'item', '{ id: item.id', '{ id: item.id }; throw new Error()'])(+ 'rejects argument expressions whose keys cannot be checked: %s',+ (args) => expect(() => validate(args)).toThrow(/detail_args/)+ )++ it('does not execute argument expressions during generation', () => {+ expect(() => validate('{ id: (() => { throw new Error("executed") })() }')).not.toThrow()+ })+})