: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(marketing): explain conversion goal replacement errors (#116158)
Javier Bahamondes0b197e692897
diff --git a/docs/internal/marketing-source-suggestions.md b/docs/internal/marketing-source-suggestions.mdindex 7ab48d9aa23d..fd41f9fcb46e 100644--- a/docs/internal/marketing-source-suggestions.md+++ b/docs/internal/marketing-source-suggestions.md@@ -20,6 +20,13 @@ The tool returns ranked source connection recommendations with evidence and confIt supports `refresh=true` for an explicit rescan and does not connect accounts or apply changes.Incomplete or truncated scan results must be presented as such.+## Updating conversion goals through MCP++The update tool requires `conversion_goal_id` outside the `goal` patch.+Omit `kind` for partial updates. Changing `kind` replaces the stored goal, so send the complete new definition, including its name, schema map, and target fields.+An invalid replacement returns `conversion_goal_kind_change_invalid` with the required fields in the response detail.+MCP analytics records the controlled error code and field without storing the response detail.+## Search performanceReported conversions and reported CPA require a synced ad platform source in the current search filters.diff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.pyindex 9bf8b556b7ba..01ea2df85ed0 100644--- a/products/marketing_analytics/backend/api.py+++ b/products/marketing_analytics/backend/api.py@@ -415,13 +415,15 @@ def _normalized_goal_name(name: Any) -> str | None:def _readable_pydantic_errors(error: PydanticValidationError, kind: Any = None) -> list[str]:"""Pydantic reports one error per union member, which is noise. Keep the field and the message.- Errors are preferred from the member matching the payload's `kind`: otherwise the first member- wins per field, so a data warehouse payload could be told about the events node's requirements- for a field it did send correctly.+ Errors use the member matching the payload's `kind` when it is known. Otherwise the first member+ wins per field. This keeps errors for other goal shapes out of the replacement instructions."""preferred_model = _GOAL_MODEL_BY_KIND.get(kind)seen: dict[str, str] = {}- for detail in sorted(error.errors(), key=lambda d: str(d["loc"][:1]) != str((preferred_model,))):+ details = error.errors()+ if preferred_model:+ details = [detail for detail in details if detail["loc"][:1] == (preferred_model,)]+ for detail in details:field = ".".join(str(part) for part in detail["loc"] if not str(part).startswith("ConversionGoalFilter"))seen.setdefault(field or "goal", detail["msg"])return [f"{field}: {message}" for field, message in seen.items()]@@ -1341,7 +1343,12 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):index = self._index_of(goals, conversion_goal_id)merged = self._merged_goal(goals[index], patch, conversion_goal_id)- goals[index] = self._validated_goal(merged, existing=goals, ignore_index=index)+ goals[index] = self._validated_goal(+ merged,+ existing=goals,+ ignore_index=index,+ replacing_kind=patch.get("kind") not in (None, goals[index].get("kind")),+ )self._store_goals(config, goals, previous=previous)return Response({"goal": goals[index], "conversion_goals": goals})@@ -1393,11 +1400,20 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):config = self.team.marketing_analytics_configreturn TeamMarketingAnalyticsConfig.objects.select_for_update().get(pk=config.pk)- def _validated_goal(self, goal: dict, existing: list[Any], ignore_index: int | None = None) -> dict[str, Any]:+ def _validated_goal(+ self, goal: dict, existing: list[Any], ignore_index: int | None = None, *, replacing_kind: bool = False+ ) -> dict[str, Any]:try:validated = _CONVERSION_GOAL_ADAPTER.validate_python(goal)except PydanticValidationError as e:- raise serializers.ValidationError({"goal": _readable_pydantic_errors(e, goal.get("kind"))})+ errors = _readable_pydantic_errors(e, goal.get("kind"))+ if replacing_kind:+ message = (+ "Changing kind replaces the conversion goal. Send the complete new goal, including "+ "conversion_goal_name, schema_map, and the target fields for the new kind. " + "; ".join(errors)+ )+ raise serializers.ValidationError({"goal": message}, code="conversion_goal_kind_change_invalid") from e+ raise serializers.ValidationError({"goal": errors}) from ename = goal.get("conversion_goal_name")# Normalized, because names differing only in case collide as SQL column aliases.diff --git a/products/marketing_analytics/backend/test_api_conversion_goals.py b/products/marketing_analytics/backend/test_api_conversion_goals.pyindex 9a6a4ec5463c..88c5569af8b2 100644--- a/products/marketing_analytics/backend/test_api_conversion_goals.py+++ b/products/marketing_analytics/backend/test_api_conversion_goals.py@@ -301,6 +301,26 @@ class TestConversionGoalWrites(APIBaseTest):assert "event" not in storedassert stored["conversion_goal_id"] == goal["conversion_goal_id"]+ @parameterized.expand([("ActionsNode", {"id": "7"}), ("DataWarehouseNode", {"table_name": "example_orders"})])+ def test_update_kind_requires_a_complete_replacement(self, kind: str, target: dict) -> None:+ goal = self.create_goal("Sign ups").json()["goal"]++ response = self.client.patch(+ f"{self.base_url}/{goal['conversion_goal_id']}/update",+ {"goal": {"kind": kind, **target}},+ format="json",+ )++ assert response.status_code == 400, response.json()+ body = response.json()+ assert body["code"] == "conversion_goal_kind_change_invalid"+ assert body["attr"] == "goal"+ assert "Changing kind replaces the conversion goal" in body["detail"]+ assert "conversion_goal_name: Field required" in body["detail"]+ assert "schema_map: Field required" in body["detail"]+ assert "'EventsNode'" not in body["detail"]+ assert self.stored_goals() == [goal]+def test_error_message_describes_the_shape_that_was_sent(self):response = self.client.post(f"{self.base_url}/create",diff --git a/products/marketing_analytics/mcp/tools.yaml b/products/marketing_analytics/mcp/tools.yamlindex ab730881a402..5d9792d8c573 100644--- a/products/marketing_analytics/mcp/tools.yaml+++ b/products/marketing_analytics/mcp/tools.yaml@@ -189,7 +189,11 @@ tools:Change one conversion goal in place, identified by its conversion_goal_id — callmarketing-analytics-conversion-goals first to get it. The patch goes inside a single `goal` object; only thefields you send are changed and the goal keeps its position in the list. Use this to retarget a goal, rename- it, or set counts_as_customer / counts_as_revenue on a goal that already exists.+ it, or set counts_as_customer / counts_as_revenue on a goal that already exists. Omit kind for partial+ updates. Changing kind replaces the goal: send conversion_goal_name, schema_map, and the complete target for+ the new kind (event for EventsNode; id for ActionsNode; id, table_name, id_field, timestamp_field, and+ distinct_id_field for DataWarehouseNode). Read the existing goal first and carry over the fields you want to+ keep. The conversion_goal_id belongs at the top level, outside goal.feature_flag: marketing-analytics-mcpmarketing-analytics-utm-audit:operation: marketing_analytics_utm_audit_retrievediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 7f6498db6d16..d9a2d7aff6dd 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -9463,7 +9463,7 @@"feature_flag": "marketing-analytics-mcp"},"marketing-analytics-update-conversion-goal": {- "description": "Change one conversion goal in place, identified by its conversion_goal_id — call marketing-analytics-conversion-goals first to get it. The patch goes inside a single `goal` object; only the fields you send are changed and the goal keeps its position in the list. Use this to retarget a goal, rename it, or set counts_as_customer / counts_as_revenue on a goal that already exists.",+ "description": "Change one conversion goal in place, identified by its conversion_goal_id — call marketing-analytics-conversion-goals first to get it. The patch goes inside a single `goal` object; only the fields you send are changed and the goal keeps its position in the list. Use this to retarget a goal, rename it, or set counts_as_customer / counts_as_revenue on a goal that already exists. Omit kind for partial updates. Changing kind replaces the goal: send conversion_goal_name, schema_map, and the complete target for the new kind (event for EventsNode; id for ActionsNode; id, table_name, id_field, timestamp_field, and distinct_id_field for DataWarehouseNode). Read the existing goal first and carry over the fields you want to keep. The conversion_goal_id belongs at the top level, outside goal.","category": "Marketing analytics","feature": "marketing_analytics","summary": "Update conversion goal",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 338cb4a3f9e4..75881d2955ac 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -9860,7 +9860,7 @@"feature_flag": "marketing-analytics-mcp"},"marketing-analytics-update-conversion-goal": {- "description": "Change one conversion goal in place, identified by its conversion_goal_id — call marketing-analytics-conversion-goals first to get it. The patch goes inside a single `goal` object; only the fields you send are changed and the goal keeps its position in the list. Use this to retarget a goal, rename it, or set counts_as_customer / counts_as_revenue on a goal that already exists.",+ "description": "Change one conversion goal in place, identified by its conversion_goal_id — call marketing-analytics-conversion-goals first to get it. The patch goes inside a single `goal` object; only the fields you send are changed and the goal keeps its position in the list. Use this to retarget a goal, rename it, or set counts_as_customer / counts_as_revenue on a goal that already exists. Omit kind for partial updates. Changing kind replaces the goal: send conversion_goal_name, schema_map, and the complete target for the new kind (event for EventsNode; id for ActionsNode; id, table_name, id_field, timestamp_field, and distinct_id_field for DataWarehouseNode). Read the existing goal first and carry over the fields you want to keep. The conversion_goal_id belongs at the top level, outside goal.","category": "Marketing analytics","feature": "marketing_analytics","summary": "Update conversion goal",