: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
feat(workflows): surgical email template design updates via MCP (#63945)
Harley Alexander50b8d2859f1d
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex bfa81d07a4e5..02c3410e5972 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -504,6 +504,21 @@ SPECTACULAR_SETTINGS = {"HeatmapType": "products.web_analytics.backend.models.heatmap_saved.SavedHeatmap.Type",# --- Inline value lists (type-hint enums, no x-spec-enum-id) ---"PropertyGroupOperator": ["AND", "OR"],+ # Two serializers now expose an `op` ChoiceField (metrics filters and email-template design+ # patches). Pin both to stable names so neither gets a component-prefixed auto-name on collision.+ # "OpEnum" keeps the metrics filter enum at its pre-existing generated name.+ "OpEnum": ["eq", "neq", "regex", "not_regex"],+ "EmailTemplateDesignOperationEnum": [+ "update_content",+ "update_column",+ "update_row",+ "update_body",+ "add_content",+ "remove_content",+ "move_content",+ "add_row",+ "remove_row",+ ],"PropertyFilterTypeEnum": ["event","event_metadata",diff --git a/products/messaging/backend/api/design_operations.py b/products/messaging/backend/api/design_operations.pynew file mode 100644index 000000000000..338a09622f68--- /dev/null+++ b/products/messaging/backend/api/design_operations.py@@ -0,0 +1,186 @@+import uuid+from copy import deepcopy+from typing import Any, NoReturn, Optional++from rest_framework import serializers++# Surgical, id-addressed edits to an Unlayer email design (the content.email.design tree). The caller+# sends a small, ordered list of operations instead of re-transmitting the whole design; these are+# applied to the stored design and the result is validated + re-rendered to HTML by the serializer.+# Pure functions here — no DB, no HTML rendering — so they're cheap to unit-test exhaustively.+#+# The design tree is body.rows[].columns[].contents[]; every row, column, and content item carries a+# stable string `id`, which is how operations address them (indexes shift when blocks are added or+# removed; ids don't). For add_* operations the caller may omit the bookkeeping fields (`id`, and the+# `_meta.htmlID` / `counters` numbering Unlayer tracks per element type) — they're filled in here so a+# caller never has to compute them.+++def _deep_merge(target: dict, patch: dict) -> dict:+ """Recursively merge `patch` into `target`. A null leaf deletes the key; a dict merges into a dict;+ anything else replaces. Lets a caller change values.text without resending the rest of values."""+ for key, value in patch.items():+ if value is None:+ target.pop(key, None)+ elif isinstance(value, dict) and isinstance(target.get(key), dict):+ _deep_merge(target[key], value)+ else:+ target[key] = value+ return target+++def _fail(message: str) -> NoReturn:+ raise serializers.ValidationError({"operations": message})+++def _new_id() -> str:+ # Unlayer ids are arbitrary unique strings; the editor uses ~10-char tokens. uuid4 keeps collisions+ # astronomically unlikely without needing to scan the existing tree.+ return uuid.uuid4().hex[:10]+++def _counter_key(node_kind: str, content_type: Optional[str] = None) -> str:+ # Counter/htmlID prefixes mirror what the Unlayer editor emits: u_row, u_column, u_content_<type>.+ if node_kind == "content":+ return f"u_content_{content_type or 'text'}"+ return f"u_{node_kind}"+++def _assign_meta(node: dict, counter_key: str, counters: dict) -> None:+ """Number a freshly added node the way the editor would: bump the per-type counter and stamp the+ matching _meta.htmlID so the rendered HTML ids stay consistent."""+ n = int(counters.get(counter_key, 0)) + 1+ counters[counter_key] = n+ values = node.setdefault("values", {})+ meta = values.setdefault("_meta", {})+ meta["htmlID"] = f"{counter_key}_{n}"+ meta.setdefault("htmlClassNames", counter_key)+++def _prepare_content(content: dict, counters: dict) -> dict:+ content = deepcopy(content)+ if not content.get("id"):+ content["id"] = _new_id()+ _assign_meta(content, _counter_key("content", content.get("type")), counters)+ return content+++def _prepare_row(row: dict, counters: dict) -> dict:+ row = deepcopy(row)+ if not row.get("id"):+ row["id"] = _new_id()+ _assign_meta(row, _counter_key("row"), counters)+ for column in row.get("columns") or []:+ if not column.get("id"):+ column["id"] = _new_id()+ _assign_meta(column, _counter_key("column"), counters)+ column["contents"] = [_prepare_content(c, counters) for c in column.get("contents") or []]+ return row+++def _iter_rows(design: dict) -> list[dict]:+ body = design.get("body") or {}+ return body.get("rows") or []+++def _find_content(design: dict, content_id: str) -> Optional[tuple[dict, dict]]:+ """Return (content, containing_column) for the content item with `content_id`, or None."""+ for row in _iter_rows(design):+ for column in row.get("columns") or []:+ for content in column.get("contents") or []:+ if content.get("id") == content_id:+ return content, column+ return None+++def _find_column(design: dict, column_id: str) -> Optional[dict]:+ for row in _iter_rows(design):+ for column in row.get("columns") or []:+ if column.get("id") == column_id:+ return column+ return None+++def _find_row(design: dict, row_id: str) -> Optional[dict]:+ for row in _iter_rows(design):+ if row.get("id") == row_id:+ return row+ return None+++def _insert(items: list, item: Any, index: Optional[int]) -> None:+ if index is None or index >= len(items):+ items.append(item)+ else:+ items.insert(max(index, 0), item)+++def apply_design_operations(design: dict, operations: list[dict]) -> dict:+ """Apply the ordered operations to a copy of `design` and return the new design. Does not mutate the+ input. Raises ValidationError on operations that can't be applied (unknown id, missing target).+ Structural validity of the result is the caller's responsibility (validate_design)."""+ design = deepcopy(design)+ design.setdefault("counters", {})+ counters = design["counters"]++ for op in operations:+ kind = op["op"]++ if kind == "update_content":+ found = _find_content(design, op["id"])+ if found is None:+ _fail(f"update_content: content '{op['id']}' not found")+ _deep_merge(found[0], op["patch"])++ elif kind == "update_column":+ column = _find_column(design, op["id"])+ if column is None:+ _fail(f"update_column: column '{op['id']}' not found")+ _deep_merge(column, op["patch"])++ elif kind == "update_row":+ row = _find_row(design, op["id"])+ if row is None:+ _fail(f"update_row: row '{op['id']}' not found")+ _deep_merge(row, op["patch"])++ elif kind == "update_body":+ _deep_merge(design.setdefault("body", {}), op["patch"])++ elif kind == "add_content":+ column = _find_column(design, op["column_id"])+ if column is None:+ _fail(f"add_content: column '{op['column_id']}' not found")+ new_content = _prepare_content(op["content"], counters)+ _insert(column.setdefault("contents", []), new_content, op.get("index"))++ elif kind == "remove_content":+ found = _find_content(design, op["id"])+ if found is None:+ _fail(f"remove_content: content '{op['id']}' not found")+ content, column = found+ column["contents"] = [c for c in column["contents"] if c.get("id") != op["id"]]++ elif kind == "move_content":+ found = _find_content(design, op["id"])+ if found is None:+ _fail(f"move_content: content '{op['id']}' not found")+ target_column = _find_column(design, op["column_id"])+ if target_column is None:+ _fail(f"move_content: column '{op['column_id']}' not found")+ content, source_column = found+ source_column["contents"] = [c for c in source_column["contents"] if c.get("id") != op["id"]]+ _insert(target_column.setdefault("contents", []), content, op.get("index"))++ elif kind == "add_row":+ new_row = _prepare_row(op["row"], counters)+ _insert(design.setdefault("body", {}).setdefault("rows", []), new_row, op.get("index"))++ elif kind == "remove_row":+ body = design.get("body") or {}+ rows = body.get("rows") or []+ if not any(r.get("id") == op["id"] for r in rows):+ _fail(f"remove_row: row '{op['id']}' not found")+ body["rows"] = [r for r in rows if r.get("id") != op["id"]]++ return designdiff --git a/products/messaging/backend/api/design_validation.py b/products/messaging/backend/api/design_validation.pynew file mode 100644index 000000000000..decac52ae72e--- /dev/null+++ b/products/messaging/backend/api/design_validation.py@@ -0,0 +1,72 @@+from typing import NoReturn++from rest_framework import serializers++# Structural validation for an Unlayer email design after operations are applied. Hard errors (raised)+# are things Unlayer's renderer can't recover from — a missing body, a non-list rows, or duplicate ids+# that would make later id-addressed edits ambiguous. Everything else is advisory: returned as warnings+# for the caller to log, not reject, so the design model stays forward-compatible as Unlayer adds block+# types.++# Content types the Unlayer editor emits today; an unknown type is a warning, not a hard error.+KNOWN_CONTENT_TYPES = frozenset(+ {+ "text",+ "heading",+ "button",+ "image",+ "divider",+ "social",+ "html",+ "video",+ "menu",+ "timer",+ "table",+ "carousel",+ }+)+++def _fail(message: str) -> NoReturn:+ raise serializers.ValidationError({"design": message})+++def validate_design(design: dict) -> list[str]:+ """Validate the structure of an Unlayer design. Raises ValidationError on hard errors; returns a+ list of advisory warnings the caller should log rather than reject."""+ if not isinstance(design, dict):+ _fail("design must be an object")++ body = design.get("body")+ if not isinstance(body, dict):+ _fail("design.body must be an object")++ rows = body.get("rows")+ if not isinstance(rows, list):+ _fail("design.body.rows must be a list")++ warnings: list[str] = []+ seen_ids: set[str] = set()++ def check_id(node_id: object, label: str) -> None:+ if not isinstance(node_id, str) or not node_id:+ warnings.append(f"{label} is missing an id")+ return+ if node_id in seen_ids:+ _fail(f"duplicate id '{node_id}' — ids must be unique so edits can address one node")+ seen_ids.add(node_id)++ if not rows:+ warnings.append("design has no rows — the rendered email will be empty")++ for row in rows:+ check_id(row.get("id"), "row")+ for column in row.get("columns") or []:+ check_id(column.get("id"), "column")+ for content in column.get("contents") or []:+ check_id(content.get("id"), "content")+ content_type = content.get("type")+ if content_type not in KNOWN_CONTENT_TYPES:+ warnings.append(f"content '{content.get('id')}' has unknown type '{content_type}'")++ return warningsdiff --git a/products/messaging/backend/api/message_templates.py b/products/messaging/backend/api/message_templates.pyindex fb2fd31b362e..370a64d59c7a 100644--- a/products/messaging/backend/api/message_templates.py+++ b/products/messaging/backend/api/message_templates.py@@ -1,18 +1,29 @@+from copy import deepcopyfrom typing import Any-from drf_spectacular.utils import extend_schema_field+from django.db import transaction++import structlog+from drf_spectacular.utils import extend_schema, extend_schema_fieldfrom rest_framework import serializers, viewsets+from rest_framework.decorators import actionfrom rest_framework.permissions import IsAuthenticated+from rest_framework.request import Request+from rest_framework.response import Responsefrom posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.shared import UserBasicSerializer+from products.messaging.backend.api.design_operations import apply_design_operations+from products.messaging.backend.api.design_validation import validate_designfrom products.messaging.backend.models.message_category import MessageCategoryfrom products.messaging.backend.models.message_template import MessageTemplatefrom products.messaging.backend.unlayer import UnlayerNotConfiguredError, UnlayerRenderError, render_design_html+logger = structlog.get_logger(__name__)+# Shallow skeleton of the Unlayer design document — enough structure for API callers# (and the LLMs behind MCP tools) to author against; the full row/column/content@@ -161,6 +172,106 @@ class MessageTemplateSerializer(serializers.ModelSerializer):return instance+DESIGN_OPERATION_TYPES = [+ "update_content",+ "update_column",+ "update_row",+ "update_body",+ "add_content",+ "remove_content",+ "move_content",+ "add_row",+ "remove_row",+]++# Per-op required fields, validated in DesignOperationSerializer.validate so a malformed op is rejected+# before any are applied (the whole batch is atomic).+_DESIGN_OPERATION_REQUIRED_FIELDS: dict[str, list[str]] = {+ "update_content": ["id", "patch"],+ "update_column": ["id", "patch"],+ "update_row": ["id", "patch"],+ "update_body": ["patch"],+ "add_content": ["column_id", "content"],+ "remove_content": ["id"],+ "move_content": ["id", "column_id"],+ "add_row": ["row"],+ "remove_row": ["id"],+}+++class DesignOperationSerializer(serializers.Serializer):+ op = serializers.ChoiceField(+ choices=DESIGN_OPERATION_TYPES,+ help_text=(+ "Design edit. update_content {id, patch}: deep-merge patch into the content block's fields (a null "+ "leaf deletes that key) — the surgical path, e.g. change just values.text. update_row / update_column "+ "{id, patch} and update_body {patch}: same deep-merge for row/column/body-level settings. add_content "+ "{column_id, content, index?}: insert a content block into a column (id and Unlayer numbering are "+ "filled in for you). remove_content {id} / move_content {id, column_id, index?}: delete or relocate a "+ "block. add_row {row, index?} / remove_row {id}: add or delete a row."+ ),+ )+ id = serializers.CharField(+ required=False,+ help_text="Target node id. Required for update_content/column/row, remove_content, remove_row, move_content.",+ )+ column_id = serializers.CharField(+ required=False, help_text="Target column id. Required for add_content and move_content."+ )+ patch = serializers.JSONField(+ required=False,+ help_text=(+ "update_* only. Partial fields deep-merged into the existing node; a null leaf deletes that key. "+ "e.g. {values: {text: '<p>Hi</p>'}} changes only the block's text."+ ),+ )+ content = serializers.JSONField(+ required=False,+ help_text=(+ "add_content only. A content block {type, values: {...}}; omit id and values._meta — they're assigned "+ "server-side. type is one of text, heading, button, image, divider, html, etc."+ ),+ )+ row = serializers.JSONField(+ required=False,+ help_text=(+ "add_row only. A full row {cells, columns: [{contents: [...], values}], values}; ids and Unlayer "+ "numbering are assigned server-side for the row and everything nested in it."+ ),+ )+ index = serializers.IntegerField(+ required=False,+ help_text="add_*/move_content only. 0-based insert position; omit to append to the end.",+ )++ def validate(self, data: Any) -> Any:+ op = data["op"]+ missing = [field for field in _DESIGN_OPERATION_REQUIRED_FIELDS[op] if data.get(field) is None]+ if missing:+ raise serializers.ValidationError(f"op '{op}' requires: {', '.join(missing)}")+ if op in ("update_content", "update_column", "update_row", "update_body") and not isinstance(+ data.get("patch"), dict+ ):+ raise serializers.ValidationError(f"{op} 'patch' must be an object")+ if op == "add_content" and not isinstance(data.get("content"), dict):+ raise serializers.ValidationError("add_content 'content' must be an object")+ if op == "add_row" and not isinstance(data.get("row"), dict):+ raise serializers.ValidationError("add_row 'row' must be an object")+ return data+++class DesignPatchSerializer(serializers.Serializer):+ operations = serializers.ListField(+ child=DesignOperationSerializer(),+ allow_empty=False,+ help_text=(+ "Ordered edits applied atomically to a 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 it's saved only if valid — "+ "otherwise the template is unchanged. Reference blocks by id so you never resend the whole design."+ ),+ )++class MessageTemplatesViewSet(TeamAndOrgViewSetMixin,ForbidDestroyModel,@@ -168,6 +279,9 @@ class MessageTemplatesViewSet():scope_object = "hog_flow"permission_classes = [IsAuthenticated]+ # `design` is a custom write action; list it so programmatic callers (MCP/personal API key) get+ # hog_flow:write checked instead of being rejected as an action with no declared scope.+ scope_object_write_actions = ["create", "update", "partial_update", "patch", "destroy", "design"]serializer_class = MessageTemplateSerializerqueryset = MessageTemplate.objects.all()@@ -181,3 +295,47 @@ class MessageTemplatesViewSet(.select_related("created_by").order_by("-created_at"))++ @extend_schema(request=DesignPatchSerializer, responses={200: MessageTemplateSerializer})+ @action(detail=True, methods=["PATCH"])+ def design(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ # Surgical design editing: apply a small, id-addressed op list to the stored Unlayer design instead+ # of re-transmitting the whole design JSON. Reads, applies, validates, re-renders, and saves+ # atomically so a rejected batch leaves the template untouched (and concurrent visual-editor saves+ # can't interleave).+ op_serializer = DesignPatchSerializer(data=request.data)+ op_serializer.is_valid(raise_exception=True)+ operations = op_serializer.validated_data["operations"]++ # Authorize + team-scope via the normal lookup, then re-read FOR UPDATE inside the transaction.+ instance = self.get_object()++ with transaction.atomic():+ # nosemgrep: semgrep.rules.idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)+ locked = MessageTemplate.objects.select_for_update().get(pk=instance.pk)++ content = deepcopy(locked.content or {})+ email = content.get("email") or {}+ design = email.get("design")+ if not isinstance(design, dict):+ raise serializers.ValidationError(+ {+ "design": "This template has no editable design JSON to patch. Set content.email.design "+ "with a full update first, then use surgical operations."+ }+ )++ new_design = apply_design_operations(design, operations)+ for warning in validate_design(new_design):+ logger.info("email_template_design_warning", warning=warning, template_id=str(locked.id))++ email["design"] = new_design+ # Drop html so the serializer re-renders it from the patched design (its design->html path).+ email.pop("html", None)+ content["email"] = email++ serializer = self.get_serializer(locked, data={"content": content}, partial=True)+ serializer.is_valid(raise_exception=True)+ serializer.save()++ return Response(self.get_serializer(locked).data)diff --git a/products/messaging/backend/api/test/test_design_operations.py b/products/messaging/backend/api/test/test_design_operations.pynew file mode 100644index 000000000000..db7f5862fb91--- /dev/null+++ b/products/messaging/backend/api/test/test_design_operations.py@@ -0,0 +1,225 @@+from copy import deepcopy++import pytest++from rest_framework import serializers++from products.messaging.backend.api.design_operations import apply_design_operations+from products.messaging.backend.api.design_validation import validate_design+++def _sample_design() -> dict:+ return {+ "counters": {"u_row": 1, "u_column": 2, "u_content_text": 1},+ "schemaVersion": 16,+ "body": {+ "id": "body1",+ "rows": [+ {+ "id": "row1",+ "cells": [1, 1],+ "columns": [+ {+ "id": "col1",+ "contents": [+ {+ "id": "txt1",+ "type": "text",+ "values": {+ "text": "<p>Hello</p>",+ "containerPadding": "10px",+ "_meta": {"htmlID": "u_content_text_1", "htmlClassNames": "u_content_text"},+ },+ }+ ],+ "values": {"_meta": {"htmlID": "u_column_1"}, "padding": "0px"},+ },+ {"id": "col2", "contents": [], "values": {"_meta": {"htmlID": "u_column_2"}}},+ ],+ "values": {"backgroundColor": "#eee"},+ }+ ],+ "values": {"backgroundColor": "#ffffff", "contentWidth": "600px"},+ },+ }+++def _content_by_id(design: dict, content_id: str) -> dict:+ for row in design["body"]["rows"]:+ for column in row["columns"]:+ for content in column["contents"]:+ if content["id"] == content_id:+ return content+ raise AssertionError(f"content {content_id} not found")+++class TestApplyDesignOperations:+ def test_update_content_merges_one_field(self):+ result = apply_design_operations(+ _sample_design(), [{"op": "update_content", "id": "txt1", "patch": {"values": {"text": "<p>Bye</p>"}}}]+ )+ content = _content_by_id(result, "txt1")+ assert content["values"]["text"] == "<p>Bye</p>"+ # Untouched siblings survive the deep-merge.+ assert content["values"]["containerPadding"] == "10px"+ assert content["values"]["_meta"]["htmlID"] == "u_content_text_1"++ def test_update_content_null_leaf_deletes_key(self):+ result = apply_design_operations(+ _sample_design(),+ [{"op": "update_content", "id": "txt1", "patch": {"values": {"containerPadding": None}}}],+ )+ assert "containerPadding" not in _content_by_id(result, "txt1")["values"]++ @pytest.mark.parametrize(+ "operation",+ [+ {"op": "update_content", "id": "nope", "patch": {"values": {}}},+ {"op": "update_column", "id": "nope", "patch": {"values": {}}},+ {"op": "update_row", "id": "nope", "patch": {"values": {}}},+ {"op": "add_content", "column_id": "nope", "content": {"type": "text"}},+ {"op": "remove_content", "id": "nope"},+ {"op": "move_content", "id": "nope", "column_id": "col2"},+ {"op": "move_content", "id": "txt1", "column_id": "nope"},+ {"op": "remove_row", "id": "nope"},+ ],+ ids=lambda op: f"{op['op']}:{op.get('id') or op.get('column_id')}",+ )+ def test_operation_with_unknown_target_raises(self, operation):+ with pytest.raises(serializers.ValidationError):+ apply_design_operations(_sample_design(), [operation])++ def test_update_body_merges_into_values(self):+ result = apply_design_operations(+ _sample_design(), [{"op": "update_body", "patch": {"values": {"backgroundColor": "#000000"}}}]+ )+ assert result["body"]["values"]["backgroundColor"] == "#000000"+ assert result["body"]["values"]["contentWidth"] == "600px"++ def test_update_row_and_column(self):+ result = apply_design_operations(+ _sample_design(),+ [+ {"op": "update_row", "id": "row1", "patch": {"values": {"backgroundColor": "#111"}}},+ {"op": "update_column", "id": "col1", "patch": {"values": {"padding": "5px"}}},+ ],+ )+ assert result["body"]["rows"][0]["values"]["backgroundColor"] == "#111"+ assert result["body"]["rows"][0]["columns"][0]["values"]["padding"] == "5px"++ def test_add_content_appends_and_assigns_meta(self):+ result = apply_design_operations(+ _sample_design(),+ [{"op": "add_content", "column_id": "col1", "content": {"type": "text", "values": {"text": "<p>New</p>"}}}],+ )+ contents = result["body"]["rows"][0]["columns"][0]["contents"]+ assert len(contents) == 2+ added = contents[1]+ assert added["id"] # server-assigned+ # counter bumped from 1 -> 2 and _meta numbered to match+ assert result["counters"]["u_content_text"] == 2+ assert added["values"]["_meta"]["htmlID"] == "u_content_text_2"+ assert added["values"]["_meta"]["htmlClassNames"] == "u_content_text"++ def test_add_content_respects_index(self):+ result = apply_design_operations(+ _sample_design(),+ [+ {+ "op": "add_content",+ "column_id": "col1",+ "index": 0,+ "content": {"type": "button", "values": {}},+ }+ ],+ )+ contents = result["body"]["rows"][0]["columns"][0]["contents"]+ assert contents[0]["type"] == "button"+ assert contents[1]["id"] == "txt1"+ assert result["counters"]["u_content_button"] == 1++ def test_remove_content(self):+ result = apply_design_operations(_sample_design(), [{"op": "remove_content", "id": "txt1"}])+ assert result["body"]["rows"][0]["columns"][0]["contents"] == []++ def test_move_content_between_columns(self):+ result = apply_design_operations(_sample_design(), [{"op": "move_content", "id": "txt1", "column_id": "col2"}])+ assert result["body"]["rows"][0]["columns"][0]["contents"] == []+ moved = result["body"]["rows"][0]["columns"][1]["contents"]+ assert len(moved) == 1 and moved[0]["id"] == "txt1"++ def test_add_row_numbers_nested_nodes(self):+ result = apply_design_operations(+ _sample_design(),+ [+ {+ "op": "add_row",+ "row": {+ "cells": [1],+ "columns": [{"contents": [{"type": "text", "values": {"text": "<p>R2</p>"}}], "values": {}}],+ "values": {},+ },+ }+ ],+ )+ rows = result["body"]["rows"]+ assert len(rows) == 2+ new_row = rows[1]+ assert new_row["id"] and new_row["values"]["_meta"]["htmlID"] == "u_row_2"+ new_col = new_row["columns"][0]+ assert new_col["id"] and new_col["values"]["_meta"]["htmlID"] == "u_column_3"+ new_content = new_col["contents"][0]+ assert new_content["id"] and new_content["values"]["_meta"]["htmlID"] == "u_content_text_2"++ def test_remove_row(self):+ result = apply_design_operations(_sample_design(), [{"op": "remove_row", "id": "row1"}])+ assert result["body"]["rows"] == []++ def test_does_not_mutate_input(self):+ original = _sample_design()+ snapshot = deepcopy(original)+ apply_design_operations(+ original, [{"op": "update_content", "id": "txt1", "patch": {"values": {"text": "<p>x</p>"}}}]+ )+ assert original == snapshot++ def test_operations_apply_in_order(self):+ # add then update the just-added block by the id we can't predict — instead update an existing+ # block, remove it, and confirm the later op sees the earlier op's result.+ with pytest.raises(serializers.ValidationError):+ apply_design_operations(+ _sample_design(),+ [+ {"op": "remove_content", "id": "txt1"},+ {"op": "update_content", "id": "txt1", "patch": {"values": {}}},+ ],+ )+++class TestValidateDesign:+ def test_valid_design_returns_no_blocking_warnings(self):+ assert validate_design(_sample_design()) == []++ def test_duplicate_id_raises(self):+ design = _sample_design()+ design["body"]["rows"][0]["columns"][0]["id"] = "row1" # collide with the row id+ with pytest.raises(serializers.ValidationError):+ validate_design(design)++ def test_missing_body_raises(self):+ with pytest.raises(serializers.ValidationError):+ validate_design({"counters": {}})++ def test_rows_not_a_list_raises(self):+ with pytest.raises(serializers.ValidationError):+ validate_design({"body": {"rows": "nope"}})++ def test_empty_rows_warns(self):+ design = _sample_design()+ design["body"]["rows"] = []+ assert any("no rows" in w for w in validate_design(design))++ def test_unknown_content_type_warns(self):+ design = _sample_design()+ design["body"]["rows"][0]["columns"][0]["contents"][0]["type"] = "hologram"+ assert any("unknown type" in w for w in validate_design(design))diff --git a/products/messaging/backend/api/test/test_message_templates.py b/products/messaging/backend/api/test/test_message_templates.pyindex 64fee02210d5..2463df171521 100644--- a/products/messaging/backend/api/test/test_message_templates.py+++ b/products/messaging/backend/api/test/test_message_templates.py@@ -317,3 +317,147 @@ class TestMessageTemplatesAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKself.message_template.refresh_from_db()assert self.message_template.message_category_id == own_category.id++ def _design_with_text(self) -> dict:+ return {+ "counters": {"u_row": 1, "u_column": 1, "u_content_text": 1},+ "schemaVersion": 16,+ "body": {+ "id": "body1",+ "rows": [+ {+ "id": "row1",+ "cells": [1],+ "columns": [+ {+ "id": "col1",+ "contents": [{"id": "txt1", "type": "text", "values": {"text": "<p>Old</p>"}}],+ "values": {},+ }+ ],+ "values": {},+ }+ ],+ "values": {},+ },+ }++ @patch("products.messaging.backend.api.message_templates.render_design_html")+ def test_design_patch_updates_one_block_and_rerenders(self, mock_render):+ mock_render.return_value = "<html>patched</html>"+ self.message_template.content = {"email": {"subject": "Hi", "design": self._design_with_text()}}+ self.message_template.save()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/messaging_templates/{self.message_template.id}/design/",+ data={"operations": [{"op": "update_content", "id": "txt1", "patch": {"values": {"text": "<p>New</p>"}}}]},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ self.message_template.refresh_from_db()+ email = self.message_template.content["email"]+ assert email["design"]["body"]["rows"][0]["columns"][0]["contents"][0]["values"]["text"] == "<p>New</p>"+ # subject is preserved; html re-rendered from the patched design+ assert email["subject"] == "Hi"+ assert email["html"] == "<html>patched</html>"+ mock_render.assert_called_once()++ @patch("products.messaging.backend.api.message_templates.render_design_html")+ def test_design_patch_unknown_id_leaves_template_untouched(self, mock_render):+ mock_render.return_value = "<html>x</html>"+ original = self._design_with_text()+ self.message_template.content = {"email": {"subject": "Hi", "design": original}}+ self.message_template.save()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/messaging_templates/{self.message_template.id}/design/",+ data={"operations": [{"op": "update_content", "id": "nope", "patch": {"values": {}}}]},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ self.message_template.refresh_from_db()+ assert self.message_template.content["email"]["design"] == original+ mock_render.assert_not_called()++ def test_design_patch_without_design_returns_400(self):+ # self.message_template has no design in content.email+ response = self.client.patch(+ f"/api/projects/{self.team.id}/messaging_templates/{self.message_template.id}/design/",+ data={"operations": [{"op": "update_content", "id": "txt1", "patch": {"values": {}}}]},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "no editable design" in str(response.json())++ def test_design_patch_empty_operations_returns_400(self):+ self.message_template.content = {"email": {"subject": "Hi", "design": self._design_with_text()}}+ self.message_template.save()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/messaging_templates/{self.message_template.id}/design/",+ data={"operations": []},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_design_patch_missing_required_op_field_returns_400(self):+ self.message_template.content = {"email": {"subject": "Hi", "design": self._design_with_text()}}+ self.message_template.save()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/messaging_templates/{self.message_template.id}/design/",+ data={"operations": [{"op": "update_content", "id": "txt1"}]}, # missing patch+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_design_patch_requires_write_scope(self):+ self.message_template.content = {"email": {"subject": "Hi", "design": self._design_with_text()}}+ self.message_template.save()+ api_key = self.create_personal_api_key_with_scopes(["hog_flow:read"])+ self.client.logout()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")++ response = self.client.patch(+ f"/api/projects/{self.team.id}/messaging_templates/{self.message_template.id}/design/",+ data={"operations": [{"op": "update_content", "id": "txt1", "patch": {"values": {}}}]},+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN++ @patch("products.messaging.backend.api.message_templates.render_design_html")+ def test_design_patch_allows_write_scoped_personal_api_key(self, mock_render):+ # Regression: the design action must declare hog_flow:write so MCP / personal API key callers+ # aren't rejected as "action does not support personal API key access".+ mock_render.return_value = "<html>ok</html>"+ self.message_template.content = {"email": {"subject": "Hi", "design": self._design_with_text()}}+ self.message_template.save()+ api_key = self.create_personal_api_key_with_scopes(["hog_flow:write"])+ self.client.logout()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")++ response = self.client.patch(+ f"/api/projects/{self.team.id}/messaging_templates/{self.message_template.id}/design/",+ data={"operations": [{"op": "update_content", "id": "txt1", "patch": {"values": {"text": "<p>Hi</p>"}}}]},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.json()++ def test_design_patch_cannot_touch_other_teams_template(self):+ self.other_team_template.content = {"email": {"subject": "Hi", "design": self._design_with_text()}}+ self.other_team_template.save()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/messaging_templates/{self.other_team_template.id}/design/",+ data={"operations": [{"op": "update_content", "id": "txt1", "patch": {"values": {}}}]},+ format="json",+ )++ assert response.status_code == status.HTTP_404_NOT_FOUNDdiff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.tsindex 2fc465200677..f1eae1260af3 100644--- a/products/messaging/frontend/generated/api.schemas.ts+++ b/products/messaging/frontend/generated/api.schemas.ts@@ -267,6 +267,64 @@ export interface PatchedMessageTemplateApi {deleted?: boolean}+/**+ * * `update_content` - update_content+ * * `update_column` - update_column+ * * `update_row` - update_row+ * * `update_body` - update_body+ * * `add_content` - add_content+ * * `remove_content` - remove_content+ * * `move_content` - move_content+ * * `add_row` - add_row+ * * `remove_row` - remove_row+ */+export type EmailTemplateDesignOperationEnumApi =+ (typeof EmailTemplateDesignOperationEnumApi)[keyof typeof EmailTemplateDesignOperationEnumApi]++export const EmailTemplateDesignOperationEnumApi = {+ UpdateContent: 'update_content',+ UpdateColumn: 'update_column',+ UpdateRow: 'update_row',+ UpdateBody: 'update_body',+ AddContent: 'add_content',+ RemoveContent: 'remove_content',+ MoveContent: 'move_content',+ AddRow: 'add_row',+ RemoveRow: 'remove_row',+} as const++export interface DesignOperationApi {+ /** Design edit. update_content {id, patch}: deep-merge patch into the content block's fields (a null leaf deletes that key) — the surgical path, e.g. change just values.text. update_row / update_column {id, patch} and update_body {patch}: same deep-merge for row/column/body-level settings. add_content {column_id, content, index?}: insert a content block into a column (id and Unlayer numbering are filled in for you). remove_content {id} / move_content {id, column_id, index?}: delete or relocate a block. add_row {row, index?} / remove_row {id}: add or delete a row.+ *+ * * `update_content` - update_content+ * * `update_column` - update_column+ * * `update_row` - update_row+ * * `update_body` - update_body+ * * `add_content` - add_content+ * * `remove_content` - remove_content+ * * `move_content` - move_content+ * * `add_row` - add_row+ * * `remove_row` - remove_row */+ op: EmailTemplateDesignOperationEnumApi+ /** Target node id. Required for update_content/column/row, remove_content, remove_row, move_content. */+ id?: string+ /** Target column id. Required for add_content and move_content. */+ column_id?: string+ /** update_* only. Partial fields deep-merged into the existing node; a null leaf deletes that key. e.g. {values: {text: '<p>Hi</p>'}} changes only the block's text. */+ patch?: unknown+ /** add_content only. A content block {type, values: {...}}; omit id and values._meta — they're assigned server-side. type is one of text, heading, button, image, divider, html, etc. */+ content?: unknown+ /** add_row only. A full row {cells, columns: [{contents: [...], values}], values}; ids and Unlayer numbering are assigned server-side for the row and everything nested in it. */+ row?: unknown+ /** add_*\/move_content only. 0-based insert position; omit to append to the end. */+ index?: number+}++export interface PatchedDesignPatchApi {+ /** Ordered edits applied atomically to a 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 it's saved only if valid — otherwise the template is unchanged. Reference blocks by id so you never resend the whole design. */+ operations?: DesignOperationApi[]+}+export type MessagingCategoriesListParams = {/*** Number of results to return per page.diff --git a/products/messaging/frontend/generated/api.ts b/products/messaging/frontend/generated/api.tsindex 14018e5b4dd0..cc919a6cbb2f 100644--- a/products/messaging/frontend/generated/api.ts+++ b/products/messaging/frontend/generated/api.ts@@ -17,6 +17,7 @@ import type {MessagingTemplatesListParams,PaginatedMessageCategoryListApi,PaginatedMessageTemplateListApi,+ PatchedDesignPatchApi,PatchedMessageCategoryApi,PatchedMessageTemplateApi,} from './api.schemas'@@ -509,3 +510,21 @@ export const messagingTemplatesDestroy = async (method: 'DELETE',})}++export const getMessagingTemplatesDesignPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/messaging_templates/${id}/design/`+}++export const messagingTemplatesDesignPartialUpdate = async (+ projectId: string,+ id: string,+ patchedDesignPatchApi?: PatchedDesignPatchApi,+ options?: RequestInit+): Promise<MessageTemplateApi> => {+ return apiMutator<MessageTemplateApi>(getMessagingTemplatesDesignPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedDesignPatchApi),+ })+}diff --git a/products/messaging/frontend/generated/api.zod.ts b/products/messaging/frontend/generated/api.zod.tsindex 5dd73b8be273..bb6d1355d384 100644--- a/products/messaging/frontend/generated/api.zod.ts+++ b/products/messaging/frontend/generated/api.zod.ts@@ -430,3 +430,65 @@ export const MessagingTemplatesPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('Message category ID to file the template under. Must belong to the same project.'),deleted: zod.boolean().optional().describe('Soft-delete flag. Set true to remove the template from the library.'),})++export const MessagingTemplatesDesignPartialUpdateBody = /* @__PURE__ */ zod.object({+ operations: zod+ .array(+ zod.object({+ op: zod+ .enum([+ 'update_content',+ 'update_column',+ 'update_row',+ 'update_body',+ 'add_content',+ 'remove_content',+ 'move_content',+ 'add_row',+ 'remove_row',+ ])+ .describe(+ '\* `update_content` - update_content\n\* `update_column` - update_column\n\* `update_row` - update_row\n\* `update_body` - update_body\n\* `add_content` - add_content\n\* `remove_content` - remove_content\n\* `move_content` - move_content\n\* `add_row` - add_row\n\* `remove_row` - remove_row'+ )+ .describe(+ "Design edit. update_content {id, patch}: deep-merge patch into the content block's fields (a null leaf deletes that key) — the surgical path, e.g. change just values.text. update_row \/ update_column {id, patch} and update_body {patch}: same deep-merge for row\/column\/body-level settings. add_content {column_id, content, index?}: insert a content block into a column (id and Unlayer numbering are filled in for you). remove_content {id} \/ move_content {id, column_id, index?}: delete or relocate a block. add_row {row, index?} \/ remove_row {id}: add or delete a row.\n\n\* `update_content` - update_content\n\* `update_column` - update_column\n\* `update_row` - update_row\n\* `update_body` - update_body\n\* `add_content` - add_content\n\* `remove_content` - remove_content\n\* `move_content` - move_content\n\* `add_row` - add_row\n\* `remove_row` - remove_row"+ ),+ id: zod+ .string()+ .optional()+ .describe(+ 'Target node id. Required for update_content\/column\/row, remove_content, remove_row, move_content.'+ ),+ column_id: zod+ .string()+ .optional()+ .describe('Target column id. Required for add_content and move_content.'),+ patch: zod+ .unknown()+ .optional()+ .describe(+ "update_\* only. Partial fields deep-merged into the existing node; a null leaf deletes that key. e.g. {values: {text: '<p>Hi<\/p>'}} changes only the block's text."+ ),+ content: zod+ .unknown()+ .optional()+ .describe(+ "add_content only. A content block {type, values: {...}}; omit id and values._meta — they're assigned server-side. type is one of text, heading, button, image, divider, html, etc."+ ),+ row: zod+ .unknown()+ .optional()+ .describe(+ 'add_row only. A full row {cells, columns: [{contents: [...], values}], values}; ids and Unlayer numbering are assigned server-side for the row and everything nested in it.'+ ),+ index: zod+ .number()+ .optional()+ .describe('add_\*\/move_content only. 0-based insert position; omit to append to the end.'),+ })+ )+ .optional()+ .describe(+ "Ordered edits applied atomically to a 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 it's saved only if valid — otherwise the template is unchanged. Reference blocks by id so you never resend the whole design."+ ),+})diff --git a/products/workflows/mcp/email_templates.yaml b/products/workflows/mcp/email_templates.yamlindex 5088a2499563..726f290d4635 100644--- a/products/workflows/mcp/email_templates.yaml+++ b/products/workflows/mcp/email_templates.yaml@@ -73,6 +73,33 @@ tools:exclude:- content- created_by+ workflows-patch-email-template:+ operation: messaging_templates_design_partial_update+ enabled: true+ scopes:+ - hog_flow:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ input_schema: EmailTemplateDesignPatchSchema+ enrich_url: '{id}'+ title: Patch email template design+ description: >+ Surgically edit an email template's design by sending a small, ordered list of operations instead of+ resending the whole design JSON. Prefer this over workflows-update-email-template for any change to an+ existing design. Reference blocks by their id (call workflows-get-email-template first to read the current+ design and its ids). For the common case — tweak one block — use update_content with a deep-merge patch+ (e.g. {op: update_content, id: '<block-id>', patch: {values: {text: '<p>New copy</p>'}}}); a null leaf+ deletes that key. Use add_content / remove_content / move_content / add_row / remove_row for structural+ changes; ids and Unlayer numbering for added blocks are assigned for you. Operations apply atomically — the+ design is read, the ops applied in order, the result validated and re-rendered to HTML, and saved only if+ valid, otherwise nothing changes. After patching, call workflows-show-email-template so the user sees the+ result.+ response:+ exclude:+ - content+ - created_byworkflows-show-email-template:operation: messaging_templates_retrieveenabled: true@@ -105,7 +132,9 @@ tools:enrich_url: '{id}'title: Update email templatedescription: >- Update an email template by ID. content is replaced as a whole, never merged — call+ 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: callworkflows-get-email-template first (the design may carry fresh human edits from the visual editor) and sendback the complete content.email with your edited design. The server re-renders the sent email from thedesign on save. After updating, call workflows-show-email-template so the user sees the result, and sharediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 108ffc965204..ee8f0b8d1276 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -7550,6 +7550,20 @@"readOnlyHint": true}},+ "workflows-patch-email-template": {+ "description": "Surgically edit an email template's design by sending a small, ordered list of operations instead of resending the whole design JSON. Prefer this over workflows-update-email-template for any change to an existing design. Reference blocks by their id (call workflows-get-email-template first to read the current design and its ids). For the common case — tweak one block — use update_content with a deep-merge patch (e.g. {op: update_content, id: '<block-id>', patch: {values: {text: '<p>New copy</p>'}}}); a null leaf deletes that key. Use add_content / remove_content / move_content / add_row / remove_row for structural changes; ids and Unlayer numbering for added blocks are assigned for you. Operations apply atomically — the design is read, the ops applied in order, the result validated and re-rendered to HTML, and saved only if valid, otherwise nothing changes. After patching, call workflows-show-email-template so the user sees the result.",+ "category": "Workflows",+ "feature": "workflows",+ "summary": "Patch email template design",+ "title": "Patch email template design",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"workflows-show-email-template": {"description": "Render an email template as an inline preview for the user. Call after creating or updating a template, and whenever the user asks to see one. The response carries the final rendered html — read it before describing the result. For fetching a template to edit it, use workflows-get-email-template.","category": "Workflows",@@ -7607,7 +7621,7 @@}},"workflows-update-email-template": {- "description": "Update an email template by ID. content is replaced as a whole, never merged — 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.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.","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.jsonindex aa9dde26ba5a..4f433cb8e4a6 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -8101,6 +8101,20 @@"readOnlyHint": true}},+ "workflows-patch-email-template": {+ "description": "Surgically edit an email template's design by sending a small, ordered list of operations instead of resending the whole design JSON. Prefer this over workflows-update-email-template for any change to an existing design. Reference blocks by their id (call workflows-get-email-template first to read the current design and its ids). For the common case — tweak one block — use update_content with a deep-merge patch (e.g. {op: update_content, id: '<block-id>', patch: {values: {text: '<p>New copy</p>'}}}); a null leaf deletes that key. Use add_content / remove_content / move_content / add_row / remove_row for structural changes; ids and Unlayer numbering for added blocks are assigned for you. Operations apply atomically — the design is read, the ops applied in order, the result validated and re-rendered to HTML, and saved only if valid, otherwise nothing changes. After patching, call workflows-show-email-template so the user sees the result.",+ "category": "Workflows",+ "feature": "workflows",+ "summary": "Patch email template design",+ "title": "Patch email template design",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"workflows-run-batch": {"description": "Broadcast a batch workflow to its matching users NOW — sends real messages/webhooks, not a test. Workflow must be enabled. STOP before calling: show the user the audience size from workflows-blast-radius and get their explicit confirmation in a separate turn — never size and fire in one step. Requires acknowledged_affected_count from workflows-blast-radius; rejects on drift or over the cap.","category": "Workflows",@@ -8186,7 +8200,7 @@}},"workflows-update-email-template": {- "description": "Update an email template by ID. content is replaced as a whole, never merged — 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.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.","category": "Workflows","feature": "workflows","summary": "Update email template",diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 644971122b7e..bfda60b6fe5c 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -53,6 +53,213 @@}}},+ "EmailTemplateDesignPatchSchema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "description": "The email template id to edit."+ },+ "operations": {+ "minItems": 1,+ "type": "array",+ "items": {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "update_content"+ },+ "id": {+ "type": "string",+ "description": "Id of the content block to update."+ },+ "patch": {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {},+ "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"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "update_column"+ },+ "id": {+ "type": "string",+ "description": "Id of the column to update."+ },+ "patch": {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {},+ "description": "Partial column fields, deep-merged; a null leaf deletes that key."+ }+ },+ "required": ["op", "id", "patch"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "update_row"+ },+ "id": {+ "type": "string",+ "description": "Id of the row to update."+ },+ "patch": {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {},+ "description": "Partial row fields, deep-merged; a null leaf deletes that key."+ }+ },+ "required": ["op", "id", "patch"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "update_body"+ },+ "patch": {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {},+ "description": "Partial body fields, deep-merged. e.g. {values: {backgroundColor: '#ffffff'}}."+ }+ },+ "required": ["op", "patch"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "add_content"+ },+ "column_id": {+ "type": "string",+ "description": "Id of the column to insert the block into."+ },+ "content": {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {},+ "description": "A content block {type, values: {...}}; omit id and values._meta — they are assigned server-side. type is one of text, heading, button, image, divider, html, etc."+ },+ "index": {+ "description": "0-based insert position; omit to append to the end.",+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ }+ },+ "required": ["op", "column_id", "content"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "remove_content"+ },+ "id": {+ "type": "string",+ "description": "Id of the content block to remove."+ }+ },+ "required": ["op", "id"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "move_content"+ },+ "id": {+ "type": "string",+ "description": "Id of the content block to move."+ },+ "column_id": {+ "type": "string",+ "description": "Id of the destination column."+ },+ "index": {+ "description": "0-based position in the destination column; omit to append.",+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ }+ },+ "required": ["op", "id", "column_id"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "add_row"+ },+ "row": {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {},+ "description": "A full row {cells, columns: [{contents: [...], values}], values}; ids and Unlayer numbering are assigned server-side for the row and everything nested in it."+ },+ "index": {+ "description": "0-based insert position; omit to append to the end.",+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ }+ },+ "required": ["op", "row"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "remove_row"+ },+ "id": {+ "type": "string",+ "description": "Id of the row to remove."+ }+ },+ "required": ["op", "id"]+ }+ ]+ },+ "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"]+ },"EventDefinitionUpdateInputSchema": {"type": "object","properties": {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex cd19b60e39ba..a2ae28deb976 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -16536,6 +16536,59 @@ export namespace Schemas {Text: 'text',} as const;+ /**+ * * `update_content` - update_content+ * * `update_column` - update_column+ * * `update_row` - update_row+ * * `update_body` - update_body+ * * `add_content` - add_content+ * * `remove_content` - remove_content+ * * `move_content` - move_content+ * * `add_row` - add_row+ * * `remove_row` - remove_row+ */+ export type EmailTemplateDesignOperationEnum = typeof EmailTemplateDesignOperationEnum[keyof typeof EmailTemplateDesignOperationEnum];+++ export const EmailTemplateDesignOperationEnum = {+ UpdateContent: 'update_content',+ UpdateColumn: 'update_column',+ UpdateRow: 'update_row',+ UpdateBody: 'update_body',+ AddContent: 'add_content',+ RemoveContent: 'remove_content',+ MoveContent: 'move_content',+ AddRow: 'add_row',+ RemoveRow: 'remove_row',+ } as const;++ export interface DesignOperation {+ /** Design edit. update_content {id, patch}: deep-merge patch into the content block's fields (a null leaf deletes that key) — the surgical path, e.g. change just values.text. update_row / update_column {id, patch} and update_body {patch}: same deep-merge for row/column/body-level settings. add_content {column_id, content, index?}: insert a content block into a column (id and Unlayer numbering are filled in for you). remove_content {id} / move_content {id, column_id, index?}: delete or relocate a block. add_row {row, index?} / remove_row {id}: add or delete a row.+ *+ * * `update_content` - update_content+ * * `update_column` - update_column+ * * `update_row` - update_row+ * * `update_body` - update_body+ * * `add_content` - add_content+ * * `remove_content` - remove_content+ * * `move_content` - move_content+ * * `add_row` - add_row+ * * `remove_row` - remove_row */+ op: EmailTemplateDesignOperationEnum;+ /** Target node id. Required for update_content/column/row, remove_content, remove_row, move_content. */+ id?: string;+ /** Target column id. Required for add_content and move_content. */+ column_id?: string;+ /** update_* only. Partial fields deep-merged into the existing node; a null leaf deletes that key. e.g. {values: {text: '<p>Hi</p>'}} changes only the block's text. */+ patch?: unknown;+ /** add_content only. A content block {type, values: {...}}; omit id and values._meta — they're assigned server-side. type is one of text, heading, button, image, divider, html, etc. */+ content?: unknown;+ /** add_row only. A full row {cells, columns: [{contents: [...], values}], values}; ids and Unlayer numbering are assigned server-side for the row and everything nested in it. */+ row?: unknown;+ /** add_*\/move_content only. 0-based insert position; omit to append to the end. */+ index?: number;+ }+export interface DesktopRecording {readonly id: string;readonly team: number;@@ -33336,6 +33389,11 @@ export namespace Schemas {readonly team?: number;}+ export interface PatchedDesignPatch {+ /** Ordered edits applied atomically to a 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 it's saved only if valid — otherwise the template is unchanged. Reference blocks by id so you never resend the whole design. */+ operations?: DesignOperation[];+ }+export interface PatchedDesktopRecording {readonly id?: string;readonly team?: number;diff --git a/services/mcp/src/generated/email_templates/api.ts b/services/mcp/src/generated/email_templates/api.tsindex 6e5dcc4b8068..33d279489632 100644--- a/services/mcp/src/generated/email_templates/api.ts+++ b/services/mcp/src/generated/email_templates/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 4 enabled ops+ * PostHog API - MCP 5 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -225,3 +225,74 @@ export const MessagingTemplatesPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('Message category ID to file the template under. Must belong to the same project.'),deleted: zod.boolean().optional().describe('Soft-delete flag. Set true to remove the template from the library.'),})++export const MessagingTemplatesDesignPartialUpdateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this message template.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const MessagingTemplatesDesignPartialUpdateBody = /* @__PURE__ */ zod.object({+ operations: zod+ .array(+ zod.object({+ op: zod+ .enum([+ 'update_content',+ 'update_column',+ 'update_row',+ 'update_body',+ 'add_content',+ 'remove_content',+ 'move_content',+ 'add_row',+ 'remove_row',+ ])+ .describe(+ '* `update_content` - update_content\n* `update_column` - update_column\n* `update_row` - update_row\n* `update_body` - update_body\n* `add_content` - add_content\n* `remove_content` - remove_content\n* `move_content` - move_content\n* `add_row` - add_row\n* `remove_row` - remove_row'+ )+ .describe(+ "Design edit. update_content {id, patch}: deep-merge patch into the content block's fields (a null leaf deletes that key) — the surgical path, e.g. change just values.text. update_row / update_column {id, patch} and update_body {patch}: same deep-merge for row/column/body-level settings. add_content {column_id, content, index?}: insert a content block into a column (id and Unlayer numbering are filled in for you). remove_content {id} / move_content {id, column_id, index?}: delete or relocate a block. add_row {row, index?} / remove_row {id}: add or delete a row.\n\n* `update_content` - update_content\n* `update_column` - update_column\n* `update_row` - update_row\n* `update_body` - update_body\n* `add_content` - add_content\n* `remove_content` - remove_content\n* `move_content` - move_content\n* `add_row` - add_row\n* `remove_row` - remove_row"+ ),+ id: zod+ .string()+ .optional()+ .describe(+ 'Target node id. Required for update_content/column/row, remove_content, remove_row, move_content.'+ ),+ column_id: zod+ .string()+ .optional()+ .describe('Target column id. Required for add_content and move_content.'),+ patch: zod+ .unknown()+ .optional()+ .describe(+ "update_* only. Partial fields deep-merged into the existing node; a null leaf deletes that key. e.g. {values: {text: '<p>Hi</p>'}} changes only the block's text."+ ),+ content: zod+ .unknown()+ .optional()+ .describe(+ "add_content only. A content block {type, values: {...}}; omit id and values._meta — they're assigned server-side. type is one of text, heading, button, image, divider, html, etc."+ ),+ row: zod+ .unknown()+ .optional()+ .describe(+ 'add_row only. A full row {cells, columns: [{contents: [...], values}], values}; ids and Unlayer numbering are assigned server-side for the row and everything nested in it.'+ ),+ index: zod+ .number()+ .optional()+ .describe('add_*/move_content only. 0-based insert position; omit to append to the end.'),+ })+ )+ .optional()+ .describe(+ "Ordered edits applied atomically to a 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 it's saved only if valid — otherwise the template is unchanged. Reference blocks by id so you never resend the whole design."+ ),+})diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex f33859b84c97..69cc9949f78f 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -395,3 +395,79 @@ export function validateDistinctIdPersonIdExclusive(})}}++// Surgical edits to an email template's Unlayer design — one discriminated op per change, addressed by+// the stable block id. Mirrors DesignOperationSerializer; kept as a hand-authored discriminated union so+// the LLM sees exactly which fields each op needs (the auto-generated PATCH schema flattens them all to+// optional). `patch`/`content`/`row` are freeform Unlayer JSON.+const EmailDesignFreeformObject = z.record(z.string(), z.unknown())++const EmailDesignPatchOperationSchema = z.discriminatedUnion('op', [+ z.object({+ op: z.literal('update_content'),+ id: z.string().describe('Id of the content block to update.'),+ patch: EmailDesignFreeformObject.describe(+ '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."+ ),+ }),+ z.object({+ 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({+ 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({+ op: z.literal('update_body'),+ patch: EmailDesignFreeformObject.describe(+ "Partial body fields, deep-merged. e.g. {values: {backgroundColor: '#ffffff'}}."+ ),+ }),+ z.object({+ op: z.literal('add_content'),+ column_id: z.string().describe('Id of the column to insert the block into.'),+ content: EmailDesignFreeformObject.describe(+ 'A content block {type, values: {...}}; omit id and values._meta — they are assigned server-side. ' ++ 'type is one of text, heading, button, image, divider, html, etc.'+ ),+ index: z.number().int().optional().describe('0-based insert position; omit to append to the end.'),+ }),+ z.object({+ op: z.literal('remove_content'),+ id: z.string().describe('Id of the content block to remove.'),+ }),+ z.object({+ 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({+ op: z.literal('add_row'),+ row: EmailDesignFreeformObject.describe(+ 'A full row {cells, columns: [{contents: [...], values}], values}; ids and Unlayer numbering are ' ++ 'assigned server-side for the row and everything nested in it.'+ ),+ index: z.number().int().optional().describe('0-based insert position; omit to append to the end.'),+ }),+ z.object({+ op: z.literal('remove_row'),+ id: z.string().describe('Id of the row to remove.'),+ }),+])++export const EmailTemplateDesignPatchSchema = z.object({+ id: z.string().describe('The email template id to edit.'),+ operations: z+ .array(EmailDesignPatchOperationSchema)+ .min(1)+ .describe(+ "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.'+ ),+})diff --git a/services/mcp/src/tools/generated/email_templates.ts b/services/mcp/src/tools/generated/email_templates.tsindex 7f9299b6208f..7ab4573a7d25 100644--- a/services/mcp/src/tools/generated/email_templates.ts+++ b/services/mcp/src/tools/generated/email_templates.ts@@ -10,6 +10,7 @@ import {MessagingTemplatesRetrieveParams,} from '@/generated/email_templates/api'import { withUiApp } from '@/resources/ui-apps'+import { EmailTemplateDesignPatchSchema } from '@/schema/tool-inputs'import { withPostHogUrl, omitResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'@@ -108,6 +109,28 @@ const workflowsListEmailTemplates = (): ToolBase<},})+const WorkflowsPatchEmailTemplateSchema = EmailTemplateDesignPatchSchema++const workflowsPatchEmailTemplate = (): ToolBase<+ typeof WorkflowsPatchEmailTemplateSchema,+ Schemas.MessageTemplate+> => ({+ name: 'workflows-patch-email-template',+ schema: WorkflowsPatchEmailTemplateSchema,+ handler: async (context: Context, params: z.infer<typeof WorkflowsPatchEmailTemplateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const parsedParams = WorkflowsPatchEmailTemplateSchema.parse(params)+ const { id, ...body } = parsedParams+ const result = await context.api.request<Schemas.MessageTemplate>({+ method: 'PATCH',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_templates/${encodeURIComponent(String(id))}/design/`,+ body,+ })+ const filtered = omitResponseFields(result, ['content', 'created_by']) as typeof result+ return await withPostHogUrl(context, filtered, `/workflows/library/templates/${filtered.id}`)+ },+})+const WorkflowsShowEmailTemplateSchema = MessagingTemplatesRetrieveParams.omit({ project_id: true })const workflowsShowEmailTemplate = (): ToolBase<@@ -173,6 +196,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'workflows-create-email-template': workflowsCreateEmailTemplate,'workflows-get-email-template': workflowsGetEmailTemplate,'workflows-list-email-templates': workflowsListEmailTemplates,+ 'workflows-patch-email-template': workflowsPatchEmailTemplate,'workflows-show-email-template': workflowsShowEmailTemplate,'workflows-update-email-template': workflowsUpdateEmailTemplate,}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.jsonnew file mode 100644index 000000000000..a28fea4259fc--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-email-template.json@@ -0,0 +1,208 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "The email template id to edit.",+ "type": "string"+ },+ "operations": {+ "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.",+ "items": {+ "oneOf": [+ {+ "properties": {+ "id": {+ "description": "Id of the content block to update.",+ "type": "string"+ },+ "op": {+ "const": "update_content",+ "type": "string"+ },+ "patch": {+ "additionalProperties": {},+ "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.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ }+ },+ "required": ["op", "id", "patch"],+ "type": "object"+ },+ {+ "properties": {+ "id": {+ "description": "Id of the column to update.",+ "type": "string"+ },+ "op": {+ "const": "update_column",+ "type": "string"+ },+ "patch": {+ "additionalProperties": {},+ "description": "Partial column fields, deep-merged; a null leaf deletes that key.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ }+ },+ "required": ["op", "id", "patch"],+ "type": "object"+ },+ {+ "properties": {+ "id": {+ "description": "Id of the row to update.",+ "type": "string"+ },+ "op": {+ "const": "update_row",+ "type": "string"+ },+ "patch": {+ "additionalProperties": {},+ "description": "Partial row fields, deep-merged; a null leaf deletes that key.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ }+ },+ "required": ["op", "id", "patch"],+ "type": "object"+ },+ {+ "properties": {+ "op": {+ "const": "update_body",+ "type": "string"+ },+ "patch": {+ "additionalProperties": {},+ "description": "Partial body fields, deep-merged. e.g. {values: {backgroundColor: '#ffffff'}}.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ }+ },+ "required": ["op", "patch"],+ "type": "object"+ },+ {+ "properties": {+ "column_id": {+ "description": "Id of the column to insert the block into.",+ "type": "string"+ },+ "content": {+ "additionalProperties": {},+ "description": "A content block {type, values: {...}}; omit id and values._meta — they are assigned server-side. type is one of text, heading, button, image, divider, html, etc.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "index": {+ "description": "0-based insert position; omit to append to the end.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "op": {+ "const": "add_content",+ "type": "string"+ }+ },+ "required": ["op", "column_id", "content"],+ "type": "object"+ },+ {+ "properties": {+ "id": {+ "description": "Id of the content block to remove.",+ "type": "string"+ },+ "op": {+ "const": "remove_content",+ "type": "string"+ }+ },+ "required": ["op", "id"],+ "type": "object"+ },+ {+ "properties": {+ "column_id": {+ "description": "Id of the destination column.",+ "type": "string"+ },+ "id": {+ "description": "Id of the content block to move.",+ "type": "string"+ },+ "index": {+ "description": "0-based position in the destination column; omit to append.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "op": {+ "const": "move_content",+ "type": "string"+ }+ },+ "required": ["op", "id", "column_id"],+ "type": "object"+ },+ {+ "properties": {+ "index": {+ "description": "0-based insert position; omit to append to the end.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "op": {+ "const": "add_row",+ "type": "string"+ },+ "row": {+ "additionalProperties": {},+ "description": "A full row {cells, columns: [{contents: [...], values}], values}; ids and Unlayer numbering are assigned server-side for the row and everything nested in it.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ }+ },+ "required": ["op", "row"],+ "type": "object"+ },+ {+ "properties": {+ "id": {+ "description": "Id of the row to remove.",+ "type": "string"+ },+ "op": {+ "const": "remove_row",+ "type": "string"+ }+ },+ "required": ["op", "id"],+ "type": "object"+ }+ ]+ },+ "minItems": 1,+ "type": "array"+ }+ },+ "required": ["id", "operations"],+ "type": "object"+}