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): refuse unknown fields in the email template tools (#127183)

Michael Reichenbachd7f54b22bd9f
diff --git a/products/messaging/backend/presentation/views/message_templates.py b/products/messaging/backend/presentation/views/message_templates.py
index 7102afea3b03..622d02e07851 100644
--- a/products/messaging/backend/presentation/views/message_templates.py
+++ b/products/messaging/backend/presentation/views/message_templates.py
@@ -95,6 +95,7 @@ logger = structlog.get_logger(__name__)
@extend_schema_field(
{
"type": "object",
+ "additionalProperties": True,
"properties": {
"counters": {
"type": "object",
@@ -103,6 +104,7 @@ logger = structlog.get_logger(__name__)
"schemaVersion": {"type": "integer", "description": "Design schema version, e.g. 16."},
"body": {
"type": "object",
+ "additionalProperties": True,
"properties": {
"id": {"type": "string", "description": "Any unique string."},
"rows": {
diff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.ts
index 4118521f164a..a7ad4e5763c2 100644
--- a/products/messaging/frontend/generated/api.schemas.ts
+++ b/products/messaging/frontend/generated/api.schemas.ts
@@ -683,6 +683,7 @@ export type EmailTemplateApiDesignBody = {
footers?: EmailTemplateApiDesignBodyFootersItem[]
/** Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor. */
values?: EmailTemplateApiDesignBodyValues
+ [key: string]: unknown
}
/**
@@ -694,6 +695,7 @@ export type EmailTemplateApiDesign = {
/** Design schema version, e.g. 16. */
schemaVersion: number
body: EmailTemplateApiDesignBody
+ [key: string]: unknown
}
export interface EmailTemplateApi {
diff --git a/products/workflows/mcp/email_templates.yaml b/products/workflows/mcp/email_templates.yaml
index 9b414c51ce9b..9f0c50f108de 100644
--- a/products/workflows/mcp/email_templates.yaml
+++ b/products/workflows/mcp/email_templates.yaml
@@ -50,8 +50,8 @@ tools:
description: >
Get an email template by ID, including content.email (subject, text, design). Use this to fetch before
updating — content is replaced as a whole and humans may have edited the design in the visual editor since
- you last saw it, so build your update payload from this response. To display a template to the user, use
- workflows-show-email-template instead.
+ you last saw it, so build the content of your update from this response. To display a template to the user,
+ use workflows-show-email-template instead.
response:
exclude:
- content.email.html
@@ -227,9 +227,10 @@ tools:
button color, one paragraph), prefer workflows-patch-email-template — it sends just the changed fields
instead of the entire design JSON. Use this tool to set content from scratch or replace it wholesale: call
workflows-get-email-template first (the design may carry fresh human edits from the visual editor) and send
- back the complete content.email with your edited design. The server re-renders the sent email from the
- design on save. After updating, call workflows-show-email-template so the user sees the result, and share
- the returned _posthogUrl edit link.
+ back the complete content with your edited design, plus only the other writable fields you change. The tool
+ refuses the read-only fields of a fetched template: created_at, updated_at, transactional_hog_flow_id and
+ _posthogUrl. The server re-renders the sent email from the design on save. After updating, call
+ workflows-show-email-template so the user sees the result, and share the returned _posthogUrl edit link.
exclude_params:
- content.email.html
- draft_content
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 94c42f47071f..999bea81d5d2 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -17010,7 +17010,7 @@
}
},
"workflows-get-email-template": {
- "description": "Get an email template by ID, including content.email (subject, text, design). Use this to fetch before updating — content is replaced as a whole and humans may have edited the design in the visual editor since you last saw it, so build your update payload from this response. To display a template to the user, use workflows-show-email-template instead.",
+ "description": "Get an email template by ID, including content.email (subject, text, design). Use this to fetch before updating — content is replaced as a whole and humans may have edited the design in the visual editor since you last saw it, so build the content of your update from this response. To display a template to the user, use workflows-show-email-template instead.",
"category": "Workflows",
"feature": "workflows",
"summary": "Get email template",
@@ -17498,7 +17498,7 @@
}
},
"workflows-update-email-template": {
- "description": "Replace an email template's content as a whole. For small edits to an existing design (change a heading, a button color, one paragraph), prefer workflows-patch-email-template — it sends just the changed fields instead of the entire design JSON. Use this tool to set content from scratch or replace it wholesale: call workflows-get-email-template first (the design may carry fresh human edits from the visual editor) and send back the complete content.email with your edited design. The server re-renders the sent email from the design on save. After updating, call workflows-show-email-template so the user sees the result, and share the returned _posthogUrl edit link.",
+ "description": "Replace an email template's content as a whole. For small edits to an existing design (change a heading, a button color, one paragraph), prefer workflows-patch-email-template — it sends just the changed fields instead of the entire design JSON. Use this tool to set content from scratch or replace it wholesale: call workflows-get-email-template first (the design may carry fresh human edits from the visual editor) and send back the complete content with your edited design, plus only the other writable fields you change. The tool refuses the read-only fields of a fetched template: created_at, updated_at, transactional_hog_flow_id and _posthogUrl. The server re-renders the sent email from the design on save. After updating, call workflows-show-email-template so the user sees the result, and share the returned _posthogUrl edit link.",
"category": "Workflows",
"feature": "workflows",
"summary": "Update email template",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index c99d82387b00..bcb65aaa72cb 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -17827,7 +17827,7 @@
}
},
"workflows-get-email-template": {
- "description": "Get an email template by ID, including content.email (subject, text, design). Use this to fetch before updating — content is replaced as a whole and humans may have edited the design in the visual editor since you last saw it, so build your update payload from this response. To display a template to the user, use workflows-show-email-template instead.",
+ "description": "Get an email template by ID, including content.email (subject, text, design). Use this to fetch before updating — content is replaced as a whole and humans may have edited the design in the visual editor since you last saw it, so build the content of your update from this response. To display a template to the user, use workflows-show-email-template instead.",
"category": "Workflows",
"feature": "workflows",
"summary": "Get email template",
@@ -18343,7 +18343,7 @@
}
},
"workflows-update-email-template": {
- "description": "Replace an email template's content as a whole. For small edits to an existing design (change a heading, a button color, one paragraph), prefer workflows-patch-email-template — it sends just the changed fields instead of the entire design JSON. Use this tool to set content from scratch or replace it wholesale: call workflows-get-email-template first (the design may carry fresh human edits from the visual editor) and send back the complete content.email with your edited design. The server re-renders the sent email from the design on save. After updating, call workflows-show-email-template so the user sees the result, and share the returned _posthogUrl edit link.",
+ "description": "Replace an email template's content as a whole. For small edits to an existing design (change a heading, a button color, one paragraph), prefer workflows-patch-email-template — it sends just the changed fields instead of the entire design JSON. Use this tool to set content from scratch or replace it wholesale: call workflows-get-email-template first (the design may carry fresh human edits from the visual editor) and send back the complete content with your edited design, plus only the other writable fields you change. The tool refuses the read-only fields of a fetched template: created_at, updated_at, transactional_hog_flow_id and _posthogUrl. The server re-renders the sent email from the design on save. After updating, call workflows-show-email-template so the user sees the result, and share the returned _posthogUrl edit link.",
"category": "Workflows",
"feature": "workflows",
"summary": "Update email template",
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index 7fda6a07eacc..ad91f6c57960 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -290,7 +290,8 @@
"description": "Partial content-block fields, deep-merged into the existing block; a null leaf deletes that key. e.g. {values: {text: '<p>Hi</p>'}} changes only the block's text."
}
},
- "required": ["op", "id", "patch"]
+ "required": ["op", "id", "patch"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -312,7 +313,8 @@
"description": "Partial column fields, deep-merged; a null leaf deletes that key."
}
},
- "required": ["op", "id", "patch"]
+ "required": ["op", "id", "patch"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -334,7 +336,8 @@
"description": "Partial row fields, deep-merged; a null leaf deletes that key."
}
},
- "required": ["op", "id", "patch"]
+ "required": ["op", "id", "patch"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -352,7 +355,8 @@
"description": "Partial body fields, deep-merged. e.g. {values: {backgroundColor: '#ffffff'}}."
}
},
- "required": ["op", "patch"]
+ "required": ["op", "patch"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -380,7 +384,8 @@
"maximum": 9007199254740991
}
},
- "required": ["op", "column_id", "content"]
+ "required": ["op", "column_id", "content"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -394,7 +399,8 @@
"description": "Id of the content block to remove."
}
},
- "required": ["op", "id"]
+ "required": ["op", "id"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -418,7 +424,8 @@
"maximum": 9007199254740991
}
},
- "required": ["op", "id", "column_id"]
+ "required": ["op", "id", "column_id"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -442,7 +449,8 @@
"maximum": 9007199254740991
}
},
- "required": ["op", "row"]
+ "required": ["op", "row"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -456,14 +464,16 @@
"description": "Id of the row to remove."
}
},
- "required": ["op", "id"]
+ "required": ["op", "id"],
+ "additionalProperties": false
}
]
},
"description": "Ordered edits applied atomically to the template's Unlayer design: the stored design is read, the ops are applied in order, the result is validated and re-rendered to HTML, and saved only if valid — otherwise the template is left unchanged. Reference blocks by id so you never resend the whole design."
}
},
- "required": ["id", "operations"]
+ "required": ["id", "operations"],
+ "additionalProperties": false
},
"EventDefinitionCreateSchema": {
"type": "object",
@@ -3086,7 +3096,8 @@
"description": "Partial content-block fields, deep-merged into the existing block; a null leaf deletes that key. e.g. {values: {text: '<p>Hi</p>'}} changes only the block's text."
}
},
- "required": ["op", "id", "patch"]
+ "required": ["op", "id", "patch"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -3108,7 +3119,8 @@
"description": "Partial column fields, deep-merged; a null leaf deletes that key."
}
},
- "required": ["op", "id", "patch"]
+ "required": ["op", "id", "patch"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -3130,7 +3142,8 @@
"description": "Partial row fields, deep-merged; a null leaf deletes that key."
}
},
- "required": ["op", "id", "patch"]
+ "required": ["op", "id", "patch"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -3148,7 +3161,8 @@
"description": "Partial body fields, deep-merged. e.g. {values: {backgroundColor: '#ffffff'}}."
}
},
- "required": ["op", "patch"]
+ "required": ["op", "patch"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -3176,7 +3190,8 @@
"maximum": 9007199254740991
}
},
- "required": ["op", "column_id", "content"]
+ "required": ["op", "column_id", "content"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -3190,7 +3205,8 @@
"description": "Id of the content block to remove."
}
},
- "required": ["op", "id"]
+ "required": ["op", "id"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -3214,7 +3230,8 @@
"maximum": 9007199254740991
}
},
- "required": ["op", "id", "column_id"]
+ "required": ["op", "id", "column_id"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -3238,7 +3255,8 @@
"maximum": 9007199254740991
}
},
- "required": ["op", "row"]
+ "required": ["op", "row"],
+ "additionalProperties": false
},
{
"type": "object",
@@ -3252,7 +3270,8 @@
"description": "Id of the row to remove."
}
},
- "required": ["op", "id"]
+ "required": ["op", "id"],
+ "additionalProperties": false
}
]
}
diff --git a/services/mcp/scripts/generate-orval-schemas.mjs b/services/mcp/scripts/generate-orval-schemas.mjs
index 6d9220ff7c4c..ecc63c302e89 100644
--- a/services/mcp/scripts/generate-orval-schemas.mjs
+++ b/services/mcp/scripts/generate-orval-schemas.mjs
@@ -25,8 +25,9 @@ import {
runOrvalParallel,
} from '@posthog/openapi-codegen'
-import { discoverDefinitions, resolveSchemaPath } from './lib/definitions.mjs'
+import { discoverDefinitions, modulesWithStrictBodies, resolveSchemaPath } from './lib/definitions.mjs'
import { lazifyZodSchemas } from './lib/lazy-zod-schemas.mjs'
+import { collectOpenObjectPaths, loosenOpenObjects } from './lib/loosen-open-objects.mjs'
import { stripEnumMinLength, stripUuidFormat } from './lib/schema-transforms.mjs'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
@@ -168,6 +169,7 @@ function prepareOrval(moduleName, filteredSchema, tmpDir) {
components: {
schemas: { suffix: 'Api' },
},
+ ...(modulesWithStrictBodies.has(moduleName) && { zod: { strict: { body: true } } }),
},
},
}
@@ -175,8 +177,8 @@ function prepareOrval(moduleName, filteredSchema, tmpDir) {
return { config, outputFile, moduleOutputDir }
}
-function postprocessOrvalOutput(outputFile) {
- const generated = fs.readFileSync(outputFile, 'utf-8')
+function postprocessOrvalOutput(outputFile, openTargetsByExport) {
+ const generated = loosenOpenObjects(fs.readFileSync(outputFile, 'utf-8'), openTargetsByExport)
const withoutRedundantEnumDescriptions = generated.replace(
/\n\s*\.describe\(\n\s*(['"`])\* `(?:\\.|(?!\1)[\s\S])*?\1\n\s*\)(?=\s*(?:\.(?:optional|nullish)\(\)\s*)?\.describe\()/g,
''
@@ -216,57 +218,77 @@ if (definitions.length === 0) {
const fullSchema = preprocessSchema(JSON.parse(fs.readFileSync(schemaPath, 'utf-8')))
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-orval-'))
-// Phase 1: Prepare all modules (filter schemas, write temp files) — synchronous, fast
const tasks = []
let totalEnabledOps = 0
+const outputDirs = []
+let failed = false
-for (const def of definitions) {
- const { operationIds, schemaExclusions } = parseToolDefinition(def.filePath)
- if (operationIds.size === 0) {
- continue
+try {
+ // Phase 1: Prepare all modules (filter schemas, write temp files) — synchronous, fast
+ for (const def of definitions) {
+ const { operationIds, schemaExclusions } = parseToolDefinition(def.filePath)
+ if (operationIds.size === 0) {
+ continue
+ }
+ totalEnabledOps += operationIds.size
+
+ const filtered = filterSchemaByOperationIds(fullSchema, operationIds, { includeResponseSchemas: false })
+
+ // Annotate title for easier debugging
+ filtered.info.title = `${fullSchema.info?.title ?? 'API'} - MCP ${operationIds.size} enabled ops`
+
+ stripDefaultsFromPatchedSchemas(filtered)
+ stripUuidFormat(filtered)
+ stripReadOnlyFromRequired(filtered)
+ applyNestedExclusions(filtered, schemaExclusions)
+ stripEnumMinLength(filtered)
+ const pathCount = Object.keys(filtered.paths).length
+ const schemaCount = Object.keys(filtered.components.schemas).length
+
+ const { config, outputFile, moduleOutputDir } = prepareOrval(def.moduleName, filtered, tmpDir)
+ const openTargetsByExport = modulesWithStrictBodies.has(def.moduleName)
+ ? collectOpenObjectPaths(filtered, def.moduleName)
+ : new Map()
+ tasks.push({
+ def,
+ config,
+ outputFile,
+ moduleOutputDir,
+ pathCount,
+ schemaCount,
+ operationIds,
+ openTargetsByExport,
+ })
}
- totalEnabledOps += operationIds.size
- const filtered = filterSchemaByOperationIds(fullSchema, operationIds, { includeResponseSchemas: false })
-
- // Annotate title for easier debugging
- filtered.info.title = `${fullSchema.info?.title ?? 'API'} - MCP ${operationIds.size} enabled ops`
-
- stripDefaultsFromPatchedSchemas(filtered)
- stripUuidFormat(filtered)
- stripReadOnlyFromRequired(filtered)
- applyNestedExclusions(filtered, schemaExclusions)
- stripEnumMinLength(filtered)
- const pathCount = Object.keys(filtered.paths).length
- const schemaCount = Object.keys(filtered.components.schemas).length
-
- const { config, outputFile, moduleOutputDir } = prepareOrval(def.moduleName, filtered, tmpDir)
- tasks.push({ def, config, outputFile, moduleOutputDir, pathCount, schemaCount, operationIds })
-}
-
-// Phase 2: Run all Orval generations in parallel (in-process, no subprocess overhead)
-const orvalJobs = tasks.map((t) => ({ config: t.config, label: t.def.moduleName }))
-const results = await runOrvalParallel(orvalJobs)
-
-const outputDirs = []
-let failed = false
-for (let i = 0; i < results.length; i++) {
- const result = results[i]
- const task = tasks[i]
- if (result.status === 'fulfilled') {
- postprocessOrvalOutput(task.outputFile)
- console.log(
- ` ✓ ${task.def.moduleName}: ${task.pathCount} paths, ${task.schemaCount} schemas (${task.operationIds.size} enabled ops)`
- )
- outputDirs.push(task.moduleOutputDir)
- } else {
- console.error(` ✗ ${task.def.moduleName}: Orval failed — ${result.reason.message}`)
- failed = true
+ // Phase 2: Run all Orval generations in parallel (in-process, no subprocess overhead)
+ const orvalJobs = tasks.map((t) => ({ config: t.config, label: t.def.moduleName }))
+ const results = await runOrvalParallel(orvalJobs)
+
+ for (let i = 0; i < results.length; i++) {
+ const result = results[i]
+ const task = tasks[i]
+ if (result.status === 'fulfilled') {
+ try {
+ postprocessOrvalOutput(task.outputFile, task.openTargetsByExport)
+ } catch (error) {
+ console.error(` ✗ ${task.def.moduleName}: post-processing failed — ${error.message}`)
+ failed = true
+ continue
+ }
+ console.log(
+ ` ✓ ${task.def.moduleName}: ${task.pathCount} paths, ${task.schemaCount} schemas (${task.operationIds.size} enabled ops)`
+ )
+ outputDirs.push(task.moduleOutputDir)
+ } else {
+ console.error(` ✗ ${task.def.moduleName}: Orval failed — ${result.reason.message}`)
+ failed = true
+ }
}
+} finally {
+ fs.rmSync(tmpDir, { recursive: true, force: true })
}
-fs.rmSync(tmpDir, { recursive: true, force: true })
-
if (failed) {
process.exit(1)
}
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index d3405d7d4b5a..066477ebdc2b 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -22,7 +22,12 @@ import { fileURLToPath } from 'node:url'
import { parse as parseYaml } from 'yaml'
import { hasScope } from '../src/lib/api'
-import { discoverDefinitions, isQueryWrappersConfig } from './lib/definitions.mjs'
+import {
+ discoverDefinitions,
+ isQueryWrappersConfig,
+ modulesWithStrictBodies,
+ operationIdToPascal,
+} from './lib/definitions.mjs'
import { type JsonSchemaRoot, generateZodFromSchemaRef, getEntryVarName } from './lib/json-schema-to-zod'
import {
type CategoryConfig,
@@ -448,14 +453,6 @@ function parseEnrichUrl(enrichUrl: string): {
}
}
-/** Convert operationId (snake_case) to PascalCase for Orval schema names */
-function operationIdToPascal(operationId: string): string {
- return operationId
- .split(/[_.]/)
- .map((s) => s.charAt(0).toUpperCase() + s.slice(1))
- .join('')
-}
-
// ------------------------------------------------------------------
// Schema composition — determine Orval imports and build expressions
// ------------------------------------------------------------------
@@ -507,7 +504,8 @@ function composeToolSchema(
config: ToolConfig,
resolved: ResolvedOperation,
spec: OpenApiSpec,
- getQuerySchema: () => JsonSchemaRoot
+ getQuerySchema: () => JsonSchemaRoot,
+ hasStrictBody = false
): SchemaComposition {
const pascal = operationIdToPascal(config.operation)
const orvalImports: string[] = []
@@ -525,6 +523,7 @@ function composeToolSchema(
* Path params are omitted (always required).
*/
const optionalParamNames = new Set<string>()
+ let composesBody = false
const excludeSet = new Set(config.exclude_params ?? [])
const includeSet = config.include_params ? new Set(config.include_params) : undefined
@@ -607,6 +606,7 @@ function composeToolSchema(
const bodySchemaRef = resolved.operation.requestBody?.content?.['application/json']?.schema
if (bodySchemaRef) {
const importName = `${pascal}Body`
+ composesBody = true
orvalImports.push(importName)
const bodyOmitFields = new Set<string>()
@@ -686,6 +686,9 @@ function composeToolSchema(
for (let i = 1; i < schemaParts.length; i++) {
schemaExpr += `.extend(${schemaParts[i]}.shape)`
}
+ if (hasStrictBody && composesBody) {
+ schemaExpr += '.strict()'
+ }
}
// param_overrides:
@@ -1136,7 +1139,8 @@ function generateToolCode(
category: CategoryConfig,
spec: OpenApiSpec,
knownTypes: Set<string>,
- getQuerySchema: () => JsonSchemaRoot
+ getQuerySchema: () => JsonSchemaRoot,
+ hasStrictBody = false
): {
code: string
orvalImports: string[]
@@ -1159,7 +1163,7 @@ function generateToolCode(
return generateCustomSchemaToolCode(toolName, config, resolved, category, schemaName, factoryName, knownTypes)
}
- const composition = composeToolSchema(config, resolved, spec, getQuerySchema)
+ const composition = composeToolSchema(config, resolved, spec, getQuerySchema, hasStrictBody)
let responseType = config.response_type ?? resolveResponseType(resolved.operation, knownTypes)
// Soft-delete overrides the HTTP method: use PATCH instead of DELETE.
@@ -1951,7 +1955,16 @@ function generateCategoryFile(
const requiredToolUtilsValueImports = new Set<string>()
for (const [name, config, resolved] of enabledTools) {
- const result = generateToolCode(name, config, resolved, category, spec, knownTypes, getQuerySchema)
+ const result = generateToolCode(
+ name,
+ config,
+ resolved,
+ category,
+ spec,
+ knownTypes,
+ getQuerySchema,
+ modulesWithStrictBodies.has(moduleName)
+ )
toolCodes.push(result.code)
for (const imp of result.orvalImports) {
allOrvalImports.add(imp)
diff --git a/services/mcp/scripts/lib/definitions.mjs b/services/mcp/scripts/lib/definitions.mjs
index c82706c076bc..09f0e748339f 100644
--- a/services/mcp/scripts/lib/definitions.mjs
+++ b/services/mcp/scripts/lib/definitions.mjs
@@ -7,6 +7,8 @@
import fs from 'node:fs'
import path from 'node:path'
+export const modulesWithStrictBodies = new Set(['email_templates'])
+
/**
* Resolve the OpenAPI schema path, respecting OPENAPI_SCHEMA_PATH env override.
*
@@ -86,3 +88,15 @@ export function isQueryWrappersConfig(parsed) {
export function isToolsConfig(parsed) {
return typeof parsed === 'object' && parsed !== null && 'tools' in parsed
}
+
+/**
+ * Orval's export name for an operation: `messaging_templates_create` becomes `MessagingTemplatesCreate`.
+ * @param {string} operationId
+ * @returns {string}
+ */
+export function operationIdToPascal(operationId) {
+ return operationId
+ .split(/[_.]/)
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
+ .join('')
+}
diff --git a/services/mcp/scripts/lib/loosen-open-objects.mjs b/services/mcp/scripts/lib/loosen-open-objects.mjs
new file mode 100644
index 000000000000..287f1a0610c2
--- /dev/null
+++ b/services/mcp/scripts/lib/loosen-open-objects.mjs
@@ -0,0 +1,152 @@
+import ts from 'typescript'
+
+import { operationIdToPascal } from './definitions.mjs'
+
+export function collectOpenObjectPaths(schema, moduleName) {
+ const targetsByExport = new Map()
+ for (const methods of Object.values(schema.paths ?? {})) {
+ for (const operation of Object.values(methods ?? {})) {
+ const bodySchema = operation?.requestBody?.content?.['application/json']?.schema
+ if (!bodySchema || !operation.operationId) {
+ continue
+ }
+ const target = { moduleName, operationId: operation.operationId, paths: new Set(), dottedPath: undefined }
+ collectFrom(bodySchema, schema, [], false, target, new Set())
+ if (target.paths.size > 0) {
+ refuseDottedPropertyNames(target)
+ targetsByExport.set(`${operationIdToPascal(operation.operationId)}Body`, target)
+ }
+ }
+ }
+ return targetsByExport
+}
+
+export function loosenOpenObjects(source, targetsByExport) {
+ if (targetsByExport.size === 0) {
+ return source
+ }
+ const sourceFile = ts.createSourceFile('api.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
+ const edits = []
+ const placedByExport = new Map([...targetsByExport.keys()].map((exportName) => [exportName, new Set()]))
+
+ for (const statement of sourceFile.statements) {
+ if (!ts.isVariableStatement(statement)) {
+ continue
+ }
+ for (const declaration of statement.declarationList.declarations) {
+ const exportName = ts.isIdentifier(declaration.name) ? declaration.name.text : undefined
+ const target = targetsByExport.get(exportName)
+ if (!target || !declaration.initializer) {
+ continue
+ }
+ const place = (expression, path) => {
+ const joinedPath = path.join('.')
+ if (target.paths.has(joinedPath) && placeObject(expression, edits)) {
+ placedByExport.get(exportName).add(joinedPath)
+ }
+ }
+ place(declaration.initializer, [])
+ visitProperties(declaration.initializer, [], place)
+ }
+ }
+
+ for (const [exportName, target] of targetsByExport) {
+ const unplacedPath = [...target.paths].find((path) => !placedByExport.get(exportName).has(path))
+ if (unplacedPath !== undefined) {
+ throw targetError(target, unplacedPath, `matches no generated object in ${exportName}`)
+ }
+ }
+
+ return edits
+ .sort((a, b) => b.start - a.start)
+ .reduce((text, { start, end }) => `${text.slice(0, start)}looseObject${text.slice(end)}`, source)
+}
+
+function collectFrom(node, schema, path, underUnion, target, ancestors) {
+ const resolved = resolveRef(node, schema)
+ if (!resolved || typeof resolved !== 'object' || ancestors.has(resolved)) {
+ return
+ }
+ ancestors.add(resolved)
+ if (resolved.properties && resolved.additionalProperties === true) {
+ addOpenPath(target, path, underUnion)
+ }
+ for (const member of resolved.allOf ?? []) {
+ collectFrom(member, schema, path, underUnion, target, ancestors)
+ }
+ const unionMembers = [...(resolved.anyOf ?? []), ...(resolved.oneOf ?? [])]
+ const isRealUnion = withoutNull(unionMembers, schema).length > 1
+ for (const member of unionMembers) {
+ collectFrom(member, schema, path, underUnion || isRealUnion, target, ancestors)
+ }
+ if (resolved.items) {
+ collectFrom(resolved.items, schema, path, underUnion, target, ancestors)
+ }
+ for (const [key, property] of Object.entries(resolved.properties ?? {})) {
+ if (key.includes('.')) {
+ target.dottedPath ??= [...path, key].join('.')
+ }
+ collectFrom(property, schema, [...path, key], underUnion, target, ancestors)
+ }
+ ancestors.delete(resolved)
+}
+
+function addOpenPath(target, path, underUnion) {
+ const joinedPath = path.join('.')
+ if (underUnion) {
+ throw targetError(target, joinedPath, 'sits under oneOf or anyOf')
+ }
+ if (target.paths.has(joinedPath)) {
+ throw targetError(target, joinedPath, 'is opened by more than one schema branch')
+ }
+ target.paths.add(joinedPath)
+}
+
+function refuseDottedPropertyNames(target) {
+ if (target.dottedPath !== undefined) {
+ throw targetError(target, target.dottedPath, 'has a property name with a dot')
+ }
+}
+
+function targetError(target, path, reason) {
+ return new Error(
+ `loosen-open-objects: ${target.moduleName} ${target.operationId} open object at "${path || '<body>'}" ${reason}`
+ )
+}
+
+function withoutNull(members, schema) {
+ return members.filter((member) => resolveRef(member, schema)?.type !== 'null')
+}
+
+function resolveRef(node, schema) {
+ let resolved = node
+ while (resolved?.$ref) {
+ resolved = schema.components?.schemas?.[resolved.$ref.split('/').pop()]
+ }
+ return resolved
+}
+
+function visitProperties(node, path, place) {
+ if (ts.isPropertyAssignment(node)) {
+ const propertyPath = [...path, node.name.text]
+ place(node.initializer, propertyPath)
+ ts.forEachChild(node.initializer, (child) => visitProperties(child, propertyPath, place))
+ return
+ }
+ ts.forEachChild(node, (child) => visitProperties(child, path, place))
+}
+
+function placeObject(expression, edits) {
+ let current = expression
+ while (ts.isCallExpression(current) || ts.isPropertyAccessExpression(current)) {
+ if (ts.isPropertyAccessExpression(current) && current.name.text === 'looseObject') {
+ return true
+ }
+ if (ts.isPropertyAccessExpression(current) && current.name.text === 'strictObject') {
+ edits.push({ start: current.name.getStart(), end: current.name.getEnd() })
+ return true
+ }
+ current = current.expression
+ }
+ return false
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e78b343883fc..b41f1885c923 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -37242,7 +37242,8 @@ export namespace Schemas {
footers?: EmailTemplateDesignBodyFootersItem[];
/** Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor. */
values?: EmailTemplateDesignBodyValues;
- };
+ [key: string]: unknown;
+ };
/**
* Design JSON for PostHog's visual email editor — the authoring surface and source of truth. The server renders the sent email from it, and it opens as editable blocks in the editor. Full schema in the designing-email-templates skill.
@@ -37253,7 +37254,8 @@ export namespace Schemas {
/** Design schema version, e.g. 16. */
schemaVersion: number;
body: EmailTemplateDesignBody;
- };
+ [key: string]: unknown;
+ };
export interface EmailTemplateSender {
/**
diff --git a/services/mcp/src/generated/email_templates/api.ts b/services/mcp/src/generated/email_templates/api.ts
index 662a17245869..e72c16fef73e 100644
--- a/services/mcp/src/generated/email_templates/api.ts
+++ b/services/mcp/src/generated/email_templates/api.ts
@@ -38,7 +38,7 @@ export const messagingSendEmailCreateBodyReplyToMax = 10
export const messagingSendEmailCreateBodyFromMax = 1024
-export const MessagingSendEmailCreateBody = () => zod.object({
+export const MessagingSendEmailCreateBody = () => zod.strictObject({
to: zod.email().describe('Email address of the recipient.'),
template_key: zod
.string()
@@ -115,7 +115,7 @@ export const messagingTemplatesCreateBodyContentOneEmailOneFromOneEmailMax = 254
export const messagingTemplatesCreateBodyTypeMax = 24
-export const MessagingTemplatesCreateBody = () => zod.object({
+export const MessagingTemplatesCreateBody = () => zod.strictObject({
name: zod
.string()
.max(messagingTemplatesCreateBodyNameMax)
@@ -129,7 +129,7 @@ export const MessagingTemplatesCreateBody = () => zod.object({
'Tags for organizing templates, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.'
),
content: zod
- .object({
+ .strictObject({
templating: zod
.enum(['liquid'])
.describe('\* `liquid` - liquid')
@@ -139,7 +139,7 @@ export const MessagingTemplatesCreateBody = () => zod.object({
),
email: zod
.union([
- zod.object({
+ zod.strictObject({
subject: zod
.string()
.optional()
@@ -157,7 +157,7 @@ export const MessagingTemplatesCreateBody = () => zod.object({
'Preview text that most inboxes show after the subject. Supports Liquid templating.'
),
design: zod
- .object({
+ .looseObject({
counters: zod
.looseObject({})
.optional()
@@ -165,7 +165,7 @@ export const MessagingTemplatesCreateBody = () => zod.object({
'Highest htmlID suffix per element type, e.g. {\"u_row\": 1, \"u_content_text\": 2}.'
),
schemaVersion: zod.number().describe('Design schema version, e.g. 16.'),
- body: zod.object({
+ body: zod.looseObject({
id: zod.string().optional().describe('Any unique string.'),
rows: zod
.array(zod.looseObject({}))
@@ -187,7 +187,7 @@ export const MessagingTemplatesCreateBody = () => zod.object({
"Design JSON for PostHog's visual email editor — the authoring surface and source of truth. The server renders the sent email from it, and it opens as editable blocks in the editor. Full schema in the designing-email-templates skill."
),
from: zod
- .object({
+ .strictObject({
email: zod
.string()
.max(messagingTemplatesCreateBodyContentOneEmailOneFromOneEmailMax)
@@ -272,7 +272,7 @@ export const messagingTemplatesPartialUpdateBodyContentOneEmailOneFromOneEmailMa
export const messagingTemplatesPartialUpdateBodyTypeMax = 24
-export const MessagingTemplatesPartialUpdateBody = () => zod.object({
+export const MessagingTemplatesPartialUpdateBody = () => zod.strictObject({
name: zod
.string()
.max(messagingTemplatesPartialUpdateBodyNameMax)
@@ -287,7 +287,7 @@ export const MessagingTemplatesPartialUpdateBody = () => zod.object({
'Tags for organizing templates, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.'
),
content: zod
- .object({
+ .strictObject({
templating: zod
.enum(['liquid'])
.describe('\* `liquid` - liquid')
@@ -297,7 +297,7 @@ export const MessagingTemplatesPartialUpdateBody = () => zod.object({
),
email: zod
.union([
- zod.object({
+ zod.strictObject({
subject: zod
.string()
.optional()
@@ -315,7 +315,7 @@ export const MessagingTemplatesPartialUpdateBody = () => zod.object({
'Preview text that most inboxes show after the subject. Supports Liquid templating.'
),
design: zod
- .object({
+ .looseObject({
counters: zod
.looseObject({})
.optional()
@@ -323,7 +323,7 @@ export const MessagingTemplatesPartialUpdateBody = () => zod.object({
'Highest htmlID suffix per element type, e.g. {\"u_row\": 1, \"u_content_text\": 2}.'
),
schemaVersion: zod.number().describe('Design schema version, e.g. 16.'),
- body: zod.object({
+ body: zod.looseObject({
id: zod.string().optional().describe('Any unique string.'),
rows: zod
.array(zod.looseObject({}))
@@ -345,7 +345,7 @@ export const MessagingTemplatesPartialUpdateBody = () => zod.object({
"Design JSON for PostHog's visual email editor — the authoring surface and source of truth. The server renders the sent email from it, and it opens as editable blocks in the editor. Full schema in the designing-email-templates skill."
),
from: zod
- .object({
+ .strictObject({
email: zod
.string()
.max(messagingTemplatesPartialUpdateBodyContentOneEmailOneFromOneEmailMax)
@@ -410,10 +410,10 @@ export const MessagingTemplatesDesignPartialUpdateParams = () => zod.object({
),
})
-export const MessagingTemplatesDesignPartialUpdateBody = () => zod.object({
+export const MessagingTemplatesDesignPartialUpdateBody = () => zod.strictObject({
operations: zod
.array(
- zod.object({
+ zod.strictObject({
op: zod
.enum([
'update_content',
@@ -485,7 +485,7 @@ export const MessagingTemplatesMakeTransactionalCreateParams = () => zod.object(
),
})
-export const MessagingTemplatesMakeTransactionalCreateBody = () => zod.object({
+export const MessagingTemplatesMakeTransactionalCreateBody = () => zod.strictObject({
from_integration_id: zod
.number()
.nullish()
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 827b35bb4ec1..adf4b5d8b2dc 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -1335,7 +1335,7 @@ export const WorkflowGraphPatchSchema = z.object({
const EmailDesignFreeformObject = z.record(z.string(), z.unknown())
const EmailDesignPatchOperationSchema = z.discriminatedUnion('op', [
- z.object({
+ z.strictObject({
op: z.literal('update_content'),
id: z.string().describe('Id of the content block to update.'),
patch: EmailDesignFreeformObject.describe(
@@ -1343,23 +1343,23 @@ const EmailDesignPatchOperationSchema = z.discriminatedUnion('op', [
"e.g. {values: {text: '<p>Hi</p>'}} changes only the block's text."
),
}),
- z.object({
+ z.strictObject({
op: z.literal('update_column'),
id: z.string().describe('Id of the column to update.'),
patch: EmailDesignFreeformObject.describe('Partial column fields, deep-merged; a null leaf deletes that key.'),
}),
- z.object({
+ z.strictObject({
op: z.literal('update_row'),
id: z.string().describe('Id of the row to update.'),
patch: EmailDesignFreeformObject.describe('Partial row fields, deep-merged; a null leaf deletes that key.'),
}),
- z.object({
+ z.strictObject({
op: z.literal('update_body'),
patch: EmailDesignFreeformObject.describe(
"Partial body fields, deep-merged. e.g. {values: {backgroundColor: '#ffffff'}}."
),
}),
- z.object({
+ z.strictObject({
op: z.literal('add_content'),
column_id: z.string().describe('Id of the column to insert the block into.'),
content: EmailDesignFreeformObject.describe(
@@ -1368,17 +1368,17 @@ const EmailDesignPatchOperationSchema = z.discriminatedUnion('op', [
),
index: z.number().int().optional().describe('0-based insert position; omit to append to the end.'),
}),
- z.object({
+ z.strictObject({
op: z.literal('remove_content'),
id: z.string().describe('Id of the content block to remove.'),
}),
- z.object({
+ z.strictObject({
op: z.literal('move_content'),
id: z.string().describe('Id of the content block to move.'),
column_id: z.string().describe('Id of the destination column.'),
index: z.number().int().optional().describe('0-based position in the destination column; omit to append.'),
}),
- z.object({
+ z.strictObject({
op: z.literal('add_row'),
row: EmailDesignFreeformObject.describe(
'A full row {cells, columns: [{contents: [...], values}], values}; ids and Unlayer numbering are ' +
@@ -1386,13 +1386,13 @@ const EmailDesignPatchOperationSchema = z.discriminatedUnion('op', [
),
index: z.number().int().optional().describe('0-based insert position; omit to append to the end.'),
}),
- z.object({
+ z.strictObject({
op: z.literal('remove_row'),
id: z.string().describe('Id of the row to remove.'),
}),
])
-export const EmailTemplateDesignPatchSchema = z.object({
+export const EmailTemplateDesignPatchSchema = z.strictObject({
id: z.string().describe('The email template id to edit.'),
operations: z
.array(EmailDesignPatchOperationSchema)
diff --git a/services/mcp/src/tools/generated/email_templates.ts b/services/mcp/src/tools/generated/email_templates.ts
index d43ac025207b..2fa29e0861d9 100644
--- a/services/mcp/src/tools/generated/email_templates.ts
+++ b/services/mcp/src/tools/generated/email_templates.ts
@@ -134,9 +134,9 @@ const WorkflowsMakeEmailTemplateTransactionalSchema = () => {
const MessagingTemplatesMakeTransactionalCreateBody = orvalSchemas.MessagingTemplatesMakeTransactionalCreateBody()
const MessagingTemplatesMakeTransactionalCreateParams =
orvalSchemas.MessagingTemplatesMakeTransactionalCreateParams()
- return MessagingTemplatesMakeTransactionalCreateParams.omit({ project_id: true }).extend(
- MessagingTemplatesMakeTransactionalCreateBody.shape
- )
+ return MessagingTemplatesMakeTransactionalCreateParams.omit({ project_id: true })
+ .extend(MessagingTemplatesMakeTransactionalCreateBody.shape)
+ .strict()
}
const WorkflowsMakeEmailTemplateTransactionalSchemaExecute = z.strictObject({
@@ -365,9 +365,9 @@ const workflowsShowEmailTemplate = (): ToolBase<
const WorkflowsUpdateEmailTemplateSchema = () => {
const MessagingTemplatesPartialUpdateBody = orvalSchemas.MessagingTemplatesPartialUpdateBody()
const MessagingTemplatesPartialUpdateParams = orvalSchemas.MessagingTemplatesPartialUpdateParams()
- return MessagingTemplatesPartialUpdateParams.omit({ project_id: true }).extend(
- MessagingTemplatesPartialUpdateBody.shape
- )
+ return MessagingTemplatesPartialUpdateParams.omit({ project_id: true })
+ .extend(MessagingTemplatesPartialUpdateBody.shape)
+ .strict()
}
const workflowsUpdateEmailTemplate = (): ToolBase<
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.json
index 981ecde88d3e..31fd594cadcc 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.json
@@ -1,17 +1,22 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
+ "additionalProperties": false,
"properties": {
"content": {
+ "additionalProperties": false,
"description": "Template content keyed by channel. Replaced as a whole on update, not merged.",
"properties": {
"email": {
"anyOf": [
{
+ "additionalProperties": false,
"properties": {
"design": {
+ "additionalProperties": {},
"description": "Design JSON for PostHog's visual email editor — the authoring surface and source of truth. The server renders the sent email from it, and it opens as editable blocks in the editor. Full schema in the designing-email-templates skill.",
"properties": {
"body": {
+ "additionalProperties": {},
"properties": {
"footers": {
"items": {
@@ -67,6 +72,7 @@
"type": "object"
},
"from": {
+ "additionalProperties": false,
"description": "The sender a transactional template sends from. A template made transactional without one gets the sender it was made transactional with.",
"properties": {
"email": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-make-email-template-transactional-prepare.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-make-email-template-transactional-prepare.json
index 778419a42fd7..38f1b85c97b5 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-make-email-template-transactional-prepare.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-make-email-template-transactional-prepare.json
@@ -1,5 +1,6 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
+ "additionalProperties": false,
"properties": {
"from_integration_id": {
"anyOf": [
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-action-email.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-action-email.json
index 3d7874ec84bc..3cc668c440ae 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-action-email.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-action-email.json
@@ -26,6 +26,7 @@
"items": {
"oneOf": [
{
+ "additionalProperties": false,
"properties": {
"id": {
"description": "Id of the content block to update.",
@@ -48,6 +49,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"id": {
"description": "Id of the column to update.",
@@ -70,6 +72,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"id": {
"description": "Id of the row to update.",
@@ -92,6 +95,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"op": {
"const": "update_body",
@@ -110,6 +114,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"column_id": {
"description": "Id of the column to insert the block into.",
@@ -138,6 +143,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"id": {
"description": "Id of the content block to remove.",
@@ -152,6 +158,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"column_id": {
"description": "Id of the destination column.",
@@ -176,6 +183,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"index": {
"description": "0-based insert position; omit to append to the end.",
@@ -200,6 +208,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"id": {
"description": "Id of the row to remove.",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-email-template.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-email-template.json
index a28fea4259fc..9f4423b3b3ca 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-email-template.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-email-template.json
@@ -1,5 +1,6 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
+ "additionalProperties": false,
"properties": {
"id": {
"description": "The email template id to edit.",
@@ -10,6 +11,7 @@
"items": {
"oneOf": [
{
+ "additionalProperties": false,
"properties": {
"id": {
"description": "Id of the content block to update.",
@@ -32,6 +34,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"id": {
"description": "Id of the column to update.",
@@ -54,6 +57,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"id": {
"description": "Id of the row to update.",
@@ -76,6 +80,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"op": {
"const": "update_body",
@@ -94,6 +99,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"column_id": {
"description": "Id of the column to insert the block into.",
@@ -122,6 +128,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"id": {
"description": "Id of the content block to remove.",
@@ -136,6 +143,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"column_id": {
"description": "Id of the destination column.",
@@ -160,6 +168,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"index": {
"description": "0-based insert position; omit to append to the end.",
@@ -184,6 +193,7 @@
"type": "object"
},
{
+ "additionalProperties": false,
"properties": {
"id": {
"description": "Id of the row to remove.",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-send-email-prepare.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-send-email-prepare.json
index 622c83e69af2..ba085c752524 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-send-email-prepare.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-send-email-prepare.json
@@ -1,5 +1,6 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
+ "additionalProperties": false,
"properties": {
"capture_engagement": {
"description": "Whether the engagement events (sent, delivered, opened, clicked, bounced) of the email your code rendered are captured as analytics events of the recipient. Defaults to true. A project whose admin turned engagement capture off captures nothing, whatever the send says.",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.json
index aa998c3d50e8..ec0cb2e3e04f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.json
@@ -1,17 +1,22 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
+ "additionalProperties": false,
"properties": {
"content": {
+ "additionalProperties": false,
"description": "Template content keyed by channel. Replaced as a whole on update, not merged.",
"properties": {
"email": {
"anyOf": [
{
+ "additionalProperties": false,
"properties": {
"design": {
+ "additionalProperties": {},
"description": "Design JSON for PostHog's visual email editor — the authoring surface and source of truth. The server renders the sent email from it, and it opens as editable blocks in the editor. Full schema in the designing-email-templates skill.",
"properties": {
"body": {
+ "additionalProperties": {},
"properties": {
"footers": {
"items": {
@@ -67,6 +72,7 @@
"type": "object"
},
"from": {
+ "additionalProperties": false,
"description": "The sender a transactional template sends from. A template made transactional without one gets the sender it was made transactional with.",
"properties": {
"email": {
diff --git a/services/mcp/tests/unit/email-templates-generated.test.ts b/services/mcp/tests/unit/email-templates-generated.test.ts
new file mode 100644
index 000000000000..6054f12e93a0
--- /dev/null
+++ b/services/mcp/tests/unit/email-templates-generated.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest'
+import type { z } from 'zod'
+
+import { GENERATED_TOOL_MAP } from '@/tools/generated'
+
+describe('Generated email template tools', () => {
+ const toolSchema = (name: string): z.ZodType => GENERATED_TOOL_MAP[name]!().schema
+ const templateId = '0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b'
+ const design = {
+ schemaVersion: 16,
+ body: { id: 'body', rows: [], values: {} },
+ }
+ const codeSend = { to: '[email protected]', template_key: 'welcome', subject: 'Hi', html: '<p>Hi</p>' }
+ const createWithEmail = (email: Record<string, unknown>): Record<string, unknown> => ({
+ name: 'Welcome',
+ content: { templating: 'liquid', email: { subject: 'Hi', text: 'Hi', design, ...email } },
+ })
+
+ it.each([
+ ['workflows-send-email-prepare', 'a misspelled field', { ...codeSend, capture_engagment: false }],
+ ['workflows-send-email-prepare', 'a field of a send by template', { ...codeSend, template_id: templateId }],
+ [
+ 'workflows-make-email-template-transactional-prepare',
+ 'an unknown top-level field',
+ { id: templateId, from_integration: 1 },
+ ],
+ [
+ 'workflows-update-email-template',
+ 'a read-only field',
+ { id: templateId, name: 'Welcome', created_at: '2026-01-01T00:00:00Z' },
+ ],
+ [
+ 'workflows-create-email-template',
+ 'a misspelled field in content.email',
+ createWithEmail({ preview_text: 'Hi' }),
+ ],
+ [
+ 'workflows-patch-email-template',
+ 'a misspelled operation field',
+ { id: templateId, operations: [{ op: 'move_content', id: 'block', column_id: 'column', indx: 0 }] },
+ ],
+ [
+ 'workflows-patch-email-template',
+ 'an unknown top-level field',
+ { id: templateId, operations: [{ op: 'remove_content', id: 'block' }], dry_run: true },
+ ],
+ ])('%s refuses an input with %s', (tool, _case, input) => {
+ expect(toolSchema(tool).safeParse(input).success).toBe(false)
+ })
+
+ it('accepts a send of the email your code rendered', () => {
+ expect(toolSchema('workflows-send-email-prepare').parse(codeSend)).toEqual(codeSend)
+ })
+
+ it('keeps keys the design format adds at its top level and in its body', () => {
+ const editorDesign = {
+ ...design,
+ idCounter: 3,
+ body: { ...design.body, footers: [], customKey: { nested: true } },
+ }
+ const input = createWithEmail({ design: editorDesign })
+
+ expect(toolSchema('workflows-create-email-template').parse(input)).toMatchObject(input)
+ })
+})
diff --git a/services/mcp/tests/unit/loosen-open-objects.test.ts b/services/mcp/tests/unit/loosen-open-objects.test.ts
new file mode 100644
index 000000000000..86ae9aecdf50
--- /dev/null
+++ b/services/mcp/tests/unit/loosen-open-objects.test.ts
@@ -0,0 +1,114 @@
+import { describe, expect, it } from 'vitest'
+
+import { collectOpenObjectPaths, loosenOpenObjects } from '../../scripts/lib/loosen-open-objects.mjs'
+
+const openObject = (properties: Record<string, unknown>): Record<string, unknown> => ({
+ type: 'object',
+ additionalProperties: true,
+ properties,
+})
+
+const closedObject = (properties: Record<string, unknown>): Record<string, unknown> => ({
+ type: 'object',
+ properties,
+})
+
+const schemaWithBody = (body: Record<string, unknown>): Record<string, unknown> => ({
+ paths: {
+ '/things/': {
+ post: {
+ operationId: 'things_create',
+ requestBody: { content: { 'application/json': { schema: body } } },
+ },
+ },
+ },
+})
+
+const loosen = (body: Record<string, unknown>, source: string): string =>
+ loosenOpenObjects(source, collectOpenObjectPaths(schemaWithBody(body), 'things'))
+
+const designBody = closedObject({ design: openObject({ version: { type: 'integer' } }) })
+
+describe('loosenOpenObjects', () => {
+ it('loosens an open object under a nullable oneOf and keeps its closed sibling strict', () => {
+ const body = closedObject({
+ email: { oneOf: [designBody, { type: 'null' }] },
+ sender: closedObject({ name: { type: 'string' } }),
+ })
+ const source = [
+ 'export const ThingsCreateBody = zod.strictObject({',
+ ' email: zod.strictObject({ design: zod.strictObject({ version: zod.number() }) }).nullable(),',
+ ' sender: zod.strictObject({ name: zod.string() }),',
+ '})',
+ ].join('\n')
+
+ expect(loosen(body, source)).toBe(
+ [
+ 'export const ThingsCreateBody = zod.strictObject({',
+ ' email: zod.strictObject({ design: zod.looseObject({ version: zod.number() }) }).nullable(),',
+ ' sender: zod.strictObject({ name: zod.string() }),',
+ '})',
+ ].join('\n')
+ )
+ })
+
+ it.each([
+ {
+ case: 'the body export is missing',
+ body: designBody,
+ source: 'export const OtherBody = zod.strictObject({ design: zod.strictObject({ version: zod.number() }) })',
+ error: /things things_create .*"design"/,
+ },
+ {
+ case: 'the open object is hoisted into a const',
+ body: designBody,
+ source: [
+ 'const Design = zod.strictObject({ version: zod.number() })',
+ 'export const ThingsCreateBody = zod.strictObject({ design: Design })',
+ ].join('\n'),
+ error: /things things_create .*"design"/,
+ },
+ {
+ case: 'the open object sits under items',
+ body: closedObject({ entries: { type: 'array', items: openObject({ name: { type: 'string' } }) } }),
+ source: 'export const ThingsCreateBody = zod.strictObject({ entries: zod.array(zod.strictObject({ name: zod.string() })) })',
+ error: /things things_create .*"entries"/,
+ },
+ {
+ case: 'the open object sits under oneOf',
+ body: closedObject({
+ data: { oneOf: [openObject({ a: { type: 'string' } }), closedObject({ a: { type: 'string' } })] },
+ }),
+ source: 'export const ThingsCreateBody = zod.strictObject({ data: zod.union([zod.strictObject({ a: zod.string() }), zod.strictObject({ a: zod.string() })]) })',
+ error: /things things_create .*"data"/,
+ },
+ {
+ case: 'two branches open the same path',
+ body: {
+ allOf: [
+ closedObject({ data: openObject({ a: { type: 'string' } }) }),
+ closedObject({ data: openObject({ b: { type: 'string' } }) }),
+ ],
+ },
+ source: 'export const ThingsCreateBody = zod.strictObject({ data: zod.strictObject({ a: zod.string(), b: zod.string() }) })',
+ error: /things things_create .*"data"/,
+ },
+ {
+ case: 'a property name on the path has a dot',
+ body: closedObject({ 'a.b': openObject({ c: { type: 'string' } }) }),
+ source: "export const ThingsCreateBody = zod.strictObject({ 'a.b': zod.strictObject({ c: zod.string() }) })",
+ error: /things things_create .*"a\.b"/,
+ },
+ {
+ case: 'a closed sibling name with a dot aliases a nested open path',
+ body: closedObject({
+ a: closedObject({ b: openObject({ c: { type: 'string' } }) }),
+ 'a.b': closedObject({ c: { type: 'string' } }),
+ }),
+ source: "export const ThingsCreateBody = zod.strictObject({ a: zod.strictObject({ b: zod.strictObject({ c: zod.string() }) }), 'a.b': zod.strictObject({ c: zod.string() }) })",
+ error: /things things_create .*"a\.b"/,
+ },
+ ])('refuses to generate when $case', ({ body, source, error }) => {
+ expect(() => loosen(body, source)).toThrow(error)
+ })
+})