:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(workflows): read real customer.io snippet, event and webhook shapes (#126015)
Daniel Marchuk422a1eb955eb
diff --git a/products/workflows/backend/presentation/views/workflow_imports.py b/products/workflows/backend/presentation/views/workflow_imports.pyindex e8e627de4601..8e51e5baa107 100644--- a/products/workflows/backend/presentation/views/workflow_imports.py+++ b/products/workflows/backend/presentation/views/workflow_imports.py@@ -88,7 +88,8 @@ class WorkflowImportRequestSerializer(serializers.Serializer):child=serializers.CharField(allow_blank=True),required=False,default=dict,- help_text='Customer.io snippet name to its content, inlined where a message uses `{% snippet "name" %}`.',+ help_text="Customer.io snippet name to its content, inlined where a message uses `{{ snippets.name }}`. "+ "When PostHog reads the message content with a stored Customer.io App API key, it reads the snippets too.",)segment_cohorts = serializers.DictField(child=serializers.IntegerField(),diff --git a/products/workflows/backend/services/customerio_import/app_api.py b/products/workflows/backend/services/customerio_import/app_api.pyindex b356097ddb36..4adf83bfab3e 100644--- a/products/workflows/backend/services/customerio_import/app_api.py+++ b/products/workflows/backend/services/customerio_import/app_api.py@@ -44,6 +44,9 @@ class CustomerioAppApi:def segments(self) -> list[dict[str, Any]]:return list(self._get("/segments").get("segments") or [])+ def snippets(self) -> list[dict[str, Any]]:+ return list(self._get("/snippets").get("snippets") or [])+def _paged(self, path: str, key: str) -> list[dict[str, Any]]:items: list[dict[str, Any]] = []start: str | None = Nonediff --git a/products/workflows/backend/services/customerio_import/content.py b/products/workflows/backend/services/customerio_import/content.pyindex c00a2fe5af98..ceb97e231fc8 100644--- a/products/workflows/backend/services/customerio_import/content.py+++ b/products/workflows/backend/services/customerio_import/content.py@@ -26,7 +26,7 @@ from products.workflows.backend.services.customerio_import.app_api import Customlogger = structlog.get_logger(__name__)-_MESSAGE_ACTION_TYPES = {"email_action", "webhook_action", "attribute_update_action"}+_MESSAGE_ACTION_TYPES = {"email_action", "webhook_action", "attribute_update_action", "create_event_action"}def import_content(@@ -40,6 +40,7 @@ def import_content() -> ImportContent:sender_addresses = {**_identity_addresses(sender_identities), **options.sender_addresses}segment_info = {**_segment_info(segments), **options.segments}+ snippets = options.snippetsfetch_notes: dict[str, tuple[ImportNote, ...]] = {}fetched = False@@ -57,6 +58,8 @@ def import_content(sender_addresses = _identity_addresses(api.sender_identities())if not segment_info:segment_info = _segment_info(api.segments())+ if not snippets:+ snippets = _snippet_values(api.snippets())except CustomerioApiError as error:logger.info("workflows.import.customerio_lookup_failed", team_id=team_id, status=error.status)filled: list[CampaignSource] = []@@ -81,7 +84,7 @@ def import_content(return ImportContent(sources=sources,options=ImportOptions(- snippets=options.snippets,+ snippets=snippets,segment_cohorts=options.segment_cohorts,layouts=options.layouts,sender_addresses=sender_addresses,@@ -192,3 +195,11 @@ def _segment_info(segments: list[dict[str, Any]]) -> dict[str, ImportSegment]:for segment in segmentsif isinstance(segment, dict) and segment.get("id") is not None}+++def _snippet_values(snippets: list[dict[str, Any]]) -> dict[str, str]:+ return {+ str(snippet["name"]): str(snippet.get("value") or "")+ for snippet in snippets+ if isinstance(snippet, dict) and snippet.get("name")+ }diff --git a/products/workflows/backend/services/customerio_import/liquid.py b/products/workflows/backend/services/customerio_import/liquid.pyindex 7a20088c725b..fa347f6ac727 100644--- a/products/workflows/backend/services/customerio_import/liquid.py+++ b/products/workflows/backend/services/customerio_import/liquid.py@@ -9,7 +9,11 @@ from products.workflows.backend.facade.contracts import SnippetRoom# Tag bodies are capped, so text full of unclosed `{{` scans in linear time._TAG = re.compile(r"\{\{.{0,1000}?\}\}|\{%.{0,1000}?%\}", re.DOTALL)_UNSUBSCRIBE_TAG = re.compile(r"\{%-?\s*(?:unsubscribe_url|manage_subscription_preferences_url)\s*-?%\}")-_SNIPPET_TAG = re.compile(r"\{%-?\s*snippet\s+[\"']([^\"']+)[\"']\s*-?%\}")+# Customer.io prints a snippet with `{{ snippets.name }}`. The `{% snippet %}` tag is an older form.+_SNIPPET_TAG = re.compile(+ r"\{%-?\s*snippet\s+[\"']([^\"']+)[\"']\s*-?%\}"+ r"|\{\{-?\s*snippets(?:\.([\w-]+)|\[\s*[\"']([^\"']+)[\"']\s*\])\s*-?\}\}"+)_CAPTURE_TAG = re.compile(r"\{%-?\s*capture\s+(\w+)\s*-?%\}")_QUOTED = re.compile(r"(\"[^\"]*\"|'[^']*')")_OUTPUT_TAG = re.compile(r"\{\{(.{0,1000}?)\}\}", re.DOTALL)@@ -51,7 +55,7 @@ def rewrite(text: str | None, snippets: dict[str, str], room: SnippetRoom | Noneroom = room or SnippetRoom()def inline_snippet(match: re.Match[str]) -> str:- name = match.group(1)+ name = next(group for group in match.groups() if group)content = snippets.get(name)if content is not None and len(content) <= room.remaining:room.remaining -= len(content)diff --git a/products/workflows/backend/services/customerio_import/translator.py b/products/workflows/backend/services/customerio_import/translator.pyindex 63fb9c40d011..781e47b7c3d2 100644--- a/products/workflows/backend/services/customerio_import/translator.py+++ b/products/workflows/backend/services/customerio_import/translator.py@@ -7,6 +7,7 @@ the team can review the draft before enabling it. Nothing about people is read.import reimport json+import secretsfrom collections import dequefrom collections.abc import Iteratorfrom email.utils import parseaddr@@ -232,7 +233,10 @@ class _Builder:return Noneconversion_type = self.campaign.get("conversion_type")window = _duration(self.campaign.get("conversion_window") or 0)- if conversion_type != "perform_event" or not self.campaign.get("conversion_event_name"):+ if conversion_type == "perform_event" and not self.campaign.get("conversion_event_name"):+ # New Customer.io automations have the goal switched on with no event until someone picks one.+ return None+ if conversion_type != "perform_event":self.note(NoteLevel.UNSUPPORTED,"The goal counts people entering or leaving a segment. Set a conversion goal on an event instead.",@@ -586,7 +590,7 @@ class _Builder:inputs["secret_headers"] = {"value": secret_headers}if body_text:try:- inputs["body"] = {"value": json.loads(body_text), "templating": "liquid"}+ inputs["body"] = {"value": _json_with_liquid(body_text), "templating": "liquid"}except ValueError:# Liquid outside a JSON string, like `{% if %}` around a key, makes the stored body invalid JSON.self.note(@@ -605,28 +609,7 @@ class _Builder:f"`{base['name']}` sets a journey attribute, which PostHog has no equivalent for. It was left out.",)return None- template = self._template(source, base)- attributes: Any = []- for raw in (template.get("body"), template.get("body_json")):- if not raw:- continue- try:- attributes = json.loads(raw) if isinstance(raw, str) else raw- except ValueError:- continue- if attributes:- break- properties: dict[str, Any] = {}- for attribute in attributes if isinstance(attributes, list) else []:- if not isinstance(attribute, dict) or not attribute.get("name"):- continue- value = attribute.get("value")- if attribute.get("type") == "profile_attribute":- value = "{{customer." + str(value or "") + "}}"- if value is None or isinstance(value, str):- properties[str(attribute["name"])] = self._liquid(value or "", base, "property value")- else:- properties[str(attribute["name"])] = value+ properties = self._template_properties(self._template(source, base), base)if not properties:self.note(NoteLevel.NEEDS_INPUT, "Set the person properties this step updates.", base)return {@@ -642,22 +625,57 @@ class _Builder:}def _create_event(self, source: dict[str, Any], base: dict[str, Any]) -> dict[str, Any] | None:- event_name = source.get("event_name")+ event_name: Any = source.get("event_name")+ # The editor stores the name as JSON, like `{"type": "static", "value": "signed_up"}`.+ if isinstance(event_name, str) and event_name.lstrip().startswith("{"):+ try:+ event_name = json.loads(event_name)+ except ValueError:+ pass+ if isinstance(event_name, dict):+ event_name = event_name.get("value")if not event_name:self.note(NoteLevel.UNSUPPORTED, f"`{base['name']}` sends an event with no name, so it was left out.")return None+ inputs: dict[str, Any] = {+ "event": {"value": self._liquid(str(event_name), base, "event name"), "templating": "liquid"},+ "distinct_id": {"value": "{{ event.distinct_id }}", "templating": "liquid"},+ }+ if source.get("template_id") is not None:+ properties = self._template_properties(self._template(source, base), base)+ if properties:+ inputs["properties"] = {"value": properties, "templating": "liquid"}return {**base,"type": "function",- "config": {- "template_id": "template-posthog-capture",- "inputs": {- "event": {"value": str(event_name)},- "distinct_id": {"value": "{{ event.distinct_id }}", "templating": "liquid"},- },- },+ "config": {"template_id": "template-posthog-capture", "inputs": inputs},}+ def _template_properties(self, template: dict[str, Any], base: dict[str, Any]) -> dict[str, Any]:+ """The `[{name, type, value}]` list that attribute update and create event steps keep in their template."""+ attributes: Any = []+ for raw in (template.get("body"), template.get("body_json")):+ if not raw:+ continue+ try:+ attributes = json.loads(raw) if isinstance(raw, str) else raw+ except ValueError:+ continue+ if attributes:+ break+ properties: dict[str, Any] = {}+ for attribute in attributes if isinstance(attributes, list) else []:+ if not isinstance(attribute, dict) or not attribute.get("name"):+ continue+ value = attribute.get("value")+ if attribute.get("type") == "profile_attribute":+ value = "{{customer." + str(value or "") + "}}"+ if value is None or isinstance(value, str):+ properties[str(attribute["name"])] = self._liquid(value or "", base, "property value")+ else:+ properties[str(attribute["name"])] = value+ return properties+def _delay(self, action: dict[str, Any], seconds: Any) -> str:total = int(seconds or 0)if total > _MAX_DELAY_SECONDS:@@ -1001,3 +1019,37 @@ def _strip_comments(html: str) -> str:position = end + 3parts.append(html[position:])return "".join(parts)+++def _json_with_liquid(text: str) -> Any:+ """Parses a JSON body whose strings hold Liquid, like `"{{ customer.name | default: "" }}"`.++ Quotes inside a tag make the raw text invalid JSON, so each tag is swapped for a placeholder while parsing.+ Liquid outside a string still fails to parse.+ """+ try:+ return json.loads(text)+ except ValueError:+ pass+ # A random marker, so text in the body itself can never read as a placeholder.+ marker = f"liquid-{secrets.token_hex(8)}-"+ tags: dict[str, str] = {}++ def hold(match: re.Match[str]) -> str:+ key = f"{marker}{len(tags)}"+ tags[key] = match.group(0)+ return key++ parsed = json.loads(_LIQUID_TAG.sub(hold, text))+ placeholder = re.compile(re.escape(marker) + r"\d+")++ def restore(value: Any) -> Any:+ if isinstance(value, str):+ return placeholder.sub(lambda match: tags.get(match.group(0), match.group(0)), value)+ if isinstance(value, list):+ return [restore(item) for item in value]+ if isinstance(value, dict):+ return {restore(key): restore(item) for key, item in value.items()}+ return value++ return restore(parsed)diff --git a/products/workflows/backend/tests/test_customerio_import.py b/products/workflows/backend/tests/test_customerio_import.pyindex 940d4f0d8374..2dea26f52422 100644--- a/products/workflows/backend/tests/test_customerio_import.py+++ b/products/workflows/backend/tests/test_customerio_import.py@@ -38,7 +38,7 @@ from products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.presentation.views.data_suggestion_drafts import validated_draftfrom products.workflows.backend.services.customerio_import import conditions, liquidfrom products.workflows.backend.services.customerio_import.images import _file_name-from products.workflows.backend.services.customerio_import.translator import translate_campaign+from products.workflows.backend.services.customerio_import.translator import _json_with_liquid, translate_campaigndef _encode(condition: list[dict[str, Any]]) -> str:@@ -172,13 +172,14 @@ class TestCustomerioCampaignTranslation(BaseTest):edges = [edge for edge in source.campaign["edges"] if edge["from"] != "5"]campaign = {**source.campaign,- "workflow_action_ids": [*source.campaign["workflow_action_ids"], "10", "11"],+ "workflow_action_ids": [*source.campaign["workflow_action_ids"], "10", "11", "12"],"exit_on_conversion_matched": False,"edges": [*edges,{"from": "5", "to": "10", "type": "continue"},{"from": "10", "to": "11", "type": "continue"},- {"from": "11", "to": "9", "type": "continue"},+ {"from": "11", "to": "12", "type": "continue"},+ {"from": "12", "to": "9", "type": "continue"},],"conversion_event_filters": {"or": [@@ -193,18 +194,34 @@ class TestCustomerioCampaignTranslation(BaseTest):actions = [{**action, "delay": 129600} if action["id"] == "3" else action for action in source.actions] + [{"id": "10", "type": "attribute_update_action", "name": "Flags", "template_id": "14"},{"id": "11", "type": "webhook_action", "name": "CRM", "template_id": "15"},+ {+ "id": "12",+ "type": "create_event_action",+ "name": "Reminder sent",+ "template_id": "16",+ "event_name": json.dumps({"type": "static", "value": "reminder_sent"}),+ },]templates = {**source.templates,"14": {"body": json.dumps([{"name": "active", "value": False}, {"name": "score", "value": 0}])},"15": {"url": "https://crm.example.com",+ "body": '{"name": "{{ customer.first_name | default: "" }}", "seats": 3}',"headers": [{"name": "Authorization", "value": "Bearer fake-token"},{"name": "X-Api-Key", "value": "{{customer.key}}"},{"name": "X-Source", "value": "{{customer.id}}"},],},+ "16": {+ "body": json.dumps(+ [+ {"name": "days_left", "type": "static", "value": "3"},+ {"name": "plan", "type": "liquid", "value": "{{ customer.plan }}"},+ ]+ )+ },}translated = translate_campaign(CampaignSource(campaign=campaign, actions=actions, templates=templates), _OPTIONS@@ -214,9 +231,13 @@ class TestCustomerioCampaignTranslation(BaseTest):assert steps["cio_3"]["config"] == {"delay_duration": "1.5d"}assert steps["cio_10"]["config"]["inputs"]["set_properties"]["value"] == {"active": False, "score": 0}+ reminder = steps["cio_12"]["config"]["inputs"]+ assert reminder["event"]["value"] == "reminder_sent"+ assert reminder["properties"]["value"] == {"days_left": "3", "plan": "{{ person.properties.plan }}"}webhook = steps["cio_11"]["config"]["inputs"]assert webhook["headers"]["value"] == {"X-Source": "{{event.distinct_id}}"}assert webhook["secret_headers"]["value"] == {"Authorization": "Bearer fake-token"}+ assert webhook["body"]["value"] == {"name": '{{ person.properties.first_name | default: "" }}', "seats": 3}assert "properties" not in workflow["conversion"]["events"][0]["filters"]["events"][0]assert workflow["exit_condition"] == "exit_only_at_end"messages = [note.message for note in translated.notes]@@ -224,6 +245,16 @@ class TestCustomerioCampaignTranslation(BaseTest):assert any("any of several conditions" in message for message in messages)assert any("removes people from this automation" in message for message in messages)+ def test_goal_switched_on_without_an_event_is_left_out_quietly(self) -> None:+ source = _onboarding_campaign()+ campaign = {**source.campaign, "conversion_event_name": None}+ translated = translate_campaign(+ CampaignSource(campaign=campaign, actions=source.actions, templates=source.templates), _OPTIONS+ )++ assert translated.workflow["conversion"] is None+ assert not any("goal" in note.message for note in translated.notes)+def test_long_chain_of_left_out_steps_resolves(self) -> None:source = _onboarding_campaign()ids = [str(index) for index in range(100, 1300)]@@ -414,6 +445,20 @@ class TestCustomerioConditions(SimpleTestCase):class TestCustomerioLiquid(SimpleTestCase):+ @parameterized.expand(+ [+ ("quotes_inside_liquid", '{"a": "{{ x | default: "" }}"}', {"a": '{{ x | default: "" }}'}),+ ("escaped_quotes_in_valid_json", '{"a": "{{ x | default: \\"\\" }}"}', {"a": '{{ x | default: "" }}'}),+ (+ "text_like_a_placeholder",+ '{"a": "liquid-0 \\ue0000\\ue001", "b": "{{ y | default: "" }}"}',+ {"a": "liquid-0 \ue0000\ue001", "b": '{{ y | default: "" }}'},+ ),+ ]+ )+ def test_webhook_body_keeps_its_liquid(self, _name: str, body: str, expected: dict[str, str]) -> None:+ assert _json_with_liquid(body) == expected+@parameterized.expand([("customer attribute", "{{ customer.first_name }}", "{{ person.properties.first_name }}"),@@ -450,10 +495,17 @@ class TestCustomerioLiquid(SimpleTestCase):assert rewritten.unsupported_globals == ("journey",)assert rewritten.missing_snippets == ("legal",)- def test_stops_inlining_snippets_past_the_budget(self) -> None:+ @parameterized.expand(+ [+ ("output_tag", "{{ snippets.big }}"),+ ("output_tag_with_brackets", '{{- snippets["big"] -}}'),+ ("legacy_tag", '{% snippet "big" %}'),+ ]+ )+ def test_stops_inlining_snippets_past_the_budget(self, _name: str, tag: str) -> None:room = SnippetRoom(remaining=10)- rewritten = liquid.rewrite('{% snippet "big" %}' * 3, {"big": "0123456"}, room)- assert rewritten.text == '0123456{% snippet "big" %}{% snippet "big" %}'+ rewritten = liquid.rewrite(tag * 3, {"big": "0123456"}, room)+ assert rewritten.text == "0123456" + tag * 2assert rewritten.missing_snippets == ("big",)@@ -604,7 +656,13 @@ class TestWorkflowImportAPI(APIBaseTest):Integration.objects.create(team=self.team, kind="customerio-app", sensitive_config={"app_api_key": "k"})create_category(self.team.id, None, {"key": "customerio_topic_3", "name": "Product news"})email_actions = [- {"id": 1, "type": "email", "subject": "Hi", "body": "<p>Fetched {{customer.first_name}}</p>", "from_id": 4},+ {+ "id": 1,+ "type": "email",+ "subject": "Hi",+ "body": "<p>Fetched {{customer.first_name}}</p>{{ snippets.signature }}",+ "from_id": 4,+ },{"id": 5, "type": "email", "subject": "Tips", "body": "<p>Tips</p>"},]@@ -618,6 +676,10 @@ class TestWorkflowImportAPI(APIBaseTest):response.json.return_value = {"actions": email_actions[1:], "next": ""}elif url.endswith("/sender_identities"):response.json.return_value = {"sender_identities": [{"id": 4, "email": "[email protected]"}]}+ elif url.endswith("/snippets"):+ response.json.return_value = {+ "snippets": [{"name": "signature", "value": "<p>Bye {{customer.id}}</p>"}]+ }else:response.json.return_value = {}return response@@ -637,7 +699,8 @@ class TestWorkflowImportAPI(APIBaseTest):flow_actions = {action["id"]: action for action in flow.actions}welcome = flow_actions["cio_1"]["config"]assert welcome["inputs"]["email"]["value"]["html"] == (- '<div style="font-family: Arial, Helvetica, sans-serif;"><p>Fetched {{person.properties.first_name}}</p></div>'+ '<div style="font-family: Arial, Helvetica, sans-serif;"><p>Fetched {{person.properties.first_name}}</p>'+ "<p>Bye {{event.distinct_id}}</p></div>")assert welcome["inputs"]["email"]["value"]["from"]["email"] == "[email protected]"assert welcome["message_category_type"] == "marketing"diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 381b1704f0cf..0a976086aa12 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -2709,7 +2709,7 @@ export interface EmailDraftApi {}/**- * Customer.io snippet name to its content, inlined where a message uses `{% snippet "name" %}`.+ * Customer.io snippet name to its content, inlined where a message uses `{{ snippets.name }}`. When PostHog reads the message content with a stored Customer.io App API key, it reads the snippets too.*/export type WorkflowImportRequestApiSnippets = { [key: string]: string }@@ -2773,7 +2773,7 @@ export interface WorkflowImportRequestApi {source: ImportProviderKeyEnumApi/** The automations to import, at most 50. People are never read from these objects. */campaigns: CustomerioCampaignApi[]- /** Customer.io snippet name to its content, inlined where a message uses `{% snippet "name" %}`. */+ /** Customer.io snippet name to its content, inlined where a message uses `{{ snippets.name }}`. When PostHog reads the message content with a stored Customer.io App API key, it reads the snippets too. */snippets?: WorkflowImportRequestApiSnippets/** Customer.io segment id to the PostHog cohort that replaces it. Segment triggers and segment conditions with no cohort here are left for the team to set. */segment_cohorts?: WorkflowImportRequestApiSegmentCohortsdiff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex e8501ebb28d2..9068491ffdc9 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -3514,7 +3514,9 @@ export const WorkflowImportsCreateBody = /* @__PURE__ */ zod.object({snippets: zod.record(zod.string(), zod.string()).optional()- .describe('Customer.io snippet name to its content, inlined where a message uses `{% snippet \"name\" %}`.'),+ .describe(+ 'Customer.io snippet name to its content, inlined where a message uses `{{ snippets.name }}`. When PostHog reads the message content with a stored Customer.io App API key, it reads the snippets too.'+ ),segment_cohorts: zod.record(zod.string(), zod.number()).optional()diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yamlindex b2c5e8aabb2b..889c65ad255c 100644--- a/products/workflows/mcp/tools.yaml+++ b/products/workflows/mcp/tools.yaml@@ -336,10 +336,12 @@ tools:idempotent: truetitle: Import Customer.io automationsdescription: >- Turn Customer.io automations into draft PostHog workflows. Read each automation with the Customer.io MCP or- CLI first: GET /v1/environments/{environment_id}/campaigns/{campaign_id} gives `campaign` and `actions`.- Pass them unchanged; never pass people or customer profiles. Leave message templates out on the first call:- when the project stored a Customer.io App API key, PostHog reads the content itself and the response says+ Turn Customer.io automations into draft PostHog workflows in the active project. Before the first call, tell+ the user the active project's name and id and ask whether the drafts belong there; switch project if not.+ Read each automation with the Customer.io MCP or CLI first: GET+ /v1/environments/{environment_id}/campaigns/{campaign_id} gives `campaign` and `actions`. Pass them+ unchanged; never pass people or customer profiles. Leave message templates out on the first call: when the+ project stored a Customer.io App API key, PostHog reads the content itself and the response sayscontent_fetched=true. For each automation whose notes still say its message content was not part of theimport, read each message action's template with GET/v1/environments/{environment_id}/templates/{template_id} and pass them. Pass snippets that notes name. In adiff --git a/products/workflows/skills/migrating-from-customer-io/SKILL.md b/products/workflows/skills/migrating-from-customer-io/SKILL.mdindex 2e2b8dc34ed5..9897f0b666a4 100644--- a/products/workflows/skills/migrating-from-customer-io/SKILL.md+++ b/products/workflows/skills/migrating-from-customer-io/SKILL.md@@ -19,15 +19,16 @@ Email templates are large, often tens of kilobytes of HTML each. When the PostHo## Steps-1. **Find the environment.** Ask which Customer.io workspace to migrate if there is more than one. Its id is the `environment_id` in every path below.-2. **List the automations.** `GET /v1/environments/{environment_id}/campaigns` with the Customer.io read tool (`cio_read_api` on the MCP, `cio api` on the CLI). It returns 20 per page through `page` (0-based): read every page until one returns fewer than 20. Show the user the list with each automation's state, and ask which to move. Running automations are the usual answer; skip archived ones unless asked.-3. **Read each automation.** `GET /v1/environments/{environment_id}/campaigns/{campaign_id}`. Keep the response's `campaign` object and its **top-level** `actions` array. `campaign.actions` does not exist.-4. **Read senders and segments.** `GET /v1/environments/{environment_id}/identities?type=email` for `sender_identities` (`id`, `email`, `name`), and the segment list for `segments` (`id`, `name`, `type` only). PostHog matches each email to the PostHog sender with the same address, and names the segments in its notes.-5. **Preview without templates.** Call `workflows-import-customerio` with `source: "customerio"`, `dry_run: true`, `campaigns: [{campaign, actions}]`, `sender_identities` and `segments`. Up to 50 automations per call.-6. **Read templates only if needed.** Go by each automation's notes, not by `content_fetched` alone: `true` only means PostHog read some content, and one automation can still miss its messages. For every automation whose notes say message content was not part of the import, or that PostHog could not read its messages, read the template of every action that has a `template_id` with `GET /v1/environments/{environment_id}/templates/{template_id}`, keep the `template` object, and preview again with `campaigns: [{campaign, actions, templates}]`. Read templates one at a time: listing every template in the workspace times out on large ones. Tell the user that Import from Customer.io on the Workflows Opt-outs tab stores their App API key, which skips this step next time.-7. **Collect snippets and layouts.** If a note names a Customer.io snippet, or a template body you read contains `{% snippet "name" %}`, read the workspace snippets and pass them as `snippets` (`{name: content}`). When PostHog read the content itself, the notes are the only place the snippet names appear. If a note names a layout, read `GET /v1/environments/{environment_id}/layouts/{layout_id}` and pass its `body` as `layouts` (`{layout_id: body}`).-8. **Report the preview.** For each automation, give its status and its notes, grouped by level (see below). Ask before importing anything with status `failed`; its `validation_errors` say why the draft would be rejected.-9. **Import.** Call again with `dry_run: false` and the same arguments. Share each draft's link (`/workflows/{workflow_id}`) and the `needs_input` notes again, since the team must handle those before enabling.+1. **Confirm the PostHog project.** The drafts go into the PostHog MCP's active project. Read it with `project-get`, tell the user its name and id, and ask whether the drafts should go there. If not, switch with `switch-project` before you read anything from Customer.io.+2. **Find the environment.** Ask which Customer.io workspace to migrate if there is more than one. Its id is the `environment_id` in every path below.+3. **List the automations.** `GET /v1/environments/{environment_id}/campaigns` with the Customer.io read tool (`cio_read_api` on the MCP, `cio api` on the CLI). It returns 20 per page through `page` (0-based): read every page until one returns fewer than 20. Show the user the list with each automation's state, and ask which to move. Running automations are the usual answer; skip archived ones unless asked.+4. **Read each automation.** `GET /v1/environments/{environment_id}/campaigns/{campaign_id}`. Keep the response's `campaign` object and its **top-level** `actions` array. `campaign.actions` does not exist.+5. **Read senders and segments.** `GET /v1/environments/{environment_id}/identities?type=email` for `sender_identities` (`id`, `email`, `name`), and the segment list for `segments` (`id`, `name`, `type` only). PostHog matches each email to the PostHog sender with the same address, and names the segments in its notes.+6. **Preview without templates.** Call `workflows-import-customerio` with `source: "customerio"`, `dry_run: true`, `campaigns: [{campaign, actions}]`, `sender_identities` and `segments`. Up to 50 automations per call.+7. **Read templates only if needed.** Go by each automation's notes, not by `content_fetched` alone: `true` only means PostHog read some content, and one automation can still miss its messages. For every automation whose notes say message content was not part of the import, or that PostHog could not read its messages, read the template of every action that has a `template_id` with `GET /v1/environments/{environment_id}/templates/{template_id}`, keep the `template` object, and preview again with `campaigns: [{campaign, actions, templates}]`. Read templates one at a time: listing every template in the workspace times out on large ones. Tell the user that Import from Customer.io on the Workflows Opt-outs tab stores their App API key, which skips this step next time.+8. **Collect snippets and layouts.** If a note names a Customer.io snippet, or a template body you read contains `{{ snippets.name }}`, read the workspace snippets and pass them as `snippets` (`{name: content}`). When PostHog read the content itself, it read the snippets too, and a note names any it could not find. If a note names a layout, read `GET /v1/environments/{environment_id}/layouts/{layout_id}` and pass its `body` as `layouts` (`{layout_id: body}`).+9. **Report the preview.** For each automation, give its status and its notes, grouped by level (see below). Ask before importing anything with status `failed`; its `validation_errors` say why the draft would be rejected.+10. **Import.** Call again with `dry_run: false` and the same arguments. Share each draft's link (`/workflows/{workflow_id}`) and the `needs_input` notes again, since the team must handle those before enabling.When you are unsure of an endpoint's parameters, ask for that one endpoint's schema (`cio_schema` with `resource.method`). A whole resource's schema costs tens of thousands of tokens.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 535b95754f3d..2fcb0849add5 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -16869,7 +16869,7 @@}},"workflows-import-customerio": {- "description": "Turn Customer.io automations into draft PostHog workflows. Read each automation with the Customer.io MCP or CLI first: GET /v1/environments/{environment_id}/campaigns/{campaign_id} gives `campaign` and `actions`. Pass them unchanged; never pass people or customer profiles. Leave message templates out on the first call: when the project stored a Customer.io App API key, PostHog reads the content itself and the response says content_fetched=true. For each automation whose notes still say its message content was not part of the import, read each message action's template with GET /v1/environments/{environment_id}/templates/{template_id} and pass them. Pass snippets that notes name. In a preview, a workflow_id means the import replaces that existing draft. Pass sender identities and segment ids, names and types too, never segment members. Run once with dry_run=true and show the user each automation's notes, then import for real. Drafts never send until a person enables them. Re-importing an automation replaces its draft, discarding edits made there since, so confirm with the user first. Share each draft's link and the notes marked needs_input, since the team must set those before enabling.",+ "description": "Turn Customer.io automations into draft PostHog workflows in the active project. Before the first call, tell the user the active project's name and id and ask whether the drafts belong there; switch project if not. Read each automation with the Customer.io MCP or CLI first: GET /v1/environments/{environment_id}/campaigns/{campaign_id} gives `campaign` and `actions`. Pass them unchanged; never pass people or customer profiles. Leave message templates out on the first call: when the project stored a Customer.io App API key, PostHog reads the content itself and the response says content_fetched=true. For each automation whose notes still say its message content was not part of the import, read each message action's template with GET /v1/environments/{environment_id}/templates/{template_id} and pass them. Pass snippets that notes name. In a preview, a workflow_id means the import replaces that existing draft. Pass sender identities and segment ids, names and types too, never segment members. Run once with dry_run=true and show the user each automation's notes, then import for real. Drafts never send until a person enables them. Re-importing an automation replaces its draft, discarding edits made there since, so confirm with the user first. Share each draft's link and the notes marked needs_input, since the team must set those before enabling.","category": "Workflows","feature": "workflows","summary": "Import Customer.io automations",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 402d70977758..79642a203f7e 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -17688,7 +17688,7 @@}},"workflows-import-customerio": {- "description": "Turn Customer.io automations into draft PostHog workflows. Read each automation with the Customer.io MCP or CLI first: GET /v1/environments/{environment_id}/campaigns/{campaign_id} gives `campaign` and `actions`. Pass them unchanged; never pass people or customer profiles. Leave message templates out on the first call: when the project stored a Customer.io App API key, PostHog reads the content itself and the response says content_fetched=true. For each automation whose notes still say its message content was not part of the import, read each message action's template with GET /v1/environments/{environment_id}/templates/{template_id} and pass them. Pass snippets that notes name. In a preview, a workflow_id means the import replaces that existing draft. Pass sender identities and segment ids, names and types too, never segment members. Run once with dry_run=true and show the user each automation's notes, then import for real. Drafts never send until a person enables them. Re-importing an automation replaces its draft, discarding edits made there since, so confirm with the user first. Share each draft's link and the notes marked needs_input, since the team must set those before enabling.",+ "description": "Turn Customer.io automations into draft PostHog workflows in the active project. Before the first call, tell the user the active project's name and id and ask whether the drafts belong there; switch project if not. Read each automation with the Customer.io MCP or CLI first: GET /v1/environments/{environment_id}/campaigns/{campaign_id} gives `campaign` and `actions`. Pass them unchanged; never pass people or customer profiles. Leave message templates out on the first call: when the project stored a Customer.io App API key, PostHog reads the content itself and the response says content_fetched=true. For each automation whose notes still say its message content was not part of the import, read each message action's template with GET /v1/environments/{environment_id}/templates/{template_id} and pass them. Pass snippets that notes name. In a preview, a workflow_id means the import replaces that existing draft. Pass sender identities and segment ids, names and types too, never segment members. Run once with dry_run=true and show the user each automation's notes, then import for real. Drafts never send until a person enables them. Re-importing an automation replaces its draft, discarding edits made there since, so confirm with the user first. Share each draft's link and the notes marked needs_input, since the team must set those before enabling.","category": "Workflows","feature": "workflows","summary": "Import Customer.io automations",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 0594669f6289..f8e1fec4519b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -125346,7 +125346,7 @@ export namespace Schemas {}/**- * Customer.io snippet name to its content, inlined where a message uses `{% snippet "name" %}`.+ * Customer.io snippet name to its content, inlined where a message uses `{{ snippets.name }}`. When PostHog reads the message content with a stored Customer.io App API key, it reads the snippets too.*/export type WorkflowImportRequestSnippets = {[key: string]: string};@@ -125367,7 +125367,7 @@ export namespace Schemas {source: ImportProviderKeyEnum;/** The automations to import, at most 50. People are never read from these objects. */campaigns: CustomerioCampaign[];- /** Customer.io snippet name to its content, inlined where a message uses `{% snippet "name" %}`. */+ /** Customer.io snippet name to its content, inlined where a message uses `{{ snippets.name }}`. When PostHog reads the message content with a stored Customer.io App API key, it reads the snippets too. */snippets?: WorkflowImportRequestSnippets;/** Customer.io segment id to the PostHog cohort that replaces it. Segment triggers and segment conditions with no cohort here are left for the team to set. */segment_cohorts?: WorkflowImportRequestSegmentCohorts;diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.tsindex a01bce24330f..95cbaa9d9ff0 100644--- a/services/mcp/src/generated/workflows/api.ts+++ b/services/mcp/src/generated/workflows/api.ts@@ -1520,7 +1520,9 @@ export const WorkflowImportsCreateBody = () => zod.object({snippets: zod.record(zod.string(), zod.string()).optional()- .describe('Customer.io snippet name to its content, inlined where a message uses `{% snippet \"name\" %}`.'),+ .describe(+ 'Customer.io snippet name to its content, inlined where a message uses `{{ snippets.name }}`. When PostHog reads the message content with a stored Customer.io App API key, it reads the snippets too.'+ ),segment_cohorts: zod.record(zod.string(), zod.number()).optional()