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(marketing-analytics): expose 7 read-only services as MCP tools (#61034)

Javier Bahamondes06f2ad575556
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 82ee2517f2d4..1521a8790ffb 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -365,6 +365,7 @@ export const FEATURE_FLAGS = {
MARKETING_ANALYTICS_AI: 'marketing-analytics-ai', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_DRILL_DOWN: 'marketing-analytics-drill-down', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_EXTENDED_DRILL_DOWN: 'marketing-analytics-extended-drill-down', // owner: @jabahamondes #team-web-analytics
+ MARKETING_ANALYTICS_MCP: 'marketing-analytics-mcp', // owner: @jabahamondes #team-web-analytics — gates MCP tool exposure (read-only marketing-analytics tools)
MARKETING_ANALYTICS_MULTI_TOUCH_ATTRIBUTION: 'marketing-analytics-multi-touch-attribution', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_UTM_AUDIT: 'marketing-analytics-utm-audit', // owner: @jabahamondes #team-web-analytics
MAX_AI_INSIGHT_SEARCH: 'max-ai-insight-search', // owner: #team-posthog-ai
diff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.py
index 1b568756e1dd..721b86eae1c1 100644
--- a/products/marketing_analytics/backend/api.py
+++ b/products/marketing_analytics/backend/api.py
@@ -1,7 +1,8 @@
from dataclasses import asdict
import structlog
-from drf_spectacular.utils import OpenApiResponse
+from asgiref.sync import async_to_sync
+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
from rest_framework import serializers, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
@@ -9,7 +10,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
-from posthog.schema import SourceMap
+from posthog.schema import DateRange, SourceMap
from posthog.hogql import ast
from posthog.hogql.query import execute_hogql_query
@@ -23,12 +24,32 @@ from products.marketing_analytics.backend.hogql_queries.adapters.base import Ext
from products.marketing_analytics.backend.hogql_queries.adapters.factory import MarketingSourceFactory
from products.marketing_analytics.backend.hogql_queries.adapters.self_managed import SelfManagedAdapter
from products.marketing_analytics.backend.hogql_queries.utils import map_url_to_provider
+from products.marketing_analytics.backend.services.conversion_goals_inspector import (
+ explain_conversion_goal,
+ list_conversion_goals,
+)
+from products.marketing_analytics.backend.services.data_source_health import get_data_source_health
+from products.marketing_analytics.backend.services.event_suggestions import suggest_conversion_goals
+from products.marketing_analytics.backend.services.mapping_suggester import suggest_utm_mappings
+from products.marketing_analytics.backend.services.marketing_diagnostic import get_marketing_diagnostic
from products.marketing_analytics.backend.services.utm_audit import run_utm_audit
from products.warehouse_sources.backend.models.table import DataWarehouseTable
logger = structlog.get_logger(__name__)
+@extend_schema_field(
+ {
+ "type": "array",
+ "prefixItems": [{"type": "string"}, {"type": "integer"}],
+ "minItems": 2,
+ "maxItems": 2,
+ }
+)
+class LabelCountField(serializers.ListField):
+ """A `[label, count]` pair — a 2-element tuple of (string, integer)."""
+
+
class TestMappingSerializer(serializers.Serializer):
table_id = serializers.UUIDField()
source_map = serializers.DictField(child=serializers.CharField(allow_null=True, allow_blank=True))
@@ -83,8 +104,374 @@ class UtmAuditResponseSerializer(serializers.Serializer):
all_utm_events = UtmEventSerializer(many=True, help_text="All UTM events with match status")
+class ConversionGoalSummarySerializer(serializers.Serializer):
+ id = serializers.CharField(help_text="Unique id of the goal (event name, action id, or DW goal id)")
+ name = serializers.CharField(help_text="Display name of the conversion goal")
+ # `kind` is a collision-prone enum name in drf-spectacular, so we expose it as a
+ # documented string rather than a ChoiceField to avoid a CI --fail-on-warn break.
+ kind = serializers.CharField(
+ help_text="Goal type — one of: EventsNode (PostHog event), ActionsNode (PostHog action), DataWarehouseNode (external table)"
+ )
+ target_label = serializers.CharField(
+ help_text="Human-readable target the goal matches (event/action name or table)"
+ )
+ last_30d_count = serializers.IntegerField(help_text="Count of matching conversion events in the last 30 days")
+ integrated_count = serializers.IntegerField(
+ allow_null=True,
+ help_text="Conversions whose utm_source matches a known integration. Null for DataWarehouseNode goals.",
+ )
+ events_without_utm_source = serializers.IntegerField(
+ allow_null=True,
+ help_text="Conversions with no utm_source at all (fix by tagging UTMs). Null for DataWarehouseNode goals.",
+ )
+ events_with_unmatched_utm_source = serializers.IntegerField(
+ allow_null=True,
+ help_text="Conversions with a utm_source that matches no integration (fix with custom_source_mappings). Null for DataWarehouseNode goals.",
+ )
+ non_integrated_count = serializers.IntegerField(
+ allow_null=True,
+ help_text="Total non-integrated conversions (without + unmatched utm_source). Null for DataWarehouseNode goals.",
+ )
+ integrated_pct = serializers.FloatField(
+ allow_null=True, help_text="Percentage of conversions that are integrated. Null for DataWarehouseNode goals."
+ )
+ is_misconfigured = serializers.BooleanField(
+ help_text="Whether the goal could not be evaluated (e.g. deleted action)"
+ )
+ misconfig_reason = serializers.CharField(allow_null=True, help_text="Explanation when is_misconfigured is true")
+ is_approximate = serializers.BooleanField(
+ help_text="True when this 30d count may differ from the dashboard's attribution-windowed number"
+ )
+ approximation_reason = serializers.CharField(allow_null=True, help_text="Explanation when is_approximate is true")
+
+
+class ConversionGoalsListResponseSerializer(serializers.Serializer):
+ goals = ConversionGoalSummarySerializer(many=True, help_text="One summary entry per configured conversion goal")
+ attribution_window_days = serializers.IntegerField(help_text="The team's configured attribution window in days")
+ attribution_mode = serializers.CharField(
+ help_text="The team's attribution model (e.g. last_touch, first_touch, linear)"
+ )
+ has_misconfigured = serializers.BooleanField(help_text="True if any goal is misconfigured")
+
+
+# --- list_data_sources ---
+
+
+class DataSourcesQuerySerializer(serializers.Serializer):
+ source_type = serializers.CharField(
+ required=False,
+ default=None,
+ allow_null=True,
+ help_text="Optional. Restrict to one integration (e.g. 'GoogleAds').",
+ )
+
+
+class RequiredTableStatusSerializer(serializers.Serializer):
+ table_name = serializers.CharField(
+ help_text="Name of the required source table (e.g. 'campaign', 'campaign_stats')"
+ )
+ present = serializers.BooleanField(help_text="Whether the table exists as a schema on the connected source")
+ should_sync = serializers.BooleanField(help_text="Whether the table is enabled for sync")
+ status = serializers.CharField(
+ allow_null=True,
+ help_text="ExternalDataSchema status: Completed/Running/Failed/Paused/Cancelled, or null",
+ )
+ last_synced_at = serializers.DateTimeField(allow_null=True, help_text="When this table last completed a sync")
+
+
+class DataSourceHealthEntrySerializer(serializers.Serializer):
+ source_type = serializers.CharField(help_text="External data source type key (e.g. 'GoogleAds', 'MetaAds')")
+ is_native = serializers.BooleanField(help_text="Whether this is a native marketing integration")
+ display_name = serializers.CharField(help_text="Human-readable integration name (e.g. 'Google Ads')")
+ connected = serializers.BooleanField(help_text="Whether a live source of this type is connected")
+ last_sync_at = serializers.DateTimeField(allow_null=True, help_text="When the source last completed a sync")
+ last_sync_status = serializers.CharField(help_text="Sync status: ok/error/stale/tables_failed/not_connected/never")
+ last_error = serializers.CharField(allow_null=True, help_text="Latest unresolved sync error message, if any")
+ rows_last_24h = serializers.IntegerField(help_text="Rows synced in the last 24 hours")
+ rows_last_7d = serializers.IntegerField(help_text="Rows synced in the last 7 days")
+ sources_map_present = serializers.BooleanField(help_text="Whether a column mapping exists for this source")
+ schema_columns_mapped = serializers.ListField(
+ child=serializers.CharField(), help_text="Schema columns currently mapped for this source"
+ )
+ schema_columns_required_missing = serializers.ListField(
+ child=serializers.CharField(), help_text="Required schema columns that are not yet mapped"
+ )
+ required_tables = RequiredTableStatusSerializer(
+ many=True, help_text="Per-required-table sync status for this integration"
+ )
+ settings_url = serializers.CharField(help_text="URL to the Marketing analytics global settings page")
+ schemas_url = serializers.CharField(
+ allow_null=True, help_text="URL to the per-source Schemas tab, or null if not connected"
+ )
+ diagnosis = serializers.CharField(help_text="Human-readable diagnosis of this source's health")
+ fix_suggestion = serializers.CharField(allow_null=True, help_text="Suggested fix when the source is unhealthy")
+
+
+class DataSourceHealthResponseSerializer(serializers.Serializer):
+ integrations = DataSourceHealthEntrySerializer(many=True, help_text="One health entry per native integration")
+ has_any_data = serializers.BooleanField(help_text="True if any integration synced rows in the last 7 days")
+ overall_status = serializers.CharField(help_text="Overall: healthy/degraded/broken/no_sources")
+ issues_summary = serializers.ListField(
+ child=serializers.CharField(), help_text="Short human-readable summary of detected issues"
+ )
+
+
+# --- explain_conversion_goal ---
+
+
+class ExplainConversionGoalQuerySerializer(serializers.Serializer):
+ goal_id = serializers.CharField(
+ required=True, help_text="Id of the conversion goal to explain (from list_conversion_goals)."
+ )
+ date_from = serializers.CharField(
+ required=False, default=None, allow_null=True, help_text="ISO start; defaults to 30 days ago"
+ )
+ date_to = serializers.CharField(required=False, default=None, allow_null=True, help_text="ISO end; defaults to now")
+
+
+class GoalEventSampleSerializer(serializers.Serializer):
+ event_uuid = serializers.CharField(help_text="UUID of the sampled conversion event")
+ timestamp = serializers.DateTimeField(help_text="When the event occurred")
+ distinct_id = serializers.CharField(help_text="Distinct id associated with the event")
+ utm_source = serializers.CharField(allow_null=True, help_text="utm_source value on the event, if any")
+ utm_campaign = serializers.CharField(allow_null=True, help_text="utm_campaign value on the event, if any")
+ matched_integration = serializers.CharField(allow_null=True, help_text="Integration the utm_source matched, if any")
+
+
+class GoalExplanationPeriodSerializer(serializers.Serializer):
+ date_from = serializers.CharField(allow_null=True, help_text="Start of the analyzed period (ISO)")
+ date_to = serializers.CharField(allow_null=True, help_text="End of the analyzed period (ISO)")
+
+
+class GoalExplanationSerializer(serializers.Serializer):
+ goal_id = serializers.CharField(help_text="Id of the explained conversion goal")
+ goal_name = serializers.CharField(help_text="Display name of the conversion goal")
+ kind = serializers.CharField(help_text="EventsNode/ActionsNode/DataWarehouseNode")
+ period = GoalExplanationPeriodSerializer(help_text="The period the breakdown was computed over")
+ total_count = serializers.IntegerField(help_text="Total matching conversion events in the period")
+ integrated_count = serializers.IntegerField(
+ allow_null=True, help_text="Events whose utm_source matched a known integration. Null for DataWarehouseNode."
+ )
+ events_without_utm_source = serializers.IntegerField(
+ allow_null=True, help_text="Events with no utm_source at all. Null for DataWarehouseNode."
+ )
+ events_with_unmatched_utm_source = serializers.IntegerField(
+ allow_null=True, help_text="Events with a utm_source matching no integration. Null for DataWarehouseNode."
+ )
+ non_integrated_count = serializers.IntegerField(
+ allow_null=True, help_text="Total non-integrated events (without + unmatched). Null for DataWarehouseNode."
+ )
+ by_event = serializers.ListField(child=LabelCountField(), help_text="List of [event_name, count] pairs")
+ by_utm_source = serializers.ListField(child=LabelCountField(), help_text="List of [utm_source, count] pairs")
+ by_matched_integration = serializers.ListField(
+ child=LabelCountField(), help_text="List of [integration, count] pairs"
+ )
+ samples = GoalEventSampleSerializer(many=True, help_text="A small sample of matching events")
+ notes = serializers.ListField(
+ child=serializers.CharField(), help_text="Caveats about the breakdown (sampling, attribution, etc.)"
+ )
+
+
+# --- suggest_conversion_goals ---
+
+
+class SuggestConversionGoalsQuerySerializer(serializers.Serializer):
+ top_n = serializers.IntegerField(required=False, default=10, help_text="Max candidates to return")
+ min_count = serializers.IntegerField(
+ required=False, default=50, help_text="Minimum 30d event count to be a candidate"
+ )
+
+
+class CandidateEventSerializer(serializers.Serializer):
+ event_name = serializers.CharField(help_text="Name of the candidate event")
+ last_30d_count = serializers.IntegerField(help_text="Count of this event in the last 30 days")
+ distinct_users_30d = serializers.IntegerField(help_text="Distinct users who triggered the event in 30 days")
+ pct_with_utm_source = serializers.FloatField(help_text="Percentage of events that carry a utm_source")
+ pct_with_utm_campaign = serializers.FloatField(help_text="Percentage of events that carry a utm_campaign")
+ top_utm_sources = serializers.ListField(child=LabelCountField(), help_text="List of [utm_source, count] pairs")
+ is_already_a_goal = serializers.BooleanField(help_text="Whether this event is already configured as a goal")
+ suggestion_score = serializers.FloatField(help_text="Ranking score (higher is a stronger candidate)")
+ suggestion_reason = serializers.CharField(help_text="Human-readable rationale for the suggestion")
+
+
+class EventSuggestionsResponseSerializer(serializers.Serializer):
+ candidates = CandidateEventSerializer(many=True, help_text="Ranked candidate events for conversion goals")
+ lookback_days = serializers.IntegerField(help_text="Lookback window in days used for the analysis")
+ excluded_events_count = serializers.IntegerField(help_text="Number of system/autocaptured events excluded")
+
+
+# --- suggest_utm_mappings ---
+
+
+class SuggestUtmMappingsQuerySerializer(serializers.Serializer):
+ min_event_count = serializers.IntegerField(
+ required=False, default=10, help_text="Only suggest for raw values with >= this many events"
+ )
+ lookback_days = serializers.IntegerField(
+ required=False,
+ default=90,
+ min_value=1,
+ max_value=365,
+ help_text="Days of history to inspect (1-365); defaults to 90",
+ )
+
+
+class SourceMappingSuggestionSerializer(serializers.Serializer):
+ raw_utm_source = serializers.CharField(help_text="The raw utm_source value seen on events")
+ suggested_target = serializers.CharField(help_text="Integration key it maps to")
+ suggested_target_display_name = serializers.CharField(help_text="Human-readable name of the suggested integration")
+ reason = serializers.CharField(help_text="Why this mapping is suggested")
+
+
+class CampaignMappingSuggestionSerializer(serializers.Serializer):
+ integration = serializers.CharField(help_text="Integration key the campaign values belong to")
+ integration_display_name = serializers.CharField(help_text="Human-readable integration name")
+ suggested_clean_name = serializers.CharField(help_text="Proposed canonical campaign name")
+ raw_campaign_values = serializers.ListField(
+ child=serializers.CharField(), help_text="Raw campaign values clustered under this clean name"
+ )
+ confidence = serializers.FloatField(help_text="Confidence score for the clustering (0-1)")
+ method = serializers.CharField(help_text="Mapping method")
+ reason = serializers.CharField(help_text="Why these campaign values were clustered together")
+
+
+class RawUnmatchedSampleSerializer(serializers.Serializer):
+ raw_utm_source = serializers.CharField(help_text="A raw utm_source value matching no integration")
+ event_count = serializers.IntegerField(help_text="Number of events with this raw value in the window")
+ suggested_integration = serializers.CharField(
+ allow_null=True, help_text="Integration suggested by token match, if any"
+ )
+
+
+class CurrentMappingSerializer(serializers.Serializer):
+ raw_utm_source = serializers.CharField(help_text="A utm_source value already mapped to an integration")
+ target = serializers.CharField(help_text="Integration key it maps to")
+ target_display_name = serializers.CharField(help_text="Human-readable name of the target integration")
+ source = serializers.CharField(help_text="canonical or team_custom") # type: ignore[assignment]
+
+
+class CatalogueEntrySerializer(serializers.Serializer):
+ raw_utm_source = serializers.CharField(help_text="A raw utm_source value seen in the window")
+ event_count = serializers.IntegerField(help_text="Number of events with this value")
+ matched_integration = serializers.CharField(
+ allow_null=True, help_text="Integration this value exactly matches, if any"
+ )
+ matched_integration_display_name = serializers.CharField(
+ allow_null=True, help_text="Human-readable name of the matched integration, if any"
+ )
+ suggested_integration = serializers.CharField(
+ allow_null=True, help_text="Integration suggested by token match, if any"
+ )
+
+
+class UtmMappingSuggestionsResponseSerializer(serializers.Serializer):
+ source_suggestions = SourceMappingSuggestionSerializer(
+ many=True, help_text="Suggested custom_source_mappings entries"
+ )
+ campaign_suggestions = CampaignMappingSuggestionSerializer(
+ many=True, help_text="Suggested campaign-name clusters (empty in v1)"
+ )
+ raw_unmatched_samples = RawUnmatchedSampleSerializer(
+ many=True, help_text="All unmatched raw utm_source values worth reviewing"
+ )
+ full_utm_source_catalogue = CatalogueEntrySerializer(
+ many=True, help_text="Every utm_source value seen in the window, matched or not"
+ )
+ current_mappings = CurrentMappingSerializer(
+ many=True, help_text="Mappings already in effect (canonical + team_custom)"
+ )
+ total_unmatched_events_in_window = serializers.IntegerField(help_text="Total events with an unmatched utm_source")
+ total_events_with_utm_in_window = serializers.IntegerField(help_text="Total events with any utm_source")
+ lookback_days_used = serializers.IntegerField(help_text="Lookback window in days used for the analysis")
+ notes = serializers.ListField(child=serializers.CharField(), help_text="Caveats and guidance about the suggestions")
+
+
+# --- diagnose ---
+
+
+class DiagnoseQuerySerializer(serializers.Serializer):
+ source_type = serializers.CharField(
+ required=False, default=None, allow_null=True, help_text="Optional integration filter"
+ )
+ include_conversion_goals = serializers.BooleanField(
+ required=False, default=True, help_text="Whether to include the conversion-goal summary in the diagnostic"
+ )
+ attribution_lookback_days = serializers.IntegerField(
+ required=False,
+ default=7,
+ min_value=1,
+ max_value=365,
+ help_text="Lookback window for attribution health (1-365 days); defaults to 7",
+ )
+
+
+class RecommendedActionSerializer(serializers.Serializer):
+ title = serializers.CharField(help_text="Short title of the recommended action")
+ detail = serializers.CharField(help_text="Detailed explanation of the action")
+ severity = serializers.CharField(help_text="Action severity")
+ target_tool = serializers.CharField(allow_null=True, help_text="Follow-up tool to call next, if any")
+
+
+class UnmatchedUtmSampleSerializer(serializers.Serializer):
+ raw_value = serializers.CharField(help_text="A raw utm_source value that doesn't match the integration exactly")
+ event_count = serializers.IntegerField(help_text="Number of events with this raw value in the window")
+ suggested_integration = serializers.CharField(
+ allow_null=True, help_text="Integration suggested by token match, if any"
+ )
+
+
+class AttributionHealthEntrySerializer(serializers.Serializer):
+ integration_key = serializers.CharField(help_text="Integration key (e.g. 'google', 'meta')")
+ display_name = serializers.CharField(help_text="Human-readable integration name")
+ events_with_utm_last_7d = serializers.IntegerField(help_text="Total events with any utm_source in the window")
+ events_matched_last_7d = serializers.IntegerField(help_text="Events whose utm_source matched this integration")
+ events_unmatched_likely_yours_last_7d = serializers.IntegerField(
+ help_text="Events that look like this integration's but don't match exactly"
+ )
+ last_event_with_matching_utm_at = serializers.DateTimeField(
+ allow_null=True, help_text="Timestamp of the most recent matched event"
+ )
+ matched_pct = serializers.FloatField(help_text="Percentage of UTM events matched to this integration")
+ sample_unmatched_utm_sources = UnmatchedUtmSampleSerializer(
+ many=True, help_text="Sample of likely-yours unmatched utm_source values"
+ )
+
+
+class IntegrationDiagnosticSerializer(serializers.Serializer):
+ integration_key = serializers.CharField(help_text="Integration key (e.g. 'google', 'meta')")
+ source_type = serializers.CharField(help_text="External data source type key (e.g. 'GoogleAds')")
+ display_name = serializers.CharField(help_text="Human-readable integration name")
+ overall_status = serializers.CharField(help_text="Per-integration status")
+ diagnosis = serializers.CharField(help_text="Human-readable cross-domain diagnosis")
+ data_source = DataSourceHealthEntrySerializer(
+ allow_null=True, required=False, help_text="Data-source (sync) side health, or null if not connected"
+ )
+ attribution = AttributionHealthEntrySerializer(
+ allow_null=True, required=False, help_text="Attribution (UTM events) side health, or null if no data"
+ )
+ recommended_actions = RecommendedActionSerializer(
+ many=True, help_text="Recommended next steps for this integration"
+ )
+
+
+class MarketingDiagnosticResponseSerializer(serializers.Serializer):
+ integrations = IntegrationDiagnosticSerializer(many=True, help_text="Per-integration cross-domain diagnostics")
+ overall_status = serializers.CharField(help_text="healthy/degraded/broken/no_sources")
+ summary = serializers.CharField(help_text="One-line plain-English summary of the diagnostic")
+ conversion_goals = ConversionGoalsListResponseSerializer(
+ allow_null=True, required=False, help_text="Conversion goal summary, when requested"
+ )
+ recommended_actions = RecommendedActionSerializer(
+ many=True, help_text="Top global recommended actions across all integrations"
+ )
+
+
class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
- scope_object = "INTERNAL"
+ # `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
+ # below are not standard CRUD names, so each declares its own `required_scopes`;
+ # actions without it stay session-only (not reachable via API key / OAuth / MCP).
+ scope_object = "marketing_analytics"
serializer_class = _FallbackSerializer
permission_classes = [IsAuthenticated]
@@ -96,7 +483,7 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
summary="Run UTM audit",
description="Cross-reference campaigns with spend from ad platforms against pageview events with UTM parameters to identify tracking issues.",
)
- @action(methods=["GET"], detail=False, url_path="utm_audit")
+ @action(methods=["GET"], detail=False, url_path="utm_audit", required_scopes=["marketing_analytics:read"])
def utm_audit(self, request: Request, *args, **kwargs) -> Response:
date_from = request.validated_query_data["date_from"]
date_to = request.validated_query_data["date_to"]
@@ -112,6 +499,170 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
+ @extend_schema(
+ responses={
+ 200: OpenApiResponse(
+ response=ConversionGoalsListResponseSerializer,
+ description="Configured conversion goals with last-30d performance",
+ ),
+ },
+ summary="List conversion goals",
+ description="Read the configured conversion goals for the current project — each with its kind, target, last-30d count, integrated vs non-integrated split, and a misconfiguration flag. Read-only.",
+ )
+ @action(methods=["GET"], detail=False, url_path="conversion_goals", required_scopes=["marketing_analytics:read"])
+ def conversion_goals(self, request: Request, *args, **kwargs) -> Response:
+ try:
+ response = async_to_sync(list_conversion_goals)(self.team)
+ return Response(ConversionGoalsListResponseSerializer(response.to_dict()).data)
+ except Exception:
+ logger.exception("list_conversion_goals_failed", team_id=self.team.pk)
+ return Response(
+ {"detail": "Failed to list conversion goals. Check server logs for details."},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
+ @validated_request(
+ query_serializer=DataSourcesQuerySerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=DataSourceHealthResponseSerializer,
+ description="Per-integration data-source (sync) health",
+ ),
+ },
+ summary="List marketing data sources",
+ description="Check the platform → data-warehouse side of every native marketing integration: connection state, sync recency, row counts, required-table status, and schema-mapping coverage. Read-only.",
+ )
+ @action(methods=["GET"], detail=False, url_path="data_sources", required_scopes=["marketing_analytics:read"])
+ def list_data_sources(self, request: Request, *args, **kwargs) -> Response:
+ source_type = request.validated_query_data["source_type"]
+ try:
+ response = async_to_sync(get_data_source_health)(self.team, source_type=source_type)
+ return Response(DataSourceHealthResponseSerializer(response.to_dict()).data)
+ except Exception:
+ logger.exception("list_data_sources_failed", team_id=self.team.pk, source_type=source_type)
+ return Response(
+ {"detail": "Failed to list marketing data sources. Check server logs for details."},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
+ @validated_request(
+ query_serializer=ExplainConversionGoalQuerySerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=GoalExplanationSerializer,
+ description="Per-event breakdown of a single conversion goal",
+ ),
+ },
+ summary="Explain a conversion goal",
+ description="Break down a single conversion goal's events over a period by event name, utm_source, and matched integration, with a small sample of events. Read-only.",
+ )
+ @action(
+ methods=["GET"], detail=False, url_path="explain_conversion_goal", required_scopes=["marketing_analytics:read"]
+ )
+ def explain_conversion_goal(self, request: Request, *args, **kwargs) -> Response:
+ goal_id = request.validated_query_data["goal_id"]
+ date_from = request.validated_query_data["date_from"]
+ date_to = request.validated_query_data["date_to"]
+ period = DateRange(date_from=date_from, date_to=date_to) if (date_from or date_to) else None
+ try:
+ response = async_to_sync(explain_conversion_goal)(self.team, goal_id, period=period)
+ return Response(GoalExplanationSerializer(response.to_dict()).data)
+ except ValueError as exc:
+ return Response({"detail": str(exc)}, status=status.HTTP_404_NOT_FOUND)
+ except Exception:
+ logger.exception("explain_conversion_goal_failed", team_id=self.team.pk, goal_id=goal_id)
+ return Response(
+ {"detail": "Failed to explain conversion goal. Check server logs for details."},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
+ @validated_request(
+ query_serializer=SuggestConversionGoalsQuerySerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=EventSuggestionsResponseSerializer,
+ description="Ranked candidate events for conversion goals",
+ ),
+ },
+ summary="Suggest conversion goals",
+ description="Rank existing custom events as conversion-goal candidates by volume, UTM-tag coverage, and unique users, excluding system/autocaptured events. Read-only.",
+ )
+ @action(
+ methods=["GET"], detail=False, url_path="suggest_conversion_goals", required_scopes=["marketing_analytics:read"]
+ )
+ def suggest_conversion_goals(self, request: Request, *args, **kwargs) -> Response:
+ top_n = request.validated_query_data["top_n"]
+ min_count = request.validated_query_data["min_count"]
+ try:
+ response = async_to_sync(suggest_conversion_goals)(self.team, top_n=top_n, min_count=min_count)
+ return Response(EventSuggestionsResponseSerializer(response.to_dict()).data)
+ except Exception:
+ logger.exception("suggest_conversion_goals_failed", team_id=self.team.pk)
+ return Response(
+ {"detail": "Failed to suggest conversion goals. Check server logs for details."},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
+ @validated_request(
+ query_serializer=SuggestUtmMappingsQuerySerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=UtmMappingSuggestionsResponseSerializer,
+ description="Suggested utm_source → integration mappings",
+ ),
+ },
+ summary="Suggest UTM source mappings",
+ description="Detect unmatched utm_source values from recent events and propose custom_source_mappings entries, alongside the full utm_source catalogue and current mappings. Read-only.",
+ )
+ @action(
+ methods=["GET"], detail=False, url_path="suggest_utm_mappings", required_scopes=["marketing_analytics:read"]
+ )
+ def suggest_utm_mappings(self, request: Request, *args, **kwargs) -> Response:
+ min_event_count = request.validated_query_data["min_event_count"]
+ lookback_days = request.validated_query_data["lookback_days"]
+ try:
+ response = async_to_sync(suggest_utm_mappings)(
+ self.team, min_event_count=min_event_count, lookback_days=lookback_days
+ )
+ return Response(UtmMappingSuggestionsResponseSerializer(response.to_dict()).data)
+ except Exception:
+ logger.exception("suggest_utm_mappings_failed", team_id=self.team.pk)
+ return Response(
+ {"detail": "Failed to suggest UTM mappings. Check server logs for details."},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
+ @validated_request(
+ query_serializer=DiagnoseQuerySerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=MarketingDiagnosticResponseSerializer,
+ description="End-to-end marketing analytics diagnostic",
+ ),
+ },
+ summary="Diagnose marketing analytics",
+ description="Aggregate data-source sync health, UTM attribution health, and conversion-goal config into a single per-integration diagnostic with recommended actions. Read-only.",
+ )
+ @action(methods=["GET"], detail=False, url_path="diagnose", required_scopes=["marketing_analytics:read"])
+ def diagnose(self, request: Request, *args, **kwargs) -> Response:
+ source_type = request.validated_query_data["source_type"]
+ include_conversion_goals = request.validated_query_data["include_conversion_goals"]
+ attribution_lookback_days = request.validated_query_data["attribution_lookback_days"]
+ try:
+ response = async_to_sync(get_marketing_diagnostic)(
+ self.team,
+ source_type=source_type,
+ include_conversion_goals=include_conversion_goals,
+ attribution_lookback_days=attribution_lookback_days,
+ )
+ return Response(MarketingDiagnosticResponseSerializer(response.to_dict()).data)
+ except Exception:
+ logger.exception("marketing_diagnose_failed", team_id=self.team.pk, source_type=source_type)
+ return Response(
+ {"detail": "Failed to run marketing diagnostic. 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/frontend/generated/api.schemas.ts b/products/marketing_analytics/frontend/generated/api.schemas.ts
index 3aff1e63ad15..1bfaa4cdc25e 100644
--- a/products/marketing_analytics/frontend/generated/api.schemas.ts
+++ b/products/marketing_analytics/frontend/generated/api.schemas.ts
@@ -7,6 +7,432 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+export interface ConversionGoalSummaryApi {
+ /** Unique id of the goal (event name, action id, or DW goal id) */
+ id: string
+ /** Display name of the conversion goal */
+ name: string
+ /** Goal type — one of: EventsNode (PostHog event), ActionsNode (PostHog action), DataWarehouseNode (external table) */
+ kind: string
+ /** Human-readable target the goal matches (event/action name or table) */
+ target_label: string
+ /** Count of matching conversion events in the last 30 days */
+ last_30d_count: number
+ /**
+ * Conversions whose utm_source matches a known integration. Null for DataWarehouseNode goals.
+ * @nullable
+ */
+ integrated_count: number | null
+ /**
+ * Conversions with no utm_source at all (fix by tagging UTMs). Null for DataWarehouseNode goals.
+ * @nullable
+ */
+ events_without_utm_source: number | null
+ /**
+ * Conversions with a utm_source that matches no integration (fix with custom_source_mappings). Null for DataWarehouseNode goals.
+ * @nullable
+ */
+ events_with_unmatched_utm_source: number | null
+ /**
+ * Total non-integrated conversions (without + unmatched utm_source). Null for DataWarehouseNode goals.
+ * @nullable
+ */
+ non_integrated_count: number | null
+ /**
+ * Percentage of conversions that are integrated. Null for DataWarehouseNode goals.
+ * @nullable
+ */
+ integrated_pct: number | null
+ /** Whether the goal could not be evaluated (e.g. deleted action) */
+ is_misconfigured: boolean
+ /**
+ * Explanation when is_misconfigured is true
+ * @nullable
+ */
+ misconfig_reason: string | null
+ /** True when this 30d count may differ from the dashboard's attribution-windowed number */
+ is_approximate: boolean
+ /**
+ * Explanation when is_approximate is true
+ * @nullable
+ */
+ approximation_reason: string | null
+}
+
+export interface ConversionGoalsListResponseApi {
+ /** One summary entry per configured conversion goal */
+ goals: ConversionGoalSummaryApi[]
+ /** The team's configured attribution window in days */
+ attribution_window_days: number
+ /** The team's attribution model (e.g. last_touch, first_touch, linear) */
+ attribution_mode: string
+ /** True if any goal is misconfigured */
+ has_misconfigured: boolean
+}
+
+export interface RequiredTableStatusApi {
+ /** Name of the required source table (e.g. 'campaign', 'campaign_stats') */
+ table_name: string
+ /** Whether the table exists as a schema on the connected source */
+ present: boolean
+ /** Whether the table is enabled for sync */
+ should_sync: boolean
+ /**
+ * ExternalDataSchema status: Completed/Running/Failed/Paused/Cancelled, or null
+ * @nullable
+ */
+ status: string | null
+ /**
+ * When this table last completed a sync
+ * @nullable
+ */
+ last_synced_at: string | null
+}
+
+export interface DataSourceHealthEntryApi {
+ /** External data source type key (e.g. 'GoogleAds', 'MetaAds') */
+ source_type: string
+ /** Whether this is a native marketing integration */
+ is_native: boolean
+ /** Human-readable integration name (e.g. 'Google Ads') */
+ display_name: string
+ /** Whether a live source of this type is connected */
+ connected: boolean
+ /**
+ * When the source last completed a sync
+ * @nullable
+ */
+ last_sync_at: string | null
+ /** Sync status: ok/error/stale/tables_failed/not_connected/never */
+ last_sync_status: string
+ /**
+ * Latest unresolved sync error message, if any
+ * @nullable
+ */
+ last_error: string | null
+ /** Rows synced in the last 24 hours */
+ rows_last_24h: number
+ /** Rows synced in the last 7 days */
+ rows_last_7d: number
+ /** Whether a column mapping exists for this source */
+ sources_map_present: boolean
+ /** Schema columns currently mapped for this source */
+ schema_columns_mapped: string[]
+ /** Required schema columns that are not yet mapped */
+ schema_columns_required_missing: string[]
+ /** Per-required-table sync status for this integration */
+ required_tables: RequiredTableStatusApi[]
+ /** URL to the Marketing analytics global settings page */
+ settings_url: string
+ /**
+ * URL to the per-source Schemas tab, or null if not connected
+ * @nullable
+ */
+ schemas_url: string | null
+ /** Human-readable diagnosis of this source's health */
+ diagnosis: string
+ /**
+ * Suggested fix when the source is unhealthy
+ * @nullable
+ */
+ fix_suggestion: string | null
+}
+
+export interface DataSourceHealthResponseApi {
+ /** One health entry per native integration */
+ integrations: DataSourceHealthEntryApi[]
+ /** True if any integration synced rows in the last 7 days */
+ has_any_data: boolean
+ /** Overall: healthy/degraded/broken/no_sources */
+ overall_status: string
+ /** Short human-readable summary of detected issues */
+ issues_summary: string[]
+}
+
+export interface UnmatchedUtmSampleApi {
+ /** A raw utm_source value that doesn't match the integration exactly */
+ raw_value: string
+ /** Number of events with this raw value in the window */
+ event_count: number
+ /**
+ * Integration suggested by token match, if any
+ * @nullable
+ */
+ suggested_integration: string | null
+}
+
+export interface AttributionHealthEntryApi {
+ /** Integration key (e.g. 'google', 'meta') */
+ integration_key: string
+ /** Human-readable integration name */
+ display_name: string
+ /** Total events with any utm_source in the window */
+ events_with_utm_last_7d: number
+ /** Events whose utm_source matched this integration */
+ events_matched_last_7d: number
+ /** Events that look like this integration's but don't match exactly */
+ events_unmatched_likely_yours_last_7d: number
+ /**
+ * Timestamp of the most recent matched event
+ * @nullable
+ */
+ last_event_with_matching_utm_at: string | null
+ /** Percentage of UTM events matched to this integration */
+ matched_pct: number
+ /** Sample of likely-yours unmatched utm_source values */
+ sample_unmatched_utm_sources: UnmatchedUtmSampleApi[]
+}
+
+export interface RecommendedActionApi {
+ /** Short title of the recommended action */
+ title: string
+ /** Detailed explanation of the action */
+ detail: string
+ /** Action severity */
+ severity: string
+ /**
+ * Follow-up tool to call next, if any
+ * @nullable
+ */
+ target_tool: string | null
+}
+
+export interface IntegrationDiagnosticApi {
+ /** Integration key (e.g. 'google', 'meta') */
+ integration_key: string
+ /** External data source type key (e.g. 'GoogleAds') */
+ source_type: string
+ /** Human-readable integration name */
+ display_name: string
+ /** Per-integration status */
+ overall_status: string
+ /** Human-readable cross-domain diagnosis */
+ diagnosis: string
+ /** Data-source (sync) side health, or null if not connected */
+ data_source?: DataSourceHealthEntryApi | null
+ /** Attribution (UTM events) side health, or null if no data */
+ attribution?: AttributionHealthEntryApi | null
+ /** Recommended next steps for this integration */
+ recommended_actions: RecommendedActionApi[]
+}
+
+export interface MarketingDiagnosticResponseApi {
+ /** Per-integration cross-domain diagnostics */
+ integrations: IntegrationDiagnosticApi[]
+ /** healthy/degraded/broken/no_sources */
+ overall_status: string
+ /** One-line plain-English summary of the diagnostic */
+ summary: string
+ /** Conversion goal summary, when requested */
+ conversion_goals?: ConversionGoalsListResponseApi | null
+ /** Top global recommended actions across all integrations */
+ recommended_actions: RecommendedActionApi[]
+}
+
+export interface GoalExplanationPeriodApi {
+ /**
+ * Start of the analyzed period (ISO)
+ * @nullable
+ */
+ date_from: string | null
+ /**
+ * End of the analyzed period (ISO)
+ * @nullable
+ */
+ date_to: string | null
+}
+
+export interface GoalEventSampleApi {
+ /** UUID of the sampled conversion event */
+ event_uuid: string
+ /** When the event occurred */
+ timestamp: string
+ /** Distinct id associated with the event */
+ distinct_id: string
+ /**
+ * utm_source value on the event, if any
+ * @nullable
+ */
+ utm_source: string | null
+ /**
+ * utm_campaign value on the event, if any
+ * @nullable
+ */
+ utm_campaign: string | null
+ /**
+ * Integration the utm_source matched, if any
+ * @nullable
+ */
+ matched_integration: string | null
+}
+
+export interface GoalExplanationApi {
+ /** Id of the explained conversion goal */
+ goal_id: string
+ /** Display name of the conversion goal */
+ goal_name: string
+ /** EventsNode/ActionsNode/DataWarehouseNode */
+ kind: string
+ /** The period the breakdown was computed over */
+ period: GoalExplanationPeriodApi
+ /** Total matching conversion events in the period */
+ total_count: number
+ /**
+ * Events whose utm_source matched a known integration. Null for DataWarehouseNode.
+ * @nullable
+ */
+ integrated_count: number | null
+ /**
+ * Events with no utm_source at all. Null for DataWarehouseNode.
+ * @nullable
+ */
+ events_without_utm_source: number | null
+ /**
+ * Events with a utm_source matching no integration. Null for DataWarehouseNode.
+ * @nullable
+ */
+ events_with_unmatched_utm_source: number | null
+ /**
+ * Total non-integrated events (without + unmatched). Null for DataWarehouseNode.
+ * @nullable
+ */
+ non_integrated_count: number | null
+ /** List of [event_name, count] pairs */
+ by_event: [string, number][]
+ /** List of [utm_source, count] pairs */
+ by_utm_source: [string, number][]
+ /** List of [integration, count] pairs */
+ by_matched_integration: [string, number][]
+ /** A small sample of matching events */
+ samples: GoalEventSampleApi[]
+ /** Caveats about the breakdown (sampling, attribution, etc.) */
+ notes: string[]
+}
+
+export interface CandidateEventApi {
+ /** Name of the candidate event */
+ event_name: string
+ /** Count of this event in the last 30 days */
+ last_30d_count: number
+ /** Distinct users who triggered the event in 30 days */
+ distinct_users_30d: number
+ /** Percentage of events that carry a utm_source */
+ pct_with_utm_source: number
+ /** Percentage of events that carry a utm_campaign */
+ pct_with_utm_campaign: number
+ /** List of [utm_source, count] pairs */
+ top_utm_sources: [string, number][]
+ /** Whether this event is already configured as a goal */
+ is_already_a_goal: boolean
+ /** Ranking score (higher is a stronger candidate) */
+ suggestion_score: number
+ /** Human-readable rationale for the suggestion */
+ suggestion_reason: string
+}
+
+export interface EventSuggestionsResponseApi {
+ /** Ranked candidate events for conversion goals */
+ candidates: CandidateEventApi[]
+ /** Lookback window in days used for the analysis */
+ lookback_days: number
+ /** Number of system/autocaptured events excluded */
+ excluded_events_count: number
+}
+
+export interface SourceMappingSuggestionApi {
+ /** The raw utm_source value seen on events */
+ raw_utm_source: string
+ /** Integration key it maps to */
+ suggested_target: string
+ /** Human-readable name of the suggested integration */
+ suggested_target_display_name: string
+ /** Why this mapping is suggested */
+ reason: string
+}
+
+export interface CampaignMappingSuggestionApi {
+ /** Integration key the campaign values belong to */
+ integration: string
+ /** Human-readable integration name */
+ integration_display_name: string
+ /** Proposed canonical campaign name */
+ suggested_clean_name: string
+ /** Raw campaign values clustered under this clean name */
+ raw_campaign_values: string[]
+ /** Confidence score for the clustering (0-1) */
+ confidence: number
+ /** Mapping method */
+ method: string
+ /** Why these campaign values were clustered together */
+ reason: string
+}
+
+export interface RawUnmatchedSampleApi {
+ /** A raw utm_source value matching no integration */
+ raw_utm_source: string
+ /** Number of events with this raw value in the window */
+ event_count: number
+ /**
+ * Integration suggested by token match, if any
+ * @nullable
+ */
+ suggested_integration: string | null
+}
+
+export interface CatalogueEntryApi {
+ /** A raw utm_source value seen in the window */
+ raw_utm_source: string
+ /** Number of events with this value */
+ event_count: number
+ /**
+ * Integration this value exactly matches, if any
+ * @nullable
+ */
+ matched_integration: string | null
+ /**
+ * Human-readable name of the matched integration, if any
+ * @nullable
+ */
+ matched_integration_display_name: string | null
+ /**
+ * Integration suggested by token match, if any
+ * @nullable
+ */
+ suggested_integration: string | null
+}
+
+export interface CurrentMappingApi {
+ /** A utm_source value already mapped to an integration */
+ raw_utm_source: string
+ /** Integration key it maps to */
+ target: string
+ /** Human-readable name of the target integration */
+ target_display_name: string
+ /** canonical or team_custom */
+ source: string
+}
+
+export interface UtmMappingSuggestionsResponseApi {
+ /** Suggested custom_source_mappings entries */
+ source_suggestions: SourceMappingSuggestionApi[]
+ /** Suggested campaign-name clusters (empty in v1) */
+ campaign_suggestions: CampaignMappingSuggestionApi[]
+ /** All unmatched raw utm_source values worth reviewing */
+ raw_unmatched_samples: RawUnmatchedSampleApi[]
+ /** Every utm_source value seen in the window, matched or not */
+ full_utm_source_catalogue: CatalogueEntryApi[]
+ /** Mappings already in effect (canonical + team_custom) */
+ current_mappings: CurrentMappingApi[]
+ /** Total events with an unmatched utm_source */
+ total_unmatched_events_in_window: number
+ /** Total events with any utm_source */
+ total_events_with_utm_in_window: number
+ /** Lookback window in days used for the analysis */
+ lookback_days_used: number
+ /** Caveats and guidance about the suggestions */
+ notes: string[]
+}
+
/**
* * `error` - error
* `warning` - warning
@@ -105,6 +531,74 @@ export interface UtmAuditResponseApi {
all_utm_events: UtmEventApi[]
}
+export type MarketingAnalyticsDataSourcesRetrieveParams = {
+ /**
+ * Optional. Restrict to one integration (e.g. 'GoogleAds').
+ * @nullable
+ */
+ source_type?: string | null
+}
+
+export type MarketingAnalyticsDiagnoseRetrieveParams = {
+ /**
+ * Lookback window for attribution health (1-365 days); defaults to 7
+ * @minimum 1
+ * @maximum 365
+ */
+ attribution_lookback_days?: number
+ /**
+ * Whether to include the conversion-goal summary in the diagnostic
+ */
+ include_conversion_goals?: boolean
+ /**
+ * Optional integration filter
+ * @nullable
+ */
+ source_type?: string | null
+}
+
+export type MarketingAnalyticsExplainConversionGoalRetrieveParams = {
+ /**
+ * ISO start; defaults to 30 days ago
+ * @nullable
+ */
+ date_from?: string | null
+ /**
+ * ISO end; defaults to now
+ * @nullable
+ */
+ date_to?: string | null
+ /**
+ * Id of the conversion goal to explain (from list_conversion_goals).
+ * @minLength 1
+ */
+ goal_id: string
+}
+
+export type MarketingAnalyticsSuggestConversionGoalsRetrieveParams = {
+ /**
+ * Minimum 30d event count to be a candidate
+ */
+ min_count?: number
+ /**
+ * Max candidates to return
+ */
+ top_n?: number
+}
+
+export type MarketingAnalyticsSuggestUtmMappingsRetrieveParams = {
+ /**
+ * Days of history to inspect (1-365); defaults to 90
+ * @minimum 1
+ * @maximum 365
+ */
+ lookback_days?: number
+ /**
+ * Only suggest for raw values with >= this many events
+ */
+ min_event_count?: number
+}
+
export type MarketingAnalyticsUtmAuditRetrieveParams = {
/**
* Start date for the audit period
diff --git a/products/marketing_analytics/frontend/generated/api.ts b/products/marketing_analytics/frontend/generated/api.ts
index 579dc84f6aac..3e64ca73f190 100644
--- a/products/marketing_analytics/frontend/generated/api.ts
+++ b/products/marketing_analytics/frontend/generated/api.ts
@@ -8,7 +8,215 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
-import type { MarketingAnalyticsUtmAuditRetrieveParams, UtmAuditResponseApi } from './api.schemas'
+import type {
+ ConversionGoalsListResponseApi,
+ DataSourceHealthResponseApi,
+ EventSuggestionsResponseApi,
+ GoalExplanationApi,
+ MarketingAnalyticsDataSourcesRetrieveParams,
+ MarketingAnalyticsDiagnoseRetrieveParams,
+ MarketingAnalyticsExplainConversionGoalRetrieveParams,
+ MarketingAnalyticsSuggestConversionGoalsRetrieveParams,
+ MarketingAnalyticsSuggestUtmMappingsRetrieveParams,
+ MarketingAnalyticsUtmAuditRetrieveParams,
+ MarketingDiagnosticResponseApi,
+ UtmAuditResponseApi,
+ UtmMappingSuggestionsResponseApi,
+} from './api.schemas'
+
+export const getMarketingAnalyticsConversionGoalsRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/marketing_analytics/conversion_goals/`
+}
+
+/**
+ * Read the configured conversion goals for the current project — each with its kind, target, last-30d count, integrated vs non-integrated split, and a misconfiguration flag. Read-only.
+ * @summary List conversion goals
+ */
+export const marketingAnalyticsConversionGoalsRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<ConversionGoalsListResponseApi> => {
+ return apiMutator<ConversionGoalsListResponseApi>(getMarketingAnalyticsConversionGoalsRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getMarketingAnalyticsDataSourcesRetrieveUrl = (
+ projectId: string,
+ params?: MarketingAnalyticsDataSourcesRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/marketing_analytics/data_sources/?${stringifiedParams}`
+ : `/api/projects/${projectId}/marketing_analytics/data_sources/`
+}
+
+/**
+ * Check the platform → data-warehouse side of every native marketing integration: connection state, sync recency, row counts, required-table status, and schema-mapping coverage. Read-only.
+ * @summary List marketing data sources
+ */
+export const marketingAnalyticsDataSourcesRetrieve = async (
+ projectId: string,
+ params?: MarketingAnalyticsDataSourcesRetrieveParams,
+ options?: RequestInit
+): Promise<DataSourceHealthResponseApi> => {
+ return apiMutator<DataSourceHealthResponseApi>(getMarketingAnalyticsDataSourcesRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getMarketingAnalyticsDiagnoseRetrieveUrl = (
+ projectId: string,
+ params?: MarketingAnalyticsDiagnoseRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/marketing_analytics/diagnose/?${stringifiedParams}`
+ : `/api/projects/${projectId}/marketing_analytics/diagnose/`
+}
+
+/**
+ * Aggregate data-source sync health, UTM attribution health, and conversion-goal config into a single per-integration diagnostic with recommended actions. Read-only.
+ * @summary Diagnose marketing analytics
+ */
+export const marketingAnalyticsDiagnoseRetrieve = async (
+ projectId: string,
+ params?: MarketingAnalyticsDiagnoseRetrieveParams,
+ options?: RequestInit
+): Promise<MarketingDiagnosticResponseApi> => {
+ return apiMutator<MarketingDiagnosticResponseApi>(getMarketingAnalyticsDiagnoseRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getMarketingAnalyticsExplainConversionGoalRetrieveUrl = (
+ projectId: string,
+ params: MarketingAnalyticsExplainConversionGoalRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/marketing_analytics/explain_conversion_goal/?${stringifiedParams}`
+ : `/api/projects/${projectId}/marketing_analytics/explain_conversion_goal/`
+}
+
+/**
+ * Break down a single conversion goal's events over a period by event name, utm_source, and matched integration, with a small sample of events. Read-only.
+ * @summary Explain a conversion goal
+ */
+export const marketingAnalyticsExplainConversionGoalRetrieve = async (
+ projectId: string,
+ params: MarketingAnalyticsExplainConversionGoalRetrieveParams,
+ options?: RequestInit
+): Promise<GoalExplanationApi> => {
+ return apiMutator<GoalExplanationApi>(getMarketingAnalyticsExplainConversionGoalRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getMarketingAnalyticsSuggestConversionGoalsRetrieveUrl = (
+ projectId: string,
+ params?: MarketingAnalyticsSuggestConversionGoalsRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/marketing_analytics/suggest_conversion_goals/?${stringifiedParams}`
+ : `/api/projects/${projectId}/marketing_analytics/suggest_conversion_goals/`
+}
+
+/**
+ * Rank existing custom events as conversion-goal candidates by volume, UTM-tag coverage, and unique users, excluding system/autocaptured events. Read-only.
+ * @summary Suggest conversion goals
+ */
+export const marketingAnalyticsSuggestConversionGoalsRetrieve = async (
+ projectId: string,
+ params?: MarketingAnalyticsSuggestConversionGoalsRetrieveParams,
+ options?: RequestInit
+): Promise<EventSuggestionsResponseApi> => {
+ return apiMutator<EventSuggestionsResponseApi>(
+ getMarketingAnalyticsSuggestConversionGoalsRetrieveUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getMarketingAnalyticsSuggestUtmMappingsRetrieveUrl = (
+ projectId: string,
+ params?: MarketingAnalyticsSuggestUtmMappingsRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/marketing_analytics/suggest_utm_mappings/?${stringifiedParams}`
+ : `/api/projects/${projectId}/marketing_analytics/suggest_utm_mappings/`
+}
+
+/**
+ * Detect unmatched utm_source values from recent events and propose custom_source_mappings entries, alongside the full utm_source catalogue and current mappings. Read-only.
+ * @summary Suggest UTM source mappings
+ */
+export const marketingAnalyticsSuggestUtmMappingsRetrieve = async (
+ projectId: string,
+ params?: MarketingAnalyticsSuggestUtmMappingsRetrieveParams,
+ options?: RequestInit
+): Promise<UtmMappingSuggestionsResponseApi> => {
+ return apiMutator<UtmMappingSuggestionsResponseApi>(
+ getMarketingAnalyticsSuggestUtmMappingsRetrieveUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
export const getMarketingAnalyticsTestMappingCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/marketing_analytics/test_mapping/`
diff --git a/products/marketing_analytics/frontend/generated/api.zod.schemas.ts b/products/marketing_analytics/frontend/generated/api.zod.schemas.ts
index c044658263b9..67d54e413cdd 100644
--- a/products/marketing_analytics/frontend/generated/api.zod.schemas.ts
+++ b/products/marketing_analytics/frontend/generated/api.zod.schemas.ts
@@ -9,6 +9,862 @@
*/
import { z as zod } from 'zod'
+export const ConversionGoalSummaryApi = zod.object({
+ id: zod.string().describe('Unique id of the goal (event name, action id, or DW goal id)'),
+ name: zod.string().describe('Display name of the conversion goal'),
+ kind: zod
+ .string()
+ .describe(
+ 'Goal type — one of: EventsNode (PostHog event), ActionsNode (PostHog action), DataWarehouseNode (external table)'
+ ),
+ target_label: zod.string().describe('Human-readable target the goal matches (event\/action name or table)'),
+ last_30d_count: zod.number().describe('Count of matching conversion events in the last 30 days'),
+ integrated_count: zod
+ .number()
+ .nullable()
+ .describe('Conversions whose utm_source matches a known integration. Null for DataWarehouseNode goals.'),
+ events_without_utm_source: zod
+ .number()
+ .nullable()
+ .describe('Conversions with no utm_source at all (fix by tagging UTMs). Null for DataWarehouseNode goals.'),
+ events_with_unmatched_utm_source: zod
+ .number()
+ .nullable()
+ .describe(
+ 'Conversions with a utm_source that matches no integration (fix with custom_source_mappings). Null for DataWarehouseNode goals.'
+ ),
+ non_integrated_count: zod
+ .number()
+ .nullable()
+ .describe(
+ 'Total non-integrated conversions (without + unmatched utm_source). Null for DataWarehouseNode goals.'
+ ),
+ integrated_pct: zod
+ .number()
+ .nullable()
+ .describe('Percentage of conversions that are integrated. Null for DataWarehouseNode goals.'),
+ is_misconfigured: zod.boolean().describe('Whether the goal could not be evaluated (e.g. deleted action)'),
+ misconfig_reason: zod.string().nullable().describe('Explanation when is_misconfigured is true'),
+ is_approximate: zod
+ .boolean()
+ .describe("True when this 30d count may differ from the dashboard's attribution-windowed number"),
+ approximation_reason: zod.string().nullable().describe('Explanation when is_approximate is true'),
+})
+
+export type ConversionGoalSummaryApi = zod.input<typeof ConversionGoalSummaryApi>
+export type ConversionGoalSummaryApiOutput = zod.output<typeof ConversionGoalSummaryApi>
+
+export const ConversionGoalsListResponseApi = zod.object({
+ goals: zod
+ .array(
+ zod.object({
+ id: zod.string().describe('Unique id of the goal (event name, action id, or DW goal id)'),
+ name: zod.string().describe('Display name of the conversion goal'),
+ kind: zod
+ .string()
+ .describe(
+ 'Goal type — one of: EventsNode (PostHog event), ActionsNode (PostHog action), DataWarehouseNode (external table)'
+ ),
+ target_label: zod
+ .string()
+ .describe('Human-readable target the goal matches (event\/action name or table)'),
+ last_30d_count: zod.number().describe('Count of matching conversion events in the last 30 days'),
+ integrated_count: zod
+ .number()
+ .nullable()
+ .describe(
+ 'Conversions whose utm_source matches a known integration. Null for DataWarehouseNode goals.'
+ ),
+ events_without_utm_source: zod
+ .number()
+ .nullable()
+ .describe(
+ 'Conversions with no utm_source at all (fix by tagging UTMs). Null for DataWarehouseNode goals.'
+ ),
+ events_with_unmatched_utm_source: zod
+ .number()
+ .nullable()
+ .describe(
+ 'Conversions with a utm_source that matches no integration (fix with custom_source_mappings). Null for DataWarehouseNode goals.'
+ ),
+ non_integrated_count: zod
+ .number()
+ .nullable()
+ .describe(
+ 'Total non-integrated conversions (without + unmatched utm_source). Null for DataWarehouseNode goals.'
+ ),
+ integrated_pct: zod
+ .number()
+ .nullable()
+ .describe('Percentage of conversions that are integrated. Null for DataWarehouseNode goals.'),
+ is_misconfigured: zod
+ .boolean()
+ .describe('Whether the goal could not be evaluated (e.g. deleted action)'),
+ misconfig_reason: zod.string().nullable().describe('Explanation when is_misconfigured is true'),
+ is_approximate: zod
+ .boolean()
+ .describe("True when this 30d count may differ from the dashboard's attribution-windowed number"),
+ approximation_reason: zod.string().nullable().describe('Explanation when is_approximate is true'),
+ })
+ )
+ .describe('One summary entry per configured conversion goal'),
+ attribution_window_days: zod.number().describe("The team's configured attribution window in days"),
+ attribution_mode: zod.string().describe("The team's attribution model (e.g. last_touch, first_touch, linear)"),
+ has_misconfigured: zod.boolean().describe('True if any goal is misconfigured'),
+})
+
+export type ConversionGoalsListResponseApi = zod.input<typeof ConversionGoalsListResponseApi>
+export type ConversionGoalsListResponseApiOutput = zod.output<typeof ConversionGoalsListResponseApi>
+
+export const RequiredTableStatusApi = zod.object({
+ table_name: zod.string().describe("Name of the required source table (e.g. 'campaign', 'campaign_stats')"),
+ present: zod.boolean().describe('Whether the table exists as a schema on the connected source'),
+ should_sync: zod.boolean().describe('Whether the table is enabled for sync'),
+ status: zod
+ .string()
+ .nullable()
+ .describe('ExternalDataSchema status: Completed\/Running\/Failed\/Paused\/Cancelled, or null'),
+ last_synced_at: zod.iso.datetime({ offset: true }).nullable().describe('When this table last completed a sync'),
+})
+
+export type RequiredTableStatusApi = zod.input<typeof RequiredTableStatusApi>
+export type RequiredTableStatusApiOutput = zod.output<typeof RequiredTableStatusApi>
+
+export const DataSourceHealthEntryApi = zod.object({
+ source_type: zod.string().describe("External data source type key (e.g. 'GoogleAds', 'MetaAds')"),
+ is_native: zod.boolean().describe('Whether this is a native marketing integration'),
+ display_name: zod.string().describe("Human-readable integration name (e.g. 'Google Ads')"),
+ connected: zod.boolean().describe('Whether a live source of this type is connected'),
+ last_sync_at: zod.iso.datetime({ offset: true }).nullable().describe('When the source last completed a sync'),
+ last_sync_status: zod.string().describe('Sync status: ok\/error\/stale\/tables_failed\/not_connected\/never'),
+ last_error: zod.string().nullable().describe('Latest unresolved sync error message, if any'),
+ rows_last_24h: zod.number().describe('Rows synced in the last 24 hours'),
+ rows_last_7d: zod.number().describe('Rows synced in the last 7 days'),
+ sources_map_present: zod.boolean().describe('Whether a column mapping exists for this source'),
+ schema_columns_mapped: zod.array(zod.string()).describe('Schema columns currently mapped for this source'),
+ schema_columns_required_missing: zod
+ .array(zod.string())
+ .describe('Required schema columns that are not yet mapped'),
+ required_tables: zod
+ .array(
+ zod.object({
+ table_name: zod
+ .string()
+ .describe("Name of the required source table (e.g. 'campaign', 'campaign_stats')"),
+ present: zod.boolean().describe('Whether the table exists as a schema on the connected source'),
+ should_sync: zod.boolean().describe('Whether the table is enabled for sync'),
+ status: zod
+ .string()
+ .nullable()
+ .describe('ExternalDataSchema status: Completed\/Running\/Failed\/Paused\/Cancelled, or null'),
+ last_synced_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When this table last completed a sync'),
+ })
+ )
+ .describe('Per-required-table sync status for this integration'),
+ settings_url: zod.string().describe('URL to the Marketing analytics global settings page'),
+ schemas_url: zod.string().nullable().describe('URL to the per-source Schemas tab, or null if not connected'),
+ diagnosis: zod.string().describe("Human-readable diagnosis of this source's health"),
+ fix_suggestion: zod.string().nullable().describe('Suggested fix when the source is unhealthy'),
+})
+
+export type DataSourceHealthEntryApi = zod.input<typeof DataSourceHealthEntryApi>
+export type DataSourceHealthEntryApiOutput = zod.output<typeof DataSourceHealthEntryApi>
+
+export const DataSourceHealthResponseApi = zod.object({
+ integrations: zod
+ .array(
+ zod.object({
+ source_type: zod.string().describe("External data source type key (e.g. 'GoogleAds', 'MetaAds')"),
+ is_native: zod.boolean().describe('Whether this is a native marketing integration'),
+ display_name: zod.string().describe("Human-readable integration name (e.g. 'Google Ads')"),
+ connected: zod.boolean().describe('Whether a live source of this type is connected'),
+ last_sync_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When the source last completed a sync'),
+ last_sync_status: zod
+ .string()
+ .describe('Sync status: ok\/error\/stale\/tables_failed\/not_connected\/never'),
+ last_error: zod.string().nullable().describe('Latest unresolved sync error message, if any'),
+ rows_last_24h: zod.number().describe('Rows synced in the last 24 hours'),
+ rows_last_7d: zod.number().describe('Rows synced in the last 7 days'),
+ sources_map_present: zod.boolean().describe('Whether a column mapping exists for this source'),
+ schema_columns_mapped: zod
+ .array(zod.string())
+ .describe('Schema columns currently mapped for this source'),
+ schema_columns_required_missing: zod
+ .array(zod.string())
+ .describe('Required schema columns that are not yet mapped'),
+ required_tables: zod
+ .array(
+ zod.object({
+ table_name: zod
+ .string()
+ .describe("Name of the required source table (e.g. 'campaign', 'campaign_stats')"),
+ present: zod
+ .boolean()
+ .describe('Whether the table exists as a schema on the connected source'),
+ should_sync: zod.boolean().describe('Whether the table is enabled for sync'),
+ status: zod
+ .string()
+ .nullable()
+ .describe(
+ 'ExternalDataSchema status: Completed\/Running\/Failed\/Paused\/Cancelled, or null'
+ ),
+ last_synced_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When this table last completed a sync'),
+ })
+ )
+ .describe('Per-required-table sync status for this integration'),
+ settings_url: zod.string().describe('URL to the Marketing analytics global settings page'),
+ schemas_url: zod
+ .string()
+ .nullable()
+ .describe('URL to the per-source Schemas tab, or null if not connected'),
+ diagnosis: zod.string().describe("Human-readable diagnosis of this source's health"),
+ fix_suggestion: zod.string().nullable().describe('Suggested fix when the source is unhealthy'),
+ })
+ )
+ .describe('One health entry per native integration'),
+ has_any_data: zod.boolean().describe('True if any integration synced rows in the last 7 days'),
+ overall_status: zod.string().describe('Overall: healthy\/degraded\/broken\/no_sources'),
+ issues_summary: zod.array(zod.string()).describe('Short human-readable summary of detected issues'),
+})
+
+export type DataSourceHealthResponseApi = zod.input<typeof DataSourceHealthResponseApi>
+export type DataSourceHealthResponseApiOutput = zod.output<typeof DataSourceHealthResponseApi>
+
+export const UnmatchedUtmSampleApi = zod.object({
+ raw_value: zod.string().describe("A raw utm_source value that doesn't match the integration exactly"),
+ event_count: zod.number().describe('Number of events with this raw value in the window'),
+ suggested_integration: zod.string().nullable().describe('Integration suggested by token match, if any'),
+})
+
+export type UnmatchedUtmSampleApi = zod.input<typeof UnmatchedUtmSampleApi>
+export type UnmatchedUtmSampleApiOutput = zod.output<typeof UnmatchedUtmSampleApi>
+
+export const AttributionHealthEntryApi = zod.object({
+ integration_key: zod.string().describe("Integration key (e.g. 'google', 'meta')"),
+ display_name: zod.string().describe('Human-readable integration name'),
+ events_with_utm_last_7d: zod.number().describe('Total events with any utm_source in the window'),
+ events_matched_last_7d: zod.number().describe('Events whose utm_source matched this integration'),
+ events_unmatched_likely_yours_last_7d: zod
+ .number()
+ .describe("Events that look like this integration's but don't match exactly"),
+ last_event_with_matching_utm_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('Timestamp of the most recent matched event'),
+ matched_pct: zod.number().describe('Percentage of UTM events matched to this integration'),
+ sample_unmatched_utm_sources: zod
+ .array(
+ zod.object({
+ raw_value: zod.string().describe("A raw utm_source value that doesn't match the integration exactly"),
+ event_count: zod.number().describe('Number of events with this raw value in the window'),
+ suggested_integration: zod.string().nullable().describe('Integration suggested by token match, if any'),
+ })
+ )
+ .describe('Sample of likely-yours unmatched utm_source values'),
+})
+
+export type AttributionHealthEntryApi = zod.input<typeof AttributionHealthEntryApi>
+export type AttributionHealthEntryApiOutput = zod.output<typeof AttributionHealthEntryApi>
+
+export const RecommendedActionApi = zod.object({
+ title: zod.string().describe('Short title of the recommended action'),
+ detail: zod.string().describe('Detailed explanation of the action'),
+ severity: zod.string().describe('Action severity'),
+ target_tool: zod.string().nullable().describe('Follow-up tool to call next, if any'),
+})
+
+export type RecommendedActionApi = zod.input<typeof RecommendedActionApi>
+export type RecommendedActionApiOutput = zod.output<typeof RecommendedActionApi>
+
+export const IntegrationDiagnosticApi = zod.object({
+ integration_key: zod.string().describe("Integration key (e.g. 'google', 'meta')"),
+ source_type: zod.string().describe("External data source type key (e.g. 'GoogleAds')"),
+ display_name: zod.string().describe('Human-readable integration name'),
+ overall_status: zod.string().describe('Per-integration status'),
+ diagnosis: zod.string().describe('Human-readable cross-domain diagnosis'),
+ data_source: zod
+ .union([
+ zod.object({
+ source_type: zod.string().describe("External data source type key (e.g. 'GoogleAds', 'MetaAds')"),
+ is_native: zod.boolean().describe('Whether this is a native marketing integration'),
+ display_name: zod.string().describe("Human-readable integration name (e.g. 'Google Ads')"),
+ connected: zod.boolean().describe('Whether a live source of this type is connected'),
+ last_sync_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When the source last completed a sync'),
+ last_sync_status: zod
+ .string()
+ .describe('Sync status: ok\/error\/stale\/tables_failed\/not_connected\/never'),
+ last_error: zod.string().nullable().describe('Latest unresolved sync error message, if any'),
+ rows_last_24h: zod.number().describe('Rows synced in the last 24 hours'),
+ rows_last_7d: zod.number().describe('Rows synced in the last 7 days'),
+ sources_map_present: zod.boolean().describe('Whether a column mapping exists for this source'),
+ schema_columns_mapped: zod
+ .array(zod.string())
+ .describe('Schema columns currently mapped for this source'),
+ schema_columns_required_missing: zod
+ .array(zod.string())
+ .describe('Required schema columns that are not yet mapped'),
+ required_tables: zod
+ .array(
+ zod.object({
+ table_name: zod
+ .string()
+ .describe("Name of the required source table (e.g. 'campaign', 'campaign_stats')"),
+ present: zod
+ .boolean()
+ .describe('Whether the table exists as a schema on the connected source'),
+ should_sync: zod.boolean().describe('Whether the table is enabled for sync'),
+ status: zod
+ .string()
+ .nullable()
+ .describe(
+ 'ExternalDataSchema status: Completed\/Running\/Failed\/Paused\/Cancelled, or null'
+ ),
+ last_synced_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When this table last completed a sync'),
+ })
+ )
+ .describe('Per-required-table sync status for this integration'),
+ settings_url: zod.string().describe('URL to the Marketing analytics global settings page'),
+ schemas_url: zod
+ .string()
+ .nullable()
+ .describe('URL to the per-source Schemas tab, or null if not connected'),
+ diagnosis: zod.string().describe("Human-readable diagnosis of this source's health"),
+ fix_suggestion: zod.string().nullable().describe('Suggested fix when the source is unhealthy'),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe('Data-source (sync) side health, or null if not connected'),
+ attribution: zod
+ .union([
+ zod.object({
+ integration_key: zod.string().describe("Integration key (e.g. 'google', 'meta')"),
+ display_name: zod.string().describe('Human-readable integration name'),
+ events_with_utm_last_7d: zod.number().describe('Total events with any utm_source in the window'),
+ events_matched_last_7d: zod.number().describe('Events whose utm_source matched this integration'),
+ events_unmatched_likely_yours_last_7d: zod
+ .number()
+ .describe("Events that look like this integration's but don't match exactly"),
+ last_event_with_matching_utm_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('Timestamp of the most recent matched event'),
+ matched_pct: zod.number().describe('Percentage of UTM events matched to this integration'),
+ sample_unmatched_utm_sources: zod
+ .array(
+ zod.object({
+ raw_value: zod
+ .string()
+ .describe("A raw utm_source value that doesn't match the integration exactly"),
+ event_count: zod.number().describe('Number of events with this raw value in the window'),
+ suggested_integration: zod
+ .string()
+ .nullable()
+ .describe('Integration suggested by token match, if any'),
+ })
+ )
+ .describe('Sample of likely-yours unmatched utm_source values'),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe('Attribution (UTM events) side health, or null if no data'),
+ recommended_actions: zod
+ .array(
+ zod.object({
+ title: zod.string().describe('Short title of the recommended action'),
+ detail: zod.string().describe('Detailed explanation of the action'),
+ severity: zod.string().describe('Action severity'),
+ target_tool: zod.string().nullable().describe('Follow-up tool to call next, if any'),
+ })
+ )
+ .describe('Recommended next steps for this integration'),
+})
+
+export type IntegrationDiagnosticApi = zod.input<typeof IntegrationDiagnosticApi>
+export type IntegrationDiagnosticApiOutput = zod.output<typeof IntegrationDiagnosticApi>
+
+export const MarketingDiagnosticResponseApi = zod.object({
+ integrations: zod
+ .array(
+ zod.object({
+ integration_key: zod.string().describe("Integration key (e.g. 'google', 'meta')"),
+ source_type: zod.string().describe("External data source type key (e.g. 'GoogleAds')"),
+ display_name: zod.string().describe('Human-readable integration name'),
+ overall_status: zod.string().describe('Per-integration status'),
+ diagnosis: zod.string().describe('Human-readable cross-domain diagnosis'),
+ data_source: zod
+ .union([
+ zod.object({
+ source_type: zod
+ .string()
+ .describe("External data source type key (e.g. 'GoogleAds', 'MetaAds')"),
+ is_native: zod.boolean().describe('Whether this is a native marketing integration'),
+ display_name: zod.string().describe("Human-readable integration name (e.g. 'Google Ads')"),
+ connected: zod.boolean().describe('Whether a live source of this type is connected'),
+ last_sync_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When the source last completed a sync'),
+ last_sync_status: zod
+ .string()
+ .describe('Sync status: ok\/error\/stale\/tables_failed\/not_connected\/never'),
+ last_error: zod
+ .string()
+ .nullable()
+ .describe('Latest unresolved sync error message, if any'),
+ rows_last_24h: zod.number().describe('Rows synced in the last 24 hours'),
+ rows_last_7d: zod.number().describe('Rows synced in the last 7 days'),
+ sources_map_present: zod
+ .boolean()
+ .describe('Whether a column mapping exists for this source'),
+ schema_columns_mapped: zod
+ .array(zod.string())
+ .describe('Schema columns currently mapped for this source'),
+ schema_columns_required_missing: zod
+ .array(zod.string())
+ .describe('Required schema columns that are not yet mapped'),
+ required_tables: zod
+ .array(
+ zod.object({
+ table_name: zod
+ .string()
+ .describe(
+ "Name of the required source table (e.g. 'campaign', 'campaign_stats')"
+ ),
+ present: zod
+ .boolean()
+ .describe('Whether the table exists as a schema on the connected source'),
+ should_sync: zod.boolean().describe('Whether the table is enabled for sync'),
+ status: zod
+ .string()
+ .nullable()
+ .describe(
+ 'ExternalDataSchema status: Completed\/Running\/Failed\/Paused\/Cancelled, or null'
+ ),
+ last_synced_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When this table last completed a sync'),
+ })
+ )
+ .describe('Per-required-table sync status for this integration'),
+ settings_url: zod.string().describe('URL to the Marketing analytics global settings page'),
+ schemas_url: zod
+ .string()
+ .nullable()
+ .describe('URL to the per-source Schemas tab, or null if not connected'),
+ diagnosis: zod.string().describe("Human-readable diagnosis of this source's health"),
+ fix_suggestion: zod
+ .string()
+ .nullable()
+ .describe('Suggested fix when the source is unhealthy'),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe('Data-source (sync) side health, or null if not connected'),
+ attribution: zod
+ .union([
+ zod.object({
+ integration_key: zod.string().describe("Integration key (e.g. 'google', 'meta')"),
+ display_name: zod.string().describe('Human-readable integration name'),
+ events_with_utm_last_7d: zod
+ .number()
+ .describe('Total events with any utm_source in the window'),
+ events_matched_last_7d: zod
+ .number()
+ .describe('Events whose utm_source matched this integration'),
+ events_unmatched_likely_yours_last_7d: zod
+ .number()
+ .describe("Events that look like this integration's but don't match exactly"),
+ last_event_with_matching_utm_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('Timestamp of the most recent matched event'),
+ matched_pct: zod.number().describe('Percentage of UTM events matched to this integration'),
+ sample_unmatched_utm_sources: zod
+ .array(
+ zod.object({
+ raw_value: zod
+ .string()
+ .describe(
+ "A raw utm_source value that doesn't match the integration exactly"
+ ),
+ event_count: zod
+ .number()
+ .describe('Number of events with this raw value in the window'),
+ suggested_integration: zod
+ .string()
+ .nullable()
+ .describe('Integration suggested by token match, if any'),
+ })
+ )
+ .describe('Sample of likely-yours unmatched utm_source values'),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe('Attribution (UTM events) side health, or null if no data'),
+ recommended_actions: zod
+ .array(
+ zod.object({
+ title: zod.string().describe('Short title of the recommended action'),
+ detail: zod.string().describe('Detailed explanation of the action'),
+ severity: zod.string().describe('Action severity'),
+ target_tool: zod.string().nullable().describe('Follow-up tool to call next, if any'),
+ })
+ )
+ .describe('Recommended next steps for this integration'),
+ })
+ )
+ .describe('Per-integration cross-domain diagnostics'),
+ overall_status: zod.string().describe('healthy\/degraded\/broken\/no_sources'),
+ summary: zod.string().describe('One-line plain-English summary of the diagnostic'),
+ conversion_goals: zod
+ .union([
+ zod.object({
+ goals: zod
+ .array(
+ zod.object({
+ id: zod.string().describe('Unique id of the goal (event name, action id, or DW goal id)'),
+ name: zod.string().describe('Display name of the conversion goal'),
+ kind: zod
+ .string()
+ .describe(
+ 'Goal type — one of: EventsNode (PostHog event), ActionsNode (PostHog action), DataWarehouseNode (external table)'
+ ),
+ target_label: zod
+ .string()
+ .describe('Human-readable target the goal matches (event\/action name or table)'),
+ last_30d_count: zod
+ .number()
+ .describe('Count of matching conversion events in the last 30 days'),
+ integrated_count: zod
+ .number()
+ .nullable()
+ .describe(
+ 'Conversions whose utm_source matches a known integration. Null for DataWarehouseNode goals.'
+ ),
+ events_without_utm_source: zod
+ .number()
+ .nullable()
+ .describe(
+ 'Conversions with no utm_source at all (fix by tagging UTMs). Null for DataWarehouseNode goals.'
+ ),
+ events_with_unmatched_utm_source: zod
+ .number()
+ .nullable()
+ .describe(
+ 'Conversions with a utm_source that matches no integration (fix with custom_source_mappings). Null for DataWarehouseNode goals.'
+ ),
+ non_integrated_count: zod
+ .number()
+ .nullable()
+ .describe(
+ 'Total non-integrated conversions (without + unmatched utm_source). Null for DataWarehouseNode goals.'
+ ),
+ integrated_pct: zod
+ .number()
+ .nullable()
+ .describe(
+ 'Percentage of conversions that are integrated. Null for DataWarehouseNode goals.'
+ ),
+ is_misconfigured: zod
+ .boolean()
+ .describe('Whether the goal could not be evaluated (e.g. deleted action)'),
+ misconfig_reason: zod
+ .string()
+ .nullable()
+ .describe('Explanation when is_misconfigured is true'),
+ is_approximate: zod
+ .boolean()
+ .describe(
+ "True when this 30d count may differ from the dashboard's attribution-windowed number"
+ ),
+ approximation_reason: zod
+ .string()
+ .nullable()
+ .describe('Explanation when is_approximate is true'),
+ })
+ )
+ .describe('One summary entry per configured conversion goal'),
+ attribution_window_days: zod.number().describe("The team's configured attribution window in days"),
+ attribution_mode: zod
+ .string()
+ .describe("The team's attribution model (e.g. last_touch, first_touch, linear)"),
+ has_misconfigured: zod.boolean().describe('True if any goal is misconfigured'),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe('Conversion goal summary, when requested'),
+ recommended_actions: zod
+ .array(
+ zod.object({
+ title: zod.string().describe('Short title of the recommended action'),
+ detail: zod.string().describe('Detailed explanation of the action'),
+ severity: zod.string().describe('Action severity'),
+ target_tool: zod.string().nullable().describe('Follow-up tool to call next, if any'),
+ })
+ )
+ .describe('Top global recommended actions across all integrations'),
+})
+
+export type MarketingDiagnosticResponseApi = zod.input<typeof MarketingDiagnosticResponseApi>
+export type MarketingDiagnosticResponseApiOutput = zod.output<typeof MarketingDiagnosticResponseApi>
+
+export const GoalExplanationPeriodApi = zod.object({
+ date_from: zod.string().nullable().describe('Start of the analyzed period (ISO)'),
+ date_to: zod.string().nullable().describe('End of the analyzed period (ISO)'),
+})
+
+export type GoalExplanationPeriodApi = zod.input<typeof GoalExplanationPeriodApi>
+export type GoalExplanationPeriodApiOutput = zod.output<typeof GoalExplanationPeriodApi>
+
+export const GoalEventSampleApi = zod.object({
+ event_uuid: zod.string().describe('UUID of the sampled conversion event'),
+ timestamp: zod.iso.datetime({ offset: true }).describe('When the event occurred'),
+ distinct_id: zod.string().describe('Distinct id associated with the event'),
+ utm_source: zod.string().nullable().describe('utm_source value on the event, if any'),
+ utm_campaign: zod.string().nullable().describe('utm_campaign value on the event, if any'),
+ matched_integration: zod.string().nullable().describe('Integration the utm_source matched, if any'),
+})
+
+export type GoalEventSampleApi = zod.input<typeof GoalEventSampleApi>
+export type GoalEventSampleApiOutput = zod.output<typeof GoalEventSampleApi>
+
+export const GoalExplanationApi = zod.object({
+ goal_id: zod.string().describe('Id of the explained conversion goal'),
+ goal_name: zod.string().describe('Display name of the conversion goal'),
+ kind: zod.string().describe('EventsNode\/ActionsNode\/DataWarehouseNode'),
+ period: zod
+ .object({
+ date_from: zod.string().nullable().describe('Start of the analyzed period (ISO)'),
+ date_to: zod.string().nullable().describe('End of the analyzed period (ISO)'),
+ })
+ .describe('The period the breakdown was computed over'),
+ total_count: zod.number().describe('Total matching conversion events in the period'),
+ integrated_count: zod
+ .number()
+ .nullable()
+ .describe('Events whose utm_source matched a known integration. Null for DataWarehouseNode.'),
+ events_without_utm_source: zod
+ .number()
+ .nullable()
+ .describe('Events with no utm_source at all. Null for DataWarehouseNode.'),
+ events_with_unmatched_utm_source: zod
+ .number()
+ .nullable()
+ .describe('Events with a utm_source matching no integration. Null for DataWarehouseNode.'),
+ non_integrated_count: zod
+ .number()
+ .nullable()
+ .describe('Total non-integrated events (without + unmatched). Null for DataWarehouseNode.'),
+ by_event: zod.array(zod.tuple([zod.string(), zod.number()])).describe('List of [event_name, count] pairs'),
+ by_utm_source: zod.array(zod.tuple([zod.string(), zod.number()])).describe('List of [utm_source, count] pairs'),
+ by_matched_integration: zod
+ .array(zod.tuple([zod.string(), zod.number()]))
+ .describe('List of [integration, count] pairs'),
+ samples: zod
+ .array(
+ zod.object({
+ event_uuid: zod.string().describe('UUID of the sampled conversion event'),
+ timestamp: zod.iso.datetime({ offset: true }).describe('When the event occurred'),
+ distinct_id: zod.string().describe('Distinct id associated with the event'),
+ utm_source: zod.string().nullable().describe('utm_source value on the event, if any'),
+ utm_campaign: zod.string().nullable().describe('utm_campaign value on the event, if any'),
+ matched_integration: zod.string().nullable().describe('Integration the utm_source matched, if any'),
+ })
+ )
+ .describe('A small sample of matching events'),
+ notes: zod.array(zod.string()).describe('Caveats about the breakdown (sampling, attribution, etc.)'),
+})
+
+export type GoalExplanationApi = zod.input<typeof GoalExplanationApi>
+export type GoalExplanationApiOutput = zod.output<typeof GoalExplanationApi>
+
+export const CandidateEventApi = zod.object({
+ event_name: zod.string().describe('Name of the candidate event'),
+ last_30d_count: zod.number().describe('Count of this event in the last 30 days'),
+ distinct_users_30d: zod.number().describe('Distinct users who triggered the event in 30 days'),
+ pct_with_utm_source: zod.number().describe('Percentage of events that carry a utm_source'),
+ pct_with_utm_campaign: zod.number().describe('Percentage of events that carry a utm_campaign'),
+ top_utm_sources: zod.array(zod.tuple([zod.string(), zod.number()])).describe('List of [utm_source, count] pairs'),
+ is_already_a_goal: zod.boolean().describe('Whether this event is already configured as a goal'),
+ suggestion_score: zod.number().describe('Ranking score (higher is a stronger candidate)'),
+ suggestion_reason: zod.string().describe('Human-readable rationale for the suggestion'),
+})
+
+export type CandidateEventApi = zod.input<typeof CandidateEventApi>
+export type CandidateEventApiOutput = zod.output<typeof CandidateEventApi>
+
+export const EventSuggestionsResponseApi = zod.object({
+ candidates: zod
+ .array(
+ zod.object({
+ event_name: zod.string().describe('Name of the candidate event'),
+ last_30d_count: zod.number().describe('Count of this event in the last 30 days'),
+ distinct_users_30d: zod.number().describe('Distinct users who triggered the event in 30 days'),
+ pct_with_utm_source: zod.number().describe('Percentage of events that carry a utm_source'),
+ pct_with_utm_campaign: zod.number().describe('Percentage of events that carry a utm_campaign'),
+ top_utm_sources: zod
+ .array(zod.tuple([zod.string(), zod.number()]))
+ .describe('List of [utm_source, count] pairs'),
+ is_already_a_goal: zod.boolean().describe('Whether this event is already configured as a goal'),
+ suggestion_score: zod.number().describe('Ranking score (higher is a stronger candidate)'),
+ suggestion_reason: zod.string().describe('Human-readable rationale for the suggestion'),
+ })
+ )
+ .describe('Ranked candidate events for conversion goals'),
+ lookback_days: zod.number().describe('Lookback window in days used for the analysis'),
+ excluded_events_count: zod.number().describe('Number of system\/autocaptured events excluded'),
+})
+
+export type EventSuggestionsResponseApi = zod.input<typeof EventSuggestionsResponseApi>
+export type EventSuggestionsResponseApiOutput = zod.output<typeof EventSuggestionsResponseApi>
+
+export const SourceMappingSuggestionApi = zod.object({
+ raw_utm_source: zod.string().describe('The raw utm_source value seen on events'),
+ suggested_target: zod.string().describe('Integration key it maps to'),
+ suggested_target_display_name: zod.string().describe('Human-readable name of the suggested integration'),
+ reason: zod.string().describe('Why this mapping is suggested'),
+})
+
+export type SourceMappingSuggestionApi = zod.input<typeof SourceMappingSuggestionApi>
+export type SourceMappingSuggestionApiOutput = zod.output<typeof SourceMappingSuggestionApi>
+
+export const CampaignMappingSuggestionApi = zod.object({
+ integration: zod.string().describe('Integration key the campaign values belong to'),
+ integration_display_name: zod.string().describe('Human-readable integration name'),
+ suggested_clean_name: zod.string().describe('Proposed canonical campaign name'),
+ raw_campaign_values: zod.array(zod.string()).describe('Raw campaign values clustered under this clean name'),
+ confidence: zod.number().describe('Confidence score for the clustering (0-1)'),
+ method: zod.string().describe('Mapping method'),
+ reason: zod.string().describe('Why these campaign values were clustered together'),
+})
+
+export type CampaignMappingSuggestionApi = zod.input<typeof CampaignMappingSuggestionApi>
+export type CampaignMappingSuggestionApiOutput = zod.output<typeof CampaignMappingSuggestionApi>
+
+export const RawUnmatchedSampleApi = zod.object({
+ raw_utm_source: zod.string().describe('A raw utm_source value matching no integration'),
+ event_count: zod.number().describe('Number of events with this raw value in the window'),
+ suggested_integration: zod.string().nullable().describe('Integration suggested by token match, if any'),
+})
+
+export type RawUnmatchedSampleApi = zod.input<typeof RawUnmatchedSampleApi>
+export type RawUnmatchedSampleApiOutput = zod.output<typeof RawUnmatchedSampleApi>
+
+export const CatalogueEntryApi = zod.object({
+ raw_utm_source: zod.string().describe('A raw utm_source value seen in the window'),
+ event_count: zod.number().describe('Number of events with this value'),
+ matched_integration: zod.string().nullable().describe('Integration this value exactly matches, if any'),
+ matched_integration_display_name: zod
+ .string()
+ .nullable()
+ .describe('Human-readable name of the matched integration, if any'),
+ suggested_integration: zod.string().nullable().describe('Integration suggested by token match, if any'),
+})
+
+export type CatalogueEntryApi = zod.input<typeof CatalogueEntryApi>
+export type CatalogueEntryApiOutput = zod.output<typeof CatalogueEntryApi>
+
+export const CurrentMappingApi = zod.object({
+ raw_utm_source: zod.string().describe('A utm_source value already mapped to an integration'),
+ target: zod.string().describe('Integration key it maps to'),
+ target_display_name: zod.string().describe('Human-readable name of the target integration'),
+ source: zod.string().describe('canonical or team_custom'),
+})
+
+export type CurrentMappingApi = zod.input<typeof CurrentMappingApi>
+export type CurrentMappingApiOutput = zod.output<typeof CurrentMappingApi>
+
+export const UtmMappingSuggestionsResponseApi = zod.object({
+ source_suggestions: zod
+ .array(
+ zod.object({
+ raw_utm_source: zod.string().describe('The raw utm_source value seen on events'),
+ suggested_target: zod.string().describe('Integration key it maps to'),
+ suggested_target_display_name: zod
+ .string()
+ .describe('Human-readable name of the suggested integration'),
+ reason: zod.string().describe('Why this mapping is suggested'),
+ })
+ )
+ .describe('Suggested custom_source_mappings entries'),
+ campaign_suggestions: zod
+ .array(
+ zod.object({
+ integration: zod.string().describe('Integration key the campaign values belong to'),
+ integration_display_name: zod.string().describe('Human-readable integration name'),
+ suggested_clean_name: zod.string().describe('Proposed canonical campaign name'),
+ raw_campaign_values: zod
+ .array(zod.string())
+ .describe('Raw campaign values clustered under this clean name'),
+ confidence: zod.number().describe('Confidence score for the clustering (0-1)'),
+ method: zod.string().describe('Mapping method'),
+ reason: zod.string().describe('Why these campaign values were clustered together'),
+ })
+ )
+ .describe('Suggested campaign-name clusters (empty in v1)'),
+ raw_unmatched_samples: zod
+ .array(
+ zod.object({
+ raw_utm_source: zod.string().describe('A raw utm_source value matching no integration'),
+ event_count: zod.number().describe('Number of events with this raw value in the window'),
+ suggested_integration: zod.string().nullable().describe('Integration suggested by token match, if any'),
+ })
+ )
+ .describe('All unmatched raw utm_source values worth reviewing'),
+ full_utm_source_catalogue: zod
+ .array(
+ zod.object({
+ raw_utm_source: zod.string().describe('A raw utm_source value seen in the window'),
+ event_count: zod.number().describe('Number of events with this value'),
+ matched_integration: zod.string().nullable().describe('Integration this value exactly matches, if any'),
+ matched_integration_display_name: zod
+ .string()
+ .nullable()
+ .describe('Human-readable name of the matched integration, if any'),
+ suggested_integration: zod.string().nullable().describe('Integration suggested by token match, if any'),
+ })
+ )
+ .describe('Every utm_source value seen in the window, matched or not'),
+ current_mappings: zod
+ .array(
+ zod.object({
+ raw_utm_source: zod.string().describe('A utm_source value already mapped to an integration'),
+ target: zod.string().describe('Integration key it maps to'),
+ target_display_name: zod.string().describe('Human-readable name of the target integration'),
+ source: zod.string().describe('canonical or team_custom'),
+ })
+ )
+ .describe('Mappings already in effect (canonical + team_custom)'),
+ total_unmatched_events_in_window: zod.number().describe('Total events with an unmatched utm_source'),
+ total_events_with_utm_in_window: zod.number().describe('Total events with any utm_source'),
+ lookback_days_used: zod.number().describe('Lookback window in days used for the analysis'),
+ notes: zod.array(zod.string()).describe('Caveats and guidance about the suggestions'),
+})
+
+export type UtmMappingSuggestionsResponseApi = zod.input<typeof UtmMappingSuggestionsResponseApi>
+export type UtmMappingSuggestionsResponseApiOutput = zod.output<typeof UtmMappingSuggestionsResponseApi>
+
export const UtmIssueSeverityEnumApi = zod
.enum(['error', 'warning'])
.describe('\* `error` - error\n\* `warning` - warning')
diff --git a/products/marketing_analytics/mcp/tools.yaml b/products/marketing_analytics/mcp/tools.yaml
new file mode 100644
index 000000000000..3d811bc96350
--- /dev/null
+++ b/products/marketing_analytics/mcp/tools.yaml
@@ -0,0 +1,133 @@
+# 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: Marketing analytics
+feature: marketing_analytics
+url_prefix: /marketing
+ui_apps: {}
+tools:
+ marketing-analytics-conversion-goals:
+ operation: marketing_analytics_conversion_goals_retrieve
+ enabled: true
+ scopes:
+ - marketing_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List conversion goals
+ description: >
+ List the configured marketing conversion goals for the current project. Each goal returns its kind
+ (EventsNode / ActionsNode / DataWarehouseNode), target, last-30d count, and the integrated vs non-integrated
+ split. Non-integrated breaks into two buckets with OPPOSITE fixes: events_without_utm_source (tag UTMs) vs
+ events_with_unmatched_utm_source (add a custom source mapping). is_approximate is true when the 30d count
+ may differ from the dashboard's attribution-windowed number.
+ feature_flag: marketing-analytics-mcp
+ marketing-analytics-data-sources:
+ operation: marketing_analytics_data_sources_retrieve
+ enabled: true
+ scopes:
+ - marketing_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List marketing data sources health
+ description: >
+ List the platform-side health of every native marketing integration: connected/not, last sync time and
+ status, last error, rows synced, and schema-mapping coverage. This is the platform → data-warehouse side
+ only. For PostHog-events-side health (UTM matching), call marketing-analytics-diagnose.
+ feature_flag: marketing-analytics-mcp
+ marketing-analytics-diagnose:
+ operation: marketing_analytics_diagnose_retrieve
+ enabled: true
+ scopes:
+ - marketing_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Diagnose marketing analytics setup
+ description: >
+ READ-ONLY end-to-end diagnostic of Marketing analytics for the current project. Returns per-integration
+ overall_status (healthy / sync_broken / events_broken / events_unmatched / events_only /
+ schema_misconfigured / not_connected), sync state, attribution state (UTM-tagged events arriving, matched vs
+ likely-yours-but-unmatched), conversion goals with last-30d performance and misconfig flags, and recommended
+ next actions each pointing to the right follow-up tool. USE THIS TOOL FIRST whenever the user asks why
+ marketing analytics looks wrong, missing, or broken. Do NOT speculate about causes before calling this tool.
+ feature_flag: marketing-analytics-mcp
+ marketing-analytics-explain-conversion-goal:
+ operation: marketing_analytics_explain_conversion_goal_retrieve
+ enabled: true
+ scopes:
+ - marketing_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Explain a conversion goal
+ description: >
+ Break down the events that COUNT toward a conversion goal by their own utm_source, utm_campaign, and matched
+ integration. Returns recent sample events for inspection. This is a flat per-event breakdown of the
+ conversion events themselves — NOT an analysis of the user's prior journey, and NOT the dashboard's
+ attribution calculation (first-touch / last-touch / multi-touch weighting is applied by the dashboard, not
+ here). Use when the user asks "what utm_sources are behind my N conversions?" or "where do these conversions
+ come from?". Only EventsNode and ActionsNode goals are explained at the event level; DataWarehouseNode goals
+ short-circuit with a note.
+ feature_flag: marketing-analytics-mcp
+ marketing-analytics-suggest-conversion-goals:
+ operation: marketing_analytics_suggest_conversion_goals_retrieve
+ enabled: true
+ scopes:
+ - marketing_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Suggest conversion goal candidates
+ description: >
+ Suggest custom events that are good candidates for becoming conversion goals. Ranks by volume, UTM tag
+ coverage, and uniqueness of users. Excludes autocapture / system events and events that are already
+ configured as goals.
+ feature_flag: marketing-analytics-mcp
+ marketing-analytics-suggest-utm-mappings:
+ operation: marketing_analytics_suggest_utm_mappings_retrieve
+ enabled: true
+ scopes:
+ - marketing_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Suggest utm_source → integration mappings
+ description: >
+ USE THIS TOOL — DO NOT FALL BACK TO SQL — whenever the user asks about utm_source mappings,
+ custom_source_mappings, unmatched / non-integrated UTM values, or the question "what utm_sources do I have
+ and which ad platform do they belong to?". Returns full_utm_source_catalogue (every utm_source value seen on
+ events in the window, matched + unmatched, with event count and the integration it resolves to),
+ source_suggestions (mapping recommendations where a value's token matches a known alias, e.g. raw
+ facebook_paid → MetaAds), raw_unmatched_samples (every unmatched value, including likely-not-an-ad values
+ like organic/newsletter/partner), and current_mappings (every alias already in effect — canonical +
+ team_custom — so duplicates aren't suggested). Read-only — applying mappings is a separate write tool.
+ feature_flag: marketing-analytics-mcp
+ marketing-analytics-test-mapping-create:
+ operation: marketing_analytics_test_mapping_create
+ enabled: false
+ marketing-analytics-utm-audit:
+ operation: marketing_analytics_utm_audit_retrieve
+ enabled: true
+ scopes:
+ - marketing_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Audit UTM tagging quality
+ description: >
+ Audit the UTM tagging quality of recent events: campaigns with issues, mismatched utm_source vs configured
+ integrations, unmatched custom sources, and total spend at risk. Use when the user asks why their events
+ appear in 'non-integrated', or why UTMs are not matching the ad platform data.
+ feature_flag: marketing-analytics-mcp
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index ad5a0ead33d7..7c92bbd414b8 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -3926,6 +3926,111 @@
"readOnlyHint": true
}
},
+ "marketing-analytics-conversion-goals": {
+ "description": "List the configured marketing conversion goals for the current project. Each goal returns its kind (EventsNode / ActionsNode / DataWarehouseNode), target, last-30d count, and the integrated vs non-integrated split. Non-integrated breaks into two buckets with OPPOSITE fixes: events_without_utm_source (tag UTMs) vs events_with_unmatched_utm_source (add a custom source mapping). is_approximate is true when the 30d count may differ from the dashboard's attribution-windowed number.",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "List conversion goals",
+ "title": "List conversion goals",
+ "required_scopes": ["marketing_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-mcp"
+ },
+ "marketing-analytics-data-sources": {
+ "description": "List the platform-side health of every native marketing integration: connected/not, last sync time and status, last error, rows synced, and schema-mapping coverage. This is the platform → data-warehouse side only. For PostHog-events-side health (UTM matching), call marketing-analytics-diagnose.",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "List marketing data sources health",
+ "title": "List marketing data sources health",
+ "required_scopes": ["marketing_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-mcp"
+ },
+ "marketing-analytics-diagnose": {
+ "description": "READ-ONLY end-to-end diagnostic of Marketing analytics for the current project. Returns per-integration overall_status (healthy / sync_broken / events_broken / events_unmatched / events_only / schema_misconfigured / not_connected), sync state, attribution state (UTM-tagged events arriving, matched vs likely-yours-but-unmatched), conversion goals with last-30d performance and misconfig flags, and recommended next actions each pointing to the right follow-up tool. USE THIS TOOL FIRST whenever the user asks why marketing analytics looks wrong, missing, or broken. Do NOT speculate about causes before calling this tool.",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "Diagnose marketing analytics setup",
+ "title": "Diagnose marketing analytics setup",
+ "required_scopes": ["marketing_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-mcp"
+ },
+ "marketing-analytics-explain-conversion-goal": {
+ "description": "Break down the events that COUNT toward a conversion goal by their own utm_source, utm_campaign, and matched integration. Returns recent sample events for inspection. This is a flat per-event breakdown of the conversion events themselves — NOT an analysis of the user's prior journey, and NOT the dashboard's attribution calculation (first-touch / last-touch / multi-touch weighting is applied by the dashboard, not here). Use when the user asks \"what utm_sources are behind my N conversions?\" or \"where do these conversions come from?\". Only EventsNode and ActionsNode goals are explained at the event level; DataWarehouseNode goals short-circuit with a note.",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "Explain a conversion goal",
+ "title": "Explain a conversion goal",
+ "required_scopes": ["marketing_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-mcp"
+ },
+ "marketing-analytics-suggest-conversion-goals": {
+ "description": "Suggest custom events that are good candidates for becoming conversion goals. Ranks by volume, UTM tag coverage, and uniqueness of users. Excludes autocapture / system events and events that are already configured as goals.",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "Suggest conversion goal candidates",
+ "title": "Suggest conversion goal candidates",
+ "required_scopes": ["marketing_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-mcp"
+ },
+ "marketing-analytics-suggest-utm-mappings": {
+ "description": "USE THIS TOOL — DO NOT FALL BACK TO SQL — whenever the user asks about utm_source mappings, custom_source_mappings, unmatched / non-integrated UTM values, or the question \"what utm_sources do I have and which ad platform do they belong to?\". Returns full_utm_source_catalogue (every utm_source value seen on events in the window, matched + unmatched, with event count and the integration it resolves to), source_suggestions (mapping recommendations where a value's token matches a known alias, e.g. raw facebook_paid → MetaAds), raw_unmatched_samples (every unmatched value, including likely-not-an-ad values like organic/newsletter/partner), and current_mappings (every alias already in effect — canonical + team_custom — so duplicates aren't suggested). Read-only — applying mappings is a separate write tool.",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "Suggest utm_source → integration mappings",
+ "title": "Suggest utm_source → integration mappings",
+ "required_scopes": ["marketing_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-mcp"
+ },
+ "marketing-analytics-utm-audit": {
+ "description": "Audit the UTM tagging quality of recent events: campaigns with issues, mismatched utm_source vs configured integrations, unmatched custom sources, and total spend at risk. Use when the user asks why their events appear in 'non-integrated', or why UTMs are not matching the ad platform data.",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "Audit UTM tagging quality",
+ "title": "Audit UTM tagging quality",
+ "required_scopes": ["marketing_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-mcp"
+ },
"notebooks-create": {
"description": "Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook's rich text document structure (ProseMirror-based). Returns the created notebook with its short_id.\nEmbedded charts use `{type: \"ph-query\", attrs: {nodeId, query}}` nodes. The `query` object must be one of: (a) `{kind: \"DataVisualizationNode\", source: {kind: \"HogQLQuery\", query: \"SELECT ...\"}, display: \"ActionsBar\", chartSettings: {...}}` for SQL charts — do NOT wrap this in an InsightVizNode; (b) `{kind: \"InsightVizNode\", source: <TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery>}` for product-analytics insights; or (c) `{kind: \"SavedInsightNode\", shortId: \"...\"}` to embed a saved insight. The server rejects other shapes and auto-corrects the common `InsightVizNode` wrapping a SQL chart.",
"category": "Notebooks",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index d12a3e2dd7b0..07bdfee69cba 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -4180,6 +4180,111 @@
"readOnlyHint": true
}
},
+ "marketing-analytics-conversion-goals": {
+ "description": "List the configured marketing conversion goals for the current project. Each goal returns its kind (EventsNode / ActionsNode / DataWarehouseNode), target, last-30d count, and the integrated vs non-integrated split. Non-integrated breaks into two buckets with OPPOSITE fixes: events_without_utm_source (tag UTMs) vs events_with_unmatched_utm_source (add a custom source mapping). is_approximate is true when the 30d count may differ from the dashboard's attribution-windowed number.",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "List conversion goals",
+ "title": "List conversion goals",
+ "required_scopes": ["marketing_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-mcp"
+ },
+ "marketing-analytics-data-sources": {
+ "description": "List the platform-side health of every native marketing integration: connected/not, last sync time and status, last error, rows synced, and schema-mapping coverage. This is the platform → data-warehouse side only. For PostHog-events-side health (UTM matching), call marketing-analytics-diagnose.",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "List marketing data sources health",
+ "title": "List marketing data sources health",
+ "required_scopes": ["marketing_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-mcp"
+ },
+ "marketing-analytics-diagnose": {
+ "description": "READ-ONLY end-to-end diagnostic of Marketing analytics for the current project. Returns per-integration overall_status (healthy / sync_broken / events_broken / events_unmatched / events_only / schema_misconfigured / not_connected), sync state, attribution state (UTM-tagged events arriving, matched vs likely-yours-but-unmatched), conversion goals with last-30d performance and misconfig flags, and recommended next actions each pointing to the right follow-up tool. USE THIS TOOL FIRST whenever the user asks why marketing analytics looks wrong, missing, or broken. Do NOT speculate about causes before calling this tool.",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "Diagnose marketing analytics setup",
+ "title": "Diagnose marketing analytics setup",
+ "required_scopes": ["marketing_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-mcp"
+ },
+ "marketing-analytics-explain-conversion-goal": {
+ "description": "Break down the events that COUNT toward a conversion goal by their own utm_source, utm_campaign, and matched integration. Returns recent sample events for inspection. This is a flat per-event breakdown of the conversion events themselves — NOT an analysis of the user's prior journey, and NOT the dashboard's attribution calculation (first-touch / last-touch / multi-touch weighting is applied by the dashboard, not here). Use when the user asks \"what utm_sources are behind my N conversions?\" or \"where do these conversions come from?\". Only EventsNode and ActionsNode goals are explained at the event level; DataWarehouseNode goals short-circuit with a note.",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "Explain a conversion goal",
+ "title": "Explain a conversion goal",
+ "required_scopes": ["marketing_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-mcp"
+ },
+ "marketing-analytics-suggest-conversion-goals": {
+ "description": "Suggest custom events that are good candidates for becoming conversion goals. Ranks by volume, UTM tag coverage, and uniqueness of users. Excludes autocapture / system events and events that are already configured as goals.",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "Suggest conversion goal candidates",
+ "title": "Suggest conversion goal candidates",
+ "required_scopes": ["marketing_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-mcp"
+ },
+ "marketing-analytics-suggest-utm-mappings": {
+ "description": "USE THIS TOOL — DO NOT FALL BACK TO SQL — whenever the user asks about utm_source mappings, custom_source_mappings, unmatched / non-integrated UTM values, or the question \"what utm_sources do I have and which ad platform do they belong to?\". Returns full_utm_source_catalogue (every utm_source value seen on events in the window, matched + unmatched, with event count and the integration it resolves to), source_suggestions (mapping recommendations where a value's token matches a known alias, e.g. raw facebook_paid → MetaAds), raw_unmatched_samples (every unmatched value, including likely-not-an-ad values like organic/newsletter/partner), and current_mappings (every alias already in effect — canonical + team_custom — so duplicates aren't suggested). Read-only — applying mappings is a separate write tool.",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "Suggest utm_source → integration mappings",
+ "title": "Suggest utm_source → integration mappings",
+ "required_scopes": ["marketing_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-mcp"
+ },
+ "marketing-analytics-utm-audit": {
+ "description": "Audit the UTM tagging quality of recent events: campaigns with issues, mismatched utm_source vs configured integrations, unmatched custom sources, and total spend at risk. Use when the user asks why their events appear in 'non-integrated', or why UTMs are not matching the ad platform data.",
+ "category": "Marketing analytics",
+ "feature": "marketing_analytics",
+ "summary": "Audit UTM tagging quality",
+ "title": "Audit UTM tagging quality",
+ "required_scopes": ["marketing_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "marketing-analytics-mcp"
+ },
"notebook-edit": {
"description": "Edit part of a notebook's content. Use this for any change inside a notebook — text, headings, attributes, whole paragraphs. Call `notebooks-retrieve` first to see what to target.\n\nMatching is by content. The tool finds `old_value` anywhere in the notebook and swaps it for `new_value` in place.\n\nOn success, returns the updated notebook with the new content and bumped version. On a 409 or 410 error, the notebook has changed since you loaded it — call `notebooks-retrieve` and re-apply your edit against the latest content.",
"category": "Notebooks",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 16f14d5fa1a8..fe8951348deb 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -7852,6 +7852,40 @@ export namespace Schemas {
delete_verified_at: string | null;
}
+ export interface UnmatchedUtmSample {
+ /** A raw utm_source value that doesn't match the integration exactly */
+ raw_value: string;
+ /** Number of events with this raw value in the window */
+ event_count: number;
+ /**
+ * Integration suggested by token match, if any
+ * @nullable
+ */
+ suggested_integration: string | null;
+ }
+
+ export interface AttributionHealthEntry {
+ /** Integration key (e.g. 'google', 'meta') */
+ integration_key: string;
+ /** Human-readable integration name */
+ display_name: string;
+ /** Total events with any utm_source in the window */
+ events_with_utm_last_7d: number;
+ /** Events whose utm_source matched this integration */
+ events_matched_last_7d: number;
+ /** Events that look like this integration's but don't match exactly */
+ events_unmatched_likely_yours_last_7d: number;
+ /**
+ * Timestamp of the most recent matched event
+ * @nullable
+ */
+ last_event_with_matching_utm_at: string | null;
+ /** Percentage of UTM events matched to this integration */
+ matched_pct: number;
+ /** Sample of likely-yours unmatched utm_source values */
+ sample_unmatched_utm_sources: UnmatchedUtmSample[];
+ }
+
/**
* * `first_touch` - First Touch
* `last_touch` - Last Touch
@@ -10380,6 +10414,44 @@ export namespace Schemas {
issues: UtmIssue[];
}
+ export interface CampaignMappingSuggestion {
+ /** Integration key the campaign values belong to */
+ integration: string;
+ /** Human-readable integration name */
+ integration_display_name: string;
+ /** Proposed canonical campaign name */
+ suggested_clean_name: string;
+ /** Raw campaign values clustered under this clean name */
+ raw_campaign_values: string[];
+ /** Confidence score for the clustering (0-1) */
+ confidence: number;
+ /** Mapping method */
+ method: string;
+ /** Why these campaign values were clustered together */
+ reason: string;
+ }
+
+ export interface CandidateEvent {
+ /** Name of the candidate event */
+ event_name: string;
+ /** Count of this event in the last 30 days */
+ last_30d_count: number;
+ /** Distinct users who triggered the event in 30 days */
+ distinct_users_30d: number;
+ /** Percentage of events that carry a utm_source */
+ pct_with_utm_source: number;
+ /** Percentage of events that carry a utm_campaign */
+ pct_with_utm_campaign: number;
+ /** List of [utm_source, count] pairs */
+ top_utm_sources: [string, number][];
+ /** Whether this event is already configured as a goal */
+ is_already_a_goal: boolean;
+ /** Ranking score (higher is a stronger candidate) */
+ suggestion_score: number;
+ /** Human-readable rationale for the suggestion */
+ suggestion_reason: string;
+ }
+
/**
* Supporting evidence
*/
@@ -10423,6 +10495,28 @@ export namespace Schemas {
evidence?: CapabilityStateEvidence;
}
+ export interface CatalogueEntry {
+ /** A raw utm_source value seen in the window */
+ raw_utm_source: string;
+ /** Number of events with this value */
+ event_count: number;
+ /**
+ * Integration this value exactly matches, if any
+ * @nullable
+ */
+ matched_integration: string | null;
+ /**
+ * Human-readable name of the matched integration, if any
+ * @nullable
+ */
+ matched_integration_display_name: string | null;
+ /**
+ * Integration suggested by token match, if any
+ * @nullable
+ */
+ suggested_integration: string | null;
+ }
+
export interface CategoricalScoreOption {
/**
* Stable option key. Use lowercase letters, numbers, underscores, or hyphens.
@@ -11507,6 +11601,69 @@ export namespace Schemas {
readonly slack_workspace_domain: string | null;
}
+ export interface ConversionGoalSummary {
+ /** Unique id of the goal (event name, action id, or DW goal id) */
+ id: string;
+ /** Display name of the conversion goal */
+ name: string;
+ /** Goal type — one of: EventsNode (PostHog event), ActionsNode (PostHog action), DataWarehouseNode (external table) */
+ kind: string;
+ /** Human-readable target the goal matches (event/action name or table) */
+ target_label: string;
+ /** Count of matching conversion events in the last 30 days */
+ last_30d_count: number;
+ /**
+ * Conversions whose utm_source matches a known integration. Null for DataWarehouseNode goals.
+ * @nullable
+ */
+ integrated_count: number | null;
+ /**
+ * Conversions with no utm_source at all (fix by tagging UTMs). Null for DataWarehouseNode goals.
+ * @nullable
+ */
+ events_without_utm_source: number | null;
+ /**
+ * Conversions with a utm_source that matches no integration (fix with custom_source_mappings). Null for DataWarehouseNode goals.
+ * @nullable
+ */
+ events_with_unmatched_utm_source: number | null;
+ /**
+ * Total non-integrated conversions (without + unmatched utm_source). Null for DataWarehouseNode goals.
+ * @nullable
+ */
+ non_integrated_count: number | null;
+ /**
+ * Percentage of conversions that are integrated. Null for DataWarehouseNode goals.
+ * @nullable
+ */
+ integrated_pct: number | null;
+ /** Whether the goal could not be evaluated (e.g. deleted action) */
+ is_misconfigured: boolean;
+ /**
+ * Explanation when is_misconfigured is true
+ * @nullable
+ */
+ misconfig_reason: string | null;
+ /** True when this 30d count may differ from the dashboard's attribution-windowed number */
+ is_approximate: boolean;
+ /**
+ * Explanation when is_approximate is true
+ * @nullable
+ */
+ approximation_reason: string | null;
+ }
+
+ export interface ConversionGoalsListResponse {
+ /** One summary entry per configured conversion goal */
+ goals: ConversionGoalSummary[];
+ /** The team's configured attribution window in days */
+ attribution_window_days: number;
+ /** The team's attribution model (e.g. last_touch, first_touch, linear) */
+ attribution_mode: string;
+ /** True if any goal is misconfigured */
+ has_misconfigured: boolean;
+ }
+
/**
* * `0` - Disabled
* `1` - Stateless
@@ -12091,6 +12248,17 @@ export namespace Schemas {
access_secret: string;
}
+ export interface CurrentMapping {
+ /** A utm_source value already mapped to an integration */
+ raw_utm_source: string;
+ /** Integration key it maps to */
+ target: string;
+ /** Human-readable name of the target integration */
+ target_display_name: string;
+ /** canonical or team_custom */
+ source: string;
+ }
+
export interface CustomerJourney {
readonly id: string;
insight: number;
@@ -12449,6 +12617,85 @@ export namespace Schemas {
readonly rows_expected: number | null;
}
+ export interface RequiredTableStatus {
+ /** Name of the required source table (e.g. 'campaign', 'campaign_stats') */
+ table_name: string;
+ /** Whether the table exists as a schema on the connected source */
+ present: boolean;
+ /** Whether the table is enabled for sync */
+ should_sync: boolean;
+ /**
+ * ExternalDataSchema status: Completed/Running/Failed/Paused/Cancelled, or null
+ * @nullable
+ */
+ status: string | null;
+ /**
+ * When this table last completed a sync
+ * @nullable
+ */
+ last_synced_at: string | null;
+ }
+
+ export interface DataSourceHealthEntry {
+ /** External data source type key (e.g. 'GoogleAds', 'MetaAds') */
+ source_type: string;
+ /** Whether this is a native marketing integration */
+ is_native: boolean;
+ /** Human-readable integration name (e.g. 'Google Ads') */
+ display_name: string;
+ /** Whether a live source of this type is connected */
+ connected: boolean;
+ /**
+ * When the source last completed a sync
+ * @nullable
+ */
+ last_sync_at: string | null;
+ /** Sync status: ok/error/stale/tables_failed/not_connected/never */
+ last_sync_status: string;
+ /**
+ * Latest unresolved sync error message, if any
+ * @nullable
+ */
+ last_error: string | null;
+ /** Rows synced in the last 24 hours */
+ rows_last_24h: number;
+ /** Rows synced in the last 7 days */
+ rows_last_7d: number;
+ /** Whether a column mapping exists for this source */
+ sources_map_present: boolean;
+ /** Schema columns currently mapped for this source */
+ schema_columns_mapped: string[];
+ /** Required schema columns that are not yet mapped */
+ schema_columns_required_missing: string[];
+ /** Per-required-table sync status for this integration */
+ required_tables: RequiredTableStatus[];
+ /** URL to the Marketing analytics global settings page */
+ settings_url: string;
+ /**
+ * URL to the per-source Schemas tab, or null if not connected
+ * @nullable
+ */
+ schemas_url: string | null;
+ /** Human-readable diagnosis of this source's health */
+ diagnosis: string;
+ /**
+ * Suggested fix when the source is unhealthy
+ * @nullable
+ */
+ fix_suggestion: string | null;
+ }
+
+ export interface DataSourceHealthResponse {
+ /** One health entry per native integration */
+ integrations: DataSourceHealthEntry[];
+ /** True if any integration synced rows in the last 7 days */
+ has_any_data: boolean;
+ /** Overall: healthy/degraded/broken/no_sources */
+ overall_status: string;
+ /** Short human-readable summary of detected issues */
+ issues_summary: string[];
+ }
+
export interface DataWarehouseModelPath {
readonly id: string;
readonly path: readonly string[];
@@ -16309,6 +16556,15 @@ export namespace Schemas {
readonly updated_at: string;
}
+ export interface EventSuggestionsResponse {
+ /** Ranked candidate events for conversion goals */
+ candidates: CandidateEvent[];
+ /** Lookback window in days used for the analysis */
+ lookback_days: number;
+ /** Number of system/autocaptured events excluded */
+ excluded_events_count: number;
+ }
+
export interface EventTaxonomyItem {
property: string;
sample_count: number;
@@ -18397,6 +18653,86 @@ export namespace Schemas {
change: WoWChange | null;
}
+ export interface GoalEventSample {
+ /** UUID of the sampled conversion event */
+ event_uuid: string;
+ /** When the event occurred */
+ timestamp: string;
+ /** Distinct id associated with the event */
+ distinct_id: string;
+ /**
+ * utm_source value on the event, if any
+ * @nullable
+ */
+ utm_source: string | null;
+ /**
+ * utm_campaign value on the event, if any
+ * @nullable
+ */
+ utm_campaign: string | null;
+ /**
+ * Integration the utm_source matched, if any
+ * @nullable
+ */
+ matched_integration: string | null;
+ }
+
+ export interface GoalExplanationPeriod {
+ /**
+ * Start of the analyzed period (ISO)
+ * @nullable
+ */
+ date_from: string | null;
+ /**
+ * End of the analyzed period (ISO)
+ * @nullable
+ */
+ date_to: string | null;
+ }
+
+ export interface GoalExplanation {
+ /** Id of the explained conversion goal */
+ goal_id: string;
+ /** Display name of the conversion goal */
+ goal_name: string;
+ /** EventsNode/ActionsNode/DataWarehouseNode */
+ kind: string;
+ /** The period the breakdown was computed over */
+ period: GoalExplanationPeriod;
+ /** Total matching conversion events in the period */
+ total_count: number;
+ /**
+ * Events whose utm_source matched a known integration. Null for DataWarehouseNode.
+ * @nullable
+ */
+ integrated_count: number | null;
+ /**
+ * Events with no utm_source at all. Null for DataWarehouseNode.
+ * @nullable
+ */
+ events_without_utm_source: number | null;
+ /**
+ * Events with a utm_source matching no integration. Null for DataWarehouseNode.
+ * @nullable
+ */
+ events_with_unmatched_utm_source: number | null;
+ /**
+ * Total non-integrated events (without + unmatched). Null for DataWarehouseNode.
+ * @nullable
+ */
+ non_integrated_count: number | null;
+ /** List of [event_name, count] pairs */
+ by_event: [string, number][];
+ /** List of [utm_source, count] pairs */
+ by_utm_source: [string, number][];
+ /** List of [integration, count] pairs */
+ by_matched_integration: [string, number][];
+ /** A small sample of matching events */
+ samples: GoalEventSample[];
+ /** Caveats about the breakdown (sampling, attribution, etc.) */
+ notes: string[];
+ }
+
export interface Group {
/**
* @minimum -2147483648
@@ -20650,6 +20986,39 @@ export namespace Schemas {
readonly display_name: string;
}
+ export interface RecommendedAction {
+ /** Short title of the recommended action */
+ title: string;
+ /** Detailed explanation of the action */
+ detail: string;
+ /** Action severity */
+ severity: string;
+ /**
+ * Follow-up tool to call next, if any
+ * @nullable
+ */
+ target_tool: string | null;
+ }
+
+ export interface IntegrationDiagnostic {
+ /** Integration key (e.g. 'google', 'meta') */
+ integration_key: string;
+ /** External data source type key (e.g. 'GoogleAds') */
+ source_type: string;
+ /** Human-readable integration name */
+ display_name: string;
+ /** Per-integration status */
+ overall_status: string;
+ /** Human-readable cross-domain diagnosis */
+ diagnosis: string;
+ /** Data-source (sync) side health, or null if not connected */
+ data_source?: DataSourceHealthEntry | null;
+ /** Attribution (UTM events) side health, or null if no data */
+ attribution?: AttributionHealthEntry | null;
+ /** Recommended next steps for this integration */
+ recommended_actions: RecommendedAction[];
+ }
+
/**
* One row in `inventory.integrations`. Sensitive config is intentionally excluded.
*/
@@ -22190,6 +22559,19 @@ export namespace Schemas {
snapshot_id: string;
}
+ export interface MarketingDiagnosticResponse {
+ /** Per-integration cross-domain diagnostics */
+ integrations: IntegrationDiagnostic[];
+ /** healthy/degraded/broken/no_sources */
+ overall_status: string;
+ /** One-line plain-English summary of the diagnostic */
+ summary: string;
+ /** Conversion goal summary, when requested */
+ conversion_goals?: ConversionGoalsListResponse | null;
+ /** Top global recommended actions across all integrations */
+ recommended_actions: RecommendedAction[];
+ }
+
/**
* * `key` - key
* `value` - value
@@ -37341,6 +37723,18 @@ export namespace Schemas {
limited: QuotaLimitsResponseLimited;
}
+ export interface RawUnmatchedSample {
+ /** A raw utm_source value matching no integration */
+ raw_utm_source: string;
+ /** Number of events with this raw value in the window */
+ event_count: number;
+ /**
+ * Integration suggested by token match, if any
+ * @nullable
+ */
+ suggested_integration: string | null;
+ }
+
export interface RecomputeResult {
run: Run;
counts_changed: boolean;
@@ -38458,6 +38852,17 @@ export namespace Schemas {
runs: SlackThreadContextRun[];
}
+ export interface SourceMappingSuggestion {
+ /** The raw utm_source value seen on events */
+ raw_utm_source: string;
+ /** Integration key it maps to */
+ suggested_target: string;
+ /** Human-readable name of the suggested integration */
+ suggested_target_display_name: string;
+ /** Why this mapping is suggested */
+ reason: string;
+ }
+
/**
* * `none` - none
* `auto` - auto
@@ -40436,6 +40841,27 @@ export namespace Schemas {
all_utm_events: UtmEvent[];
}
+ export interface UtmMappingSuggestionsResponse {
+ /** Suggested custom_source_mappings entries */
+ source_suggestions: SourceMappingSuggestion[];
+ /** Suggested campaign-name clusters (empty in v1) */
+ campaign_suggestions: CampaignMappingSuggestion[];
+ /** All unmatched raw utm_source values worth reviewing */
+ raw_unmatched_samples: RawUnmatchedSample[];
+ /** Every utm_source value seen in the window, matched or not */
+ full_utm_source_catalogue: CatalogueEntry[];
+ /** Mappings already in effect (canonical + team_custom) */
+ current_mappings: CurrentMapping[];
+ /** Total events with an unmatched utm_source */
+ total_unmatched_events_in_window: number;
+ /** Total events with any utm_source */
+ total_events_with_utm_in_window: number;
+ /** Lookback window in days used for the analysis */
+ lookback_days_used: number;
+ /** Caveats and guidance about the suggestions */
+ notes: string[];
+ }
+
export interface ViewLinkValidation {
/** @maxLength 255 */
joining_table_name: string;
@@ -44251,6 +44677,74 @@ export namespace Schemas {
offset?: number;
};
+ export type EnvironmentsMarketingAnalyticsDataSourcesRetrieveParams = {
+ /**
+ * Optional. Restrict to one integration (e.g. 'GoogleAds').
+ * @nullable
+ */
+ source_type?: string | null;
+ };
+
+ export type EnvironmentsMarketingAnalyticsDiagnoseRetrieveParams = {
+ /**
+ * Lookback window for attribution health (1-365 days); defaults to 7
+ * @minimum 1
+ * @maximum 365
+ */
+ attribution_lookback_days?: number;
+ /**
+ * Whether to include the conversion-goal summary in the diagnostic
+ */
+ include_conversion_goals?: boolean;
+ /**
+ * Optional integration filter
+ * @nullable
+ */
+ source_type?: string | null;
+ };
+
+ export type EnvironmentsMarketingAnalyticsExplainConversionGoalRetrieveParams = {
+ /**
+ * ISO start; defaults to 30 days ago
+ * @nullable
+ */
+ date_from?: string | null;
+ /**
+ * ISO end; defaults to now
+ * @nullable
+ */
+ date_to?: string | null;
+ /**
+ * Id of the conversion goal to explain (from list_conversion_goals).
+ * @minLength 1
+ */
+ goal_id: string;
+ };
+
+ export type EnvironmentsMarketingAnalyticsSuggestConversionGoalsRetrieveParams = {
+ /**
+ * Minimum 30d event count to be a candidate
+ */
+ min_count?: number;
+ /**
+ * Max candidates to return
+ */
+ top_n?: number;
+ };
+
+ export type EnvironmentsMarketingAnalyticsSuggestUtmMappingsRetrieveParams = {
+ /**
+ * Days of history to inspect (1-365); defaults to 90
+ * @minimum 1
+ * @maximum 365
+ */
+ lookback_days?: number;
+ /**
+ * Only suggest for raw values with >= this many events
+ */
+ min_event_count?: number;
+ };
+
export type EnvironmentsMarketingAnalyticsUtmAuditRetrieveParams = {
/**
* Start date for the audit period
@@ -49971,6 +50465,74 @@ export namespace Schemas {
Running: 'running',
} as const;
+ export type MarketingAnalyticsDataSourcesRetrieveParams = {
+ /**
+ * Optional. Restrict to one integration (e.g. 'GoogleAds').
+ * @nullable
+ */
+ source_type?: string | null;
+ };
+
+ export type MarketingAnalyticsDiagnoseRetrieveParams = {
+ /**
+ * Lookback window for attribution health (1-365 days); defaults to 7
+ * @minimum 1
+ * @maximum 365
+ */
+ attribution_lookback_days?: number;
+ /**
+ * Whether to include the conversion-goal summary in the diagnostic
+ */
+ include_conversion_goals?: boolean;
+ /**
+ * Optional integration filter
+ * @nullable
+ */
+ source_type?: string | null;
+ };
+
+ export type MarketingAnalyticsExplainConversionGoalRetrieveParams = {
+ /**
+ * ISO start; defaults to 30 days ago
+ * @nullable
+ */
+ date_from?: string | null;
+ /**
+ * ISO end; defaults to now
+ * @nullable
+ */
+ date_to?: string | null;
+ /**
+ * Id of the conversion goal to explain (from list_conversion_goals).
+ * @minLength 1
+ */
+ goal_id: string;
+ };
+
+ export type MarketingAnalyticsSuggestConversionGoalsRetrieveParams = {
+ /**
+ * Minimum 30d event count to be a candidate
+ */
+ min_count?: number;
+ /**
+ * Max candidates to return
+ */
+ top_n?: number;
+ };
+
+ export type MarketingAnalyticsSuggestUtmMappingsRetrieveParams = {
+ /**
+ * Days of history to inspect (1-365); defaults to 90
+ * @minimum 1
+ * @maximum 365
+ */
+ lookback_days?: number;
+ /**
+ * Only suggest for raw values with >= this many events
+ */
+ min_event_count?: number;
+ };
+
export type MarketingAnalyticsUtmAuditRetrieveParams = {
/**
* Start date for the audit period
diff --git a/services/mcp/src/generated/marketing_analytics/api.ts b/services/mcp/src/generated/marketing_analytics/api.ts
new file mode 100644
index 000000000000..1ae3d0327e1d
--- /dev/null
+++ b/services/mcp/src/generated/marketing_analytics/api.ts
@@ -0,0 +1,165 @@
+/**
+ * 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 7 enabled ops
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+/**
+ * Read the configured conversion goals for the current project — each with its kind, target, last-30d count, integrated vs non-integrated split, and a misconfiguration flag. Read-only.
+ * @summary List conversion goals
+ */
+export const MarketingAnalyticsConversionGoalsRetrieveParams = /* @__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/."
+ ),
+})
+
+/**
+ * Check the platform → data-warehouse side of every native marketing integration: connection state, sync recency, row counts, required-table status, and schema-mapping coverage. Read-only.
+ * @summary List marketing data sources
+ */
+export const MarketingAnalyticsDataSourcesRetrieveParams = /* @__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 MarketingAnalyticsDataSourcesRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ source_type: zod.string().nullish().describe("Optional. Restrict to one integration (e.g. 'GoogleAds')."),
+})
+
+/**
+ * Aggregate data-source sync health, UTM attribution health, and conversion-goal config into a single per-integration diagnostic with recommended actions. Read-only.
+ * @summary Diagnose marketing analytics
+ */
+export const MarketingAnalyticsDiagnoseRetrieveParams = /* @__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 marketingAnalyticsDiagnoseRetrieveQueryAttributionLookbackDaysDefault = 7
+export const marketingAnalyticsDiagnoseRetrieveQueryAttributionLookbackDaysMax = 365
+
+export const marketingAnalyticsDiagnoseRetrieveQueryIncludeConversionGoalsDefault = true
+
+export const MarketingAnalyticsDiagnoseRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ attribution_lookback_days: zod
+ .number()
+ .min(1)
+ .max(marketingAnalyticsDiagnoseRetrieveQueryAttributionLookbackDaysMax)
+ .default(marketingAnalyticsDiagnoseRetrieveQueryAttributionLookbackDaysDefault)
+ .describe('Lookback window for attribution health (1-365 days); defaults to 7'),
+ include_conversion_goals: zod
+ .boolean()
+ .default(marketingAnalyticsDiagnoseRetrieveQueryIncludeConversionGoalsDefault)
+ .describe('Whether to include the conversion-goal summary in the diagnostic'),
+ source_type: zod.string().nullish().describe('Optional integration filter'),
+})
+
+/**
+ * Break down a single conversion goal's events over a period by event name, utm_source, and matched integration, with a small sample of events. Read-only.
+ * @summary Explain a conversion goal
+ */
+export const MarketingAnalyticsExplainConversionGoalRetrieveParams = /* @__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 MarketingAnalyticsExplainConversionGoalRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ date_from: zod.string().nullish().describe('ISO start; defaults to 30 days ago'),
+ date_to: zod.string().nullish().describe('ISO end; defaults to now'),
+ goal_id: zod.string().min(1).describe('Id of the conversion goal to explain (from list_conversion_goals).'),
+})
+
+/**
+ * Rank existing custom events as conversion-goal candidates by volume, UTM-tag coverage, and unique users, excluding system/autocaptured events. Read-only.
+ * @summary Suggest conversion goals
+ */
+export const MarketingAnalyticsSuggestConversionGoalsRetrieveParams = /* @__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 marketingAnalyticsSuggestConversionGoalsRetrieveQueryMinCountDefault = 50
+export const marketingAnalyticsSuggestConversionGoalsRetrieveQueryTopNDefault = 10
+
+export const MarketingAnalyticsSuggestConversionGoalsRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ min_count: zod
+ .number()
+ .default(marketingAnalyticsSuggestConversionGoalsRetrieveQueryMinCountDefault)
+ .describe('Minimum 30d event count to be a candidate'),
+ top_n: zod
+ .number()
+ .default(marketingAnalyticsSuggestConversionGoalsRetrieveQueryTopNDefault)
+ .describe('Max candidates to return'),
+})
+
+/**
+ * Detect unmatched utm_source values from recent events and propose custom_source_mappings entries, alongside the full utm_source catalogue and current mappings. Read-only.
+ * @summary Suggest UTM source mappings
+ */
+export const MarketingAnalyticsSuggestUtmMappingsRetrieveParams = /* @__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 marketingAnalyticsSuggestUtmMappingsRetrieveQueryLookbackDaysDefault = 90
+export const marketingAnalyticsSuggestUtmMappingsRetrieveQueryLookbackDaysMax = 365
+
+export const marketingAnalyticsSuggestUtmMappingsRetrieveQueryMinEventCountDefault = 10
+
+export const MarketingAnalyticsSuggestUtmMappingsRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ lookback_days: zod
+ .number()
+ .min(1)
+ .max(marketingAnalyticsSuggestUtmMappingsRetrieveQueryLookbackDaysMax)
+ .default(marketingAnalyticsSuggestUtmMappingsRetrieveQueryLookbackDaysDefault)
+ .describe('Days of history to inspect (1-365); defaults to 90'),
+ min_event_count: zod
+ .number()
+ .default(marketingAnalyticsSuggestUtmMappingsRetrieveQueryMinEventCountDefault)
+ .describe('Only suggest for raw values with >= this many events'),
+})
+
+/**
+ * Cross-reference campaigns with spend from ad platforms against pageview events with UTM parameters to identify tracking issues.
+ * @summary Run UTM audit
+ */
+export const MarketingAnalyticsUtmAuditRetrieveParams = /* @__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 marketingAnalyticsUtmAuditRetrieveQueryDateFromDefault = `-30d`
+
+export const MarketingAnalyticsUtmAuditRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ date_from: zod
+ .string()
+ .min(1)
+ .default(marketingAnalyticsUtmAuditRetrieveQueryDateFromDefault)
+ .describe('Start date for the audit period'),
+ date_to: zod.string().nullish().describe('End date for the audit period'),
+})
diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.ts
index 2c51b8c94c47..e7689b8bbb30 100644
--- a/services/mcp/src/tools/generated/index.ts
+++ b/services/mcp/src/tools/generated/index.ts
@@ -22,6 +22,7 @@ import { GENERATED_TOOLS as experiments } from './experiments'
import { GENERATED_TOOLS as feature_flags } from './feature_flags'
import { GENERATED_TOOLS as integrations } from './integrations'
import { GENERATED_TOOLS as logs } from './logs'
+import { GENERATED_TOOLS as marketing_analytics } from './marketing_analytics'
import { GENERATED_TOOLS as notebooks } from './notebooks'
import { GENERATED_TOOLS as persons } from './persons'
import { GENERATED_TOOLS as platform_features } from './platform_features'
@@ -62,6 +63,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =
...feature_flags,
...integrations,
...logs,
+ ...marketing_analytics,
...notebooks,
...persons,
...platform_features,
diff --git a/services/mcp/src/tools/generated/marketing_analytics.ts b/services/mcp/src/tools/generated/marketing_analytics.ts
new file mode 100644
index 000000000000..61233f931d6a
--- /dev/null
+++ b/services/mcp/src/tools/generated/marketing_analytics.ts
@@ -0,0 +1,172 @@
+// AUTO-GENERATED from products/marketing_analytics/mcp/tools.yaml + OpenAPI — do not edit
+import { z } from 'zod'
+
+import type { Schemas } from '@/api/generated'
+import {
+ MarketingAnalyticsDataSourcesRetrieveQueryParams,
+ MarketingAnalyticsDiagnoseRetrieveQueryParams,
+ MarketingAnalyticsExplainConversionGoalRetrieveQueryParams,
+ MarketingAnalyticsSuggestConversionGoalsRetrieveQueryParams,
+ MarketingAnalyticsSuggestUtmMappingsRetrieveQueryParams,
+ MarketingAnalyticsUtmAuditRetrieveQueryParams,
+} from '@/generated/marketing_analytics/api'
+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+
+const MarketingAnalyticsConversionGoalsSchema = z.object({})
+
+const marketingAnalyticsConversionGoals = (): ToolBase<
+ typeof MarketingAnalyticsConversionGoalsSchema,
+ Schemas.ConversionGoalsListResponse
+> => ({
+ name: 'marketing-analytics-conversion-goals',
+ schema: MarketingAnalyticsConversionGoalsSchema,
+ // eslint-disable-next-line no-unused-vars
+ handler: async (context: Context, params: z.infer<typeof MarketingAnalyticsConversionGoalsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.ConversionGoalsListResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/marketing_analytics/conversion_goals/`,
+ })
+ return result
+ },
+})
+
+const MarketingAnalyticsDataSourcesSchema = MarketingAnalyticsDataSourcesRetrieveQueryParams
+
+const marketingAnalyticsDataSources = (): ToolBase<
+ typeof MarketingAnalyticsDataSourcesSchema,
+ Schemas.DataSourceHealthResponse
+> => ({
+ name: 'marketing-analytics-data-sources',
+ schema: MarketingAnalyticsDataSourcesSchema,
+ handler: async (context: Context, params: z.infer<typeof MarketingAnalyticsDataSourcesSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.DataSourceHealthResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/marketing_analytics/data_sources/`,
+ query: {
+ source_type: params.source_type,
+ },
+ })
+ return result
+ },
+})
+
+const MarketingAnalyticsDiagnoseSchema = MarketingAnalyticsDiagnoseRetrieveQueryParams
+
+const marketingAnalyticsDiagnose = (): ToolBase<
+ typeof MarketingAnalyticsDiagnoseSchema,
+ Schemas.MarketingDiagnosticResponse
+> => ({
+ name: 'marketing-analytics-diagnose',
+ schema: MarketingAnalyticsDiagnoseSchema,
+ handler: async (context: Context, params: z.infer<typeof MarketingAnalyticsDiagnoseSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.MarketingDiagnosticResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/marketing_analytics/diagnose/`,
+ query: {
+ attribution_lookback_days: params.attribution_lookback_days,
+ include_conversion_goals: params.include_conversion_goals,
+ source_type: params.source_type,
+ },
+ })
+ return result
+ },
+})
+
+const MarketingAnalyticsExplainConversionGoalSchema = MarketingAnalyticsExplainConversionGoalRetrieveQueryParams
+
+const marketingAnalyticsExplainConversionGoal = (): ToolBase<
+ typeof MarketingAnalyticsExplainConversionGoalSchema,
+ Schemas.GoalExplanation
+> => ({
+ name: 'marketing-analytics-explain-conversion-goal',
+ schema: MarketingAnalyticsExplainConversionGoalSchema,
+ handler: async (context: Context, params: z.infer<typeof MarketingAnalyticsExplainConversionGoalSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.GoalExplanation>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/marketing_analytics/explain_conversion_goal/`,
+ query: {
+ date_from: params.date_from,
+ date_to: params.date_to,
+ goal_id: params.goal_id,
+ },
+ })
+ return result
+ },
+})
+
+const MarketingAnalyticsSuggestConversionGoalsSchema = MarketingAnalyticsSuggestConversionGoalsRetrieveQueryParams
+
+const marketingAnalyticsSuggestConversionGoals = (): ToolBase<
+ typeof MarketingAnalyticsSuggestConversionGoalsSchema,
+ Schemas.EventSuggestionsResponse
+> => ({
+ name: 'marketing-analytics-suggest-conversion-goals',
+ schema: MarketingAnalyticsSuggestConversionGoalsSchema,
+ handler: async (context: Context, params: z.infer<typeof MarketingAnalyticsSuggestConversionGoalsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.EventSuggestionsResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/marketing_analytics/suggest_conversion_goals/`,
+ query: {
+ min_count: params.min_count,
+ top_n: params.top_n,
+ },
+ })
+ return result
+ },
+})
+
+const MarketingAnalyticsSuggestUtmMappingsSchema = MarketingAnalyticsSuggestUtmMappingsRetrieveQueryParams
+
+const marketingAnalyticsSuggestUtmMappings = (): ToolBase<
+ typeof MarketingAnalyticsSuggestUtmMappingsSchema,
+ Schemas.UtmMappingSuggestionsResponse
+> => ({
+ name: 'marketing-analytics-suggest-utm-mappings',
+ schema: MarketingAnalyticsSuggestUtmMappingsSchema,
+ handler: async (context: Context, params: z.infer<typeof MarketingAnalyticsSuggestUtmMappingsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.UtmMappingSuggestionsResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/marketing_analytics/suggest_utm_mappings/`,
+ query: {
+ lookback_days: params.lookback_days,
+ min_event_count: params.min_event_count,
+ },
+ })
+ return result
+ },
+})
+
+const MarketingAnalyticsUtmAuditSchema = MarketingAnalyticsUtmAuditRetrieveQueryParams
+
+const marketingAnalyticsUtmAudit = (): ToolBase<typeof MarketingAnalyticsUtmAuditSchema, Schemas.UtmAuditResponse> => ({
+ name: 'marketing-analytics-utm-audit',
+ schema: MarketingAnalyticsUtmAuditSchema,
+ handler: async (context: Context, params: z.infer<typeof MarketingAnalyticsUtmAuditSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.UtmAuditResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/marketing_analytics/utm_audit/`,
+ query: {
+ date_from: params.date_from,
+ date_to: params.date_to,
+ },
+ })
+ return result
+ },
+})
+
+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'marketing-analytics-conversion-goals': marketingAnalyticsConversionGoals,
+ 'marketing-analytics-data-sources': marketingAnalyticsDataSources,
+ 'marketing-analytics-diagnose': marketingAnalyticsDiagnose,
+ 'marketing-analytics-explain-conversion-goal': marketingAnalyticsExplainConversionGoal,
+ 'marketing-analytics-suggest-conversion-goals': marketingAnalyticsSuggestConversionGoals,
+ 'marketing-analytics-suggest-utm-mappings': marketingAnalyticsSuggestUtmMappings,
+ 'marketing-analytics-utm-audit': marketingAnalyticsUtmAudit,
+}
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 62b8c613438a..d6ce9e38ccea 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -712,9 +712,10 @@ describe('Tool Filtering - Feature Flags', () => {
'promoted-product',
'dashboard-widgets',
'heatmaps-mcp',
+ 'marketing-analytics-mcp',
])
)
- expect(flags).toHaveLength(13)
+ expect(flags).toHaveLength(14)
})
// Exercise the real predicate (toolPassesFlagGate) over hand-rolled entries