:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(marketing-analytics): add the setup_plan endpoint behind its flag (#81189)
Javier Bahamondes8c676b15fba8
diff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.pyindex 2e05eed06f4e..e39d055b08b4 100644--- a/products/marketing_analytics/backend/api.py+++ b/products/marketing_analytics/backend/api.py@@ -4,6 +4,7 @@ from functools import reducefrom operator import or_from typing import Any, Optional, cast+from django.core.cache import cachefrom django.db import transactionimport structlog@@ -35,9 +36,10 @@ from posthog.api.mixins import validated_requestfrom posthog.api.project import capture_team_config_difffrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.models.organization import OrganizationMembership-from posthog.models.team.team import DEFAULT_CURRENCY+from posthog.models.team.team import DEFAULT_CURRENCY, Teamfrom posthog.models.team.team_marketing_analytics_config import TeamMarketingAnalyticsConfigfrom posthog.models.user import User+from posthog.ph_client import feature_enabled_or_falsefrom products.marketing_analytics.backend.hogql_queries.adapters.base import ExternalConfig, QueryContextfrom products.marketing_analytics.backend.hogql_queries.adapters.factory import MarketingSourceFactory@@ -52,6 +54,7 @@ from products.marketing_analytics.backend.services.data_source_health import getfrom products.marketing_analytics.backend.services.event_suggestions import suggest_conversion_goalsfrom products.marketing_analytics.backend.services.mapping_suggester import suggest_utm_mappingsfrom products.marketing_analytics.backend.services.marketing_diagnostic import get_marketing_diagnostic+from products.marketing_analytics.backend.services.setup_plan import get_setup_planfrom products.marketing_analytics.backend.services.types import SUGGESTED_ACTION_CHOICES, UTM_ISSUE_KIND_CHOICESfrom products.marketing_analytics.backend.services.utm_audit import run_utm_auditfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable@@ -59,6 +62,26 @@ from products.warehouse_sources.backend.facade.models import DataWarehouseTablelogger = structlog.get_logger(__name__)+def _setup_enabled(team: Team) -> bool:+ """Evaluate the Setup flag once per team instance.++ Grouped on organization, matching how every other marketing-analytics flag is+ evaluated, so a team can't disagree with its org. Cached on the instance because a+ second call in the same request would fire a redundant `$feature_flag_called`.+ """+ cached = getattr(team, "_ma_setup_flag", None)+ if cached is not None:+ return cached+ enabled = feature_enabled_or_false(+ "marketing-analytics-setup",+ str(team.uuid),+ groups={"organization": str(team.organization.id)},+ group_properties={"organization": {"id": str(team.organization.id)}},+ )+ team._ma_setup_flag = enabled # type: ignore[attr-defined]+ return enabled++@extend_schema_field({"type": "array",@@ -672,6 +695,115 @@ class MarketingDiagnosticResponseSerializer(serializers.Serializer):)+class SetupPlanQuerySerializer(serializers.Serializer):+ date_from = serializers.CharField(+ required=False,+ default="-30d",+ help_text="Window for campaign spend and the UTM catalogue, as a relative range (e.g. '-30d'); defaults to -30d",+ )+ refresh = serializers.BooleanField(+ required=False,+ default=False,+ help_text="Re-run every check instead of serving a recent result. Use right after changing something.",+ )+++# The plan is roughly six ClickHouse queries deep, one of which unions every ad+# adapter, so moving between Setup sections must not re-run it. Short enough that an+# explicit rescan a minute later is genuinely fresh, and `refresh=true` skips it+# outright for the "I just changed something" case.+_SETUP_PLAN_CACHE_SECONDS = 60+++def _setup_plan_cache_key(team_id: int, user_id: int, date_from: str) -> str:+ # Keyed on the window because the same team asking about a different range is a+ # different question, and on the user because the plan is built from HogQL queries+ # run as them — `execute_hogql_query(..., user=user)` applies warehouse access+ # control, so two users can legitimately see different campaigns and spend. A+ # team-wide entry would serve the first caller's view to everyone.+ return f"marketing_analytics:setup_plan:{team_id}:{user_id}:{date_from}"+++class SuggestionSerializer(serializers.Serializer):+ id = serializers.CharField(+ help_text="Stable identifier for this finding. Deterministic across scans, so clients can dedupe and remember dismissals by it."+ )+ kind = serializers.CharField(help_text="Suggestion kind, e.g. connect_source / add_source_mapping")+ # Shadows `Field.source`, DRF's attribute-mapping name. Declaring it is fine — the+ # field is read out of the dict by its own name — but mypy sees the base annotation.+ source = serializers.CharField( # type: ignore[assignment]+ help_text="'deterministic' or 'ai' — how this suggestion was produced"+ )+ severity = serializers.CharField(help_text="error/warning/info")+ confidence = serializers.FloatField(help_text="0-1. Never 1.0: these are inferences, not proofs.")+ title = serializers.CharField(help_text="Short imperative title, e.g. 'Connect Meta Ads'")+ evidence = serializers.CharField(+ help_text="The concrete numbers behind the suggestion, so a user can sanity-check it without taking it on faith"+ )+ unlocks = serializers.ListField(+ child=serializers.CharField(),+ help_text="Capabilities this unblocks: cost, attribution, roas, cac, retention_by_channel, ltv_by_channel",+ )+ # DRF has no discriminated-union field and fighting drf-spectacular for one isn't+ # worth it. The shape is the `ApplyOp` union in `services/setup_types.py`, which is+ # where the apply endpoint validates it with a Pydantic TypeAdapter.+ apply = serializers.JSONField(+ allow_null=True,+ help_text=(+ "The operation that applies this suggestion, or null when there's nothing to automate. "+ "An object with an 'op' discriminator — see the ApplyOp union in setup_types. "+ "Pass it verbatim to apply_setup_ops; never hand-craft one."+ ),+ )+ also_recommended = serializers.ListField(+ child=serializers.JSONField(),+ help_text=(+ "Advice shown alongside the action. Mapping suggestions always carry a 'fix_platform_urls' entry, "+ "because a mapping is a workaround and correcting the ad platform's tracking template is the real fix."+ ),+ )+ safe_to_batch = serializers.BooleanField(+ help_text="True only for high-confidence, reversible operations — what an 'apply all safe' button may include"+ )+ rank_score = serializers.FloatField(help_text="Ranking score; higher first. Unblocking actions dominate.")+ integration = serializers.CharField(allow_null=True, help_text="Integration this concerns, if any")+ deep_link = serializers.CharField(allow_null=True, help_text="In-app URL to resolve this manually, if any")+ docs_url = serializers.CharField(allow_null=True, help_text="Documentation link, if any")+ spend_at_risk = serializers.FloatField(help_text="Ad spend currently mis- or un-attributed because of this")+ event_volume = serializers.IntegerField(help_text="Events affected in the window")+++class CapabilityReadinessSerializer(serializers.Serializer):+ capability = serializers.CharField(help_text="cost/attribution/roas/cac/retention_by_channel/ltv_by_channel")+ status = serializers.CharField(help_text="unlocked/partial/blocked")+ explanation = serializers.CharField(help_text="Why it's in that state, in plain English")+ blocked_by = serializers.ListField(+ child=serializers.CharField(),+ help_text="Suggestion ids that unblock this capability — the link from a blocked metric to its fixes",+ )+++class SetupPlanResponseSerializer(serializers.Serializer):+ suggestions = SuggestionSerializer(many=True, help_text="Ranked suggestions, most important first")+ readiness = CapabilityReadinessSerializer(+ many=True, help_text="Per-capability readiness, with the suggestions blocking each"+ )+ degraded = serializers.ListField(+ child=serializers.CharField(),+ help_text=(+ "Sub-services that failed. Their suggestions are missing, so do NOT present the plan as a "+ "complete clean bill of health when this is non-empty."+ ),+ )+ truncated = serializers.BooleanField(+ help_text=(+ "True when the campaign or UTM queries hit their row caps. Rates and totals are then top-N "+ "subtotals — present them as approximate rather than exact."+ )+ )+ summary = serializers.CharField(help_text="One-line summary of the plan")++class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):# `marketing_analytics` is gated by the API scope of the same name and inherits# RBAC from `web_analytics` (see RESOURCE_INHERITANCE_MAP). Custom @action methods@@ -1055,6 +1187,62 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):status=status.HTTP_500_INTERNAL_SERVER_ERROR,)+ @validated_request(+ query_serializer=SetupPlanQuerySerializer,+ responses={+ 200: OpenApiResponse(+ response=SetupPlanResponseSerializer,+ description="Ranked, machine-applicable setup suggestions plus per-capability readiness",+ ),+ 404: OpenApiResponse(description="The marketing-analytics-setup feature flag is off for this team"),+ },+ summary="Get the marketing analytics setup plan",+ description=(+ "Rank everything wrong with a team's marketing analytics setup into concrete suggestions, each "+ "carrying the evidence behind it and — where one exists — an `apply` operation to pass straight "+ "to apply_setup_ops, plus a `readiness` block saying which capabilities (cost, ROAS, cost per "+ "customer, retention by channel) are unlocked and which suggestion is blocking each. Prefer this "+ "over `diagnose` when the question is 'what should I fix next': diagnose explains what is wrong, "+ "setup_plan says what to do about it in a form you can act on. Read-only."+ ),+ )+ @action(methods=["GET"], detail=False, url_path="setup_plan", required_scopes=["marketing_analytics:read"])+ def setup_plan(self, request: Request, *args, **kwargs) -> Response:+ # 404 rather than 403: an unreleased endpoint should look absent, not forbidden.+ if not _setup_enabled(self.team):+ raise NotFound("Marketing analytics setup is not enabled for this project.")++ date_from = request.validated_query_data["date_from"]+ # `IsAuthenticated` on the viewset rules out AnonymousUser, which is the only+ # reason `.pk` is optional here.+ user = cast(User, request.user)+ cache_key = _setup_plan_cache_key(self.team.pk, user.pk, date_from)+ if not request.validated_query_data["refresh"]:+ cached = cache.get(cache_key)+ if cached is not None:+ return Response(SetupPlanResponseSerializer(cached).data)+ try:+ plan = async_to_sync(get_setup_plan)(+ self.team,+ date_from=date_from,+ user=user,+ )+ # `model_dump(mode="json")` so the Pydantic op models inside each suggestion+ # come out as plain JSON — the serializer exposes them as JSONField.+ payload = plan.model_dump(mode="json")+ # Only a complete plan is worth reusing. A degraded one is missing whole+ # checks, and caching it would keep serving those gaps for a minute after+ # whatever caused them has recovered.+ if not plan.degraded:+ cache.set(cache_key, payload, _SETUP_PLAN_CACHE_SECONDS)+ return Response(SetupPlanResponseSerializer(payload).data)+ except Exception:+ logger.exception("marketing_setup_plan_failed", team_id=self.team.pk)+ return Response(+ {"detail": "Failed to build the setup plan. Check server logs for details."},+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,+ )+@action(methods=["POST"], detail=False, url_path="test_mapping")def test_mapping(self, request: Request, *args, **kwargs) -> Response:serializer = TestMappingSerializer(data=request.data)diff --git a/products/marketing_analytics/backend/test_api_setup_plan.py b/products/marketing_analytics/backend/test_api_setup_plan.pynew file mode 100644index 000000000000..3fb8e6096253--- /dev/null+++ b/products/marketing_analytics/backend/test_api_setup_plan.py@@ -0,0 +1,250 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.core.cache import cache++from posthog.models.organization import Organization+from posthog.models.team.team import Team+from posthog.models.user import User++from products.marketing_analytics.backend.services.setup_types import (+ Capability,+ CapabilityReadiness,+ OpenSourceWizard,+ ReadinessStatus,+ SetupPlan,+ Severity,+ Suggestion,+ SuggestionKind,+)++_PLAN_TARGET = "products.marketing_analytics.backend.api.get_setup_plan"+_FLAG_TARGET = "products.marketing_analytics.backend.api.feature_enabled_or_false"+++def _plan() -> SetupPlan:+ return SetupPlan(+ suggestions=[+ Suggestion(+ id="connect_source:meta_ads",+ kind=SuggestionKind.CONNECT_SOURCE,+ severity=Severity.ERROR,+ confidence=0.95,+ title="Connect Meta Ads",+ evidence="12,480 events carry a Meta Ads utm_source but the platform isn't connected.",+ unlocks=[Capability.COST, Capability.ROAS],+ apply=OpenSourceWizard(kind="MetaAds"),+ event_volume=12480,+ )+ ],+ readiness=[+ CapabilityReadiness(+ capability=Capability.ROAS,+ status=ReadinessStatus.BLOCKED,+ explanation="Needs spend data and a conversion goal.",+ blocked_by=["connect_source:meta_ads"],+ )+ ],+ degraded=["attribution_health"],+ truncated=True,+ summary="1 suggestion(s), 1 blocking.",+ )+++class TestSetupPlanEndpoint(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.url = f"/api/projects/{self.team.pk}/marketing_analytics/setup_plan"+ cache.clear()+ flag = patch(_FLAG_TARGET, return_value=True)+ flag.start()+ self.addCleanup(flag.stop)++ def test_returns_the_plan(self):+ with patch(_PLAN_TARGET, return_value=_plan()):+ response = self.client.get(self.url)++ assert response.status_code == 200, response.json()+ body = response.json()+ assert body["summary"] == "1 suggestion(s), 1 blocking."+ assert [s["id"] for s in body["suggestions"]] == ["connect_source:meta_ads"]+ assert body["suggestions"][0]["unlocks"] == ["cost", "roas"]++ def test_apply_op_serializes_as_plain_json_with_its_discriminator(self):+ # The op has to survive the round trip verbatim: clients pass it straight back+ # to apply_setup_ops, and a Pydantic model leaking through would not be JSON.+ with patch(_PLAN_TARGET, return_value=_plan()):+ response = self.client.get(self.url)++ apply = response.json()["suggestions"][0]["apply"]+ assert apply == {"op": "open_source_wizard", "kind": "MetaAds"}++ def test_the_source_field_survives_shadowing_drfs_own(self):+ # `source` is DRF's attribute-mapping name on Field, so declaring one is easy to+ # get wrong — and a silently dropped key is how a client stops telling+ # deterministic suggestions from AI ones.+ with patch(_PLAN_TARGET, return_value=_plan()):+ response = self.client.get(self.url)++ assert response.json()["suggestions"][0]["source"] == "deterministic"++ def test_readiness_links_to_suggestion_ids(self):+ with patch(_PLAN_TARGET, return_value=_plan()):+ response = self.client.get(self.url)++ body = response.json()+ readiness = body["readiness"][0]+ assert readiness["blocked_by"] == ["connect_source:meta_ads"]+ assert set(readiness["blocked_by"]) <= {s["id"] for s in body["suggestions"]}++ def test_degraded_and_truncated_survive_serialization(self):+ # Both are how a client knows not to present the plan as exact or complete.+ with patch(_PLAN_TARGET, return_value=_plan()):+ response = self.client.get(self.url)++ body = response.json()+ assert body["degraded"] == ["attribution_health"]+ assert body["truncated"] is True++ def test_passes_the_date_range_through(self):+ with patch(_PLAN_TARGET, return_value=_plan()) as mock_plan:+ self.client.get(self.url, {"date_from": "-90d"})++ assert mock_plan.call_args.kwargs["date_from"] == "-90d"++ def test_defaults_the_date_range(self):+ with patch(_PLAN_TARGET, return_value=_plan()) as mock_plan:+ self.client.get(self.url)++ assert mock_plan.call_args.kwargs["date_from"] == "-30d"++ def test_service_failure_is_a_500_not_an_empty_plan(self):+ # An empty 200 would read as "nothing to fix", which is the one wrong answer.+ with patch(_PLAN_TARGET, side_effect=RuntimeError("clickhouse down")):+ response = self.client.get(self.url)++ assert response.status_code == 500+ assert "suggestions" not in response.json()++ def test_requires_authentication(self):+ self.client.logout()++ response = self.client.get(self.url)++ assert response.status_code in (401, 403)++ def test_cannot_read_another_organizations_team(self):+ other_org = Organization.objects.create(name="other")+ other_team = Team.objects.create(organization=other_org, name="other team")++ with patch(_PLAN_TARGET, return_value=_plan()):+ response = self.client.get(f"/api/projects/{other_team.pk}/marketing_analytics/setup_plan")++ assert response.status_code in (403, 404)+++class TestSetupPlanFeatureFlag(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.url = f"/api/projects/{self.team.pk}/marketing_analytics/setup_plan"+ cache.clear()++ def test_the_endpoint_is_absent_when_the_flag_is_off(self):+ with patch(_FLAG_TARGET, return_value=False), patch(_PLAN_TARGET, return_value=_plan()) as build:+ response = self.client.get(self.url)++ assert response.status_code == 404+ # 404 rather than 403 so an unreleased endpoint looks absent, not forbidden.+ assert build.call_count == 0++ def test_the_flag_is_evaluated_once_per_request(self):+ # A second call in the same request would fire a redundant `$feature_flag_called`.+ with patch(_FLAG_TARGET, return_value=True) as flag, patch(_PLAN_TARGET, return_value=_plan()):+ self.client.get(self.url)++ assert flag.call_count == 1++ def test_the_flag_is_grouped_on_the_organization(self):+ # Every other marketing-analytics flag is org-grouped; a team-only evaluation+ # here would let one project disagree with the rest of its org.+ with patch(_FLAG_TARGET, return_value=True) as flag, patch(_PLAN_TARGET, return_value=_plan()):+ self.client.get(self.url)++ assert flag.call_args.kwargs["groups"] == {"organization": str(self.team.organization.id)}+++def _clean_plan() -> SetupPlan:+ """A complete plan — the degraded fixture above is deliberately never cached."""+ plan = _plan()+ plan.degraded = []+ plan.truncated = False+ return plan+++class TestSetupPlanCaching(APIBaseTest):+ """The plan is ~6 ClickHouse queries deep, one unioning every ad adapter, so moving+ between Setup sections must not re-run it. Everything here is about not serving a+ plan that has stopped being true."""++ def setUp(self):+ super().setUp()+ self.url = f"/api/projects/{self.team.pk}/marketing_analytics/setup_plan"+ # locmem persists across tests in a process; a leaked entry would make these+ # pass or fail depending on ordering.+ cache.clear()+ flag = patch(_FLAG_TARGET, return_value=True)+ flag.start()+ self.addCleanup(flag.stop)++ def test_second_request_does_not_rebuild_the_plan(self):+ with patch(_PLAN_TARGET, return_value=_clean_plan()) as build:+ assert self.client.get(self.url).status_code == 200+ assert self.client.get(self.url).status_code == 200++ assert build.call_count == 1++ def test_refresh_bypasses_the_cache(self):+ with patch(_PLAN_TARGET, return_value=_clean_plan()) as build:+ self.client.get(self.url)+ self.client.get(f"{self.url}?refresh=true")++ assert build.call_count == 2++ def test_a_different_window_is_a_different_question(self):+ with patch(_PLAN_TARGET, return_value=_clean_plan()) as build:+ self.client.get(f"{self.url}?date_from=-30d")+ self.client.get(f"{self.url}?date_from=-7d")++ assert build.call_count == 2++ def test_a_degraded_plan_is_never_cached(self):+ # It's missing whole checks. Caching it would keep serving those gaps for a+ # minute after whatever caused them recovered.+ with patch(_PLAN_TARGET, return_value=_plan()) as build:+ self.client.get(self.url)+ self.client.get(self.url)++ assert build.call_count == 2++ def test_one_users_plan_is_not_served_to_another(self):+ """The plan is built from HogQL run as the caller, and `execute_hogql_query`+ applies warehouse access control from that user — so a shared entry would serve+ the first caller's campaigns, UTM values and spend to someone whose own access+ would not return them."""+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")++ with patch(_PLAN_TARGET, return_value=_clean_plan()) as build:+ self.client.get(self.url)+ self.client.force_login(other_user)+ self.client.get(self.url)++ assert build.call_count == 2++ def test_one_teams_plan_is_not_served_to_another(self):+ other = Team.objects.create(organization=self.organization, name="second")++ with patch(_PLAN_TARGET, return_value=_clean_plan()) as build:+ self.client.get(self.url)+ self.client.get(f"/api/projects/{other.pk}/marketing_analytics/setup_plan")++ assert build.call_count == 2diff --git a/products/marketing_analytics/frontend/generated/api.schemas.ts b/products/marketing_analytics/frontend/generated/api.schemas.tsindex a87e292b0c84..1990f935420e 100644--- a/products/marketing_analytics/frontend/generated/api.schemas.ts+++ b/products/marketing_analytics/frontend/generated/api.schemas.ts@@ -1465,6 +1465,76 @@ export interface GoalExplanationApi {notes: string[]}+export interface SuggestionApi {+ /** Stable identifier for this finding. Deterministic across scans, so clients can dedupe and remember dismissals by it. */+ id: string+ /** Suggestion kind, e.g. connect_source / add_source_mapping */+ kind: string+ /** 'deterministic' or 'ai' — how this suggestion was produced */+ source: string+ /** error/warning/info */+ severity: string+ /** 0-1. Never 1.0: these are inferences, not proofs. */+ confidence: number+ /** Short imperative title, e.g. 'Connect Meta Ads' */+ title: string+ /** The concrete numbers behind the suggestion, so a user can sanity-check it without taking it on faith */+ evidence: string+ /** Capabilities this unblocks: cost, attribution, roas, cac, retention_by_channel, ltv_by_channel */+ unlocks: string[]+ /** The operation that applies this suggestion, or null when there's nothing to automate. An object with an 'op' discriminator — see the ApplyOp union in setup_types. Pass it verbatim to apply_setup_ops; never hand-craft one. */+ apply: unknown+ /** Advice shown alongside the action. Mapping suggestions always carry a 'fix_platform_urls' entry, because a mapping is a workaround and correcting the ad platform's tracking template is the real fix. */+ also_recommended: unknown[]+ /** True only for high-confidence, reversible operations — what an 'apply all safe' button may include */+ safe_to_batch: boolean+ /** Ranking score; higher first. Unblocking actions dominate. */+ rank_score: number+ /**+ * Integration this concerns, if any+ * @nullable+ */+ integration: string | null+ /**+ * In-app URL to resolve this manually, if any+ * @nullable+ */+ deep_link: string | null+ /**+ * Documentation link, if any+ * @nullable+ */+ docs_url: string | null+ /** Ad spend currently mis- or un-attributed because of this */+ spend_at_risk: number+ /** Events affected in the window */+ event_volume: number+}++export interface CapabilityReadinessApi {+ /** cost/attribution/roas/cac/retention_by_channel/ltv_by_channel */+ capability: string+ /** unlocked/partial/blocked */+ status: string+ /** Why it's in that state, in plain English */+ explanation: string+ /** Suggestion ids that unblock this capability — the link from a blocked metric to its fixes */+ blocked_by: string[]+}++export interface SetupPlanResponseApi {+ /** Ranked suggestions, most important first */+ suggestions: SuggestionApi[]+ /** Per-capability readiness, with the suggestions blocking each */+ readiness: CapabilityReadinessApi[]+ /** Sub-services that failed. Their suggestions are missing, so do NOT present the plan as a complete clean bill of health when this is non-empty. */+ degraded: string[]+ /** True when the campaign or UTM queries hit their row caps. Rates and totals are then top-N subtotals — present them as approximate rather than exact. */+ truncated: boolean+ /** One-line summary of the plan */+ summary: string+}+export interface CandidateEventApi {/** Name of the candidate event */event_name: string@@ -1796,6 +1866,18 @@ export type MarketingAnalyticsExplainConversionGoalRetrieveParams = {goal_id: string}+export type MarketingAnalyticsSetupPlanRetrieveParams = {+ /**+ * Window for campaign spend and the UTM catalogue, as a relative range (e.g. '-30d'); defaults to -30d+ * @minLength 1+ */+ date_from?: string+ /**+ * Re-run every check instead of serving a recent result. Use right after changing something.+ */+ refresh?: boolean+}+export type MarketingAnalyticsSuggestConversionGoalsRetrieveParams = {/*** Minimum 30d event count to be a candidatediff --git a/products/marketing_analytics/frontend/generated/api.ts b/products/marketing_analytics/frontend/generated/api.tsindex 79604d203306..7af25f8c35e5 100644--- a/products/marketing_analytics/frontend/generated/api.ts+++ b/products/marketing_analytics/frontend/generated/api.ts@@ -18,11 +18,13 @@ import type {MarketingAnalyticsDataSourcesRetrieveParams,MarketingAnalyticsDiagnoseRetrieveParams,MarketingAnalyticsExplainConversionGoalRetrieveParams,+ MarketingAnalyticsSetupPlanRetrieveParams,MarketingAnalyticsSuggestConversionGoalsRetrieveParams,MarketingAnalyticsSuggestUtmMappingsRetrieveParams,MarketingAnalyticsUtmAuditRetrieveParams,MarketingDiagnosticResponseApi,PatchedConversionGoalUpdateApi,+ SetupPlanResponseApi,UtmAuditResponseApi,UtmMappingSuggestionsResponseApi,} from './api.schemas'@@ -218,6 +220,40 @@ export const marketingAnalyticsExplainConversionGoalRetrieve = async (})}+export const getMarketingAnalyticsSetupPlanRetrieveUrl = (+ projectId: string,+ params?: MarketingAnalyticsSetupPlanRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/marketing_analytics/setup_plan/?${stringifiedParams}`+ : `/api/projects/${projectId}/marketing_analytics/setup_plan/`+}++/**+ * Rank everything wrong with a team's marketing analytics setup into concrete suggestions, each carrying the evidence behind it and — where one exists — an `apply` operation to pass straight to apply_setup_ops, plus a `readiness` block saying which capabilities (cost, ROAS, cost per customer, retention by channel) are unlocked and which suggestion is blocking each. Prefer this over `diagnose` when the question is 'what should I fix next': diagnose explains what is wrong, setup_plan says what to do about it in a form you can act on. Read-only.+ * @summary Get the marketing analytics setup plan+ */+export const marketingAnalyticsSetupPlanRetrieve = async (+ projectId: string,+ params?: MarketingAnalyticsSetupPlanRetrieveParams,+ options?: RequestInit+): Promise<SetupPlanResponseApi> => {+ return apiMutator<SetupPlanResponseApi>(getMarketingAnalyticsSetupPlanRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getMarketingAnalyticsSuggestConversionGoalsRetrieveUrl = (projectId: string,params?: MarketingAnalyticsSuggestConversionGoalsRetrieveParamsdiff --git a/products/marketing_analytics/mcp/tools.yaml b/products/marketing_analytics/mcp/tools.yamlindex f6fe29a72603..cb7553fae098 100644--- a/products/marketing_analytics/mcp/tools.yaml+++ b/products/marketing_analytics/mcp/tools.yaml@@ -111,6 +111,9 @@ tools:come from?". Only EventsNode and ActionsNode goals are explained at the event level; DataWarehouseNode goalsshort-circuit with a note.feature_flag: marketing-analytics-mcp+ marketing-analytics-setup-plan-retrieve:+ operation: marketing_analytics_setup_plan_retrieve+ enabled: falsemarketing-analytics-suggest-conversion-goals:operation: marketing_analytics_suggest_conversion_goals_retrieveenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 1e5c8c09b214..ff43897c97f4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14625,6 +14625,17 @@ export namespace Schemas {created_at: string;}+ export interface CapabilityReadiness {+ /** cost/attribution/roas/cac/retention_by_channel/ltv_by_channel */+ capability: string;+ /** unlocked/partial/blocked */+ status: string;+ /** Why it's in that state, in plain English */+ explanation: string;+ /** Suggestion ids that unblock this capability — the link from a blocked metric to its fixes */+ blocked_by: string[];+ }+/*** Supporting evidence*/@@ -68608,6 +68619,65 @@ export namespace Schemas {enabled: boolean;}+ export interface Suggestion {+ /** Stable identifier for this finding. Deterministic across scans, so clients can dedupe and remember dismissals by it. */+ id: string;+ /** Suggestion kind, e.g. connect_source / add_source_mapping */+ kind: string;+ /** 'deterministic' or 'ai' — how this suggestion was produced */+ source: string;+ /** error/warning/info */+ severity: string;+ /** 0-1. Never 1.0: these are inferences, not proofs. */+ confidence: number;+ /** Short imperative title, e.g. 'Connect Meta Ads' */+ title: string;+ /** The concrete numbers behind the suggestion, so a user can sanity-check it without taking it on faith */+ evidence: string;+ /** Capabilities this unblocks: cost, attribution, roas, cac, retention_by_channel, ltv_by_channel */+ unlocks: string[];+ /** The operation that applies this suggestion, or null when there's nothing to automate. An object with an 'op' discriminator — see the ApplyOp union in setup_types. Pass it verbatim to apply_setup_ops; never hand-craft one. */+ apply: unknown;+ /** Advice shown alongside the action. Mapping suggestions always carry a 'fix_platform_urls' entry, because a mapping is a workaround and correcting the ad platform's tracking template is the real fix. */+ also_recommended: unknown[];+ /** True only for high-confidence, reversible operations — what an 'apply all safe' button may include */+ safe_to_batch: boolean;+ /** Ranking score; higher first. Unblocking actions dominate. */+ rank_score: number;+ /**+ * Integration this concerns, if any+ * @nullable+ */+ integration: string | null;+ /**+ * In-app URL to resolve this manually, if any+ * @nullable+ */+ deep_link: string | null;+ /**+ * Documentation link, if any+ * @nullable+ */+ docs_url: string | null;+ /** Ad spend currently mis- or un-attributed because of this */+ spend_at_risk: number;+ /** Events affected in the window */+ event_volume: number;+ }++ export interface SetupPlanResponse {+ /** Ranked suggestions, most important first */+ suggestions: Suggestion[];+ /** Per-capability readiness, with the suggestions blocking each */+ readiness: CapabilityReadiness[];+ /** Sub-services that failed. Their suggestions are missing, so do NOT present the plan as a complete clean bill of health when this is non-empty. */+ degraded: string[];+ /** True when the campaign or UTM queries hit their row caps. Rates and totals are then top-N subtotals — present them as approximate rather than exact. */+ truncated: boolean;+ /** One-line summary of the plan */+ summary: string;+ }+/*** * `trace` - trace* * `debug` - debug@@ -86686,6 +86756,18 @@ export namespace Schemas {goal_id: string;};+ export type MarketingAnalyticsSetupPlanRetrieveParams = {+ /**+ * Window for campaign spend and the UTM catalogue, as a relative range (e.g. '-30d'); defaults to -30d+ * @minLength 1+ */+ date_from?: string;+ /**+ * Re-run every check instead of serving a recent result. Use right after changing something.+ */+ refresh?: boolean;+ };+export type MarketingAnalyticsSuggestConversionGoalsRetrieveParams = {/*** Minimum 30d event count to be a candidate