Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(workflows): design-first email template authoring over MCP (#62753)

Harley Alexander5c87a4657a33
diff --git a/.env.local.example b/.env.local.example
index 467a6eda618c..c1c19e9670b8 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -15,6 +15,11 @@
# AZURE_INFERENCE_ENDPOINT=op://General/yw6efvcz5ooxx5fgll3kyang5a/username
# AZURE_INFERENCE_CREDENTIAL=op://General/yw6efvcz5ooxx5fgll3kyang5a/credential
+# ── Workflows / messaging (PostHog employees) ─────────────────────────
+# Server-side rendering of email template designs (Unlayer export API).
+# Without it, design-only template saves over the API return a 400.
+# UNLAYER_API_KEY=op://General/rf2j5i5qotdt5db37mhswn5dyq/credential
+
# ── Billing - Enterprise license (PostHog employees) ──────────────────
# STRIPE_PUBLIC_KEY="op://General/vr7jkjl3ael7mj3rlbi4ojy3wm/credential"
# LICENSE_SECRET_KEY="op://General/fn3h7kn2j6tt3sah7d2fhitsri/credential"
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a75ae3255a51..3b53d2fd7ad0 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -3882,6 +3882,10 @@ snapshots:
hash: v1.k794b7964.7e6363d616aabde2fa6db252c233d4b7e651dd3ed0be35e55d51264b4e994438.7k8-ggET0l7Q1xUgeTCbh-Gy0s8rDpdVjFHER1HvBcA
mcp-apps-cohorts--static--light:
hash: v1.k794b7964.7a0889e7d21c79da2f04c4a187ab6d2b63158edd0e8737cda5a6254197eb3822.Qz8oGpJlwUIi5k43JRBxSAAJo-2fB-qceXOSk8SqTWI
+ mcp-apps-email-template--plain-text-fallback--light:
+ hash: v1.k794b7964.0b1f7127b75364574793fa13d6df88361bc4656a62f6192f100c6d7ca6d9a242.9YDZrP8mjrQTwp7fZ6eFGbSa6iYT7PjJEszdl06k28I
+ mcp-apps-email-template--rendered--light:
+ hash: v1.k794b7964.5e512ddfaa318512c1495ded61c5e023474938aa61f295fecffff933a404bda6.JgWQLaxJqSve1qcp7ugrRNg-9AAvSw9HGwXuKZlFjKw
mcp-apps-error-tracking--active--light:
hash: v1.k794b7964.3c4efa7c47d8f2863f3cec2c180dbf617b7a9b4253892f83900241929ab831b4.PQds2YnDLqkVbifI_HkTi1Uh7fkqL_P_ptcsfpXAwdA
mcp-apps-error-tracking--chained-exceptions--light:
diff --git a/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx
index 27825f67d77a..1f4229f32eb9 100644
--- a/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx
+++ b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx
@@ -33,6 +33,48 @@ import { EMAIL_TYPE_SUPPORTED_FIELDS, EmailTemplaterLogicProps, emailTemplaterLo
export type EmailEditorMode = 'full' | 'preview'
+function EmailPreviewIframe({ html, title }: { html: string; title: string }): JSX.Element {
+ const iframeRef = useRef<HTMLIFrameElement>(null)
+ const observerRef = useRef<ResizeObserver | null>(null)
+ const [height, setHeight] = useState<number | null>(null)
+
+ const measure = useCallback(() => {
+ const doc = iframeRef.current?.contentDocument
+ if (doc?.documentElement) {
+ setHeight(doc.documentElement.scrollHeight)
+ }
+ }, [])
+
+ // Size the iframe to its document so the preview shows the whole email. The
+ // ResizeObserver re-measures as images load; re-attached on every load since
+ // srcDoc replaces the document.
+ const onLoad = useCallback(() => {
+ measure()
+ const body = iframeRef.current?.contentDocument?.body
+ if (body) {
+ observerRef.current?.disconnect()
+ observerRef.current = new ResizeObserver(measure)
+ observerRef.current.observe(body)
+ }
+ }, [measure])
+
+ useEffect(() => () => observerRef.current?.disconnect(), [])
+
+ return (
+ <iframe
+ ref={iframeRef}
+ srcDoc={html}
+ // allow-same-origin without allow-scripts keeps the content inert (no JS runs)
+ // while letting the parent read the document height
+ sandbox="allow-same-origin"
+ title={title}
+ className="w-full"
+ style={{ height: height ?? 150 }}
+ onLoad={onLoad}
+ />
+ )
+}
+
function AddAdvancedFieldButtons(): JSX.Element | null {
const { hiddenAdvancedFields } = useValues(emailTemplaterLogic)
const { revealAdvancedField } = useActions(emailTemplaterLogic)
@@ -208,7 +250,7 @@ function DestinationEmailTemplaterForm({
</LemonButton>
</div>
- <iframe srcDoc={value} sandbox="" title="Email template preview" className="flex-1" />
+ <EmailPreviewIframe html={value} title="Email template preview" />
</>
)}
</LemonField>
@@ -622,7 +664,7 @@ function NativeEmailTemplaterForm({
</LemonButton>
</div>
- <iframe srcDoc={value} sandbox="" title="Email template preview" className="flex-1" />
+ <EmailPreviewIframe html={value} title="Email template preview" />
</>
)}
</LemonField>
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index a8c2a8cb16c9..486936e61cd5 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -116,6 +116,10 @@ PANDADOC_WEBHOOK_SECRET = get_from_env("PANDADOC_WEBHOOK_SECRET", "")
PANDADOC_BAA_TEMPLATE_ID = get_from_env("PANDADOC_BAA_TEMPLATE_ID", "")
PANDADOC_DPA_TEMPLATE_ID = get_from_env("PANDADOC_DPA_TEMPLATE_ID", "")
+# Unlayer (server-side email design → HTML rendering for message templates)
+UNLAYER_API_KEY = get_from_env("UNLAYER_API_KEY", "")
+UNLAYER_API_BASE_URL = get_from_env("UNLAYER_API_BASE_URL", "https://api.unlayer.com")
+
HEATMAP_BROWSERLESS_URL = get_from_env("HEATMAP_BROWSERLESS_URL", "")
HEATMAP_BROWSERLESS_TOKEN = get_from_env("HEATMAP_BROWSERLESS_TOKEN", "")
# Browserless /screenshot session cap (ms); must stay under the plan's max-timeout.
diff --git a/products/messaging/backend/api/message_templates.py b/products/messaging/backend/api/message_templates.py
index 4d335a367290..fb2fd31b362e 100644
--- a/products/messaging/backend/api/message_templates.py
+++ b/products/messaging/backend/api/message_templates.py
@@ -1,5 +1,6 @@
from typing import Any
+from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers, viewsets
from rest_framework.permissions import IsAuthenticated
@@ -10,25 +11,95 @@ from posthog.api.shared import UserBasicSerializer
from products.messaging.backend.models.message_category import MessageCategory
from products.messaging.backend.models.message_template import MessageTemplate
+from products.messaging.backend.unlayer import UnlayerNotConfiguredError, UnlayerRenderError, render_design_html
+
+
+# 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
+# shape is documented in the designing-email-templates skill.
+@extend_schema_field(
+ {
+ "type": "object",
+ "properties": {
+ "counters": {
+ "type": "object",
+ "description": 'Highest htmlID suffix per element type, e.g. {"u_row": 1, "u_content_text": 2}.',
+ },
+ "schemaVersion": {"type": "integer", "description": "Design schema version, e.g. 16."},
+ "body": {
+ "type": "object",
+ "properties": {
+ "id": {"type": "string", "description": "Any unique string."},
+ "rows": {
+ "type": "array",
+ "items": {"type": "object"},
+ "description": "Rows of {id, cells, columns[{id, contents[{id, type, values}], values}], values}.",
+ },
+ "headers": {"type": "array", "items": {"type": "object"}},
+ "footers": {"type": "array", "items": {"type": "object"}},
+ "values": {
+ "type": "object",
+ "description": "Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor.",
+ },
+ },
+ "required": ["rows"],
+ },
+ },
+ "required": ["body", "schemaVersion"],
+ }
+)
+class UnlayerDesignField(serializers.JSONField):
+ pass
class EmailTemplateSerializer(serializers.Serializer):
- subject = serializers.CharField(required=False)
- text = serializers.CharField(required=False)
- html = serializers.CharField(required=False)
- design = serializers.JSONField(required=False)
+ subject = serializers.CharField(
+ required=False,
+ help_text="Email subject line. Supports Liquid templating. Required for email-type templates.",
+ )
+ text = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Plain-text fallback body for clients that can't render the email.",
+ )
+ html = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Rendered email body — derived from the design at save time. "
+ "The visual editor's save path supplies it directly; omit it otherwise.",
+ )
+ design = UnlayerDesignField(
+ required=False,
+ help_text="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.",
+ )
class MessageTemplateContentSerializer(serializers.Serializer):
- templating = serializers.ChoiceField(choices=["hog", "liquid"], required=False)
- email = EmailTemplateSerializer(required=False, allow_null=True)
+ templating = serializers.ChoiceField(
+ choices=["liquid"],
+ default="liquid",
+ help_text="Templating language for the email content. Always 'liquid' — Liquid tags pass through verbatim.",
+ )
+ email = EmailTemplateSerializer(
+ required=False,
+ allow_null=True,
+ help_text="Email message content. Replaced as a whole on update — send the complete object.",
+ )
class MessageTemplateSerializer(serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
- content = MessageTemplateContentSerializer(required=False)
+ content = MessageTemplateContentSerializer(
+ required=False,
+ help_text="Template content keyed by channel. Replaced as a whole on update, not merged.",
+ )
message_category = TeamScopedPrimaryKeyRelatedField(
- queryset=MessageCategory.objects.all(), required=False, allow_null=True
+ queryset=MessageCategory.objects.all(),
+ required=False,
+ allow_null=True,
+ help_text="Message category ID to file the template under. Must belong to the same project.",
)
class Meta:
@@ -46,6 +117,12 @@ class MessageTemplateSerializer(serializers.ModelSerializer):
"deleted",
]
read_only_fields = ["id", "created_at", "created_by", "updated_at"]
+ extra_kwargs = {
+ "name": {"help_text": "Human-readable template name shown in the library."},
+ "description": {"help_text": "What the template is for and when to use it."},
+ "type": {"help_text": "Message channel of the template. Currently 'email'."},
+ "deleted": {"help_text": "Soft-delete flag. Set true to remove the template from the library."},
+ }
def validate(self, data: Any) -> Any:
template_type = data.get("type")
@@ -54,6 +131,26 @@ class MessageTemplateSerializer(serializers.ModelSerializer):
raise serializers.ValidationError(
{"content": {"email": {"subject": "Subject is required for email templates."}}}
)
+ # Design-only saves get their html rendered server-side (the send path uses html
+ # verbatim). A submitted html is trusted as-is — that's the visual editor's own export.
+ if email and email.get("design") and not email.get("html"):
+ try:
+ email["html"] = render_design_html(email["design"])
+ except UnlayerNotConfiguredError:
+ raise serializers.ValidationError(
+ {
+ "content": {
+ "email": {
+ "design": "Design rendering is not configured on this instance — an administrator "
+ "must set UNLAYER_API_KEY to enable saving design-authored templates."
+ }
+ }
+ }
+ )
+ except UnlayerRenderError as e:
+ raise serializers.ValidationError(
+ {"content": {"email": {"design": f"Rendering the design to HTML failed: {e}"}}}
+ )
return data
def create(self, validated_data: Any) -> Any:
@@ -69,7 +166,7 @@ class MessageTemplatesViewSet(
ForbidDestroyModel,
viewsets.ModelViewSet,
):
- scope_object = "INTERNAL"
+ scope_object = "hog_flow"
permission_classes = [IsAuthenticated]
serializer_class = MessageTemplateSerializer
diff --git a/products/messaging/backend/api/test/test_message_templates.py b/products/messaging/backend/api/test/test_message_templates.py
index 1781b06fd037..64fee02210d5 100644
--- a/products/messaging/backend/api/test/test_message_templates.py
+++ b/products/messaging/backend/api/test/test_message_templates.py
@@ -1,11 +1,20 @@
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+from parameterized import parameterized
from rest_framework import status
from posthog.models import Organization, Team
from products.messaging.backend.models.message_category import MessageCategory
from products.messaging.backend.models.message_template import MessageTemplate
+from products.messaging.backend.unlayer import UnlayerNotConfiguredError, UnlayerRenderError
+
+MINIMAL_DESIGN = {
+ "counters": {"u_row": 1},
+ "schemaVersion": 16,
+ "body": {"id": "b", "rows": [{"id": "r", "cells": [1], "columns": [], "values": {}}], "values": {}},
+}
class TestMessageTemplatesAPI(APIBaseTest):
@@ -41,7 +50,11 @@ class TestMessageTemplatesAPI(APIBaseTest):
assert template["id"] == str(self.message_template.id)
assert template["name"] == "Test Template"
assert template["description"] == "Test description"
- assert template["content"] == {"email": {"subject": "Test Subject", "text": "Test Body"}}
+ # templating is injected by the serializer default for legacy rows that never stored it
+ assert template["content"] == {
+ "templating": "liquid",
+ "email": {"subject": "Test Subject", "text": "Test Body"},
+ }
assert template["type"] == "email"
def test_retrieve_message_template(self):
@@ -52,7 +65,10 @@ class TestMessageTemplatesAPI(APIBaseTest):
assert template["id"] == str(self.message_template.id)
assert template["name"] == "Test Template"
assert template["description"] == "Test description"
- assert template["content"] == {"email": {"subject": "Test Subject", "text": "Test Body"}}
+ assert template["content"] == {
+ "templating": "liquid",
+ "email": {"subject": "Test Subject", "text": "Test Body"},
+ }
assert template["type"] == "email"
def test_cannot_access_other_teams_templates(self):
@@ -112,6 +128,110 @@ class TestMessageTemplatesAPI(APIBaseTest):
)
assert response.status_code == status.HTTP_201_CREATED
+ def test_create_defaults_templating_to_liquid(self):
+ """Authored HTML is full of braces (CSS, Liquid) — anything not explicitly
+ 'liquid' is hog-transpiled downstream, where '{' is syntax and compilation fails."""
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/messaging_templates/",
+ data={
+ "name": "No templating set",
+ "content": {"email": {"subject": "Hi", "html": "<style>.a{color:red}</style><p>{{ greeting }}</p>"}},
+ "type": "email",
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.json()["content"]["templating"] == "liquid"
+
+ def test_create_rejects_hog_templating(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/messaging_templates/",
+ data={
+ "name": "Hog attempt",
+ "content": {"templating": "hog", "email": {"subject": "Hi", "html": "<p>Hi</p>"}},
+ "type": "email",
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "templating" in str(response.json())
+
+ @patch("products.messaging.backend.api.message_templates.render_design_html")
+ def test_create_with_design_only_renders_html_server_side(self, mock_render):
+ mock_render.return_value = "<html><body>Rendered</body></html>"
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/messaging_templates/",
+ data={
+ "name": "Design-first template",
+ "content": {"email": {"subject": "Hi", "design": MINIMAL_DESIGN}},
+ "type": "email",
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ mock_render.assert_called_once_with(MINIMAL_DESIGN)
+ email = response.json()["content"]["email"]
+ assert email["html"] == "<html><body>Rendered</body></html>"
+ assert email["design"] == MINIMAL_DESIGN
+
+ @patch("products.messaging.backend.api.message_templates.render_design_html")
+ def test_create_with_design_and_html_keeps_submitted_html(self, mock_render):
+ """The visual editor exports html from the design client-side and submits both —
+ a present html is trusted, not re-rendered."""
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/messaging_templates/",
+ data={
+ "name": "Editor-saved template",
+ "content": {"email": {"subject": "Hi", "html": "<p>Editor export</p>", "design": MINIMAL_DESIGN}},
+ "type": "email",
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ mock_render.assert_not_called()
+ assert response.json()["content"]["email"]["html"] == "<p>Editor export</p>"
+
+ @parameterized.expand(
+ [
+ ("render_failure", UnlayerRenderError("Unlayer returned 500"), "Rendering the design"),
+ ("not_configured", UnlayerNotConfiguredError(), "not configured"),
+ ]
+ )
+ @patch("products.messaging.backend.api.message_templates.render_design_html")
+ def test_create_with_design_render_error_returns_400(self, _name, side_effect, expected_message, mock_render):
+ mock_render.side_effect = side_effect
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/messaging_templates/",
+ data={
+ "name": "Design-first template",
+ "content": {"email": {"subject": "Hi", "design": MINIMAL_DESIGN}},
+ "type": "email",
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert expected_message in str(response.json())
+
+ @patch("products.messaging.backend.api.message_templates.render_design_html")
+ def test_update_with_design_only_renders_html_server_side(self, mock_render):
+ mock_render.return_value = "<html><body>Re-rendered</body></html>"
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/messaging_templates/{self.message_template.id}/",
+ data={"content": {"email": {"subject": "Updated", "design": MINIMAL_DESIGN}}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ mock_render.assert_called_once_with(MINIMAL_DESIGN)
+ self.message_template.refresh_from_db()
+ assert self.message_template.content["email"]["html"] == "<html><body>Re-rendered</body></html>"
+
def test_cannot_bind_template_to_other_teams_message_category_via_patch(self):
"""Regression: PATCH must not accept a MessageCategory pk owned by a different team."""
foreign_category = MessageCategory.objects.create(team=self.other_team, key="foreign-key", name="Foreign")
@@ -128,6 +248,63 @@ class TestMessageTemplatesAPI(APIBaseTest):
self.message_template.refresh_from_db()
assert self.message_template.message_category_id is None
+ @parameterized.expand(
+ [
+ ("list_with_read_scope", ["hog_flow:read"], "get", None, status.HTTP_200_OK),
+ ("retrieve_with_read_scope", ["hog_flow:read"], "get", "detail", status.HTTP_200_OK),
+ ("create_with_write_scope", ["hog_flow:write"], "post", None, status.HTTP_201_CREATED),
+ ("update_with_write_scope", ["hog_flow:write"], "patch", "detail", status.HTTP_200_OK),
+ ("create_with_read_scope_forbidden", ["hog_flow:read"], "post", None, status.HTTP_403_FORBIDDEN),
+ ("update_with_read_scope_forbidden", ["hog_flow:read"], "patch", "detail", status.HTTP_403_FORBIDDEN),
+ ("list_with_unrelated_scope_forbidden", ["insight:read"], "get", None, status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ def test_personal_api_key_scope_enforcement(self, _name, scopes, method, target, expected_status):
+ api_key = self.create_personal_api_key_with_scopes(scopes)
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")
+
+ base_url = f"/api/projects/{self.team.id}/messaging_templates/"
+ url = f"{base_url}{self.message_template.id}/" if target == "detail" else base_url
+ data = (
+ {
+ "name": "API key template",
+ "content": {"email": {"subject": "Hi", "html": "<p>Hi</p>"}},
+ "type": "email",
+ }
+ if method in ("post", "patch")
+ else None
+ )
+
+ response = getattr(self.client, method)(url, data=data, format="json")
+ assert response.status_code == expected_status, response.json()
+
+ def test_update_replaces_content_wholesale(self):
+ """The content JSONField is replaced as a unit on update, never deep-merged —
+ a payload without design makes the submitted html canonical."""
+ self.message_template.content = {
+ "email": {"subject": "Old", "html": "<p>Old</p>", "design": {"body": {"rows": []}}}
+ }
+ self.message_template.save()
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/messaging_templates/{self.message_template.id}/",
+ data={"content": {"email": {"subject": "New", "html": "<p>New</p>"}}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ self.message_template.refresh_from_db()
+ assert self.message_template.content["email"] == {"subject": "New", "html": "<p>New</p>"}
+
+ def test_personal_api_key_cannot_access_other_teams_template(self):
+ 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.get(f"/api/projects/{self.team.id}/messaging_templates/{self.other_team_template.id}/")
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
def test_can_bind_template_to_own_teams_message_category(self):
own_category = MessageCategory.objects.create(team=self.team, key="own-key", name="Own")
diff --git a/products/messaging/backend/tests/test_unlayer.py b/products/messaging/backend/tests/test_unlayer.py
new file mode 100644
index 000000000000..b685b07799f1
--- /dev/null
+++ b/products/messaging/backend/tests/test_unlayer.py
@@ -0,0 +1,55 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
+
+import requests
+from parameterized import parameterized
+
+from products.messaging.backend.unlayer import UnlayerNotConfiguredError, UnlayerRenderError, render_design_html
+
+DESIGN = {"schemaVersion": 16, "body": {"rows": []}}
+
+
+def _response(status_code: int = 200, payload: dict | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.json.return_value = payload if payload is not None else {}
+ return response
+
+
+class TestRenderDesignHtml:
+ @override_settings(UNLAYER_API_KEY="test-key", UNLAYER_API_BASE_URL="https://api.unlayer.com")
+ @patch("products.messaging.backend.unlayer.requests.post")
+ def test_renders_html_from_design(self, mock_post):
+ mock_post.return_value = _response(200, {"success": True, "data": {"html": "<html>ok</html>"}})
+
+ assert render_design_html(DESIGN) == "<html>ok</html>"
+
+ _, kwargs = mock_post.call_args
+ assert mock_post.call_args[0][0] == "https://api.unlayer.com/v2/export/html"
+ assert kwargs["auth"] == ("test-key", "")
+ assert kwargs["json"] == {"displayMode": "email", "design": DESIGN}
+
+ @override_settings(UNLAYER_API_KEY="")
+ def test_raises_when_api_key_missing(self):
+ with pytest.raises(UnlayerNotConfiguredError):
+ render_design_html(DESIGN)
+
+ @parameterized.expand(
+ [
+ ("http_error", _response(500, {"error": "boom"}), None),
+ ("missing_html", _response(200, {"success": True, "data": {}}), None),
+ ("network_error", None, requests.ConnectionError("refused")),
+ ]
+ )
+ @override_settings(UNLAYER_API_KEY="test-key")
+ @patch("products.messaging.backend.unlayer.requests.post")
+ def test_raises_render_error(self, _name, response, side_effect, mock_post):
+ if side_effect is not None:
+ mock_post.side_effect = side_effect
+ else:
+ mock_post.return_value = response
+
+ with pytest.raises(UnlayerRenderError):
+ render_design_html(DESIGN)
diff --git a/products/messaging/backend/unlayer.py b/products/messaging/backend/unlayer.py
new file mode 100644
index 000000000000..fd517896578e
--- /dev/null
+++ b/products/messaging/backend/unlayer.py
@@ -0,0 +1,49 @@
+from typing import Any
+
+from django.conf import settings
+
+import requests
+
+# Unlayer renders synchronously; exports of large designs take a few seconds.
+EXPORT_TIMEOUT_SECONDS = 30
+
+
+class UnlayerError(Exception):
+ pass
+
+
+class UnlayerNotConfiguredError(UnlayerError):
+ pass
+
+
+class UnlayerRenderError(UnlayerError):
+ pass
+
+
+def render_design_html(design: dict[str, Any]) -> str:
+ """Render an Unlayer design to email HTML via the Unlayer export API.
+
+ This is the server-side equivalent of the visual editor's exportHtml() —
+ same renderer, so design-only saves produce the same HTML a human save would.
+ """
+ if not settings.UNLAYER_API_KEY:
+ raise UnlayerNotConfiguredError("UNLAYER_API_KEY is not set")
+
+ try:
+ response = requests.post(
+ f"{settings.UNLAYER_API_BASE_URL}/v2/export/html",
+ auth=(settings.UNLAYER_API_KEY, ""),
+ json={"displayMode": "email", "design": design},
+ timeout=EXPORT_TIMEOUT_SECONDS,
+ )
+ except requests.RequestException as e:
+ raise UnlayerRenderError(f"Unlayer export request failed: {e}") from e
+
+ if response.status_code != 200:
+ raise UnlayerRenderError(f"Unlayer export returned HTTP {response.status_code}")
+
+ data = response.json().get("data") or {}
+ html = data.get("html")
+ if not html:
+ raise UnlayerRenderError("Unlayer export returned no HTML")
+ return html
diff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.ts
index d57193e9e564..2fc465200677 100644
--- a/products/messaging/frontend/generated/api.schemas.ts
+++ b/products/messaging/frontend/generated/api.schemas.ts
@@ -80,26 +80,70 @@ export interface MessagePreferencesApi {
}
/**
- * * `hog` - hog
* * `liquid` - liquid
*/
-export type HogFunctionTemplatingEnumApi =
- (typeof HogFunctionTemplatingEnumApi)[keyof typeof HogFunctionTemplatingEnumApi]
+export type MessageTemplateContentTemplatingEnumApi =
+ (typeof MessageTemplateContentTemplatingEnumApi)[keyof typeof MessageTemplateContentTemplatingEnumApi]
-export const HogFunctionTemplatingEnumApi = {
- Hog: 'hog',
+export const MessageTemplateContentTemplatingEnumApi = {
Liquid: 'liquid',
} as const
+/**
+ * Highest htmlID suffix per element type, e.g. {"u_row": 1, "u_content_text": 2}.
+ */
+export type EmailTemplateApiDesignCounters = { [key: string]: unknown }
+
+export type EmailTemplateApiDesignBodyRowsItem = { [key: string]: unknown }
+
+export type EmailTemplateApiDesignBodyHeadersItem = { [key: string]: unknown }
+
+export type EmailTemplateApiDesignBodyFootersItem = { [key: string]: unknown }
+
+/**
+ * Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor.
+ */
+export type EmailTemplateApiDesignBodyValues = { [key: string]: unknown }
+
+export type EmailTemplateApiDesignBody = {
+ /** Any unique string. */
+ id?: string
+ /** Rows of {id, cells, columns[{id, contents[{id, type, values}], values}], values}. */
+ rows: EmailTemplateApiDesignBodyRowsItem[]
+ headers?: EmailTemplateApiDesignBodyHeadersItem[]
+ footers?: EmailTemplateApiDesignBodyFootersItem[]
+ /** Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor. */
+ values?: EmailTemplateApiDesignBodyValues
+}
+
+/**
+ * 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.
+ */
+export type EmailTemplateApiDesign = {
+ /** Highest htmlID suffix per element type, e.g. {"u_row": 1, "u_content_text": 2}. */
+ counters?: EmailTemplateApiDesignCounters
+ /** Design schema version, e.g. 16. */
+ schemaVersion: number
+ body: EmailTemplateApiDesignBody
+}
+
export interface EmailTemplateApi {
+ /** Email subject line. Supports Liquid templating. Required for email-type templates. */
subject?: string
+ /** Plain-text fallback body for clients that can't render the email. */
text?: string
+ /** Rendered email body — derived from the design at save time. The visual editor's save path supplies it directly; omit it otherwise. */
html?: string
- design?: 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. */
+ design?: EmailTemplateApiDesign
}
export interface MessageTemplateContentApi {
- templating?: HogFunctionTemplatingEnumApi
+ /** Templating language for the email content. Always 'liquid' — Liquid tags pass through verbatim.
+ *
+ * * `liquid` - liquid */
+ templating?: MessageTemplateContentTemplatingEnumApi
+ /** Email message content. Replaced as a whole on update — send the complete object. */
email?: EmailTemplateApi | null
}
@@ -160,17 +204,29 @@ export interface UserBasicApi {
export interface MessageTemplateApi {
readonly id: string
- /** @maxLength 400 */
+ /**
+ * Human-readable template name shown in the library.
+ * @maxLength 400
+ */
name: string
+ /** What the template is for and when to use it. */
description?: string
readonly created_at: string
readonly updated_at: string
+ /** Template content keyed by channel. Replaced as a whole on update, not merged. */
content?: MessageTemplateContentApi
readonly created_by: UserBasicApi
- /** @maxLength 24 */
+ /**
+ * Message channel of the template. Currently 'email'.
+ * @maxLength 24
+ */
type?: string
- /** @nullable */
+ /**
+ * Message category ID to file the template under. Must belong to the same project.
+ * @nullable
+ */
message_category?: string | null
+ /** Soft-delete flag. Set true to remove the template from the library. */
deleted?: boolean
}
@@ -185,17 +241,29 @@ export interface PaginatedMessageTemplateListApi {
export interface PatchedMessageTemplateApi {
readonly id?: string
- /** @maxLength 400 */
+ /**
+ * Human-readable template name shown in the library.
+ * @maxLength 400
+ */
name?: string
+ /** What the template is for and when to use it. */
description?: string
readonly created_at?: string
readonly updated_at?: string
+ /** Template content keyed by channel. Replaced as a whole on update, not merged. */
content?: MessageTemplateContentApi
readonly created_by?: UserBasicApi
- /** @maxLength 24 */
+ /**
+ * Message channel of the template. Currently 'email'.
+ * @maxLength 24
+ */
type?: string
- /** @nullable */
+ /**
+ * Message category ID to file the template under. Must belong to the same project.
+ * @nullable
+ */
message_category?: string | null
+ /** Soft-delete flag. Set true to remove the template from the library. */
deleted?: boolean
}
diff --git a/products/messaging/frontend/generated/api.zod.ts b/products/messaging/frontend/generated/api.zod.ts
index d7f5ee9761d0..5dd73b8be273 100644
--- a/products/messaging/frontend/generated/api.zod.ts
+++ b/products/messaging/frontend/generated/api.zod.ts
@@ -165,84 +165,268 @@ export const MessagingPreferencesAddOptOutCreateBody = /* @__PURE__ */ zod.objec
export const messagingTemplatesCreateBodyNameMax = 400
+export const messagingTemplatesCreateBodyContentOneTemplatingDefault = `liquid`
export const messagingTemplatesCreateBodyTypeMax = 24
export const MessagingTemplatesCreateBody = /* @__PURE__ */ zod.object({
- name: zod.string().max(messagingTemplatesCreateBodyNameMax),
- description: zod.string().optional(),
+ name: zod
+ .string()
+ .max(messagingTemplatesCreateBodyNameMax)
+ .describe('Human-readable template name shown in the library.'),
+ description: zod.string().optional().describe('What the template is for and when to use it.'),
content: zod
.object({
- templating: zod.enum(['hog', 'liquid']).optional().describe('\* `hog` - hog\n\* `liquid` - liquid'),
+ templating: zod
+ .enum(['liquid'])
+ .describe('\* `liquid` - liquid')
+ .default(messagingTemplatesCreateBodyContentOneTemplatingDefault)
+ .describe(
+ "Templating language for the email content. Always 'liquid' — Liquid tags pass through verbatim.\n\n\* `liquid` - liquid"
+ ),
email: zod
.union([
zod.object({
- subject: zod.string().optional(),
- text: zod.string().optional(),
- html: zod.string().optional(),
- design: zod.unknown().optional(),
+ subject: zod
+ .string()
+ .optional()
+ .describe(
+ 'Email subject line. Supports Liquid templating. Required for email-type templates.'
+ ),
+ text: zod
+ .string()
+ .optional()
+ .describe("Plain-text fallback body for clients that can't render the email."),
+ html: zod
+ .string()
+ .optional()
+ .describe(
+ "Rendered email body — derived from the design at save time. The visual editor's save path supplies it directly; omit it otherwise."
+ ),
+ design: zod
+ .object({
+ counters: zod
+ .looseObject({})
+ .optional()
+ .describe(
+ '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({
+ id: zod.string().optional().describe('Any unique string.'),
+ rows: zod
+ .array(zod.looseObject({}))
+ .describe(
+ 'Rows of {id, cells, columns[{id, contents[{id, type, values}], values}], values}.'
+ ),
+ headers: zod.array(zod.looseObject({})).optional(),
+ footers: zod.array(zod.looseObject({})).optional(),
+ values: zod
+ .looseObject({})
+ .optional()
+ .describe(
+ "Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor."
+ ),
+ }),
+ })
+ .optional()
+ .describe(
+ "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."
+ ),
}),
zod.null(),
])
- .optional(),
+ .optional()
+ .describe('Email message content. Replaced as a whole on update — send the complete object.'),
})
- .optional(),
- type: zod.string().max(messagingTemplatesCreateBodyTypeMax).optional(),
- message_category: zod.uuid().nullish(),
- deleted: zod.boolean().optional(),
+ .optional()
+ .describe('Template content keyed by channel. Replaced as a whole on update, not merged.'),
+ type: zod
+ .string()
+ .max(messagingTemplatesCreateBodyTypeMax)
+ .optional()
+ .describe("Message channel of the template. Currently 'email'."),
+ message_category: zod
+ .uuid()
+ .nullish()
+ .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 messagingTemplatesUpdateBodyNameMax = 400
+export const messagingTemplatesUpdateBodyContentOneTemplatingDefault = `liquid`
export const messagingTemplatesUpdateBodyTypeMax = 24
export const MessagingTemplatesUpdateBody = /* @__PURE__ */ zod.object({
- name: zod.string().max(messagingTemplatesUpdateBodyNameMax),
- description: zod.string().optional(),
+ name: zod
+ .string()
+ .max(messagingTemplatesUpdateBodyNameMax)
+ .describe('Human-readable template name shown in the library.'),
+ description: zod.string().optional().describe('What the template is for and when to use it.'),
content: zod
.object({
- templating: zod.enum(['hog', 'liquid']).optional().describe('\* `hog` - hog\n\* `liquid` - liquid'),
+ templating: zod
+ .enum(['liquid'])
+ .describe('\* `liquid` - liquid')
+ .default(messagingTemplatesUpdateBodyContentOneTemplatingDefault)
+ .describe(
+ "Templating language for the email content. Always 'liquid' — Liquid tags pass through verbatim.\n\n\* `liquid` - liquid"
+ ),
email: zod
.union([
zod.object({
- subject: zod.string().optional(),
- text: zod.string().optional(),
- html: zod.string().optional(),
- design: zod.unknown().optional(),
+ subject: zod
+ .string()
+ .optional()
+ .describe(
+ 'Email subject line. Supports Liquid templating. Required for email-type templates.'
+ ),
+ text: zod
+ .string()
+ .optional()
+ .describe("Plain-text fallback body for clients that can't render the email."),
+ html: zod
+ .string()
+ .optional()
+ .describe(
+ "Rendered email body — derived from the design at save time. The visual editor's save path supplies it directly; omit it otherwise."
+ ),
+ design: zod
+ .object({
+ counters: zod
+ .looseObject({})
+ .optional()
+ .describe(
+ '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({
+ id: zod.string().optional().describe('Any unique string.'),
+ rows: zod
+ .array(zod.looseObject({}))
+ .describe(
+ 'Rows of {id, cells, columns[{id, contents[{id, type, values}], values}], values}.'
+ ),
+ headers: zod.array(zod.looseObject({})).optional(),
+ footers: zod.array(zod.looseObject({})).optional(),
+ values: zod
+ .looseObject({})
+ .optional()
+ .describe(
+ "Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor."
+ ),
+ }),
+ })
+ .optional()
+ .describe(
+ "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."
+ ),
}),
zod.null(),
])
- .optional(),
+ .optional()
+ .describe('Email message content. Replaced as a whole on update — send the complete object.'),
})
- .optional(),
- type: zod.string().max(messagingTemplatesUpdateBodyTypeMax).optional(),
- message_category: zod.uuid().nullish(),
- deleted: zod.boolean().optional(),
+ .optional()
+ .describe('Template content keyed by channel. Replaced as a whole on update, not merged.'),
+ type: zod
+ .string()
+ .max(messagingTemplatesUpdateBodyTypeMax)
+ .optional()
+ .describe("Message channel of the template. Currently 'email'."),
+ message_category: zod
+ .uuid()
+ .nullish()
+ .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 messagingTemplatesPartialUpdateBodyNameMax = 400
+export const messagingTemplatesPartialUpdateBodyContentOneTemplatingDefault = `liquid`
export const messagingTemplatesPartialUpdateBodyTypeMax = 24
export const MessagingTemplatesPartialUpdateBody = /* @__PURE__ */ zod.object({
- name: zod.string().max(messagingTemplatesPartialUpdateBodyNameMax).optional(),
- description: zod.string().optional(),
+ name: zod
+ .string()
+ .max(messagingTemplatesPartialUpdateBodyNameMax)
+ .optional()
+ .describe('Human-readable template name shown in the library.'),
+ description: zod.string().optional().describe('What the template is for and when to use it.'),
content: zod
.object({
- templating: zod.enum(['hog', 'liquid']).optional().describe('\* `hog` - hog\n\* `liquid` - liquid'),
+ templating: zod
+ .enum(['liquid'])
+ .describe('\* `liquid` - liquid')
+ .default(messagingTemplatesPartialUpdateBodyContentOneTemplatingDefault)
+ .describe(
+ "Templating language for the email content. Always 'liquid' — Liquid tags pass through verbatim.\n\n\* `liquid` - liquid"
+ ),
email: zod
.union([
zod.object({
- subject: zod.string().optional(),
- text: zod.string().optional(),
- html: zod.string().optional(),
- design: zod.unknown().optional(),
+ subject: zod
+ .string()
+ .optional()
+ .describe(
+ 'Email subject line. Supports Liquid templating. Required for email-type templates.'
+ ),
+ text: zod
+ .string()
+ .optional()
+ .describe("Plain-text fallback body for clients that can't render the email."),
+ html: zod
+ .string()
+ .optional()
+ .describe(
+ "Rendered email body — derived from the design at save time. The visual editor's save path supplies it directly; omit it otherwise."
+ ),
+ design: zod
+ .object({
+ counters: zod
+ .looseObject({})
+ .optional()
+ .describe(
+ '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({
+ id: zod.string().optional().describe('Any unique string.'),
+ rows: zod
+ .array(zod.looseObject({}))
+ .describe(
+ 'Rows of {id, cells, columns[{id, contents[{id, type, values}], values}], values}.'
+ ),
+ headers: zod.array(zod.looseObject({})).optional(),
+ footers: zod.array(zod.looseObject({})).optional(),
+ values: zod
+ .looseObject({})
+ .optional()
+ .describe(
+ "Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor."
+ ),
+ }),
+ })
+ .optional()
+ .describe(
+ "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."
+ ),
}),
zod.null(),
])
- .optional(),
+ .optional()
+ .describe('Email message content. Replaced as a whole on update — send the complete object.'),
})
- .optional(),
- type: zod.string().max(messagingTemplatesPartialUpdateBodyTypeMax).optional(),
- message_category: zod.uuid().nullish(),
- deleted: zod.boolean().optional(),
+ .optional()
+ .describe('Template content keyed by channel. Replaced as a whole on update, not merged.'),
+ type: zod
+ .string()
+ .max(messagingTemplatesPartialUpdateBodyTypeMax)
+ .optional()
+ .describe("Message channel of the template. Currently 'email'."),
+ message_category: zod
+ .uuid()
+ .nullish()
+ .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.'),
})
diff --git a/products/workflows/mcp/apps/EmailTemplate.stories.tsx b/products/workflows/mcp/apps/EmailTemplate.stories.tsx
new file mode 100644
index 000000000000..19f78aaa3626
--- /dev/null
+++ b/products/workflows/mcp/apps/EmailTemplate.stories.tsx
@@ -0,0 +1,69 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { McpThemeDecorator } from '@posthog/mcp-ui/storybook/decorator'
+
+import { type EmailTemplateData, EmailTemplateView } from './index'
+
+const meta: Meta = {
+ title: 'MCP Apps/Email template',
+ decorators: [McpThemeDecorator],
+ parameters: {
+ testOptions: {
+ skipDarkMode: true,
+ },
+ },
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+const sampleHtml = `<!DOCTYPE html>
+<html>
+ <body style="margin:0;font-family:Helvetica,Arial,sans-serif;background:#f7f8f9;">
+ <table width="100%" cellpadding="0" cellspacing="0" style="padding:24px 0;">
+ <tr><td align="center">
+ <table width="480" cellpadding="0" cellspacing="0" style="background:#fff;border-radius:8px;overflow:hidden;">
+ <tr><td style="background:#1d4aff;padding:24px;color:#fff;font-size:20px;font-weight:600;">Welcome to Hedgebox</td></tr>
+ <tr><td style="padding:24px;color:#111;font-size:15px;line-height:1.5;">
+ <p>Hi {{ person.properties.name }},</p>
+ <p>Thanks for signing up. Your files are ready to sync across every device.</p>
+ <p style="margin:24px 0;"><a href="https://hedgebox.net/start" style="background:#1d4aff;color:#fff;padding:12px 20px;border-radius:6px;text-decoration:none;">Get started</a></p>
+ <p style="color:#666;font-size:13px;">— The Hedgebox team</p>
+ </td></tr>
+ </table>
+ </td></tr>
+ </table>
+ </body>
+</html>`
+
+const richTemplate: EmailTemplateData = {
+ id: 'tmpl-1',
+ name: 'Welcome email',
+ description: 'Sent to new signups right after they create an account.',
+ type: 'email',
+ content: {
+ templating: 'liquid',
+ email: { subject: 'Welcome to Hedgebox!', text: 'Welcome to Hedgebox!', html: sampleHtml },
+ },
+ _posthogUrl: 'https://us.posthog.com/project/1/workflows/library/templates/tmpl-1',
+}
+
+const plainTextTemplate: EmailTemplateData = {
+ id: 'tmpl-2',
+ name: 'Password reset',
+ type: 'email',
+ content: {
+ templating: 'liquid',
+ email: { subject: 'Reset your password', text: 'Click the link to reset your password: {{ reset_url }}' },
+ },
+}
+
+export const Rendered: Story = {
+ render: () => <EmailTemplateView template={richTemplate} />,
+ name: 'Rendered email',
+}
+
+export const PlainTextFallback: Story = {
+ render: () => <EmailTemplateView template={plainTextTemplate} />,
+ name: 'Plain-text fallback',
+}
diff --git a/products/workflows/mcp/apps/EmailTemplateView.test.tsx b/products/workflows/mcp/apps/EmailTemplateView.test.tsx
new file mode 100644
index 000000000000..2eae5a2ad442
--- /dev/null
+++ b/products/workflows/mcp/apps/EmailTemplateView.test.tsx
@@ -0,0 +1,74 @@
+import { cleanup, render, screen } from '@testing-library/react'
+import { cloneElement, type ReactElement } from 'react'
+
+import { type EmailTemplateData, EmailTemplateView } from './EmailTemplateView'
+
+// quill is a workspace package that isn't transformed under the frontend jest harness — stub it
+// so this stays a unit test of EmailTemplateView's own logic (preview iframe + conditional rendering).
+jest.mock(
+ '@posthog/quill',
+ () => ({
+ Card: ({ children }: { children: ReactElement }) => <div>{children}</div>,
+ CardContent: ({ children }: { children: ReactElement }) => <div>{children}</div>,
+ Badge: ({ children }: { children: ReactElement }) => <span>{children}</span>,
+ Button: ({ children, render }: { children: ReactElement; render?: ReactElement }) =>
+ render ? cloneElement(render, {}, children) : <button>{children}</button>,
+ }),
+ { virtual: true }
+)
+
+const baseTemplate: EmailTemplateData = {
+ id: 'abc-123',
+ name: 'Welcome email',
+ type: 'email',
+ content: {
+ templating: 'liquid',
+ email: {
+ subject: 'Welcome to PostHog!',
+ text: 'Hi there',
+ html: '<html><body><h1>Hi {{ person.properties.name }}</h1></body></html>',
+ },
+ },
+ _posthogUrl: 'https://app.posthog.com/project/1/workflows/library/templates/abc-123',
+}
+
+describe('EmailTemplateView', () => {
+ afterEach(cleanup)
+
+ it('renders the subject and the email html in a script-disabled sandboxed iframe', () => {
+ const { container } = render(<EmailTemplateView template={baseTemplate} />)
+
+ expect(screen.getByText('Welcome to PostHog!')).toBeTruthy()
+
+ const iframe = container.querySelector('iframe')
+ expect(iframe).not.toBeNull()
+ expect(iframe!.getAttribute('srcdoc')).toBe(baseTemplate.content!.email!.html)
+ // AI-generated html must not be able to run scripts.
+ expect(iframe!.getAttribute('sandbox') ?? '').not.toContain('allow-scripts')
+ })
+
+ it('links the edit button to the _posthogUrl', () => {
+ render(<EmailTemplateView template={baseTemplate} />)
+
+ const link = screen.getByRole('link', { name: /open in editor/i })
+ expect(link.getAttribute('href')).toBe(baseTemplate._posthogUrl)
+ })
+
+ it('omits the edit link when there is no _posthogUrl', () => {
+ const { _posthogUrl, ...withoutUrl } = baseTemplate
+ render(<EmailTemplateView template={withoutUrl} />)
+
+ expect(screen.queryByRole('link', { name: /open in editor/i })).toBeNull()
+ })
+
+ it('falls back to plain text when there is no html', () => {
+ const noHtml: EmailTemplateData = {
+ ...baseTemplate,
+ content: { templating: 'liquid', email: { subject: 'Welcome to PostHog!', text: 'Plain body only' } },
+ }
+ const { container } = render(<EmailTemplateView template={noHtml} />)
+
+ expect(container.querySelector('iframe')).toBeNull()
+ expect(screen.getByText('Plain body only')).toBeTruthy()
+ })
+})
diff --git a/products/workflows/mcp/apps/EmailTemplateView.tsx b/products/workflows/mcp/apps/EmailTemplateView.tsx
new file mode 100644
index 000000000000..9fdb926a89ec
--- /dev/null
+++ b/products/workflows/mcp/apps/EmailTemplateView.tsx
@@ -0,0 +1,89 @@
+import type { ReactElement } from 'react'
+
+import { Badge, Button, Card, CardContent } from '@posthog/quill'
+
+export interface EmailTemplateEmail {
+ subject?: string
+ text?: string
+ html?: string
+ design?: Record<string, unknown>
+}
+
+export interface EmailTemplateData {
+ id: string
+ name: string
+ description?: string | null
+ type?: string
+ content?: {
+ templating?: string
+ email?: EmailTemplateEmail | null
+ } | null
+ _posthogUrl?: string
+}
+
+export interface EmailTemplateViewProps {
+ template: EmailTemplateData
+}
+
+export function EmailTemplateView({ template }: EmailTemplateViewProps): ReactElement {
+ const email = template.content?.email ?? undefined
+ const html = email?.html
+ const templating = template.content?.templating
+
+ return (
+ <div className="p-4">
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-lg font-semibold">{template.name}</span>
+ {template.type && <Badge>{template.type}</Badge>}
+ {templating && <Badge variant="info">{templating}</Badge>}
+ </div>
+ {template.description && (
+ <span className="text-sm text-muted-foreground">{template.description}</span>
+ )}
+ </div>
+
+ {email?.subject && (
+ <div className="flex items-baseline gap-2">
+ <span className="text-xs uppercase tracking-wide text-muted-foreground">Subject</span>
+ <span className="text-sm font-medium">{email.subject}</span>
+ </div>
+ )}
+
+ <Card>
+ <CardContent className="p-0 overflow-hidden">
+ {html ? (
+ // srcDoc keeps the email self-contained; omitting allow-scripts neutralises any
+ // <script> in the template html.
+ <iframe
+ srcDoc={html}
+ sandbox="allow-same-origin"
+ title={`Preview of ${template.name}`}
+ className="w-full h-[640px] border-0 bg-white"
+ />
+ ) : email?.text ? (
+ <pre className="whitespace-pre-wrap p-4 text-sm text-foreground">{email.text}</pre>
+ ) : (
+ <div className="p-4 text-sm text-muted-foreground">
+ No preview available for this template.
+ </div>
+ )}
+ </CardContent>
+ </Card>
+
+ {template._posthogUrl && (
+ <div>
+ <Button
+ variant="link"
+ size="sm"
+ render={<a href={template._posthogUrl} target="_blank" rel="noreferrer" />}
+ >
+ Open in editor
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/mcp/apps/index.ts b/products/workflows/mcp/apps/index.ts
index aaff5c7ace69..3618767ce84a 100644
--- a/products/workflows/mcp/apps/index.ts
+++ b/products/workflows/mcp/apps/index.ts
@@ -1,2 +1,3 @@
export { WorkflowView, type WorkflowData, type WorkflowViewProps } from './WorkflowView'
export { WorkflowListView, type WorkflowListData, type WorkflowListViewProps } from './WorkflowListView'
+export { EmailTemplateView, type EmailTemplateData, type EmailTemplateViewProps } from './EmailTemplateView'
diff --git a/products/workflows/mcp/email_templates.yaml b/products/workflows/mcp/email_templates.yaml
new file mode 100644
index 000000000000..5088a2499563
--- /dev/null
+++ b/products/workflows/mcp/email_templates.yaml
@@ -0,0 +1,116 @@
+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.
+# The tool list and operation IDs are kept in sync automatically:
+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all
+#
+# To enable a tool, set enabled: true and add required scopes + annotations.
+# All other fields (title, description, enrich_url, etc.) are yours to configure.
+category: Workflows
+feature: workflows
+url_prefix: /workflows/library/templates
+ui_apps:
+ email-template:
+ type: detail
+ view_prop: template
+tools:
+ workflows-create-email-template:
+ operation: messaging_templates_create
+ enabled: true
+ scopes:
+ - hog_flow:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ enrich_url: '{id}'
+ title: Create email template
+ description: >
+ Save an email template to the workflows library. Provide name and content.email with subject, a plain-text
+ fallback, and design (design JSON for PostHog's visual email editor — schema in the
+ designing-email-templates skill); the sent email is compiled from the design JSON. Liquid personalization
+ works throughout — Liquid tags, apostrophes, and emoji are ordinary JSON characters, so pass the design
+ inline exactly as authored. Then call workflows-show-email-template and share the _posthogUrl link with the
+ user.
+ response:
+ exclude:
+ - content
+ - created_by
+ workflows-get-email-template:
+ operation: messaging_templates_retrieve
+ enabled: true
+ scopes:
+ - hog_flow:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ enrich_url: '{id}'
+ title: 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.
+ response:
+ exclude:
+ - content.email.html
+ - created_by
+ workflows-list-email-templates:
+ operation: messaging_templates_list
+ enabled: true
+ scopes:
+ - hog_flow:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ enrich_url: '{id}'
+ list: true
+ title: List email templates
+ description: >
+ List email templates in the workflows library — metadata only; fetch a template's content with
+ workflows-get-email-template. Templates are referenced from a workflow's function_email action.
+ response:
+ exclude:
+ - content
+ - created_by
+ workflows-show-email-template:
+ operation: messaging_templates_retrieve
+ enabled: true
+ scopes:
+ - hog_flow:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ enrich_url: '{id}'
+ title: 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.
+ ui_app: email-template
+ response:
+ exclude:
+ - content.email.design
+ - created_by
+ workflows-update-email-template:
+ operation: messaging_templates_partial_update
+ enabled: true
+ scopes:
+ - hog_flow:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ enrich_url: '{id}'
+ title: 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.
+ response:
+ exclude:
+ - content
+ - created_by
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index 9cb26da8e8a8..d2a7bc46fc1e 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -6,7 +6,7 @@
# All other fields (title, description, enrich_url, etc.) are yours to configure.
category: Workflows
feature: workflows
-url_prefix: /pipeline/destinations
+url_prefix: /workflows
ui_apps:
workflow:
type: detail
@@ -90,7 +90,7 @@ tools:
readOnly: false
destructive: false
idempotent: false
- enrich_url: hog-{id}
+ enrich_url: '{id}/workflow'
title: Create workflow
description: >
Create a workflow. Needs an actions array with exactly one type='trigger' (config.type:
@@ -117,7 +117,7 @@ tools:
readOnly: true
destructive: false
idempotent: true
- enrich_url: hog-{id}
+ enrich_url: '{id}/workflow'
title: Get workflow
description: >
Get a specific workflow by ID. Returns the full workflow definition including trigger, edges, actions, exit
@@ -259,7 +259,7 @@ tools:
readOnly: false
destructive: false
idempotent: true
- enrich_url: hog-{id}
+ enrich_url: '{id}/workflow'
title: Update workflow
description: >
Update a workflow by ID. Draft only — active workflows are read-only via MCP for now (editing risks breaking
diff --git a/products/workflows/skills/designing-email-templates/SKILL.md b/products/workflows/skills/designing-email-templates/SKILL.md
new file mode 100644
index 000000000000..eeadb0be7219
--- /dev/null
+++ b/products/workflows/skills/designing-email-templates/SKILL.md
@@ -0,0 +1,77 @@
+---
+name: designing-email-templates
+description: 'Author, save, and edit email templates in the PostHog workflows library — compose email design JSON with Liquid personalization and create and round-trip-edit templates over MCP. Use when asked to design, build, update, or fix an email template for workflows, broadcasts, or campaigns.'
+---
+
+# Designing email templates
+
+Use this skill when creating or editing email templates for PostHog workflows — broadcast campaigns and `function_email` workflow actions send the rendered template.
+
+## How authoring works
+
+You author the **design JSON** (`content.email.design`) and save it with `workflows-create-email-template`. The server renders the sent email from your design with the same renderer PostHog's visual editor uses, so the template opens as editable blocks for humans and sends exactly what the design describes. Schema and a working example in [references/unlayer-design-json.md](references/unlayer-design-json.md).
+
+When talking to the user, call it the template's **design** — the design document format is an internal implementation detail. Always share the template's `_posthogUrl` edit link in your reply after creating or updating, so the user can open it in PostHog directly.
+
+Read [references/design-guidelines.md](references/design-guidelines.md) before composing — it covers committing to a design direction, typography, color, and the patterns that make an email look designed rather than generated. For one fragment the block editor can't express, use an `html`-type content block inside the design.
+
+## Personalization with Liquid
+
+Email content uses Liquid templating. Liquid tags pass through the renderer as plain text, so use them anywhere — block text, subject, links:
+
+```liquid
+Hi {{ person.properties.first_name | default: 'there' }},
+```
+
+Marketing emails must include an unsubscribe link — render it with the built-in variables:
+
+```html
+<a href="{{ unsubscribe_url }}">Unsubscribe</a>
+```
+
+(`{{ unsubscribe_url_one_click }}` is also available for one-click list-unsubscribe flows.)
+
+## Creating a template
+
+Call `workflows-create-email-template` with:
+
+```json
+{
+ "name": "Welcome email",
+ "description": "Sent to new signups on day 0",
+ "type": "email",
+ "content": {
+ "templating": "liquid",
+ "email": {
+ "subject": "Welcome to {{ person.properties.company | default: 'our product' }}",
+ "design": { "counters": { "u_row": 1 }, "schemaVersion": 16, "body": { "rows": ["…"] } },
+ "text": "Plain-text fallback of the same message"
+ }
+ }
+}
+```
+
+- `subject` is required for email templates.
+- Always provide `text` — it's the fallback for clients that block rich content and improves deliverability.
+- The tool result returns an edit link into the PostHog library.
+- After creating (or updating), call `workflows-show-email-template` — it renders an inline preview so the user sees the result.
+
+### Payload mechanics
+
+Pass the design directly in the tool call — no scratch files, no pre-validation subprocesses, no payload preview rounds. Liquid tags (`{{ }}`, `{% %}`), apostrophes, single quotes, and emoji are ordinary characters inside JSON strings; only standard JSON escaping applies. Never rewrite content to avoid them — converting Liquid's single quotes to double quotes inside markup attributes breaks the markup. If the tool call is rejected as malformed, fix the JSON escaping and resend the same content unchanged.
+
+## Editing a template (read–modify–write)
+
+`content` is replaced as a whole on update, never merged — and humans may have edited the design in PostHog's visual editor since you last saw it:
+
+1. `workflows-get-email-template` — always fetch fresh; the returned `design` is the current source of truth.
+2. Modify the `design` (keep subject/text alongside it).
+3. `workflows-update-email-template` — send the complete `content` back. The server re-renders the sent email from the edited design.
+4. `workflows-show-email-template` — render the updated template so the user sees the change; its response carries the final rendered html, so read it before describing the result.
+
+## Using templates
+
+- List what exists with `workflows-list-email-templates` (metadata only; fetch one for its content).
+- When the user asks to see a template, call `workflows-show-email-template` — it renders an inline preview.
+- Reference a template from a workflow's `function_email` action, or start a broadcast from it in the PostHog UI.
+- Templates are soft-deleted by setting `deleted: true` via `workflows-update-email-template`.
diff --git a/products/workflows/skills/designing-email-templates/references/design-guidelines.md b/products/workflows/skills/designing-email-templates/references/design-guidelines.md
new file mode 100644
index 000000000000..8161c289aef0
--- /dev/null
+++ b/products/workflows/skills/designing-email-templates/references/design-guidelines.md
@@ -0,0 +1,48 @@
+# Email design guidelines
+
+These guidelines adapt strong frontend design practice to the email medium — they apply to the Unlayer design as a whole and to the markup fragments inside its text blocks. The goal is a template that looks deliberately designed for the brand — not a generic notification.
+
+## Commit to a direction first
+
+Before writing markup, decide:
+
+- **Purpose and audience** — transactional receipt, product announcement, win-back campaign, and onboarding emails each warrant different energy.
+- **Tone** — pick one and execute it precisely: brutally minimal, editorial/magazine, luxury/refined, playful, industrial/utilitarian. Intentionality beats intensity.
+- **Brand** — pull real colors, voice, and logo from the sender's product or site. If given a URL, mine it for the palette and typographic feel.
+- **The memorable thing** — one element the reader will remember: a bold header treatment, a striking stat, an unusual color block. One, not five.
+
+## Typography
+
+- Build hierarchy with **size, weight, and color contrast**, not font variety: one display treatment for the headline (large, tight line-height, heavy weight), one comfortable body style (15–17px, 1.5–1.6 line-height).
+- Web-safe stacks can still have character: `Georgia, 'Times New Roman', serif` reads editorial; `'Trebuchet MS', Tahoma, sans-serif` reads friendly; `'Courier New', monospace` reads technical. Choose to match the tone instead of defaulting to Arial everywhere.
+- Custom fonts via `<link>`/`@font-face` render in Apple Mail and partially elsewhere — use them as enhancement with a fallback stack that still fits the design.
+- Constrain line length (~35em); let headlines breathe with padding above and below.
+
+## Color
+
+- Commit to a small palette: one dominant color, one sharp accent for the CTA, neutrals for text. Evenly-distributed timid palettes read as template-default; dominant-plus-accent reads as designed.
+- Use consistent hex values everywhere (no CSS variables in email — repeat the literal values; keep a comment block at the top of the document listing the palette so edits stay consistent).
+- Check contrast: body text ≥ 4.5:1 against its background. Test the design holds on both white and dark backgrounds — many clients force dark mode and invert naive black-on-white.
+
+## Layout and space
+
+- Asymmetry and overlap are mostly unavailable in table layout — get visual interest from **generous, deliberate whitespace**, full-bleed color sections, and strong alignment instead.
+- Vary section rhythm: a full-width color band for the header, padded white content sections, a tight dark footer. Uniform 20px-padding-everywhere is what makes emails look auto-generated.
+- One column. Side-by-side cells should be rare, content-justified, and must degrade acceptably when stacked.
+
+## Visual details that survive email clients
+
+- **Bulletproof CTA buttons**: a padded `<td>` with `bgcolor`, border-radius, and an inline-styled `<a>` — not an image, not a CSS-only button.
+- Solid `bgcolor` sections, border accents (a 4px top border in the accent color is cheap and distinctive), and spacer rows are the reliable atmosphere tools. Gradients, background images, and shadows are enhancement-only — the design must work without them.
+- A real text preheader (hidden with inline styles) controls the inbox preview line — write it like ad copy, don't let the client scrape your header nav.
+
+## What reads as machine-generated (avoid)
+
+Centered white card on gray, purple gradient header, Arial everywhere at uniform sizes, three equal feature columns with stock icons, evenly-spread pastel palette, "Hi {name}," as the only personalization. If the draft resembles that, the direction wasn't committed to — restart from the tone decision, don't polish it.
+
+## Quality pass before saving
+
+1. Read the design top to bottom: every text-block element styled inline, palette values consistent, alt text on images.
+2. Squint test on the rendered preview: clear hierarchy — eye lands on headline → key message → CTA.
+3. Confirm Liquid variables have `| default:` fallbacks so no reader sees a blank.
+4. Confirm the plain-text version carries the full message, not a stub.
diff --git a/products/workflows/skills/designing-email-templates/references/unlayer-design-json.md b/products/workflows/skills/designing-email-templates/references/unlayer-design-json.md
new file mode 100644
index 000000000000..2cc4eeede82a
--- /dev/null
+++ b/products/workflows/skills/designing-email-templates/references/unlayer-design-json.md
@@ -0,0 +1,206 @@
+# Unlayer design JSON schema
+
+Schema for `content.email.design` — the Unlayer design document that is the source of truth for a template. You author and edit the design; on save, the server renders the sent email from it with Unlayer's export API (the same renderer PostHog's visual editor uses), and the editor opens it as editable blocks. Don't supply rendered output yourself — that's the visual editor's save path.
+
+Adapted from [unlayer/unlayer-skills](https://github.com/unlayer/unlayer-skills) (`unlayer-export/references/design-json.md`), MIT License, Copyright (c) Unlayer.
+
+## Top-level structure
+
+```typescript
+interface JSONTemplate {
+ counters: Record<string, number> // e.g., { u_row: 3, u_column: 4, u_content_text: 5 }
+ schemaVersion: number // 16
+ body: {
+ id: string // any unique string, e.g., "_BZCs8S2YW"
+ rows: Row[]
+ headers: Row[] // usually []
+ footers: Row[] // usually []
+ values: BodyValues
+ }
+}
+```
+
+IDs are arbitrary unique strings. `counters` tracks the highest `_meta.htmlID` suffix per element type (`u_row`, `u_column`, `u_content_text`, `u_content_button`, …) so the editor can number new elements — keep it consistent with the `_meta.htmlID`s you emit.
+
+## Body values
+
+```typescript
+interface BodyValues {
+ backgroundColor: string
+ contentWidth: string // '600px'
+ fontFamily: { label: string; value: string }
+ textColor: string
+ linkStyle: {
+ inherit: boolean
+ linkColor: string
+ linkHoverColor: string
+ linkUnderline: boolean
+ linkHoverUnderline: boolean
+ }
+}
+```
+
+## Row structure
+
+```typescript
+interface Row {
+ id: string
+ cells: number[] // Column ratios: [1,1] = 50/50, [1,2] = 33/66
+ columns: Column[]
+ values: {
+ displayCondition: object | null
+ columns: boolean // false = locked columns
+ backgroundColor: string
+ columnsBackgroundColor: string
+ backgroundImage: {
+ url: string
+ fullWidth: boolean
+ repeat: boolean
+ center: boolean
+ cover: boolean
+ }
+ padding: string // "0px" or "10px 20px 10px 20px"
+ _meta: { htmlID: string; htmlClassNames: string }
+ }
+}
+```
+
+## Column structure
+
+```typescript
+interface Column {
+ id: string
+ contents: ContentItem[]
+ values: {
+ _meta: { htmlID: string; htmlClassNames: string }
+ border: object
+ padding: string
+ backgroundColor: string
+ }
+}
+```
+
+## Content item structure
+
+Shared properties common to all content items; each tool type adds its own fields to `values`.
+
+```typescript
+interface ContentItem {
+ id: string
+ type: string // See content types below
+ values: {
+ // --- Shared properties (all tools) ---
+ containerPadding: string
+ anchor: string
+ textAlign: string // 'left' | 'center' | 'right'
+ lineHeight: string // '140%'
+ linkStyle: {
+ inherit: boolean
+ linkColor: string
+ linkHoverColor: string
+ linkUnderline: boolean
+ linkHoverUnderline: boolean
+ }
+ hideDesktop: boolean
+ displayCondition: object | null
+ _meta: { htmlID: string; htmlClassNames: string }
+ selectable: boolean
+ draggable: boolean
+ duplicatable: boolean
+ deletable: boolean
+ hideable: boolean
+ // --- Tool-specific properties vary per type ---
+ // text/heading: { text: string } — text is an HTML fragment
+ // image: { src: { url, width, height }, alt, action }
+ // button: { text, href, buttonColors, size, borderRadius, ... }
+ // html: { html: string } — raw HTML block
+ }
+}
+```
+
+## Content types
+
+`text` | `heading` | `button` | `image` | `divider` | `social` | `html` | `video` | `menu` | `timer` | `table` | `carousel`
+
+The `html` content type is an escape hatch: a single raw-HTML block inside the design. Useful for fragments the block editor can't express, but humans can only edit it as a markup blob.
+
+## Validation constants
+
+| Constant | Valid values |
+| -------------- | ---------------------------------------------------------------- |
+| Display modes | `'email'` \| `'web'` \| `'popup'` \| `'document'` |
+| Text direction | `'ltr'` \| `'rtl'` \| `null` |
+| Alignments | `'left'` \| `'center'` \| `'right'` \| `'justify'` |
+| Padding format | `'10px'` or `'10px 20px'` or `'10px 20px 30px 40px'` (always px) |
+
+## Minimal working example
+
+```json
+{
+ "counters": { "u_row": 1, "u_column": 1, "u_content_text": 1 },
+ "schemaVersion": 16,
+ "body": {
+ "id": "_BZCs8S2YW",
+ "rows": [
+ {
+ "id": "LB2ltnM2OZ",
+ "cells": [1],
+ "columns": [
+ {
+ "id": "HI7oaTElxq",
+ "contents": [
+ {
+ "id": "PKtuJs3uBF",
+ "type": "text",
+ "values": {
+ "containerPadding": "10px",
+ "anchor": "",
+ "textAlign": "left",
+ "lineHeight": "140%",
+ "linkStyle": {
+ "inherit": true,
+ "linkColor": "#0000ee",
+ "linkHoverColor": "#0000ee",
+ "linkUnderline": true,
+ "linkHoverUnderline": true
+ },
+ "hideDesktop": false,
+ "displayCondition": null,
+ "_meta": { "htmlID": "u_content_text_1", "htmlClassNames": "u_content_text" },
+ "selectable": true,
+ "draggable": true,
+ "duplicatable": true,
+ "deletable": true,
+ "hideable": true,
+ "text": "<p>Hello World</p>"
+ }
+ }
+ ],
+ "values": {
+ "_meta": { "htmlID": "u_column_1", "htmlClassNames": "u_column" },
+ "border": {},
+ "padding": "0px",
+ "backgroundColor": ""
+ }
+ }
+ ],
+ "values": {
+ "displayCondition": null,
+ "columns": false,
+ "backgroundColor": "",
+ "columnsBackgroundColor": "",
+ "backgroundImage": { "url": "", "fullWidth": true, "repeat": false, "center": true, "cover": false },
+ "padding": "0px"
+ }
+ }
+ ],
+ "headers": [],
+ "footers": [],
+ "values": {
+ "backgroundColor": "#ffffff",
+ "contentWidth": "600px",
+ "fontFamily": { "label": "Arial", "value": "arial,helvetica,sans-serif" }
+ }
+ }
+}
+```
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 91029f633ca1..966e9b9581ec 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -6716,6 +6716,20 @@
"readOnlyHint": false
}
},
+ "workflows-create-email-template": {
+ "description": "Save an email template to the workflows library. Provide name and content.email with subject, a plain-text fallback, and design (design JSON for PostHog's visual email editor — schema in the designing-email-templates skill); the sent email is compiled from the design JSON. Liquid personalization works throughout — Liquid tags, apostrophes, and emoji are ordinary JSON characters, so pass the design inline exactly as authored. Then call workflows-show-email-template and share the _posthogUrl link with the user.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Create email template",
+ "title": "Create email template",
+ "required_scopes": ["hog_flow:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"workflows-get": {
"description": "Get a specific workflow by ID. Returns the full workflow definition including trigger, edges, actions, exit condition, variables, and any recurring 'schedules' (read-only here). For a batch workflow, check status=='active' plus an active entry in 'schedules' to confirm it will actually fire.",
"category": "Workflows",
@@ -6730,6 +6744,20 @@
"readOnlyHint": true
}
},
+ "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.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get email template",
+ "title": "Get email template",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"workflows-get-invocation": {
"description": "Get a single workflow invocation by invocation_id, including invocation_globals — the raw triggering payload (event/person/groups) that the run executed against. Use after workflows-list-invocations to inspect exactly what input produced a failure.",
"category": "Workflows",
@@ -6786,6 +6814,20 @@
"readOnlyHint": true
}
},
+ "workflows-list-email-templates": {
+ "description": "List email templates in the workflows library — metadata only; fetch a template's content with workflows-get-email-template. Templates are referenced from a workflow's function_email action.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "List email templates",
+ "title": "List email templates",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"workflows-list-invocations": {
"description": "List a workflow's individual invocations (one execution per person/event), each collapsed to its final outcome — status, error_kind/error_message, distinct_id, person_id, timings. This is the per-recipient failure view: filter status=failed to see who it failed for and why. Filter by distinct_id and time range. Distinct from workflows-list-batch-jobs (the dispatch ledger, which has no per-person outcome) — drill from a failed invocation into workflows-logs for the step-by-step trace.",
"category": "Workflows",
@@ -6814,6 +6856,20 @@
"readOnlyHint": true
}
},
+ "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",
+ "feature": "workflows",
+ "summary": "Show email template",
+ "title": "Show email template",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"workflows-stats": {
"description": "Execution stats for a single workflow by ID: time-series success/failure counts over a configurable interval (hour, day, or week). Use to inspect one workflow's health — failure spikes and reliability trends. For an at-a-glance view across ALL workflows, call workflows-global-stats first, then drill in here. Supports breakdown by metric kind (success/failure) or name, and time range filtering.",
"category": "Workflows",
@@ -6856,6 +6912,20 @@
"readOnlyHint": false
}
},
+ "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.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Update email template",
+ "title": "Update email template",
+ "required_scopes": ["hog_flow:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"workflows-update-schedule": {
"description": "Update a recurring schedule's RRULE, start time, timezone, or variable overrides. Changing the cadence reschedules the next run. Each firing re-broadcasts to the workflow's current trigger audience.",
"category": "Workflows",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 6601ea38e6c4..7ec4b6c62a8b 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -7113,6 +7113,20 @@
"readOnlyHint": false
}
},
+ "workflows-create-email-template": {
+ "description": "Save an email template to the workflows library. Provide name and content.email with subject, a plain-text fallback, and design (design JSON for PostHog's visual email editor — schema in the designing-email-templates skill); the sent email is compiled from the design JSON. Liquid personalization works throughout — Liquid tags, apostrophes, and emoji are ordinary JSON characters, so pass the design inline exactly as authored. Then call workflows-show-email-template and share the _posthogUrl link with the user.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Create email template",
+ "title": "Create email template",
+ "required_scopes": ["hog_flow:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"workflows-enable": {
"description": "Enable / activate a draft workflow and start processing events. Confirm with the user before invoking.",
"category": "Workflows",
@@ -7141,6 +7155,20 @@
"readOnlyHint": true
}
},
+ "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.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get email template",
+ "title": "Get email template",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"workflows-get-invocation": {
"description": "Get a single workflow invocation by invocation_id, including invocation_globals — the raw triggering payload (event/person/groups) that the run executed against. Use after workflows-list-invocations to inspect exactly what input produced a failure.",
"category": "Workflows",
@@ -7197,6 +7225,20 @@
"readOnlyHint": true
}
},
+ "workflows-list-email-templates": {
+ "description": "List email templates in the workflows library — metadata only; fetch a template's content with workflows-get-email-template. Templates are referenced from a workflow's function_email action.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "List email templates",
+ "title": "List email templates",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"workflows-list-invocations": {
"description": "List a workflow's individual invocations (one execution per person/event), each collapsed to its final outcome — status, error_kind/error_message, distinct_id, person_id, timings. This is the per-recipient failure view: filter status=failed to see who it failed for and why. Filter by distinct_id and time range. Distinct from workflows-list-batch-jobs (the dispatch ledger, which has no per-person outcome) — drill from a failed invocation into workflows-logs for the step-by-step trace.",
"category": "Workflows",
@@ -7253,6 +7295,20 @@
"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",
+ "feature": "workflows",
+ "summary": "Show email template",
+ "title": "Show email template",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"workflows-stats": {
"description": "Execution stats for a single workflow by ID: time-series success/failure counts over a configurable interval (hour, day, or week). Use to inspect one workflow's health — failure spikes and reliability trends. For an at-a-glance view across ALL workflows, call workflows-global-stats first, then drill in here. Supports breakdown by metric kind (success/failure) or name, and time range filtering.",
"category": "Workflows",
@@ -7295,6 +7351,20 @@
"readOnlyHint": false
}
},
+ "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.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Update email template",
+ "title": "Update email template",
+ "required_scopes": ["hog_flow:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"workflows-update-schedule": {
"description": "Update a recurring schedule's RRULE, start time, timezone, or variable overrides. Changing the cadence reschedules the next run. Each firing re-broadcasts to the workflow's current trigger audience.",
"category": "Workflows",
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index 67ccd0127a8d..3c514edb52aa 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -377,12 +377,22 @@ function escapeForDescribe(desc: string): string {
* that return {results: [...]} with no top-level id) — the URL is built from the
* request params instead of the response body.
*/
-function parseEnrichUrl(enrichUrl: string): { prefix: string; field: string; source: 'result' | 'params' } {
- const match = enrichUrl.match(/^(.*?)\{(?:(params)\.)?(\w+)\}$/)
+function parseEnrichUrl(enrichUrl: string): {
+ prefix: string
+ field: string
+ suffix: string
+ source: 'result' | 'params'
+} {
+ const match = enrichUrl.match(/^(.*?)\{(?:(params)\.)?(\w+)\}(.*)$/)
if (!match) {
throw new Error(`Invalid enrich_url format: ${enrichUrl}`)
}
- return { prefix: match[1]!, field: match[3]!, source: match[2] === 'params' ? 'params' : 'result' }
+ return {
+ prefix: match[1]!,
+ field: match[3]!,
+ suffix: match[4] ?? '',
+ source: match[2] === 'params' ? 'params' : 'result',
+ }
}
/** Convert operationId (snake_case) to PascalCase for Orval schema names */
@@ -810,7 +820,7 @@ function buildEnrichment(config: ToolConfig, category: CategoryConfig, resultVar
const baseUrl = config.url_prefix ?? category.url_prefix
if (config.list && config.enrich_url) {
- const { prefix, field, source } = parseEnrichUrl(config.enrich_url)
+ const { prefix, field, suffix, source } = parseEnrichUrl(config.enrich_url)
// For list endpoints, 'params.x' is not meaningful (items come from the response
// array, not request params), so force 'result' source here.
if (source === 'params') {
@@ -821,7 +831,7 @@ function buildEnrichment(config: ToolConfig, category: CategoryConfig, resultVar
return [
` return await withPostHogUrl(context, {`,
` ...${resultVar},`,
- ` results: await Promise.all((${resultVar}.results ?? []).map((item) => withPostHogUrl(context, item, \`${baseUrl}/${prefix}\${item.${field}}\`))),`,
+ ` results: await Promise.all((${resultVar}.results ?? []).map((item) => withPostHogUrl(context, item, \`${baseUrl}/${prefix}\${item.${field}}${suffix}\`))),`,
` }, '${baseUrl}')`,
``,
].join('\n')
@@ -832,10 +842,10 @@ function buildEnrichment(config: ToolConfig, category: CategoryConfig, resultVar
}
if (config.enrich_url) {
- const { prefix, field, source } = parseEnrichUrl(config.enrich_url)
+ const { prefix, field, suffix, source } = parseEnrichUrl(config.enrich_url)
const sourceExpr = source === 'params' ? `params.${field}` : `${resultVar}.${field}`
- return ` return await withPostHogUrl(context, ${resultVar}, \`${baseUrl}/${prefix}\${${sourceExpr}}\`)\n`
+ return ` return await withPostHogUrl(context, ${resultVar}, \`${baseUrl}/${prefix}\${${sourceExpr}}${suffix}\`)\n`
}
return ` return ${resultVar}\n`
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ea0bc3acc669..64522f052a6c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -14737,11 +14737,53 @@ export namespace Schemas {
text?: string | null;
}
+ /**
+ * Highest htmlID suffix per element type, e.g. {"u_row": 1, "u_content_text": 2}.
+ */
+ export type EmailTemplateDesignCounters = { [key: string]: unknown };
+
+ export type EmailTemplateDesignBodyRowsItem = { [key: string]: unknown };
+
+ export type EmailTemplateDesignBodyHeadersItem = { [key: string]: unknown };
+
+ export type EmailTemplateDesignBodyFootersItem = { [key: string]: unknown };
+
+ /**
+ * Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor.
+ */
+ export type EmailTemplateDesignBodyValues = { [key: string]: unknown };
+
+ export type EmailTemplateDesignBody = {
+ /** Any unique string. */
+ id?: string;
+ /** Rows of {id, cells, columns[{id, contents[{id, type, values}], values}], values}. */
+ rows: EmailTemplateDesignBodyRowsItem[];
+ headers?: EmailTemplateDesignBodyHeadersItem[];
+ footers?: EmailTemplateDesignBodyFootersItem[];
+ /** Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor. */
+ values?: EmailTemplateDesignBodyValues;
+ };
+
+ /**
+ * 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.
+ */
+ export type EmailTemplateDesign = {
+ /** Highest htmlID suffix per element type, e.g. {"u_row": 1, "u_content_text": 2}. */
+ counters?: EmailTemplateDesignCounters;
+ /** Design schema version, e.g. 16. */
+ schemaVersion: number;
+ body: EmailTemplateDesignBody;
+ };
+
export interface EmailTemplate {
+ /** Email subject line. Supports Liquid templating. Required for email-type templates. */
subject?: string;
+ /** Plain-text fallback body for clients that can't render the email. */
text?: string;
+ /** Rendered email body — derived from the design at save time. The visual editor's save path supplies it directly; omit it otherwise. */
html?: string;
- design?: 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. */
+ design?: EmailTemplateDesign;
}
/**
@@ -23723,24 +23765,50 @@ export namespace Schemas {
scores: MessageSentimentScores;
}
+ /**
+ * * `liquid` - liquid
+ */
+ export type MessageTemplateContentTemplatingEnum = typeof MessageTemplateContentTemplatingEnum[keyof typeof MessageTemplateContentTemplatingEnum];
+
+
+ export const MessageTemplateContentTemplatingEnum = {
+ Liquid: 'liquid',
+ } as const;
+
export interface MessageTemplateContent {
- templating?: HogFunctionTemplatingEnum;
+ /** Templating language for the email content. Always 'liquid' — Liquid tags pass through verbatim.
+ *
+ * * `liquid` - liquid */
+ templating?: MessageTemplateContentTemplatingEnum;
+ /** Email message content. Replaced as a whole on update — send the complete object. */
email?: EmailTemplate | null;
}
export interface MessageTemplate {
readonly id: string;
- /** @maxLength 400 */
+ /**
+ * Human-readable template name shown in the library.
+ * @maxLength 400
+ */
name: string;
+ /** What the template is for and when to use it. */
description?: string;
readonly created_at: string;
readonly updated_at: string;
+ /** Template content keyed by channel. Replaced as a whole on update, not merged. */
content?: MessageTemplateContent;
readonly created_by: UserBasic;
- /** @maxLength 24 */
+ /**
+ * Message channel of the template. Currently 'email'.
+ * @maxLength 24
+ */
type?: string;
- /** @nullable */
+ /**
+ * Message category ID to file the template under. Must belong to the same project.
+ * @nullable
+ */
message_category?: string | null;
+ /** Soft-delete flag. Set true to remove the template from the library. */
deleted?: boolean;
}
@@ -31674,17 +31742,29 @@ export namespace Schemas {
export interface PatchedMessageTemplate {
readonly id?: string;
- /** @maxLength 400 */
+ /**
+ * Human-readable template name shown in the library.
+ * @maxLength 400
+ */
name?: string;
+ /** What the template is for and when to use it. */
description?: string;
readonly created_at?: string;
readonly updated_at?: string;
+ /** Template content keyed by channel. Replaced as a whole on update, not merged. */
content?: MessageTemplateContent;
readonly created_by?: UserBasic;
- /** @maxLength 24 */
+ /**
+ * Message channel of the template. Currently 'email'.
+ * @maxLength 24
+ */
type?: string;
- /** @nullable */
+ /**
+ * Message category ID to file the template under. Must belong to the same project.
+ * @nullable
+ */
message_category?: string | null;
+ /** Soft-delete flag. Set true to remove the template from the library. */
deleted?: boolean;
}
diff --git a/services/mcp/src/generated/email_templates/api.ts b/services/mcp/src/generated/email_templates/api.ts
new file mode 100644
index 000000000000..6e5dcc4b8068
--- /dev/null
+++ b/services/mcp/src/generated/email_templates/api.ts
@@ -0,0 +1,227 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * MCP service uses these Zod schemas for generated tool handlers.
+ * To regenerate: hogli build:openapi
+ *
+ * PostHog API - MCP 4 enabled ops
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+export const MessagingTemplatesListParams = /* @__PURE__ */ zod.object({
+ 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 MessagingTemplatesListQueryParams = /* @__PURE__ */ zod.object({
+ limit: zod.number().optional().describe('Number of results to return per page.'),
+ offset: zod.number().optional().describe('The initial index from which to return the results.'),
+})
+
+export const MessagingTemplatesCreateParams = /* @__PURE__ */ zod.object({
+ 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 messagingTemplatesCreateBodyNameMax = 400
+
+export const messagingTemplatesCreateBodyContentOneTemplatingDefault = `liquid`
+export const messagingTemplatesCreateBodyTypeMax = 24
+
+export const MessagingTemplatesCreateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(messagingTemplatesCreateBodyNameMax)
+ .describe('Human-readable template name shown in the library.'),
+ description: zod.string().optional().describe('What the template is for and when to use it.'),
+ content: zod
+ .object({
+ templating: zod
+ .enum(['liquid'])
+ .describe('* `liquid` - liquid')
+ .default(messagingTemplatesCreateBodyContentOneTemplatingDefault)
+ .describe(
+ "Templating language for the email content. Always 'liquid' — Liquid tags pass through verbatim.\n\n* `liquid` - liquid"
+ ),
+ email: zod
+ .union([
+ zod.object({
+ subject: zod
+ .string()
+ .optional()
+ .describe(
+ 'Email subject line. Supports Liquid templating. Required for email-type templates.'
+ ),
+ text: zod
+ .string()
+ .optional()
+ .describe("Plain-text fallback body for clients that can't render the email."),
+ html: zod
+ .string()
+ .optional()
+ .describe(
+ "Rendered email body — derived from the design at save time. The visual editor's save path supplies it directly; omit it otherwise."
+ ),
+ design: zod
+ .object({
+ counters: zod
+ .looseObject({})
+ .optional()
+ .describe(
+ '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({
+ id: zod.string().optional().describe('Any unique string.'),
+ rows: zod
+ .array(zod.looseObject({}))
+ .describe(
+ 'Rows of {id, cells, columns[{id, contents[{id, type, values}], values}], values}.'
+ ),
+ headers: zod.array(zod.looseObject({})).optional(),
+ footers: zod.array(zod.looseObject({})).optional(),
+ values: zod
+ .looseObject({})
+ .optional()
+ .describe(
+ "Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor."
+ ),
+ }),
+ })
+ .optional()
+ .describe(
+ "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."
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe('Email message content. Replaced as a whole on update — send the complete object.'),
+ })
+ .optional()
+ .describe('Template content keyed by channel. Replaced as a whole on update, not merged.'),
+ type: zod
+ .string()
+ .max(messagingTemplatesCreateBodyTypeMax)
+ .optional()
+ .describe("Message channel of the template. Currently 'email'."),
+ message_category: zod
+ .uuid()
+ .nullish()
+ .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 MessagingTemplatesRetrieveParams = /* @__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 MessagingTemplatesPartialUpdateParams = /* @__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 messagingTemplatesPartialUpdateBodyNameMax = 400
+
+export const messagingTemplatesPartialUpdateBodyContentOneTemplatingDefault = `liquid`
+export const messagingTemplatesPartialUpdateBodyTypeMax = 24
+
+export const MessagingTemplatesPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(messagingTemplatesPartialUpdateBodyNameMax)
+ .optional()
+ .describe('Human-readable template name shown in the library.'),
+ description: zod.string().optional().describe('What the template is for and when to use it.'),
+ content: zod
+ .object({
+ templating: zod
+ .enum(['liquid'])
+ .describe('* `liquid` - liquid')
+ .default(messagingTemplatesPartialUpdateBodyContentOneTemplatingDefault)
+ .describe(
+ "Templating language for the email content. Always 'liquid' — Liquid tags pass through verbatim.\n\n* `liquid` - liquid"
+ ),
+ email: zod
+ .union([
+ zod.object({
+ subject: zod
+ .string()
+ .optional()
+ .describe(
+ 'Email subject line. Supports Liquid templating. Required for email-type templates.'
+ ),
+ text: zod
+ .string()
+ .optional()
+ .describe("Plain-text fallback body for clients that can't render the email."),
+ html: zod
+ .string()
+ .optional()
+ .describe(
+ "Rendered email body — derived from the design at save time. The visual editor's save path supplies it directly; omit it otherwise."
+ ),
+ design: zod
+ .object({
+ counters: zod
+ .looseObject({})
+ .optional()
+ .describe(
+ '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({
+ id: zod.string().optional().describe('Any unique string.'),
+ rows: zod
+ .array(zod.looseObject({}))
+ .describe(
+ 'Rows of {id, cells, columns[{id, contents[{id, type, values}], values}], values}.'
+ ),
+ headers: zod.array(zod.looseObject({})).optional(),
+ footers: zod.array(zod.looseObject({})).optional(),
+ values: zod
+ .looseObject({})
+ .optional()
+ .describe(
+ "Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor."
+ ),
+ }),
+ })
+ .optional()
+ .describe(
+ "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."
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe('Email message content. Replaced as a whole on update — send the complete object.'),
+ })
+ .optional()
+ .describe('Template content keyed by channel. Replaced as a whole on update, not merged.'),
+ type: zod
+ .string()
+ .max(messagingTemplatesPartialUpdateBodyTypeMax)
+ .optional()
+ .describe("Message channel of the template. Currently 'email'."),
+ message_category: zod
+ .uuid()
+ .nullish()
+ .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.'),
+})
diff --git a/services/mcp/src/resources/ui-apps.generated.ts b/services/mcp/src/resources/ui-apps.generated.ts
index 3bd308aadba2..fedc5a383cda 100644
--- a/services/mcp/src/resources/ui-apps.generated.ts
+++ b/services/mcp/src/resources/ui-apps.generated.ts
@@ -5,6 +5,7 @@ export const ACTION_LIST_RESOURCE_URI = 'ui://posthog/action-list.html'
export const COHORT_RESOURCE_URI = 'ui://posthog/cohort.html'
export const COHORT_LIST_RESOURCE_URI = 'ui://posthog/cohort-list.html'
export const DEBUG_RESOURCE_URI = 'ui://posthog/debug.html'
+export const EMAIL_TEMPLATE_RESOURCE_URI = 'ui://posthog/email-template.html'
export const ERROR_DETAILS_RESOURCE_URI = 'ui://posthog/error-details.html'
export const ERROR_ISSUE_RESOURCE_URI = 'ui://posthog/error-issue.html'
export const ERROR_ISSUE_LIST_RESOURCE_URI = 'ui://posthog/error-issue-list.html'
@@ -37,6 +38,7 @@ export type UiAppKey =
| 'cohort'
| 'cohort-list'
| 'debug'
+ | 'email-template'
| 'error-details'
| 'error-issue'
| 'error-issue-list'
@@ -69,6 +71,7 @@ export const URI_MAP: Record<UiAppKey, string> = {
cohort: COHORT_RESOURCE_URI,
'cohort-list': COHORT_LIST_RESOURCE_URI,
debug: DEBUG_RESOURCE_URI,
+ 'email-template': EMAIL_TEMPLATE_RESOURCE_URI,
'error-details': ERROR_DETAILS_RESOURCE_URI,
'error-issue': ERROR_ISSUE_RESOURCE_URI,
'error-issue-list': ERROR_ISSUE_LIST_RESOURCE_URI,
@@ -105,6 +108,7 @@ export const DISPATCHABLE_APP_KEYS: UiAppKey[] = [
'action-list',
'cohort',
'cohort-list',
+ 'email-template',
'error-details',
'error-issue',
'error-issue-list',
@@ -165,6 +169,12 @@ export const UI_APPS: Array<{
description: 'Debug app for testing MCP Apps SDK integration',
appDir: 'debug',
},
+ {
+ name: 'PostHog Email Template',
+ uri: EMAIL_TEMPLATE_RESOURCE_URI,
+ description: 'Email Template detail view',
+ appDir: 'generated/email-template',
+ },
{
name: 'PostHog Error Details',
uri: ERROR_DETAILS_RESOURCE_URI,
diff --git a/services/mcp/src/tools/generated/email_templates.ts b/services/mcp/src/tools/generated/email_templates.ts
new file mode 100644
index 000000000000..7f9299b6208f
--- /dev/null
+++ b/services/mcp/src/tools/generated/email_templates.ts
@@ -0,0 +1,178 @@
+// AUTO-GENERATED from products/workflows/mcp/email_templates.yaml + OpenAPI — do not edit
+import { z } from 'zod'
+
+import type { Schemas } from '@/api/generated'
+import {
+ MessagingTemplatesCreateBody,
+ MessagingTemplatesListQueryParams,
+ MessagingTemplatesPartialUpdateBody,
+ MessagingTemplatesPartialUpdateParams,
+ MessagingTemplatesRetrieveParams,
+} from '@/generated/email_templates/api'
+import { withUiApp } from '@/resources/ui-apps'
+import { withPostHogUrl, omitResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+
+const WorkflowsCreateEmailTemplateSchema = MessagingTemplatesCreateBody
+
+const workflowsCreateEmailTemplate = (): ToolBase<
+ typeof WorkflowsCreateEmailTemplateSchema,
+ WithPostHogUrl<Schemas.MessageTemplate>
+> => ({
+ name: 'workflows-create-email-template',
+ schema: WorkflowsCreateEmailTemplateSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsCreateEmailTemplateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.description !== undefined) {
+ body['description'] = params.description
+ }
+ if (params.content !== undefined) {
+ body['content'] = params.content
+ }
+ if (params.type !== undefined) {
+ body['type'] = params.type
+ }
+ if (params.message_category !== undefined) {
+ body['message_category'] = params.message_category
+ }
+ if (params.deleted !== undefined) {
+ body['deleted'] = params.deleted
+ }
+ const result = await context.api.request<Schemas.MessageTemplate>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_templates/`,
+ body,
+ })
+ const filtered = omitResponseFields(result, ['content', 'created_by']) as typeof result
+ return await withPostHogUrl(context, filtered, `/workflows/library/templates/${filtered.id}`)
+ },
+})
+
+const WorkflowsGetEmailTemplateSchema = MessagingTemplatesRetrieveParams.omit({ project_id: true })
+
+const workflowsGetEmailTemplate = (): ToolBase<
+ typeof WorkflowsGetEmailTemplateSchema,
+ WithPostHogUrl<Schemas.MessageTemplate>
+> => ({
+ name: 'workflows-get-email-template',
+ schema: WorkflowsGetEmailTemplateSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsGetEmailTemplateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.MessageTemplate>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_templates/${encodeURIComponent(String(params.id))}/`,
+ })
+ const filtered = omitResponseFields(result, ['content.email.html', 'created_by']) as typeof result
+ return await withPostHogUrl(context, filtered, `/workflows/library/templates/${filtered.id}`)
+ },
+})
+
+const WorkflowsListEmailTemplatesSchema = MessagingTemplatesListQueryParams
+
+const workflowsListEmailTemplates = (): ToolBase<
+ typeof WorkflowsListEmailTemplatesSchema,
+ WithPostHogUrl<Schemas.PaginatedMessageTemplateList>
+> => ({
+ name: 'workflows-list-email-templates',
+ schema: WorkflowsListEmailTemplatesSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsListEmailTemplatesSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedMessageTemplateList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_templates/`,
+ query: {
+ limit: params.limit,
+ offset: params.offset,
+ },
+ })
+ const filtered = {
+ ...result,
+ results: (result.results ?? []).map((item: any) => omitResponseFields(item, ['content', 'created_by'])),
+ } as typeof result
+ return await withPostHogUrl(
+ context,
+ {
+ ...filtered,
+ results: await Promise.all(
+ (filtered.results ?? []).map((item) =>
+ withPostHogUrl(context, item, `/workflows/library/templates/${item.id}`)
+ )
+ ),
+ },
+ '/workflows/library/templates'
+ )
+ },
+})
+
+const WorkflowsShowEmailTemplateSchema = MessagingTemplatesRetrieveParams.omit({ project_id: true })
+
+const workflowsShowEmailTemplate = (): ToolBase<
+ typeof WorkflowsShowEmailTemplateSchema,
+ WithPostHogUrl<Schemas.MessageTemplate>
+> =>
+ withUiApp('email-template', {
+ name: 'workflows-show-email-template',
+ schema: WorkflowsShowEmailTemplateSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsShowEmailTemplateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.MessageTemplate>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_templates/${encodeURIComponent(String(params.id))}/`,
+ })
+ const filtered = omitResponseFields(result, ['content.email.design', 'created_by']) as typeof result
+ return await withPostHogUrl(context, filtered, `/workflows/library/templates/${filtered.id}`)
+ },
+ })
+
+const WorkflowsUpdateEmailTemplateSchema = MessagingTemplatesPartialUpdateParams.omit({ project_id: true }).extend(
+ MessagingTemplatesPartialUpdateBody.shape
+)
+
+const workflowsUpdateEmailTemplate = (): ToolBase<
+ typeof WorkflowsUpdateEmailTemplateSchema,
+ WithPostHogUrl<Schemas.MessageTemplate>
+> => ({
+ name: 'workflows-update-email-template',
+ schema: WorkflowsUpdateEmailTemplateSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsUpdateEmailTemplateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.description !== undefined) {
+ body['description'] = params.description
+ }
+ if (params.content !== undefined) {
+ body['content'] = params.content
+ }
+ if (params.type !== undefined) {
+ body['type'] = params.type
+ }
+ if (params.message_category !== undefined) {
+ body['message_category'] = params.message_category
+ }
+ if (params.deleted !== undefined) {
+ body['deleted'] = params.deleted
+ }
+ const result = await context.api.request<Schemas.MessageTemplate>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_templates/${encodeURIComponent(String(params.id))}/`,
+ body,
+ })
+ const filtered = omitResponseFields(result, ['content', 'created_by']) as typeof result
+ return await withPostHogUrl(context, filtered, `/workflows/library/templates/${filtered.id}`)
+ },
+})
+
+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'workflows-create-email-template': workflowsCreateEmailTemplate,
+ 'workflows-get-email-template': workflowsGetEmailTemplate,
+ 'workflows-list-email-templates': workflowsListEmailTemplates,
+ 'workflows-show-email-template': workflowsShowEmailTemplate,
+ 'workflows-update-email-template': workflowsUpdateEmailTemplate,
+}
diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.ts
index 05b2bcf232b9..e928a709fd2a 100644
--- a/services/mcp/src/tools/generated/index.ts
+++ b/services/mcp/src/tools/generated/index.ts
@@ -17,6 +17,7 @@ import { GENERATED_TOOLS as dashboards } from './dashboards'
import { GENERATED_TOOLS as data_warehouse } from './data_warehouse'
import { GENERATED_TOOLS as docs } from './docs'
import { GENERATED_TOOLS as early_access_features } from './early_access_features'
+import { GENERATED_TOOLS as email_templates } from './email_templates'
import { GENERATED_TOOLS as endpoints } from './endpoints'
import { GENERATED_TOOLS as engineering_analytics } from './engineering_analytics'
import { GENERATED_TOOLS as error_tracking } from './error_tracking'
@@ -62,6 +63,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =
...data_warehouse,
...docs,
...early_access_features,
+ ...email_templates,
...endpoints,
...engineering_analytics,
...error_tracking,
diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.ts
index a04ba44a5113..22d09c5eb041 100644
--- a/services/mcp/src/tools/generated/workflows.ts
+++ b/services/mcp/src/tools/generated/workflows.ts
@@ -67,7 +67,7 @@ const workflowsCreate = (): ToolBase<typeof WorkflowsCreateSchema, WithPostHogUr
path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/`,
body,
})
- return await withPostHogUrl(context, result, `/pipeline/destinations/hog-${result.id}`)
+ return await withPostHogUrl(context, result, `/workflows/${result.id}/workflow`)
},
})
@@ -83,7 +83,7 @@ const workflowsGet = (): ToolBase<typeof WorkflowsGetSchema, WithPostHogUrl<Sche
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/`,
})
- return await withPostHogUrl(context, result, `/pipeline/destinations/hog-${result.id}`)
+ return await withPostHogUrl(context, result, `/workflows/${result.id}/workflow`)
},
})
@@ -123,7 +123,7 @@ const workflowsGlobalStats = (): ToolBase<
before: params.before,
},
})
- return await withPostHogUrl(context, result, '/pipeline/destinations')
+ return await withPostHogUrl(context, result, '/workflows')
},
})
@@ -148,7 +148,7 @@ const workflowsList = (): ToolBase<typeof WorkflowsListSchema, WithPostHogUrl<Sc
updated_at: params.updated_at,
},
})
- return await withPostHogUrl(context, result, '/pipeline/destinations')
+ return await withPostHogUrl(context, result, '/workflows')
},
})
@@ -166,7 +166,7 @@ const workflowsListBatchJobs = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/batch_jobs/`,
})
- return await withPostHogUrl(context, result, '/pipeline/destinations')
+ return await withPostHogUrl(context, result, '/workflows')
},
})
@@ -193,7 +193,7 @@ const workflowsListInvocations = (): ToolBase<
status: params.status,
},
})
- return await withPostHogUrl(context, result, '/pipeline/destinations')
+ return await withPostHogUrl(context, result, '/workflows')
},
})
@@ -316,7 +316,7 @@ const workflowsUpdate = (): ToolBase<typeof WorkflowsUpdateSchema, WithPostHogUr
path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/`,
body,
})
- return await withPostHogUrl(context, result, `/pipeline/destinations/hog-${result.id}`)
+ return await withPostHogUrl(context, result, `/workflows/${result.id}/workflow`)
},
})
diff --git a/services/mcp/src/ui-apps/apps/generated/email-template.tsx b/services/mcp/src/ui-apps/apps/generated/email-template.tsx
new file mode 100644
index 000000000000..40feccf1e213
--- /dev/null
+++ b/services/mcp/src/ui-apps/apps/generated/email-template.tsx
@@ -0,0 +1,21 @@
+// AUTO-GENERATED by generate-ui-apps.ts — do not edit
+import '../../styles/tailwind.css'
+
+import { createRoot } from 'react-dom/client'
+
+import { type EmailTemplateData, EmailTemplateView } from 'products/workflows/mcp/apps'
+
+import { AppWrapper } from '../../components/AppWrapper'
+
+function EmailTemplateApp(): JSX.Element {
+ return (
+ <AppWrapper<EmailTemplateData> appName="PostHog Email Template">
+ {({ data }) => <EmailTemplateView template={data!} />}
+ </AppWrapper>
+ )
+}
+
+const container = document.getElementById('root')
+if (container) {
+ createRoot(container).render(<EmailTemplateApp />)
+}
diff --git a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx
index 903731a7bac3..aff7616603ee 100644
--- a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx
+++ b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx
@@ -46,7 +46,14 @@ import {
} from 'products/surveys/mcp/apps'
import { TraceSpanListView, TraceSpanView, type TraceSpanData, type TraceSpanListData } from 'products/tracing/mcp/apps'
import { InviteEmailPreviewView, type InviteEmailPreviewData } from 'products/user_interviews/mcp/apps'
-import { WorkflowListView, WorkflowView, type WorkflowData, type WorkflowListData } from 'products/workflows/mcp/apps'
+import {
+ EmailTemplateView,
+ WorkflowListView,
+ WorkflowView,
+ type EmailTemplateData,
+ type WorkflowData,
+ type WorkflowListData,
+} from 'products/workflows/mcp/apps'
import type { UiAppKey } from '../../resources/ui-apps.generated'
@@ -365,6 +372,7 @@ export const RENDER_DISPATCH: Partial<Record<UiAppKey, (props: RenderDispatchPro
'action-list': ({ data, app }) => <ActionListContent data={data as ActionListData} app={app} />,
cohort: ({ data }) => <CohortView cohort={data as CohortData} />,
'cohort-list': ({ data, app }) => <CohortListContent data={data as CohortListData} app={app} />,
+ 'email-template': ({ data }) => <EmailTemplateView template={data as EmailTemplateData} />,
'error-details': ({ data }) => <ErrorDetailsView data={data as ErrorDetailsData} />,
'error-issue': ({ data }) => <ErrorIssueView issue={data as ErrorIssueData} />,
'error-issue-list': ({ data, app }) => <ErrorIssueListContent data={data as ErrorIssueListData} app={app} />,
diff --git a/services/mcp/tests/tools/workflows.integration.test.ts b/services/mcp/tests/tools/workflows.integration.test.ts
index 84ead009bc02..43003a656a94 100644
--- a/services/mcp/tests/tools/workflows.integration.test.ts
+++ b/services/mcp/tests/tools/workflows.integration.test.ts
@@ -316,7 +316,7 @@ describe('Workflows', { concurrent: false }, () => {
expect(workflow.version).toBeTypeOf('number')
expect(Array.isArray(workflow.actions)).toBe(true)
expect(workflow.actions).toHaveLength(2)
- expect(workflow._posthogUrl).toContain(`/pipeline/destinations/hog-${workflow.id}`)
+ expect(workflow._posthogUrl).toContain(`/workflows/${workflow.id}/workflow`)
})
it('should reject a workflow without exactly one trigger action', async () => {
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
new file mode 100644
index 000000000000..0450c085f58d
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.json
@@ -0,0 +1,133 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "content": {
+ "description": "Template content keyed by channel. Replaced as a whole on update, not merged.",
+ "properties": {
+ "email": {
+ "anyOf": [
+ {
+ "properties": {
+ "design": {
+ "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": {
+ "properties": {
+ "footers": {
+ "items": {
+ "additionalProperties": {},
+ "properties": {},
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "headers": {
+ "items": {
+ "additionalProperties": {},
+ "properties": {},
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "id": {
+ "description": "Any unique string.",
+ "type": "string"
+ },
+ "rows": {
+ "description": "Rows of {id, cells, columns[{id, contents[{id, type, values}], values}], values}.",
+ "items": {
+ "additionalProperties": {},
+ "properties": {},
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "values": {
+ "additionalProperties": {},
+ "description": "Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor.",
+ "properties": {},
+ "type": "object"
+ }
+ },
+ "required": ["rows"],
+ "type": "object"
+ },
+ "counters": {
+ "additionalProperties": {},
+ "description": "Highest htmlID suffix per element type, e.g. {\"u_row\": 1, \"u_content_text\": 2}.",
+ "properties": {},
+ "type": "object"
+ },
+ "schemaVersion": {
+ "description": "Design schema version, e.g. 16.",
+ "type": "number"
+ }
+ },
+ "required": ["schemaVersion", "body"],
+ "type": "object"
+ },
+ "html": {
+ "description": "Rendered email body — derived from the design at save time. The visual editor's save path supplies it directly; omit it otherwise.",
+ "type": "string"
+ },
+ "subject": {
+ "description": "Email subject line. Supports Liquid templating. Required for email-type templates.",
+ "type": "string"
+ },
+ "text": {
+ "description": "Plain-text fallback body for clients that can't render the email.",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Email message content. Replaced as a whole on update — send the complete object."
+ },
+ "templating": {
+ "default": "liquid",
+ "description": "Templating language for the email content. Always 'liquid' — Liquid tags pass through verbatim.\n\n* `liquid` - liquid",
+ "enum": ["liquid"],
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "deleted": {
+ "description": "Soft-delete flag. Set true to remove the template from the library.",
+ "type": "boolean"
+ },
+ "description": {
+ "description": "What the template is for and when to use it.",
+ "type": "string"
+ },
+ "message_category": {
+ "anyOf": [
+ {
+ "format": "uuid",
+ "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Message category ID to file the template under. Must belong to the same project."
+ },
+ "name": {
+ "description": "Human-readable template name shown in the library.",
+ "maxLength": 400,
+ "type": "string"
+ },
+ "type": {
+ "description": "Message channel of the template. Currently 'email'.",
+ "maxLength": 24,
+ "type": "string"
+ }
+ },
+ "required": ["name"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-get-email-template.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-get-email-template.json
new file mode 100644
index 000000000000..1f3acba489ad
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-get-email-template.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this message template.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-email-templates.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-email-templates.json
new file mode 100644
index 000000000000..8331b796ac73
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-email-templates.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "limit": {
+ "description": "Number of results to return per page.",
+ "type": "number"
+ },
+ "offset": {
+ "description": "The initial index from which to return the results.",
+ "type": "number"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-show-email-template.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-show-email-template.json
new file mode 100644
index 000000000000..1f3acba489ad
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-show-email-template.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this message template.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
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
new file mode 100644
index 000000000000..f11e7cffeaf0
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.json
@@ -0,0 +1,137 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "content": {
+ "description": "Template content keyed by channel. Replaced as a whole on update, not merged.",
+ "properties": {
+ "email": {
+ "anyOf": [
+ {
+ "properties": {
+ "design": {
+ "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": {
+ "properties": {
+ "footers": {
+ "items": {
+ "additionalProperties": {},
+ "properties": {},
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "headers": {
+ "items": {
+ "additionalProperties": {},
+ "properties": {},
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "id": {
+ "description": "Any unique string.",
+ "type": "string"
+ },
+ "rows": {
+ "description": "Rows of {id, cells, columns[{id, contents[{id, type, values}], values}], values}.",
+ "items": {
+ "additionalProperties": {},
+ "properties": {},
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "values": {
+ "additionalProperties": {},
+ "description": "Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor.",
+ "properties": {},
+ "type": "object"
+ }
+ },
+ "required": ["rows"],
+ "type": "object"
+ },
+ "counters": {
+ "additionalProperties": {},
+ "description": "Highest htmlID suffix per element type, e.g. {\"u_row\": 1, \"u_content_text\": 2}.",
+ "properties": {},
+ "type": "object"
+ },
+ "schemaVersion": {
+ "description": "Design schema version, e.g. 16.",
+ "type": "number"
+ }
+ },
+ "required": ["schemaVersion", "body"],
+ "type": "object"
+ },
+ "html": {
+ "description": "Rendered email body — derived from the design at save time. The visual editor's save path supplies it directly; omit it otherwise.",
+ "type": "string"
+ },
+ "subject": {
+ "description": "Email subject line. Supports Liquid templating. Required for email-type templates.",
+ "type": "string"
+ },
+ "text": {
+ "description": "Plain-text fallback body for clients that can't render the email.",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Email message content. Replaced as a whole on update — send the complete object."
+ },
+ "templating": {
+ "default": "liquid",
+ "description": "Templating language for the email content. Always 'liquid' — Liquid tags pass through verbatim.\n\n* `liquid` - liquid",
+ "enum": ["liquid"],
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "deleted": {
+ "description": "Soft-delete flag. Set true to remove the template from the library.",
+ "type": "boolean"
+ },
+ "description": {
+ "description": "What the template is for and when to use it.",
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this message template.",
+ "type": "string"
+ },
+ "message_category": {
+ "anyOf": [
+ {
+ "format": "uuid",
+ "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Message category ID to file the template under. Must belong to the same project."
+ },
+ "name": {
+ "description": "Human-readable template name shown in the library.",
+ "maxLength": 400,
+ "type": "string"
+ },
+ "type": {
+ "description": "Message channel of the template. Currently 'email'.",
+ "maxLength": 24,
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}