Skip to content

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

feat(workflows): let agents create workflows from data suggestions through mcp (#116974)

Meikel Ratz510c119177ce
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c5d6c83c0c4d..8be74cb8deaf 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6414,6 +6414,10 @@ snapshots:
hash: v1.k794b7964.ad71858e2dc5a45e3d81bb38d46ad3bbe2dea9c152b625fbbf93117a27e624ca.Z4AVu3aic8bdKuv98SD1V1ZqQXsxPwGX2mZl3cL31bs
mcp-apps-workflows--archived--light:
hash: v1.k794b7964.ef7053f4c964693d5c5e5fdfbd58ff59028e629f0709a08a8e671aec82b5250e.sqIaakT_XJ9sVFNc4OkpgL2trDWUj4L2H_rFZT9c5Gw
+ mcp-apps-workflows--data-suggestions--light:
+ hash: v1.k794b7964.b2ceec3c890e9f432bf8a548bea888ee5ecb4fb943a00e914f265b6e1dde37e4.ITfYs9uRttzjpHJkLrKYopYinde_S2_TnmmxWTWfQ3o
+ mcp-apps-workflows--data-suggestions-built--light:
+ hash: v1.k794b7964.a6a2d5322df9e01bbc25c27899200c465263863b539a328312d45b4c700f3df2.D7UIfg7JMHFk-mo0_Xg3i5H_FtpA_dKVrnUuA0iD-mM
mcp-apps-workflows--draft-state--light:
hash: v1.k794b7964.4cbfe20c626f0f7912dbd47b41a152c9c30f92d12a3f599476fb10043d7f7e70.9NI9FaMch59lt8xO3Xhp9ruHKLyDcvupNp20dZrR8_Y
mcp-apps-workflows--list--light:
diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.py
index 4338bcb6aac2..75d5abe69e10 100644
--- a/products/workflows/backend/facade/contracts.py
+++ b/products/workflows/backend/facade/contracts.py
@@ -686,12 +686,24 @@ class DataSuggestionsResult:
DataSuggestionBuildStatus = Literal["ready", "building", "failed"]
+@frozen
+class MissingInput:
+ """A setting the draft leaves blank and the team must fill before enabling, like a webhook URL."""
+
+ step_id: str
+ step_name: str
+ field: str
+
+
@frozen
class BuiltSuggestion:
status: DataSuggestionBuildStatus
# Set only when the status is ready.
workflow: dict[str, Any] | None = None
uses_saved_template: bool = False
+ # Set only when the build saved the draft itself.
+ workflow_id: str | None = None
+ missing_inputs: tuple[MissingInput, ...] = ()
class DataSuggestionNotFound(Exception):
diff --git a/products/workflows/backend/facade/data_suggestions.py b/products/workflows/backend/facade/data_suggestions.py
index cd303cf8e04c..0cccab7e1109 100644
--- a/products/workflows/backend/facade/data_suggestions.py
+++ b/products/workflows/backend/facade/data_suggestions.py
@@ -6,6 +6,8 @@ from posthog.models import Team, User
from products.workflows.backend.facade.contracts import BuiltSuggestion, DataSuggestionsResult
from products.workflows.backend.services.data_suggestions import service
from products.workflows.backend.services.data_suggestions.service import (
+ build_caller,
+ email_sender_ready,
get_data_suggestions,
needs_new_build,
needs_new_generation,
@@ -13,6 +15,8 @@ from products.workflows.backend.services.data_suggestions.service import (
from products.workflows.backend.tasks.data_suggestions import build_data_suggestion, generate_data_suggestions
__all__ = [
+ "build_caller",
+ "email_sender_ready",
"get_data_suggestions",
"needs_new_build",
"needs_new_generation",
@@ -30,14 +34,14 @@ def start_data_suggestions(*, team: Team, user: User, refresh: bool) -> DataSugg
def start_build(
- *, team: Team, user: User, suggestion_id: str, retry: bool, event_source: EventSource
+ *, team: Team, user: User, suggestion_id: str, retry: bool, save: bool, event_source: EventSource
) -> BuiltSuggestion:
return service.start_build(
team=team,
suggestion_id=suggestion_id,
- caller=event_source.value,
+ caller=build_caller(event_source.value, save=save, user_id=user.id),
retry=retry,
enqueue=lambda lock_token: build_data_suggestion.delay(
- team.id, user.id, suggestion_id, lock_token, event_source.value
+ team.id, user.id, suggestion_id, lock_token, event_source.value, save
),
)
diff --git a/products/workflows/backend/presentation/views/data_suggestion_drafts.py b/products/workflows/backend/presentation/views/data_suggestion_drafts.py
index a8f507aedd26..a7106fd6a779 100644
--- a/products/workflows/backend/presentation/views/data_suggestion_drafts.py
+++ b/products/workflows/backend/presentation/views/data_suggestion_drafts.py
@@ -1,20 +1,25 @@
-"""The check a built suggestion passes before anyone can save it as a draft."""
+"""The check a built suggestion passes before anyone can save it as a draft, and the save an agent's build uses."""
-from typing import Any
+from typing import Any, cast
+from uuid import UUID
import structlog
from rest_framework.exceptions import ValidationError
from posthog.event_usage import EventSource
-from posthog.models import Team
+from posthog.models import Team, User
+from products.workflows.backend.facade.activity import log_workflow_activity
+from products.workflows.backend.facade.contracts import WorkflowActor
+from products.workflows.backend.facade.writes import create_workflow
from products.workflows.backend.presentation.views.graph_validation import validate_graph
from products.workflows.backend.presentation.views.hog_flow import HogFlowSerializer
logger = structlog.get_logger(__name__)
-def is_valid_draft(team: Team, workflow: dict[str, Any], event_source: EventSource) -> bool:
+def validated_draft(team: Team, workflow: dict[str, Any], event_source: EventSource) -> dict[str, Any] | None:
+ """The draft as the create endpoint would store it, or None when the create endpoint would reject it."""
# Checked the way the caller's own create request will be: the web editor saves drafts with blank inputs, an API
# client's draft must be complete. The graph wiring is checked in full either way.
serializer = HogFlowSerializer(
@@ -26,5 +31,19 @@ def is_valid_draft(team: Team, workflow: dict[str, Any], event_source: EventSour
serializer.is_valid(raise_exception=True)
except ValidationError as error:
logger.info("workflows.data_suggestions.invalid_workflow", team_id=team.id, errors=str(error.detail)[:500])
- return False
- return True
+ return None
+ return dict(serializer.validated_data)
+
+
+def save_draft(team: Team, user: User, validated: dict[str, Any]) -> str:
+ """Saves the draft the way the create endpoint does, activity log included, and returns its id."""
+ result = create_workflow(team_id=team.id, user_id=user.id, validated_data=validated)
+ workflow_id = cast(UUID, result.current["id"])
+ log_workflow_activity(
+ actor=WorkflowActor(organization_id=team.organization_id, team_id=team.id, user=user, was_impersonated=False),
+ workflow_id=workflow_id,
+ name=cast("str | None", result.current.get("name")),
+ activity="created",
+ detail_type="standard",
+ )
+ return str(workflow_id)
diff --git a/products/workflows/backend/presentation/views/workflow_data_suggestions.py b/products/workflows/backend/presentation/views/workflow_data_suggestions.py
index 55238e3f40e7..c9fc8ee7cbab 100644
--- a/products/workflows/backend/presentation/views/workflow_data_suggestions.py
+++ b/products/workflows/backend/presentation/views/workflow_data_suggestions.py
@@ -1,9 +1,9 @@
-from typing import Any
+from typing import Any, cast
from django.db import models
import posthoganalytics
-from drf_spectacular.utils import extend_schema
+from drf_spectacular.utils import extend_schema, extend_schema_field
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound, PermissionDenied
@@ -15,8 +15,10 @@ from posthog.event_usage import get_event_source
from posthog.models import User
from posthog.rate_limit import AIBurstRateThrottle, AISustainedRateThrottle
-from products.workflows.backend.facade.contracts import DataSuggestionNotFound
+from products.workflows.backend.facade.contracts import DataSuggestionNotFound, DataSuggestionsResult
from products.workflows.backend.facade.data_suggestions import (
+ build_caller,
+ email_sender_ready,
get_data_suggestions,
needs_new_build,
needs_new_generation,
@@ -87,6 +89,14 @@ class DataSuggestionsResponseSerializer(serializers.Serializer):
suggestions = DataSuggestionSerializer(
many=True, help_text="Up to 3 suggested workflows, ranked by lifecycle stage and then by weekly volume."
)
+ email_sender_ready = serializers.SerializerMethodField(
+ help_text="Whether the project has a verified email sender. Without one, an email workflow can be saved as a "
+ "draft but cannot send until a sending domain is added and verified."
+ )
+
+ @extend_schema_field(serializers.BooleanField())
+ def get_email_sender_ready(self, _result: object) -> bool:
+ return bool(self.context.get("email_sender_ready"))
class DataSuggestionGenerateRequestSerializer(serializers.Serializer):
@@ -101,6 +111,11 @@ class DataSuggestionBuildRequestSerializer(serializers.Serializer):
default=False,
help_text="Start a new build when the last one failed. Leave it false when asking for a running build's status.",
)
+ save_draft = serializers.BooleanField(
+ default=False,
+ help_text="Save the built draft in the project and return its workflow_id. Blank settings, like a webhook "
+ "URL, stay blank and are listed in missing_inputs. Leave it false to get the workflow back without saving.",
+ )
class DataSuggestionBuildStatus(models.TextChoices):
@@ -109,20 +124,36 @@ class DataSuggestionBuildStatus(models.TextChoices):
FAILED = "failed"
+class DataSuggestionMissingInputSerializer(serializers.Serializer):
+ step_id = serializers.CharField(help_text="The id of the workflow step (action) the setting belongs to.")
+ step_name = serializers.CharField(help_text="The step's name, as the editor shows it.")
+ field = serializers.CharField(
+ help_text="The setting to fill, like 'Webhook URL', 'Email sender' or 'Condition: Is on a paid plan'."
+ )
+
+
class DataSuggestionBuildResponseSerializer(serializers.Serializer):
status = serializers.ChoiceField(
choices=DataSuggestionBuildStatus.choices,
help_text="ready when the draft is built, building while a background build runs (call build again to "
- "check), failed when the plan did not produce a valid workflow. A failed result is reported once, so the "
- "next call starts a new build.",
+ "check), failed when the plan did not produce a valid workflow. A failed result stays until a call sends "
+ "retry.",
)
workflow = serializers.JSONField(
allow_null=True,
help_text="With status ready: a validated draft workflow (name, description, trigger, actions, edges, "
- "conversion, exit_condition) that the workflow create endpoint accepts from this caller. Nothing is saved "
- "by this call. Null otherwise.",
+ "conversion, exit_condition) that the workflow create endpoint accepts from this caller. Saved only with "
+ "save_draft. Null otherwise.",
)
uses_saved_template = serializers.BooleanField(help_text="Whether an email step reuses a saved email template.")
+ workflow_id = serializers.CharField(
+ allow_null=True,
+ help_text="With status ready and save_draft: the id of the saved draft workflow. Null otherwise.",
+ )
+ missing_inputs = DataSuggestionMissingInputSerializer(
+ many=True,
+ help_text="With status ready: the settings the draft leaves blank, which must be filled before it is enabled.",
+ )
class WorkflowDataSuggestionsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
@@ -155,7 +186,11 @@ class WorkflowDataSuggestionsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
return not payload.is_valid() or needs_new_build(
team=self.team,
suggestion_id=payload.validated_data["suggestion_id"],
- caller=get_event_source(self.request).value,
+ caller=build_caller(
+ get_event_source(self.request).value,
+ save=payload.validated_data["save_draft"],
+ user_id=cast(User, self.request.user).id,
+ ),
retry=payload.validated_data["retry"],
)
@@ -168,7 +203,7 @@ class WorkflowDataSuggestionsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
@action(detail=False, methods=["get"])
def current(self, request: Request, **kwargs: Any) -> Response:
self._user_with_feature(request)
- return Response(DataSuggestionsResponseSerializer(get_data_suggestions(team=self.team)).data)
+ return self._suggestions_response(get_data_suggestions(team=self.team))
@extend_schema(
operation_id="workflow_data_suggestions_generate",
@@ -181,7 +216,12 @@ class WorkflowDataSuggestionsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
payload = DataSuggestionGenerateRequestSerializer(data=request.data)
payload.is_valid(raise_exception=True)
result = start_data_suggestions(team=self.team, user=user, refresh=payload.validated_data["refresh"])
- return Response(DataSuggestionsResponseSerializer(result).data)
+ return self._suggestions_response(result)
+
+ def _suggestions_response(self, result: DataSuggestionsResult) -> Response:
+ # Read on every call rather than cached with the cards, so it changes as soon as a domain verifies.
+ ready = email_sender_ready(team=self.team)
+ return Response(DataSuggestionsResponseSerializer(result, context={"email_sender_ready": ready}).data)
@extend_schema(
operation_id="workflow_data_suggestions_build",
@@ -199,6 +239,7 @@ class WorkflowDataSuggestionsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
user=user,
suggestion_id=payload.validated_data["suggestion_id"],
retry=payload.validated_data["retry"],
+ save=payload.validated_data["save_draft"],
event_source=get_event_source(request),
)
except DataSuggestionNotFound:
diff --git a/products/workflows/backend/services/data_suggestions/README.md b/products/workflows/backend/services/data_suggestions/README.md
index 98c0b350957a..2501e28a0f2e 100644
--- a/products/workflows/backend/services/data_suggestions/README.md
+++ b/products/workflows/backend/services/data_suggestions/README.md
@@ -33,6 +33,10 @@ Building a draft (`_plan_and_build` in `service.py`):
2. The builder turns the plan into a workflow and rejects plans that do not hold up.
3. The draft is checked the way the caller's own create request checks it.
+Agents use the same endpoints through three MCP tools in `products/workflows/mcp/tools.yaml`: `workflows-data-suggestions-list`, `-get` and `-create`.
+The create tool always sends `save_draft`, so the build task saves the draft itself with the editor's draft rules and returns its `workflow_id`.
+Blank settings come back as `missing_inputs`, for the agent to ask the user about.
+
## Files
| File | What it does |
diff --git a/products/workflows/backend/services/data_suggestions/builder.py b/products/workflows/backend/services/data_suggestions/builder.py
index 0219d218af3d..b104355a920c 100644
--- a/products/workflows/backend/services/data_suggestions/builder.py
+++ b/products/workflows/backend/services/data_suggestions/builder.py
@@ -7,6 +7,7 @@ import structlog
from posthog.dataclasses import frozen
from products.messaging.backend.facade.api import EmailTemplateContent
+from products.workflows.backend.facade.contracts import MissingInput
from products.workflows.backend.services.data_suggestions.email_design import EmailCopy, render_email
from products.workflows.backend.services.data_suggestions.planner import (
MAX_PLANNED_STEPS,
@@ -361,3 +362,43 @@ def clean_copy(text: str) -> str:
cleaned = cleaned.replace("{", "").replace("}", "").strip()
# Sentence case starts with a capital, which the model does not always write.
return cleaned[:1].upper() + cleaned[1:]
+
+
+def missing_inputs(
+ workflow: dict[str, Any], input_schemas: dict[str, list[dict[str, Any]]], *, sender_field: str = "Email sender"
+) -> tuple[MissingInput, ...]:
+ """The settings a draft leaves blank: required template inputs, the email sender and unset branch conditions.
+ `input_schemas` maps a template id to its inputs schema."""
+ missing: list[MissingInput] = []
+ for action in workflow["actions"]:
+ config = action.get("config") or {}
+ fields: list[str] = []
+ if action["type"] == "conditional_branch":
+ fields += [
+ f"Condition: {condition.get('name') or 'unnamed'}"
+ for condition in config.get("conditions") or []
+ if not _has_conditions(condition.get("filters"))
+ ]
+ if action["type"] == "function_email":
+ sender = (((config.get("inputs") or {}).get("email") or {}).get("value") or {}).get("from") or {}
+ if not sender.get("email"):
+ fields.append(sender_field)
+ else:
+ inputs = config.get("inputs") or {}
+ fields += [
+ item.get("label") or item.get("key") or "input"
+ for item in input_schemas.get(config.get("template_id") or "", [])
+ if item.get("required") and _is_blank((inputs.get(item.get("key")) or {}).get("value"))
+ ]
+ step_name = action.get("name") or action["id"]
+ missing += [MissingInput(step_id=action["id"], step_name=step_name, field=field) for field in fields]
+ return tuple(missing)
+
+
+def _has_conditions(filters: Any) -> bool:
+ # The draft check compiles every condition, so an unset one still carries source and bytecode keys.
+ return isinstance(filters, dict) and any(filters.get(key) for key in ("properties", "events", "actions"))
+
+
+def _is_blank(value: Any) -> bool:
+ return value is None or value == "" or value == [] or value == {}
diff --git a/products/workflows/backend/services/data_suggestions/service.py b/products/workflows/backend/services/data_suggestions/service.py
index 5f51aa57e571..7119a2b43eea 100644
--- a/products/workflows/backend/services/data_suggestions/service.py
+++ b/products/workflows/backend/services/data_suggestions/service.py
@@ -17,7 +17,7 @@ from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQue
from posthog.exceptions_capture import capture_exception
from posthog.llm.system_one_client import system_one_configured
from posthog.models import Team, User
-from posthog.ph_client import get_client
+from posthog.ph_client import get_client, ph_scoped_capture
from posthog.utils import get_instance_region
from products.messaging.backend.facade.api import EmailTemplateContent, EmailTemplateSummary, get_template_email_content
@@ -26,9 +26,15 @@ from products.workflows.backend.facade.contracts import (
DataSuggestion,
DataSuggestionNotFound,
DataSuggestionsResult,
+ MissingInput,
)
from products.workflows.backend.services.data_suggestions import team_context
-from products.workflows.backend.services.data_suggestions.builder import BuildContext, build_workflow, clean_copy
+from products.workflows.backend.services.data_suggestions.builder import (
+ BuildContext,
+ build_workflow,
+ clean_copy,
+ missing_inputs,
+)
from products.workflows.backend.services.data_suggestions.event_volume import weekly_counts
from products.workflows.backend.services.data_suggestions.planner import (
MAX_PLANNED_STEPS,
@@ -49,7 +55,7 @@ from products.workflows.backend.services.data_suggestions.stages import (
StageClassificationFailed,
classify_event_stages,
)
-from products.workflows.backend.services.hog_flow_templates import list_step_templates
+from products.workflows.backend.services.hog_flow_templates import get_function_template_schema, list_step_templates
from ee.hogai.utils.feature_flags import is_privacy_mode_enabled
@@ -78,6 +84,8 @@ _BUILDING = BuiltSuggestion(status="building")
_BUILD_FAILED = BuiltSuggestion(status="failed")
_UNAVAILABLE = DataSuggestionsResult(status="unavailable", suggestions=())
_ONCE_PER_PERSON_STAGES = frozenset({"signup", "onboarding"})
+# A project without a verified sender cannot pick one yet, so the field says what to do first.
+NO_SENDER_FIELD = "Email sender (no verified sender yet: add a sending domain under Workflows > Channels)"
def get_data_suggestions(*, team: Team) -> DataSuggestionsResult:
@@ -112,6 +120,10 @@ def start_data_suggestions(*, team: Team, refresh: bool, enqueue: Callable[[str]
return _GENERATING
+def email_sender_ready(*, team: Team) -> bool:
+ return team_context.has_verified_email_sender(team)
+
+
def needs_new_generation(*, team: Team, refresh: bool) -> bool:
"""Whether a generate call would start a run, the only case that costs model time."""
# A refresh always counts, because the run it joins can end before the request reaches the lock.
@@ -155,7 +167,7 @@ def start_build(
"""
if team.organization.is_ai_data_processing_approved is not True or _cached_suggestion(team, suggestion_id) is None:
raise DataSuggestionNotFound()
- stored = _read_build(team.id, suggestion_id, caller)
+ stored = _current_build(team, suggestion_id, caller)
if stored is not None and not (retry and stored.status == "failed"):
return stored
# A second click or tab while a build runs would pay for another plan.
@@ -174,9 +186,16 @@ def start_build(
return _read_build(team.id, suggestion_id, caller) or _BUILDING
+def build_caller(event_source: str, *, save: bool, user_id: int) -> str:
+ """The key a build is stored under. A saved build is checked with the editor's draft rules, so it differs from an
+ unsaved build for the same caller. A saved build is also kept per user, because its draft can carry access
+ restrictions another editor of the project does not pass."""
+ return f"{event_source}:save:{user_id}" if save else event_source
+
+
def needs_new_build(*, team: Team, suggestion_id: str, caller: str, retry: bool) -> bool:
"""Whether a build call would start planning, the only case that costs model time."""
- stored = _read_build(team.id, suggestion_id, caller)
+ stored = _current_build(team, suggestion_id, caller)
reusable = stored is not None and not (retry and stored.status == "failed")
return not reusable and cache.get(_build_lock_key(team.id, suggestion_id, caller)) is None
@@ -188,9 +207,11 @@ def run_build(
suggestion_id: str,
caller: str,
lock_token: str,
- is_valid_draft: Callable[[Team, dict[str, Any]], bool],
+ validate_draft: Callable[[Team, dict[str, Any]], dict[str, Any] | None],
+ save_draft: Callable[[Team, User, dict[str, Any]], str] | None = None,
) -> None:
- """The background build that `start_build` queues. It stores the result and releases the lock."""
+ """The background build that `start_build` queues. It stores the result and releases the lock. With `save_draft`
+ it also saves the draft, for callers like agents that cannot save one in the editor."""
lock_key = _build_lock_key(team_id, suggestion_id, caller)
try:
try:
@@ -202,9 +223,12 @@ def run_build(
if team.organization.is_ai_data_processing_approved is not True or suggestion is None or cached is None:
result = _BUILD_FAILED
else:
- result = _plan_and_build(
- team=team, user=user, suggestion=suggestion, events=cached.events, is_valid_draft=is_valid_draft
+ result, validated = _plan_and_build(
+ team=team, user=user, suggestion=suggestion, events=cached.events, validate_draft=validate_draft
)
+ # A task that outlived its lock would save a second draft next to the newer run's draft.
+ if save_draft is not None and validated is not None and not _lost_lock(lock_key, lock_token):
+ result = dataclasses.replace(result, workflow_id=save_draft(team, user, validated))
except Exception as error:
# Without a stored failure the next poll finds no result and no lock, and queues the same build again.
logger.exception("workflows.data_suggestions.build_failed", team_id=team_id)
@@ -213,6 +237,9 @@ def run_build(
ttl = _BUILD_CACHE_SECONDS if result.status == "ready" else FAILURE_CACHE_TTL_SECONDS
if not _lost_lock(lock_key, lock_token):
cache.set(_build_key(team_id, suggestion_id, caller), dataclasses.asdict(result), ttl)
+ # Sent after the result is stored, so a slow analytics delivery never keeps a saved draft reading as building.
+ if result.workflow_id is not None and suggestion is not None:
+ _capture_saved_build(user=user, suggestion=suggestion, result=result, caller=caller)
finally:
_release(lock_key, lock_token)
@@ -223,8 +250,8 @@ def _plan_and_build(
user: User,
suggestion: DataSuggestion,
events: tuple[str, ...],
- is_valid_draft: Callable[[Team, dict[str, Any]], bool],
-) -> BuiltSuggestion:
+ validate_draft: Callable[[Team, dict[str, Any]], dict[str, Any] | None],
+) -> tuple[BuiltSuggestion, dict[str, Any] | None]:
idea = WorkflowIdea(
name=suggestion.name,
description=suggestion.description,
@@ -251,7 +278,7 @@ def _plan_and_build(
analytics_client=analytics_client,
)
if plan is None:
- return _BUILD_FAILED
+ return _BUILD_FAILED, None
built = build_workflow(
idea,
@@ -266,12 +293,67 @@ def _plan_and_build(
once_per_person=suggestion.stage in _ONCE_PER_PERSON_STAGES,
),
)
- if built is None or not is_valid_draft(team, built.workflow):
- return _BUILD_FAILED
+ if built is None:
+ return _BUILD_FAILED, None
+ validated = validate_draft(team, built.workflow)
# Saved templates are copied into every email step, and a draft larger than a request body cannot be saved.
- if len(json.dumps(built.workflow)) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE:
- return _BUILD_FAILED
- return BuiltSuggestion(status="ready", workflow=built.workflow, uses_saved_template=built.uses_saved_template)
+ if validated is None or len(json.dumps(built.workflow)) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE:
+ return _BUILD_FAILED, None
+ result = BuiltSuggestion(
+ status="ready",
+ workflow=built.workflow,
+ uses_saved_template=built.uses_saved_template,
+ missing_inputs=_missing_inputs(team, built.workflow),
+ )
+ return result, validated
+
+
+def _current_build(team: Team, suggestion_id: str, caller: str) -> BuiltSuggestion | None:
+ """The stored build. A saved draft is read again, so a deleted draft gets a new build and the blank settings
+ match the draft as it is now, for example after the team added a sender."""
+ stored = _read_build(team.id, suggestion_id, caller)
+ if stored is None or stored.workflow_id is None:
+ return stored
+ actions = team_context.saved_workflow_actions(team, stored.workflow_id)
+ if actions is None:
+ return None
+ return dataclasses.replace(stored, missing_inputs=_missing_inputs(team, {"actions": actions}))
+
+
+def _missing_inputs(team: Team, workflow: dict[str, Any]) -> tuple[MissingInput, ...]:
+ return missing_inputs(
+ workflow,
+ _input_schemas(workflow),
+ sender_field="Email sender" if team_context.has_verified_email_sender(team) else NO_SENDER_FIELD,
+ )
+
+
+def _input_schemas(workflow: dict[str, Any]) -> dict[str, list[dict[str, Any]]]:
+ template_ids = {(action.get("config") or {}).get("template_id") for action in workflow["actions"]}
+ schemas: dict[str, list[dict[str, Any]]] = {}
+ for template_id in {template_id for template_id in template_ids if isinstance(template_id, str)}:
+ schema = get_function_template_schema(template_id)
+ if schema is not None:
+ schemas[template_id] = list(schema.inputs_schema or [])
+ return schemas
+
+
+def _capture_saved_build(*, user: User, suggestion: DataSuggestion, result: BuiltSuggestion, caller: str) -> None:
+ # The web page sends this event from the browser. A saved build has no browser, so the funnel gets it from here.
+ with ph_scoped_capture() as capture:
+ # pinned: analytics event name - renaming breaks dashboards
+ capture(
+ distinct_id=user.distinct_id,
+ event="workflows data suggestion built",
+ properties={
+ "workflow_id": result.workflow_id,
+ "source": caller.split(":")[0],
+ "trigger_event": suggestion.trigger_event,
+ "stage": suggestion.stage,
+ "uses_saved_template": result.uses_saved_template,
+ "missing_inputs": len(result.missing_inputs),
+ },
+ )
def _chosen_template_bodies(
@@ -344,7 +426,9 @@ def _read_build(team_id: int, suggestion_id: str, caller: str) -> BuiltSuggestio
if not isinstance(stored, dict):
return None
try:
- return BuiltSuggestion(**stored)
+ return BuiltSuggestion(
+ **{**stored, "missing_inputs": tuple(MissingInput(**item) for item in stored.get("missing_inputs") or ())}
+ )
except TypeError:
return None
diff --git a/products/workflows/backend/services/data_suggestions/team_context.py b/products/workflows/backend/services/data_suggestions/team_context.py
index 7484a5920d2d..f0ed5238da77 100644
--- a/products/workflows/backend/services/data_suggestions/team_context.py
+++ b/products/workflows/backend/services/data_suggestions/team_context.py
@@ -1,5 +1,7 @@
"""What the team already has: workflows, integrations and saved email templates."""
+from typing import Any
+
from posthog.models import Team
from posthog.models.integration import Integration
@@ -22,6 +24,33 @@ def used_trigger_events(team: Team) -> set[str]:
return used
+def saved_workflow_actions(team: Team, workflow_id: str) -> list[dict[str, Any]] | None:
+ """The actions of a draft a build saved, or None when it was deleted or archived. A secret input someone filled
+ lives in the encrypted maps instead of the actions, so it comes back as a placeholder, never as its value."""
+ row = (
+ HogFlow.objects.filter(team_id=team.id, id=workflow_id)
+ .exclude(status="archived")
+ .values_list("actions", "encrypted_inputs", "draft_encrypted_inputs")
+ .first()
+ )
+ if row is None:
+ return None
+ actions, *secret_maps = row
+ filled: dict[str, set[str]] = {}
+ for secrets in secret_maps:
+ for action_id, inputs in (secrets or {}).items():
+ filled.setdefault(action_id, set()).update(inputs or {})
+ return [_with_filled_secrets(action, filled.get(action.get("id"), set())) for action in actions or []]
+
+
+def _with_filled_secrets(action: dict[str, Any], keys: set[str]) -> dict[str, Any]:
+ if not keys:
+ return action
+ config = action.get("config") or {}
+ inputs = {**(config.get("inputs") or {}), **{key: {"value": "<set>"} for key in keys}}
+ return {**action, "config": {**config, "inputs": inputs}}
+
+
def channels(team: Team) -> frozenset[Channel]:
kinds = set(Integration.objects.filter(team_id=team.id).values_list("kind", flat=True))
connected: set[Channel] = set()
@@ -44,11 +73,7 @@ def slack_integration_id(team: Team) -> int | None:
def email_sender(team: Team) -> EmailSender | None:
"""The project's default sender, or its only verified sender. With several and no default the step stays
blank, so the team picks one rather than a draft sending from an identity nobody chose."""
- verified = [
- EmailSender(integration_id=integration.id, email=str(config["email"]), name=str(config.get("name") or ""))
- for integration in Integration.objects.filter(team_id=team.id, kind="email").order_by("created_at")
- if (config := integration.config or {}).get("verified") is True and config.get("email")
- ]
+ verified = _verified_senders(team)
default_id = (
TeamWorkflowsConfig.objects.filter(team_id=team.id)
.values_list("default_email_integration_id", flat=True)
@@ -60,5 +85,17 @@ def email_sender(team: Team) -> EmailSender | None:
return verified[0] if len(verified) == 1 else None
+def has_verified_email_sender(team: Team) -> bool:
+ return bool(_verified_senders(team))
+
+
+def _verified_senders(team: Team) -> list[EmailSender]:
+ return [
+ EmailSender(integration_id=integration.id, email=str(config["email"]), name=str(config.get("name") or ""))
+ for integration in Integration.objects.filter(team_id=team.id, kind="email").order_by("created_at")
+ if (config := integration.config or {}).get("verified") is True and config.get("email")
+ ]
+
+
def email_templates(team: Team) -> tuple[EmailTemplateSummary, ...]:
return tuple(list_email_templates(team.id, limit=_TEMPLATES_LIMIT))
diff --git a/products/workflows/backend/tasks/data_suggestions.py b/products/workflows/backend/tasks/data_suggestions.py
index 34dde4a28f48..14692fd414cb 100644
--- a/products/workflows/backend/tasks/data_suggestions.py
+++ b/products/workflows/backend/tasks/data_suggestions.py
@@ -1,10 +1,11 @@
from celery import shared_task
from posthog.event_usage import EventSource
+from posthog.models.scoping import team_scope
from posthog.scoping_audit import skip_team_scope_audit
from posthog.tasks.utils import CeleryQueue
-from products.workflows.backend.services.data_suggestions.service import run_build, run_data_suggestions
+from products.workflows.backend.services.data_suggestions.service import build_caller, run_build, run_data_suggestions
@shared_task(ignore_result=True, queue=CeleryQueue.LONG_RUNNING.value)
@@ -15,17 +16,25 @@ def generate_data_suggestions(team_id: int, user_id: int, lock_token: str) -> No
@shared_task(ignore_result=True, queue=CeleryQueue.LONG_RUNNING.value)
@skip_team_scope_audit
-def build_data_suggestion(team_id: int, user_id: int, suggestion_id: str, lock_token: str, event_source: str) -> None:
+def build_data_suggestion(
+ team_id: int, user_id: int, suggestion_id: str, lock_token: str, event_source: str, save: bool = False
+) -> None:
# hog_flow.py imports this package through hog_flow_writes, and the draft check imports hog_flow.py.
from products.workflows.backend.presentation.views.data_suggestion_drafts import ( # noqa: PLC0415 - circular import
- is_valid_draft,
+ save_draft,
+ validated_draft,
)
- run_build(
- team_id=team_id,
- user_id=user_id,
- suggestion_id=suggestion_id,
- caller=event_source,
- lock_token=lock_token,
- is_valid_draft=lambda team, workflow: is_valid_draft(team, workflow, EventSource(event_source)),
- )
+ # A saved draft is checked with the editor's draft rules, so blank settings stay blank for the caller to fill.
+ rules = EventSource.WEB if save else EventSource(event_source)
+ # Saving writes team-scoped rows, and a worker has no request to set the team.
+ with team_scope(team_id):
+ run_build(
+ team_id=team_id,
+ user_id=user_id,
+ suggestion_id=suggestion_id,
+ caller=build_caller(event_source, save=save, user_id=user_id),
+ lock_token=lock_token,
+ validate_draft=lambda team, workflow: validated_draft(team, workflow, rules),
+ save_draft=save_draft if save else None,
+ )
diff --git a/products/workflows/backend/test/test_data_suggestions.py b/products/workflows/backend/test/test_data_suggestions.py
index 8eb7fe938f33..13cb2a9b169d 100644
--- a/products/workflows/backend/test/test_data_suggestions.py
+++ b/products/workflows/backend/test/test_data_suggestions.py
@@ -16,7 +16,7 @@ from products.workflows.backend.presentation.views.workflow_data_suggestions imp
DataSuggestionStage,
DataSuggestionStepKind,
)
-from products.workflows.backend.services.data_suggestions.builder import BuildContext, build_workflow
+from products.workflows.backend.services.data_suggestions.builder import BuildContext, build_workflow, missing_inputs
from products.workflows.backend.services.data_suggestions.email_design import EmailCopy, render_email
from products.workflows.backend.services.data_suggestions.llm import invoke_structured, strict_schema
from products.workflows.backend.services.data_suggestions.planner import (
@@ -198,6 +198,11 @@ class TestDataSuggestions(SimpleTestCase):
assert "slack_workspace" not in slack_inputs
assert slack_inputs["text"]["value"] == "Trial user needs help"
assert actions["action_5_wait_until_time_window"]["config"]["day"] == "weekday"
+ webhook_schema = {"template-webhook": [{"key": "url", "label": "Webhook URL", "required": True}]}
+ assert {(item.step_id, item.field) for item in missing_inputs(built.workflow, webhook_schema)} == {
+ ("action_0_email", "Email sender"),
+ ("action_2_function", "Webhook URL"),
+ }
@patch("products.workflows.backend.services.data_suggestions.llm.logger")
@patch("products.workflows.backend.services.data_suggestions.llm.is_privacy_mode_enabled", return_value=True)
diff --git a/products/workflows/backend/tests/api/test_workflow_data_suggestions.py b/products/workflows/backend/tests/api/test_workflow_data_suggestions.py
index b8e4cf8b4e2c..624cf828a1d2 100644
--- a/products/workflows/backend/tests/api/test_workflow_data_suggestions.py
+++ b/products/workflows/backend/tests/api/test_workflow_data_suggestions.py
@@ -10,9 +10,11 @@ from clickhouse_driver.errors import NetworkError
from parameterized import parameterized
from posthog.errors import InternalCHQueryError
+from posthog.event_usage import EventSource
from posthog.exceptions import ClickHouseQueryTimeOut
from posthog.models.integration import Integration
from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
+from posthog.models.user import User
from posthog.models.utils import generate_random_token_personal
from products.cdp.backend.templates.hog_function_template import sync_template_to_db
@@ -20,7 +22,8 @@ from products.messaging.backend.facade.testing import create_message_template_fo
from products.workflows.backend.facade.contracts import DataSuggestionsResult
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig
-from products.workflows.backend.services.data_suggestions.builder import BuildContext, build_workflow
+from products.workflows.backend.presentation.views.data_suggestion_drafts import validated_draft
+from products.workflows.backend.services.data_suggestions.builder import BuildContext, build_workflow, missing_inputs
from products.workflows.backend.services.data_suggestions.event_volume import FULL_SCAN_MAX_WEEKLY_EVENTS, weekly_counts
from products.workflows.backend.services.data_suggestions.planner import (
PlannedBranch,
@@ -30,16 +33,24 @@ from products.workflows.backend.services.data_suggestions.planner import (
)
from products.workflows.backend.services.data_suggestions.service import (
FAILURE_CACHE_TTL_SECONDS,
+ NO_SENDER_FIELD,
_build_key,
+ _build_lock_key,
_cache_key,
_generation_lock_key,
_to_cache,
+ build_caller,
run_data_suggestions,
start_build,
)
from products.workflows.backend.services.data_suggestions.stages import StageClassificationFailed
-from products.workflows.backend.services.data_suggestions.team_context import email_sender
+from products.workflows.backend.services.data_suggestions.team_context import (
+ email_sender,
+ has_verified_email_sender,
+ saved_workflow_actions,
+)
from products.workflows.backend.services.email_sending_controls import ensure_workflows_config
+from products.workflows.backend.tasks.data_suggestions import build_data_suggestion
from products.workflows.backend.tests.api.test_hog_flow_action_email import _email_function_template, webhook_template
SERVICE = "products.workflows.backend.services.data_suggestions.service"
@@ -133,7 +144,12 @@ class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):
assert dict(context.events) == {"trial_started": 3, "user_registered": 3, "query executed": 30}
assert body["status"] == "ready"
assert [(s["trigger_event"], s["weekly_count"]) for s in body["suggestions"]] == [("trial_started", 3)]
- assert self._list()["suggestions"] == body["suggestions"]
+ assert body["email_sender_ready"] is False
+ Integration.objects.create(team=self.team, kind="email", config={"email": "[email protected]", "verified": True})
+ cached = self._list()
+ assert cached["suggestions"] == body["suggestions"]
+ # The flag is read on every call, so a sender verified after the cards were cached shows up right away.
+ assert cached["email_sender_ready"] is True
assert suggest_ideas.call_count == 1
@patch(f"{SERVICE}.classify_event_stages")
@@ -210,8 +226,8 @@ class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):
classify.return_value = {}
suggest_ideas.return_value = ideas
- assert self._list() == {"status": "unavailable", "suggestions": []}
- assert self._list() == {"status": "unavailable", "suggestions": []}
+ assert self._list() == {"status": "unavailable", "suggestions": [], "email_sender_ready": False}
+ assert self._list() == {"status": "unavailable", "suggestions": [], "email_sender_ready": False}
assert classify.call_count == 1
@patch(f"{SERVICE}.suggest_ideas")
@@ -219,7 +235,7 @@ class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):
suggest_ideas.return_value = [_idea("made_up_event")]
with time_machine.travel(timezone.now(), tick=False) as clock:
- assert self._list() == {"status": "ready", "suggestions": []}
+ assert self._list() == {"status": "ready", "suggestions": [], "email_sender_ready": False}
clock.shift(FAILURE_CACHE_TTL_SECONDS + 60)
self._list()
@@ -291,8 +307,8 @@ class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):
) -> None:
execute.side_effect = error
- assert self._list() == {"status": "unavailable", "suggestions": []}
- assert self._list() == {"status": "unavailable", "suggestions": []}
+ assert self._list() == {"status": "unavailable", "suggestions": [], "email_sender_ready": False}
+ assert self._list() == {"status": "unavailable", "suggestions": [], "email_sender_ready": False}
assert execute.call_count == 1
@parameterized.expand(
@@ -381,7 +397,7 @@ class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):
self.jev_configured.return_value = jev_configured
self.privacy_mode.return_value = privacy_mode
- assert self._list() == {"status": status, "suggestions": []}
+ assert self._list() == {"status": status, "suggestions": [], "email_sender_ready": False}
suggest_ideas.assert_not_called()
@patch(f"{SERVICE}.classify_event_stages")
@@ -394,8 +410,8 @@ class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):
suggestions = self._list()["suggestions"]
classify.side_effect = StageClassificationFailed()
- assert self._list(refresh=True) == {"status": "ready", "suggestions": suggestions}
- assert self._list() == {"status": "ready", "suggestions": suggestions}
+ assert self._list(refresh=True) == {"status": "ready", "suggestions": suggestions, "email_sender_ready": False}
+ assert self._list() == {"status": "ready", "suggestions": suggestions, "email_sender_ready": False}
@patch(f"{SERVICE}.plan_steps")
@patch(f"{SERVICE}.suggest_ideas")
@@ -481,6 +497,9 @@ class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):
branch = next(action for action in built.workflow["actions"] if action["type"] == "conditional_branch")
# The editor's schema rejects null filters, so a suggested branch must look like one added by hand.
assert branch["config"]["conditions"] == [{"filters": {}, "name": "Is on a paid plan"}]
+ # The draft check compiles the empty condition, which must still count as unset.
+ assert validated_draft(self.team, built.workflow, EventSource.WEB) is not None
+ assert [item.field for item in missing_inputs(built.workflow, {})] == ["Condition: Is on a paid plan"]
@patch(f"{SERVICE}.suggest_ideas")
def test_a_second_request_does_not_generate_while_one_is_running(self, suggest_ideas: MagicMock, _flag) -> None:
@@ -488,7 +507,7 @@ class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):
assert self._list()["status"] == "ready"
cache.add(_generation_lock_key(self.team), "another-run", 60)
- assert self._list(refresh=True) == {"status": "generating", "suggestions": []}
+ assert self._list(refresh=True) == {"status": "generating", "suggestions": [], "email_sender_ready": False}
assert suggest_ideas.call_count == 1
cache.delete(_generation_lock_key(self.team))
@@ -624,7 +643,13 @@ class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):
format="json",
)
- assert response.json() == {"status": "building", "workflow": None, "uses_saved_template": False}
+ assert response.json() == {
+ "status": "building",
+ "workflow": None,
+ "uses_saved_template": False,
+ "workflow_id": None,
+ "missing_inputs": [],
+ }
plan_steps.assert_not_called()
@patch(f"{SERVICE}.plan_steps")
@@ -645,19 +670,120 @@ class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):
web = self.client.post(build_url, {"suggestion_id": suggestion_id}, format="json")
self.client.logout()
- api = self.client.post(
- build_url, {"suggestion_id": suggestion_id}, format="json", headers={"authorization": f"Bearer {key}"}
+ auth = {"authorization": f"Bearer {key}"}
+ api = self.client.post(build_url, {"suggestion_id": suggestion_id}, format="json", headers=auth)
+ saved = self.client.post(
+ build_url, {"suggestion_id": suggestion_id, "save_draft": True}, format="json", headers=auth
)
# The webhook URL stays blank, which the web editor saves as a draft and an API client's create rejects.
assert web.json()["status"] == "ready"
assert api.json()["status"] == "failed"
+ # Saving keeps the blank and lists it, so an agent can ask the user for it.
+ draft = HogFlow.objects.get(team=self.team, id=saved.json()["workflow_id"])
+ assert draft.status == "draft"
+ notify = next(action["id"] for action in draft.actions if action["type"] == "function")
+ assert notify in {item["step_id"] for item in saved.json()["missing_inputs"]}
+
+ @patch(f"{SERVICE}.plan_steps")
+ @patch(f"{SERVICE}.suggest_ideas")
+ def test_a_worker_saves_a_built_draft_outside_any_request(
+ self, suggest_ideas: MagicMock, plan_steps: MagicMock, _flag
+ ) -> None:
+ suggest_ideas.return_value = [_idea("trial_started")]
+ plan_steps.return_value = PlannedWorkflow(first_step="welcome", steps=[_email_step("welcome", "Welcome")])
+ suggestion_id = self._list()["suggestions"][0]["id"]
+ caller = build_caller(EventSource.API.value, save=True, user_id=self.user.id)
+ cache.set(_build_lock_key(self.team.id, suggestion_id, caller), "token", 60)
+
+ build_data_suggestion(self.team.id, self.user.id, suggestion_id, "token", EventSource.API.value, True)
+
+ built = cache.get(_build_key(self.team.id, suggestion_id, caller))
+ assert built["status"] == "ready"
+ assert HogFlow.objects.filter(team=self.team, id=built["workflow_id"], status="draft").exists()
+ # The project has no sender, so the agent learns it must add one before it can fill the field.
+ assert [item["field"] for item in built["missing_inputs"]] == [NO_SENDER_FIELD]
+
+ @patch(f"{SERVICE}.plan_steps")
+ @patch(f"{SERVICE}.suggest_ideas")
+ def test_a_worker_that_lost_its_lock_saves_no_draft(
+ self, suggest_ideas: MagicMock, plan_steps: MagicMock, _flag
+ ) -> None:
+ suggest_ideas.return_value = [_idea("trial_started")]
+ plan_steps.return_value = PlannedWorkflow(first_step="welcome", steps=[_email_step("welcome", "Welcome")])
+ suggestion_id = self._list()["suggestions"][0]["id"]
+ caller = build_caller(EventSource.API.value, save=True, user_id=self.user.id)
+ cache.set(_build_lock_key(self.team.id, suggestion_id, caller), "newer-run", 60)
+ drafts_before = HogFlow.objects.filter(team=self.team).count()
+
+ build_data_suggestion(self.team.id, self.user.id, suggestion_id, "stale-run", EventSource.API.value, True)
+
+ assert HogFlow.objects.filter(team=self.team).count() == drafts_before
+
+ @patch(f"{SERVICE}.plan_steps")
+ @patch(f"{SERVICE}.suggest_ideas")
+ def test_another_editor_gets_their_own_saved_draft(
+ self, suggest_ideas: MagicMock, plan_steps: MagicMock, _flag
+ ) -> None:
+ suggest_ideas.return_value = [_idea("trial_started")]
+ plan_steps.return_value = PlannedWorkflow(first_step="welcome", steps=[_email_step("welcome", "Welcome")])
+ suggestion_id = self._list()["suggestions"][0]["id"]
+ build_url = f"/api/projects/{self.team.id}/workflow_data_suggestions/build/"
+ build = {"suggestion_id": suggestion_id, "save_draft": True}
+
+ mine = self.client.post(build_url, build, format="json").json()
+ self.client.force_login(User.objects.create_and_join(self.organization, "[email protected]", None))
+ theirs = self.client.post(build_url, build, format="json").json()
+
+ # A saved draft can carry access restrictions, so one editor never receives another editor's draft.
+ assert theirs["workflow_id"] != mine["workflow_id"]
+
+ def test_a_filled_secret_counts_as_set_without_returning_its_value(self, _flag) -> None:
+ flow = HogFlow.objects.create(
+ team=self.team,
+ name="Draft",
+ status="draft",
+ trigger={"type": "event", "filters": {"events": []}},
+ actions=[{"id": "send", "type": "function", "config": {"template_id": "template-webhook", "inputs": {}}}],
+ encrypted_inputs={"send": {"token": "super-secret"}},
+ )
+
+ actions = saved_workflow_actions(self.team, str(flow.id))
+
+ assert actions is not None
+ assert actions[0]["config"]["inputs"]["token"] == {"value": "<set>"}
+ assert "super-secret" not in str(actions)
+
+ @patch(f"{SERVICE}.plan_steps")
+ @patch(f"{SERVICE}.suggest_ideas")
+ def test_a_saved_build_is_read_again_from_its_draft(
+ self, suggest_ideas: MagicMock, plan_steps: MagicMock, _flag
+ ) -> None:
+ suggest_ideas.return_value = [_idea("trial_started")]
+ plan_steps.return_value = PlannedWorkflow(first_step="welcome", steps=[_email_step("welcome", "Welcome")])
+ suggestion_id = self._list()["suggestions"][0]["id"]
+ build_url = f"/api/projects/{self.team.id}/workflow_data_suggestions/build/"
+ build = {"suggestion_id": suggestion_id, "save_draft": True}
+
+ first = self.client.post(build_url, build, format="json").json()
+ Integration.objects.create(team=self.team, kind="email", config={"email": "[email protected]", "verified": True})
+ cached = self.client.post(build_url, build, format="json").json()
+ HogFlow.objects.filter(team=self.team, id=first["workflow_id"]).delete()
+ rebuilt = self.client.post(build_url, build, format="json").json()
+
+ assert [item["field"] for item in first["missing_inputs"]] == [NO_SENDER_FIELD]
+ assert cached["workflow_id"] == first["workflow_id"]
+ assert [item["field"] for item in cached["missing_inputs"]] == ["Email sender"]
+ assert rebuilt["status"] == "ready"
+ assert rebuilt["workflow_id"] != first["workflow_id"]
+ assert plan_steps.call_count == 2
@parameterized.expand(
[
("the only verified sender", ["[email protected]"], None, "[email protected]"),
("several senders and no default", ["[email protected]", "[email protected]"], None, None),
+ ("no verified sender", [], None, None),
]
)
def test_drafts_send_from(
@@ -684,6 +810,7 @@ class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):
sender = email_sender(self.team)
assert (sender.email if sender else None) == expected
+ assert has_verified_email_sender(self.team) is bool(senders)
def test_build_with_an_unknown_suggestion_is_not_found(self, _flag) -> None:
response = self.client.post(
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 92cb05a34a35..06afbd0dfee6 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -2075,6 +2075,8 @@ export interface DataSuggestionBuildRequestApi {
suggestion_id: string
/** Start a new build when the last one failed. Leave it false when asking for a running build's status. */
retry?: boolean
+ /** Save the built draft in the project and return its workflow_id. Blank settings, like a webhook URL, stay blank and are listed in missing_inputs. Leave it false to get the workflow back without saving. */
+ save_draft?: boolean
}
/**
@@ -2091,17 +2093,33 @@ export const DataSuggestionBuildStatusEnumApi = {
Failed: 'failed',
} as const
+export interface DataSuggestionMissingInputApi {
+ /** The id of the workflow step (action) the setting belongs to. */
+ step_id: string
+ /** The step's name, as the editor shows it. */
+ step_name: string
+ /** The setting to fill, like 'Webhook URL', 'Email sender' or 'Condition: Is on a paid plan'. */
+ field: string
+}
+
export interface DataSuggestionBuildResponseApi {
- /** ready when the draft is built, building while a background build runs (call build again to check), failed when the plan did not produce a valid workflow. A failed result is reported once, so the next call starts a new build.
+ /** ready when the draft is built, building while a background build runs (call build again to check), failed when the plan did not produce a valid workflow. A failed result stays until a call sends retry.
*
* * `ready` - Ready
* * `building` - Building
* * `failed` - Failed */
status: DataSuggestionBuildStatusEnumApi
- /** With status ready: a validated draft workflow (name, description, trigger, actions, edges, conversion, exit_condition) that the workflow create endpoint accepts from this caller. Nothing is saved by this call. Null otherwise. */
+ /** With status ready: a validated draft workflow (name, description, trigger, actions, edges, conversion, exit_condition) that the workflow create endpoint accepts from this caller. Saved only with save_draft. Null otherwise. */
workflow: unknown
/** Whether an email step reuses a saved email template. */
uses_saved_template: boolean
+ /**
+ * With status ready and save_draft: the id of the saved draft workflow. Null otherwise.
+ * @nullable
+ */
+ workflow_id: string | null
+ /** With status ready: the settings the draft leaves blank, which must be filled before it is enabled. */
+ missing_inputs: DataSuggestionMissingInputApi[]
}
/**
@@ -2209,6 +2227,8 @@ export interface DataSuggestionsResponseApi {
status: DataSuggestionsStatusEnumApi
/** Up to 3 suggested workflows, ranked by lifecycle stage and then by weekly volume. */
suggestions: DataSuggestionApi[]
+ /** Whether the project has a verified email sender. Without one, an email workflow can be saved as a draft but cannot send until a sending domain is added and verified. */
+ readonly email_sender_ready: boolean
}
export interface DataSuggestionGenerateRequestApi {
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index 4bd139026435..81c724f2a05b 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -3225,6 +3225,7 @@ export const HogFlowsUserBlastRadiusCreateBody = /* @__PURE__ */ zod.object({
* Workflow ideas written by AI from the project's own events. Both calls are free for the customer.
*/
export const workflowDataSuggestionsBuildBodyRetryDefault = false
+export const workflowDataSuggestionsBuildBodySaveDraftDefault = false
export const WorkflowDataSuggestionsBuildBody = /* @__PURE__ */ zod.object({
suggestion_id: zod.string().describe('The id of a suggestion from the list endpoint.'),
@@ -3234,6 +3235,12 @@ export const WorkflowDataSuggestionsBuildBody = /* @__PURE__ */ zod.object({
.describe(
"Start a new build when the last one failed. Leave it false when asking for a running build's status."
),
+ save_draft: zod
+ .boolean()
+ .default(workflowDataSuggestionsBuildBodySaveDraftDefault)
+ .describe(
+ 'Save the built draft in the project and return its workflow_id. Blank settings, like a webhook URL, stay blank and are listed in missing_inputs. Leave it false to get the workflow back without saving.'
+ ),
})
/**
diff --git a/products/workflows/frontend/setupGuide/suggestions/workflowDataSuggestionsLogic.test.ts b/products/workflows/frontend/setupGuide/suggestions/workflowDataSuggestionsLogic.test.ts
index c28b5f5c0865..0943f1467d65 100644
--- a/products/workflows/frontend/setupGuide/suggestions/workflowDataSuggestionsLogic.test.ts
+++ b/products/workflows/frontend/setupGuide/suggestions/workflowDataSuggestionsLogic.test.ts
@@ -34,16 +34,25 @@ const card: SuggestionCard = {
describe('workflowDataSuggestionsLogic', () => {
beforeEach(() => {
- jest.mocked(workflowDataSuggestionsGenerate).mockResolvedValue({ status: 'ready', suggestions: [] })
+ jest.mocked(workflowDataSuggestionsGenerate).mockResolvedValue({
+ status: 'ready',
+ suggestions: [],
+ email_sender_ready: true,
+ })
initKeaTests()
})
it('polls while the background run generates the cards', async () => {
jest.useFakeTimers()
try {
- jest.mocked(workflowDataSuggestionsGenerate).mockResolvedValue({ status: 'generating', suggestions: [] })
+ jest.mocked(workflowDataSuggestionsGenerate).mockResolvedValue({
+ status: 'generating',
+ suggestions: [],
+ email_sender_ready: true,
+ })
jest.mocked(workflowDataSuggestionsCurrent).mockResolvedValue({
status: 'ready',
+ email_sender_ready: true,
suggestions: [
{
id: 'suggestion-1',
@@ -78,6 +87,8 @@ describe('workflowDataSuggestionsLogic', () => {
status: 'ready',
workflow: { name: 'Welcome new users' },
uses_saved_template: false,
+ workflow_id: null,
+ missing_inputs: [],
})
jest.mocked(hogFlowsCreate).mockResolvedValue({ id: 'workflow-1' } as any)
const logic = workflowDataSuggestionsLogic({ surface: 'empty_state' })
@@ -102,8 +113,20 @@ describe('workflowDataSuggestionsLogic', () => {
jest.useFakeTimers()
try {
jest.mocked(workflowDataSuggestionsBuild)
- .mockResolvedValueOnce({ status: 'building', workflow: null, uses_saved_template: false })
- .mockResolvedValue({ status: 'ready', workflow: { name: 'Welcome' }, uses_saved_template: false })
+ .mockResolvedValueOnce({
+ status: 'building',
+ workflow: null,
+ uses_saved_template: false,
+ workflow_id: null,
+ missing_inputs: [],
+ })
+ .mockResolvedValue({
+ status: 'ready',
+ workflow: { name: 'Welcome' },
+ uses_saved_template: false,
+ workflow_id: null,
+ missing_inputs: [],
+ })
jest.mocked(hogFlowsCreate).mockResolvedValue({ id: 'workflow-1' } as any)
const logic = workflowDataSuggestionsLogic({ surface: 'empty_state' })
logic.mount()
diff --git a/products/workflows/mcp/apps/WorkflowDataSuggestionBuildView.tsx b/products/workflows/mcp/apps/WorkflowDataSuggestionBuildView.tsx
new file mode 100644
index 000000000000..1ca3a8b9e465
--- /dev/null
+++ b/products/workflows/mcp/apps/WorkflowDataSuggestionBuildView.tsx
@@ -0,0 +1,36 @@
+import { type ReactElement } from 'react'
+
+import type { WorkflowDataSuggestionBuild } from './WorkflowDataSuggestionsView'
+
+export function WorkflowDataSuggestionBuildView({ build }: { build: WorkflowDataSuggestionBuild }): ReactElement {
+ if (build.status === 'building') {
+ return <p className="m-0 text-sm text-muted-foreground">Building your workflow. This takes up to a minute.</p>
+ }
+ if (build.status === 'failed') {
+ return <p className="m-0 text-sm text-destructive">{build.error}</p>
+ }
+ return (
+ <div className="flex flex-col gap-1 text-sm">
+ <div className="flex flex-wrap items-center gap-3">
+ <span className="font-medium">Draft saved. It doesn't run until you enable it.</span>
+ {build.editorUrl ? (
+ <a className="text-link underline" href={build.editorUrl} target="_blank" rel="noopener noreferrer">
+ Open in PostHog
+ </a>
+ ) : null}
+ </div>
+ {build.missingInputs.length > 0 ? (
+ <div className="text-muted-foreground">
+ Still to set before you enable it:
+ <ul className="m-0 pl-5">
+ {build.missingInputs.map((input, index) => (
+ <li key={index}>
+ {input.field} in "{input.step_name}"
+ </li>
+ ))}
+ </ul>
+ </div>
+ ) : null}
+ </div>
+ )
+}
diff --git a/products/workflows/mcp/apps/WorkflowDataSuggestionsView.tsx b/products/workflows/mcp/apps/WorkflowDataSuggestionsView.tsx
new file mode 100644
index 000000000000..c701b596d630
--- /dev/null
+++ b/products/workflows/mcp/apps/WorkflowDataSuggestionsView.tsx
@@ -0,0 +1,127 @@
+import { type ReactElement } from 'react'
+
+import { Button, Card, CardContent } from '@posthog/quill'
+
+import { WorkflowDataSuggestionBuildView } from './WorkflowDataSuggestionBuildView'
+
+export interface WorkflowDataSuggestion {
+ id: string
+ name: string
+ description: string
+ reason: string
+ trigger_event: string
+ weekly_count: number
+}
+
+export interface WorkflowDataSuggestionsData {
+ status: 'ready' | 'generating' | 'ai_not_approved' | 'unavailable'
+ suggestions: WorkflowDataSuggestion[]
+ email_sender_ready?: boolean
+}
+
+export interface WorkflowDataSuggestionMissingInput {
+ step_name: string
+ field: string
+}
+
+export type WorkflowDataSuggestionBuild =
+ | { status: 'building' }
+ | { status: 'ready'; editorUrl: string | null; missingInputs: WorkflowDataSuggestionMissingInput[] }
+ | { status: 'failed'; error: string }
+
+export interface WorkflowDataSuggestionsViewProps {
+ data: WorkflowDataSuggestionsData
+ builds: Record<string, WorkflowDataSuggestionBuild>
+ onCreate?: (suggestion: WorkflowDataSuggestion, retry: boolean) => void
+}
+
+const EMPTY_MESSAGES: Record<Exclude<WorkflowDataSuggestionsData['status'], 'ready'>, string> = {
+ generating: 'Suggesting workflows from the events your project sends. This takes a few seconds.',
+ ai_not_approved: 'Suggestions need AI data processing, which this organization has not approved.',
+ unavailable: 'There are no suggestions for this project right now.',
+}
+
+export function WorkflowDataSuggestionsView({
+ data,
+ builds,
+ onCreate,
+}: WorkflowDataSuggestionsViewProps): ReactElement {
+ if (data.status !== 'ready' || data.suggestions.length === 0) {
+ return (
+ <p className="p-4 text-sm text-muted-foreground">
+ {data.status === 'ready' ? EMPTY_MESSAGES.unavailable : EMPTY_MESSAGES[data.status]}
+ </p>
+ )
+ }
+ const building = Object.values(builds).some((build) => build.status === 'building')
+
+ return (
+ <div className="flex flex-col gap-3 p-4">
+ {data.email_sender_ready === false ? (
+ <p className="m-0 text-sm text-muted-foreground">
+ This project can't send email yet. You can create these as drafts now, then add and verify a sending
+ domain under Workflows &gt; Channels before you turn them on.
+ </p>
+ ) : null}
+ {data.suggestions.map((suggestion, index) => (
+ <SuggestionCard
+ key={suggestion.id}
+ suggestion={suggestion}
+ // The top-ranked suggestion is the one primary action, like on the Workflows empty state.
+ primary={index === 0}
+ build={builds[suggestion.id]}
+ disabled={building && builds[suggestion.id]?.status !== 'building'}
+ onCreate={onCreate}
+ />
+ ))}
+ </div>
+ )
+}
+
+function SuggestionCard({
+ suggestion,
+ primary,
+ build,
+ disabled,
+ onCreate,
+}: {
+ suggestion: WorkflowDataSuggestion
+ primary: boolean
+ build: WorkflowDataSuggestionBuild | undefined
+ disabled: boolean
+ onCreate: WorkflowDataSuggestionsViewProps['onCreate']
+}): ReactElement {
+ return (
+ <Card>
+ <CardContent className="flex flex-col gap-2 p-4">
+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
+ <span className="font-semibold">{suggestion.name}</span>
+ <span className="text-xs text-muted-foreground">
+ <code>{suggestion.trigger_event}</code> · {suggestion.weekly_count.toLocaleString()} this week
+ </span>
+ </div>
+ <p className="m-0 text-sm">{suggestion.description}</p>
+ <p className="m-0 text-sm text-muted-foreground">{suggestion.reason}</p>
+ {build?.status === 'ready' ? (
+ <WorkflowDataSuggestionBuildView build={build} />
+ ) : (
+ <div className="flex flex-wrap items-center gap-3">
+ {onCreate ? (
+ <Button
+ variant={primary ? 'primary' : 'outline'}
+ size="sm"
+ disabled={disabled || build?.status === 'building'}
+ onClick={() => onCreate(suggestion, build?.status === 'failed')}
+ >
+ {build?.status === 'building' ? 'Building your workflow…' : 'Create workflow'}
+ </Button>
+ ) : null}
+ {build?.status === 'failed' ? (
+ <span className="text-sm text-destructive">{build.error}</span>
+ ) : null}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/products/workflows/mcp/apps/Workflows.stories.tsx b/products/workflows/mcp/apps/Workflows.stories.tsx
index 93af4c7853af..dc2ef8c8b631 100644
--- a/products/workflows/mcp/apps/Workflows.stories.tsx
+++ b/products/workflows/mcp/apps/Workflows.stories.tsx
@@ -2,7 +2,14 @@ import type { Meta, StoryObj } from '@storybook/react'
import { McpThemeDecorator } from '@posthog/mcp-ui/storybook/decorator'
-import { WorkflowListView, type WorkflowData, type WorkflowListData, WorkflowView } from './index'
+import {
+ WorkflowDataSuggestionsView,
+ type WorkflowDataSuggestionsData,
+ WorkflowListView,
+ type WorkflowData,
+ type WorkflowListData,
+ WorkflowView,
+} from './index'
const meta: Meta = {
title: 'MCP Apps/Workflows',
@@ -77,3 +84,63 @@ export const List: Story = {
render: () => <WorkflowListView data={sampleListData} />,
name: 'Workflow list',
}
+
+const suggestionsData: WorkflowDataSuggestionsData = {
+ status: 'ready',
+ email_sender_ready: true,
+ suggestions: [
+ {
+ id: 'suggestion-1',
+ name: 'Welcome new sign-ups',
+ description: 'Send a welcome email, then a few tips if they have not finished onboarding.',
+ reason: 'People who just signed up are most open to guidance.',
+ trigger_event: 'user_signed_up',
+ weekly_count: 57,
+ },
+ {
+ id: 'suggestion-2',
+ name: 'Help after failed queries',
+ description: 'Send troubleshooting tips when a query fails for someone.',
+ reason: 'A quick hand after a failure keeps people from giving up.',
+ trigger_event: 'query_failed',
+ weekly_count: 21,
+ },
+ {
+ id: 'suggestion-3',
+ name: 'Next steps after onboarding',
+ description: 'Point people to inviting teammates and building a first dashboard.',
+ reason: 'People who finish onboarding are ready for the next feature.',
+ trigger_event: 'onboarding_completed',
+ weekly_count: 29,
+ },
+ ],
+}
+
+export const DataSuggestions: Story = {
+ render: () => <WorkflowDataSuggestionsView data={suggestionsData} builds={{}} onCreate={() => {}} />,
+ name: 'Data suggestions',
+}
+
+export const DataSuggestionsBuilt: Story = {
+ render: () => (
+ <WorkflowDataSuggestionsView
+ data={{ ...suggestionsData, email_sender_ready: false }}
+ builds={{
+ 'suggestion-1': {
+ status: 'ready',
+ editorUrl: 'https://us.posthog.com/project/1/workflows/wf-9/workflow',
+ missingInputs: [
+ { step_name: 'Welcome aboard', field: 'Email sender' },
+ { step_name: 'A few tips to get started', field: 'Email sender' },
+ ],
+ },
+ 'suggestion-2': {
+ status: 'failed',
+ error: "We couldn't build this workflow. Try again, or pick another suggestion.",
+ },
+ }}
+ onCreate={() => {}}
+ />
+ ),
+ name: 'Data suggestions after a build',
+}
diff --git a/products/workflows/mcp/apps/index.ts b/products/workflows/mcp/apps/index.ts
index 3618767ce84a..b7ff6c9661d2 100644
--- a/products/workflows/mcp/apps/index.ts
+++ b/products/workflows/mcp/apps/index.ts
@@ -1,3 +1,12 @@
export { WorkflowView, type WorkflowData, type WorkflowViewProps } from './WorkflowView'
export { WorkflowListView, type WorkflowListData, type WorkflowListViewProps } from './WorkflowListView'
export { EmailTemplateView, type EmailTemplateData, type EmailTemplateViewProps } from './EmailTemplateView'
+export {
+ WorkflowDataSuggestionsView,
+ type WorkflowDataSuggestion,
+ type WorkflowDataSuggestionBuild,
+ type WorkflowDataSuggestionMissingInput,
+ type WorkflowDataSuggestionsData,
+ type WorkflowDataSuggestionsViewProps,
+} from './WorkflowDataSuggestionsView'
+export { WorkflowDataSuggestionBuildView } from './WorkflowDataSuggestionBuildView'
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index 6be17a113fac..31a919a6b535 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -12,6 +12,10 @@ ui_apps:
workflow-list:
type: list
detail_tool: workflows-get
+ workflow-data-suggestions:
+ type: custom
+ app_name: PostHog Workflow Suggestions
+ description: Suggested workflows built from the events a project sends, each with a Create workflow action.
tools:
broadcasts-create:
operation: hog_flows_create
@@ -73,6 +77,93 @@ tools:
cadence with workflows-schedule-create and skip the audience preview. Behavioral targeting ('did event X at
least N times over the last M days') is unsupported; reject it and explain why.
ui_app: workflow
+ workflows-data-suggestions-create:
+ operation: workflow_data_suggestions_build
+ enabled: true
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Create a workflow from a suggestion
+ description: >
+ Build one suggested workflow (a suggestion id from workflows-data-suggestions-list) and save it as a draft
+ in the project. It never runs until enabled. Building takes 10 to 60 seconds: while status is 'building',
+ call this tool again with the same suggestion_id every few seconds; it does not start a second build. With
+ status 'ready' you get workflow_id and missing_inputs, the settings the draft leaves blank (a webhook URL,
+ an email sender, a branch condition), plus _posthogUrl, the editor link. Ask the user for all of them first,
+ then fill them in one workflows-patch-graph call: that tool checks the whole draft, so a patch that leaves
+ another required setting blank is rejected. Or tell them to finish it in the editor. A field that says there
+ is no verified sender means the project cannot send email yet: tell the user to add and verify a sending
+ domain under Workflows > Channels first, instead of asking for an address. Never guess credentials or URLs.
+ With status 'failed', call once more with retry true, then offer another suggestion.
+ exclude_params:
+ - save_draft
+ inject_body:
+ save_draft: true
+ ui_app: workflow-data-suggestions
+ hooks: workflows/dataSuggestionCreateHooks
+ feature_flag: workflows-data-suggestions
+ response:
+ include:
+ - status
+ - workflow_id
+ - missing_inputs
+ - uses_saved_template
+ workflows-data-suggestions-get:
+ operation: workflow_data_suggestions_current
+ enabled: true
+ title: Check suggested workflows
+ description: >
+ Read the suggested workflows without starting anything. Use it to check on a run that
+ workflows-data-suggestions-list started: while status is 'generating', call it again every few seconds, for
+ up to five minutes. 'ready' lists the suggestions, 'unavailable' or 'ai_not_approved' means there are none
+ to show. Present them the same way as workflows-data-suggestions-list.
+ ui_app: workflow-data-suggestions
+ feature_flag: workflows-data-suggestions
+ response:
+ include:
+ - status
+ - suggestions.*.id
+ - suggestions.*.name
+ - suggestions.*.description
+ - suggestions.*.reason
+ - suggestions.*.trigger_event
+ - suggestions.*.weekly_count
+ - email_sender_ready
+ workflows-data-suggestions-list:
+ operation: workflow_data_suggestions_generate
+ enabled: true
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: List suggested workflows
+ description: >
+ Up to three workflows suggested from the project's own events, such as a welcome email for a sign-up event.
+ Use it to help a user who is getting started with workflows. Returns the cached suggestions, or starts
+ making them and returns status 'generating', which takes about 10 to 30 seconds: then call
+ workflows-data-suggestions-get every few seconds until status is 'ready'. Clients that show apps render the
+ suggestions as cards with a Create workflow button, so do not list them again. Otherwise show one line per
+ suggestion, like 'Welcome new sign-ups: a welcome email, then tips (user_signed_up, 57 this week)', and ask
+ which one to create. Always let the user pick, even when they only asked to set up a workflow; create one
+ without asking only when they already named it. When email_sender_ready is false, say that first: the
+ project has no verified email sender, so email workflows can be saved as drafts but cannot send until a
+ sending domain is added and verified under Workflows > Channels. Then offer the suggestions. Never show the
+ ids; the user picks by name or number, and you pass that suggestion's id to
+ workflows-data-suggestions-create. 'ai_not_approved' means the organization has not approved AI data
+ processing; 'unavailable' means there is nothing to suggest right now.
+ ui_app: workflow-data-suggestions
+ feature_flag: workflows-data-suggestions
+ response:
+ include:
+ - status
+ - suggestions.*.id
+ - suggestions.*.name
+ - suggestions.*.description
+ - suggestions.*.reason
+ - suggestions.*.trigger_event
+ - suggestions.*.weekly_count
+ - email_sender_ready
workflows-discard-draft:
operation: hog_flows_discard_draft_create
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 879266126c8a..f484b7ba4a31 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -14918,6 +14918,51 @@
"readOnlyHint": false
}
},
+ "workflows-data-suggestions-create": {
+ "description": "Build one suggested workflow (a suggestion id from workflows-data-suggestions-list) and save it as a draft in the project. It never runs until enabled. Building takes 10 to 60 seconds: while status is 'building', call this tool again with the same suggestion_id every few seconds; it does not start a second build. With status 'ready' you get workflow_id and missing_inputs, the settings the draft leaves blank (a webhook URL, an email sender, a branch condition), plus _posthogUrl, the editor link. Ask the user for all of them first, then fill them in one workflows-patch-graph call: that tool checks the whole draft, so a patch that leaves another required setting blank is rejected. Or tell them to finish it in the editor. A field that says there is no verified sender means the project cannot send email yet: tell the user to add and verify a sending domain under Workflows > Channels first, instead of asking for an address. Never guess credentials or URLs. With status 'failed', call once more with retry true, then offer another suggestion.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Create a workflow from a suggestion",
+ "title": "Create a workflow from a suggestion",
+ "required_scopes": ["hog_flow:write", "query:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "workflows-data-suggestions"
+ },
+ "workflows-data-suggestions-get": {
+ "description": "Read the suggested workflows without starting anything. Use it to check on a run that workflows-data-suggestions-list started: while status is 'generating', call it again every few seconds, for up to five minutes. 'ready' lists the suggestions, 'unavailable' or 'ai_not_approved' means there are none to show. Present them the same way as workflows-data-suggestions-list.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Check suggested workflows",
+ "title": "Check suggested workflows",
+ "required_scopes": ["hog_flow:read", "query:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "workflows-data-suggestions"
+ },
+ "workflows-data-suggestions-list": {
+ "description": "Up to three workflows suggested from the project's own events, such as a welcome email for a sign-up event. Use it to help a user who is getting started with workflows. Returns the cached suggestions, or starts making them and returns status 'generating', which takes about 10 to 30 seconds: then call workflows-data-suggestions-get every few seconds until status is 'ready'. Clients that show apps render the suggestions as cards with a Create workflow button, so do not list them again. Otherwise show one line per suggestion, like 'Welcome new sign-ups: a welcome email, then tips (user_signed_up, 57 this week)', and ask which one to create. Always let the user pick, even when they only asked to set up a workflow; create one without asking only when they already named it. When email_sender_ready is false, say that first: the project has no verified email sender, so email workflows can be saved as drafts but cannot send until a sending domain is added and verified under Workflows > Channels. Then offer the suggestions. Never show the ids; the user picks by name or number, and you pass that suggestion's id to workflows-data-suggestions-create. 'ai_not_approved' means the organization has not approved AI data processing; 'unavailable' means there is nothing to suggest right now.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "List suggested workflows",
+ "title": "List suggested workflows",
+ "required_scopes": ["hog_flow:write", "query:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "workflows-data-suggestions"
+ },
"workflows-discard-draft": {
"description": "Throw away a workflow's staged draft without touching the live config. Idempotent — discarding when nothing is staged is a no-op. Returns the workflow.",
"category": "Workflows",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 9d3c2d405b6c..99c3fe095e09 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -15621,6 +15621,51 @@
"readOnlyHint": false
}
},
+ "workflows-data-suggestions-create": {
+ "description": "Build one suggested workflow (a suggestion id from workflows-data-suggestions-list) and save it as a draft in the project. It never runs until enabled. Building takes 10 to 60 seconds: while status is 'building', call this tool again with the same suggestion_id every few seconds; it does not start a second build. With status 'ready' you get workflow_id and missing_inputs, the settings the draft leaves blank (a webhook URL, an email sender, a branch condition), plus _posthogUrl, the editor link. Ask the user for all of them first, then fill them in one workflows-patch-graph call: that tool checks the whole draft, so a patch that leaves another required setting blank is rejected. Or tell them to finish it in the editor. A field that says there is no verified sender means the project cannot send email yet: tell the user to add and verify a sending domain under Workflows > Channels first, instead of asking for an address. Never guess credentials or URLs. With status 'failed', call once more with retry true, then offer another suggestion.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Create a workflow from a suggestion",
+ "title": "Create a workflow from a suggestion",
+ "required_scopes": ["hog_flow:write", "query:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "workflows-data-suggestions"
+ },
+ "workflows-data-suggestions-get": {
+ "description": "Read the suggested workflows without starting anything. Use it to check on a run that workflows-data-suggestions-list started: while status is 'generating', call it again every few seconds, for up to five minutes. 'ready' lists the suggestions, 'unavailable' or 'ai_not_approved' means there are none to show. Present them the same way as workflows-data-suggestions-list.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Check suggested workflows",
+ "title": "Check suggested workflows",
+ "required_scopes": ["hog_flow:read", "query:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "workflows-data-suggestions"
+ },
+ "workflows-data-suggestions-list": {
+ "description": "Up to three workflows suggested from the project's own events, such as a welcome email for a sign-up event. Use it to help a user who is getting started with workflows. Returns the cached suggestions, or starts making them and returns status 'generating', which takes about 10 to 30 seconds: then call workflows-data-suggestions-get every few seconds until status is 'ready'. Clients that show apps render the suggestions as cards with a Create workflow button, so do not list them again. Otherwise show one line per suggestion, like 'Welcome new sign-ups: a welcome email, then tips (user_signed_up, 57 this week)', and ask which one to create. Always let the user pick, even when they only asked to set up a workflow; create one without asking only when they already named it. When email_sender_ready is false, say that first: the project has no verified email sender, so email workflows can be saved as drafts but cannot send until a sending domain is added and verified under Workflows > Channels. Then offer the suggestions. Never show the ids; the user picks by name or number, and you pass that suggestion's id to workflows-data-suggestions-create. 'ai_not_approved' means the organization has not approved AI data processing; 'unavailable' means there is nothing to suggest right now.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "List suggested workflows",
+ "title": "List suggested workflows",
+ "required_scopes": ["hog_flow:write", "query:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "workflows-data-suggestions"
+ },
"workflows-discard-draft": {
"description": "Throw away a workflow's staged draft without touching the live config. Idempotent — discarding when nothing is staged is a no-op. Returns the workflow.",
"category": "Workflows",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1d3c1ae6414b..af7da9d78c19 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -30169,6 +30169,8 @@ export namespace Schemas {
suggestion_id: string;
/** Start a new build when the last one failed. Leave it false when asking for a running build's status. */
retry?: boolean;
+ /** Save the built draft in the project and return its workflow_id. Blank settings, like a webhook URL, stay blank and are listed in missing_inputs. Leave it false to get the workflow back without saving. */
+ save_draft?: boolean;
}
/**
@@ -30185,17 +30187,33 @@ export namespace Schemas {
Failed: 'failed',
} as const;
+ export interface DataSuggestionMissingInput {
+ /** The id of the workflow step (action) the setting belongs to. */
+ step_id: string;
+ /** The step's name, as the editor shows it. */
+ step_name: string;
+ /** The setting to fill, like 'Webhook URL', 'Email sender' or 'Condition: Is on a paid plan'. */
+ field: string;
+ }
+
export interface DataSuggestionBuildResponse {
- /** ready when the draft is built, building while a background build runs (call build again to check), failed when the plan did not produce a valid workflow. A failed result is reported once, so the next call starts a new build.
+ /** ready when the draft is built, building while a background build runs (call build again to check), failed when the plan did not produce a valid workflow. A failed result stays until a call sends retry.
*
* * `ready` - Ready
* * `building` - Building
* * `failed` - Failed */
status: DataSuggestionBuildStatusEnum;
- /** With status ready: a validated draft workflow (name, description, trigger, actions, edges, conversion, exit_condition) that the workflow create endpoint accepts from this caller. Nothing is saved by this call. Null otherwise. */
+ /** With status ready: a validated draft workflow (name, description, trigger, actions, edges, conversion, exit_condition) that the workflow create endpoint accepts from this caller. Saved only with save_draft. Null otherwise. */
workflow: unknown;
/** Whether an email step reuses a saved email template. */
uses_saved_template: boolean;
+ /**
+ * With status ready and save_draft: the id of the saved draft workflow. Null otherwise.
+ * @nullable
+ */
+ workflow_id: string | null;
+ /** With status ready: the settings the draft leaves blank, which must be filled before it is enabled. */
+ missing_inputs: DataSuggestionMissingInput[];
}
export interface DataSuggestionGenerateRequest {
@@ -30229,6 +30247,8 @@ export namespace Schemas {
status: DataSuggestionsStatusEnum;
/** Up to 3 suggested workflows, ranked by lifecycle stage and then by weekly volume. */
suggestions: DataSuggestion[];
+ /** Whether the project has a verified email sender. Without one, an email workflow can be saved as a draft but cannot send until a sending domain is added and verified. */
+ readonly email_sender_ready: boolean;
}
export interface DataWarehouseExpression {
diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.ts
index 79f7d0ed57a3..23f2b67d808d 100644
--- a/services/mcp/src/generated/workflows/api.ts
+++ b/services/mcp/src/generated/workflows/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 22 enabled ops
+ * PostHog API - MCP 25 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -1294,3 +1294,57 @@ export const HogFlowsMetricsGlobalRetrieveQueryParams = () => zod.object({
),
before: zod.string().min(1).optional().describe("End of the window. Same format as 'after'. Defaults to now."),
})
+
+/**
+ * Workflow ideas written by AI from the project's own events. Both calls are free for the customer.
+ */
+export const WorkflowDataSuggestionsBuildParams = () => 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 workflowDataSuggestionsBuildBodyRetryDefault = false
+
+export const WorkflowDataSuggestionsBuildBody = () => zod.object({
+ suggestion_id: zod.string().describe('The id of a suggestion from the list endpoint.'),
+ retry: zod
+ .boolean()
+ .default(workflowDataSuggestionsBuildBodyRetryDefault)
+ .describe(
+ "Start a new build when the last one failed. Leave it false when asking for a running build's status."
+ ),
+})
+
+/**
+ * Workflow ideas written by AI from the project's own events. Both calls are free for the customer.
+ */
+export const WorkflowDataSuggestionsCurrentParams = () => 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\/."
+ ),
+})
+
+/**
+ * Workflow ideas written by AI from the project's own events. Both calls are free for the customer.
+ */
+export const WorkflowDataSuggestionsGenerateParams = () => 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 workflowDataSuggestionsGenerateBodyRefreshDefault = false
+
+export const WorkflowDataSuggestionsGenerateBody = () => zod.object({
+ refresh: zod
+ .boolean()
+ .default(workflowDataSuggestionsGenerateBodyRefreshDefault)
+ .describe('Make new suggestions even when the cached ones are still valid.'),
+})
diff --git a/services/mcp/src/resources/ui-apps.generated.ts b/services/mcp/src/resources/ui-apps.generated.ts
index b14fa359deb2..eb92d047ffa8 100644
--- a/services/mcp/src/resources/ui-apps.generated.ts
+++ b/services/mcp/src/resources/ui-apps.generated.ts
@@ -30,6 +30,7 @@ export const TRACE_SPAN_LIST_RESOURCE_URI = 'ui://posthog/trace-span-list.html'
export const VISION_OBSERVATION_LIST_RESOURCE_URI = 'ui://posthog/vision-observation-list.html'
export const VISUAL_REVIEW_SNAPSHOTS_RESOURCE_URI = 'ui://posthog/visual-review-snapshots.html'
export const WORKFLOW_RESOURCE_URI = 'ui://posthog/workflow.html'
+export const WORKFLOW_DATA_SUGGESTIONS_RESOURCE_URI = 'ui://posthog/workflow-data-suggestions.html'
export const WORKFLOW_LIST_RESOURCE_URI = 'ui://posthog/workflow-list.html'
export type UiAppKey =
@@ -63,6 +64,7 @@ export type UiAppKey =
| 'vision-observation-list'
| 'visual-review-snapshots'
| 'workflow'
+ | 'workflow-data-suggestions'
| 'workflow-list'
export const URI_MAP: Record<UiAppKey, string> = {
@@ -96,6 +98,7 @@ export const URI_MAP: Record<UiAppKey, string> = {
'vision-observation-list': VISION_OBSERVATION_LIST_RESOURCE_URI,
'visual-review-snapshots': VISUAL_REVIEW_SNAPSHOTS_RESOURCE_URI,
workflow: WORKFLOW_RESOURCE_URI,
+ 'workflow-data-suggestions': WORKFLOW_DATA_SUGGESTIONS_RESOURCE_URI,
'workflow-list': WORKFLOW_LIST_RESOURCE_URI,
}
@@ -325,6 +328,12 @@ export const UI_APPS: Array<{
description: 'Workflow detail view',
appDir: 'generated/workflow',
},
+ {
+ name: 'PostHog Workflow Suggestions',
+ uri: WORKFLOW_DATA_SUGGESTIONS_RESOURCE_URI,
+ description: 'Suggested workflows built from the events a project sends, each with a Create workflow action.',
+ appDir: 'workflow-data-suggestions',
+ },
{
name: 'PostHog Workflow List',
uri: WORKFLOW_LIST_RESOURCE_URI,
diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.ts
index c6589f94f20f..ae9c2ba6add5 100644
--- a/services/mcp/src/tools/generated/workflows.ts
+++ b/services/mcp/src/tools/generated/workflows.ts
@@ -5,8 +5,10 @@ import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/workflows/api'
import { withUiApp } from '@/resources/ui-apps'
import { WorkflowActionEmailPatchSchema, WorkflowGraphPatchSchema } from '@/schema/tool-inputs'
-import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
+import { withToolHooks } from '@/tools/tool-hooks'
+import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+import hooks_workflowsDataSuggestionsCreate from '@/tools/workflows/dataSuggestionCreateHooks'
const BroadcastsCreateSchema = () => {
const HogFlowsCreateBody = orvalSchemas.HogFlowsCreateBody()
@@ -116,6 +118,112 @@ const workflowsCreate = (): ToolBase<ReturnType<typeof WorkflowsCreateSchema>, W
},
})
+const WorkflowsDataSuggestionsCreateSchema = () => {
+ const WorkflowDataSuggestionsBuildBody = orvalSchemas.WorkflowDataSuggestionsBuildBody()
+ return WorkflowDataSuggestionsBuildBody
+}
+
+const workflowsDataSuggestionsCreate = (): ToolBase<
+ ReturnType<typeof WorkflowsDataSuggestionsCreateSchema>,
+ Schemas.DataSuggestionBuildResponse
+> =>
+ withUiApp('workflow-data-suggestions', {
+ name: 'workflows-data-suggestions-create',
+ schema: WorkflowsDataSuggestionsCreateSchema(),
+ handler: withToolHooks(
+ hooks_workflowsDataSuggestionsCreate,
+ async (context: Context, params: z.infer<ReturnType<typeof WorkflowsDataSuggestionsCreateSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.suggestion_id !== undefined) {
+ body['suggestion_id'] = params.suggestion_id
+ }
+ if (params.retry !== undefined) {
+ body['retry'] = params.retry
+ }
+ body['save_draft'] = true
+ const result = await context.api.request<Schemas.DataSuggestionBuildResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/workflow_data_suggestions/build/`,
+ body,
+ })
+ const filtered = pickResponseFields(result, [
+ 'status',
+ 'workflow_id',
+ 'missing_inputs',
+ 'uses_saved_template',
+ ]) as typeof result
+ return filtered
+ }
+ ),
+ })
+
+const WorkflowsDataSuggestionsGetSchema = () => z.object({})
+
+const workflowsDataSuggestionsGet = (): ToolBase<
+ ReturnType<typeof WorkflowsDataSuggestionsGetSchema>,
+ Schemas.DataSuggestionsResponse
+> =>
+ withUiApp('workflow-data-suggestions', {
+ name: 'workflows-data-suggestions-get',
+ schema: WorkflowsDataSuggestionsGetSchema(),
+ handler: async (context: Context, _params: z.infer<ReturnType<typeof WorkflowsDataSuggestionsGetSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.DataSuggestionsResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/workflow_data_suggestions/current/`,
+ })
+ const filtered = pickResponseFields(result, [
+ 'status',
+ 'suggestions.*.id',
+ 'suggestions.*.name',
+ 'suggestions.*.description',
+ 'suggestions.*.reason',
+ 'suggestions.*.trigger_event',
+ 'suggestions.*.weekly_count',
+ 'email_sender_ready',
+ ]) as typeof result
+ return filtered
+ },
+ })
+
+const WorkflowsDataSuggestionsListSchema = () => {
+ const WorkflowDataSuggestionsGenerateBody = orvalSchemas.WorkflowDataSuggestionsGenerateBody()
+ return WorkflowDataSuggestionsGenerateBody
+}
+
+const workflowsDataSuggestionsList = (): ToolBase<
+ ReturnType<typeof WorkflowsDataSuggestionsListSchema>,
+ Schemas.DataSuggestionsResponse
+> =>
+ withUiApp('workflow-data-suggestions', {
+ name: 'workflows-data-suggestions-list',
+ schema: WorkflowsDataSuggestionsListSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof WorkflowsDataSuggestionsListSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.refresh !== undefined) {
+ body['refresh'] = params.refresh
+ }
+ const result = await context.api.request<Schemas.DataSuggestionsResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/workflow_data_suggestions/generate/`,
+ body,
+ })
+ const filtered = pickResponseFields(result, [
+ 'status',
+ 'suggestions.*.id',
+ 'suggestions.*.name',
+ 'suggestions.*.description',
+ 'suggestions.*.reason',
+ 'suggestions.*.trigger_event',
+ 'suggestions.*.weekly_count',
+ 'email_sender_ready',
+ ]) as typeof result
+ return filtered
+ },
+ })
+
const WorkflowsDiscardDraftSchema = () => {
const HogFlowsDiscardDraftCreateParams = orvalSchemas.HogFlowsDiscardDraftCreateParams()
return HogFlowsDiscardDraftCreateParams.omit({ project_id: true })
@@ -731,6 +839,9 @@ const workflowsVersionStats = (): ToolBase<
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'broadcasts-create': broadcastsCreate,
'workflows-create': workflowsCreate,
+ 'workflows-data-suggestions-create': workflowsDataSuggestionsCreate,
+ 'workflows-data-suggestions-get': workflowsDataSuggestionsGet,
+ 'workflows-data-suggestions-list': workflowsDataSuggestionsList,
'workflows-discard-draft': workflowsDiscardDraft,
'workflows-get': workflowsGet,
'workflows-get-invocation': workflowsGetInvocation,
diff --git a/services/mcp/src/tools/workflows/dataSuggestionCreateHooks.ts b/services/mcp/src/tools/workflows/dataSuggestionCreateHooks.ts
new file mode 100644
index 000000000000..c2d0ce349764
--- /dev/null
+++ b/services/mcp/src/tools/workflows/dataSuggestionCreateHooks.ts
@@ -0,0 +1,11 @@
+import type { ToolHooks } from '@/tools/tool-hooks'
+import { withPostHogUrl } from '@/tools/tool-utils'
+import type { Context } from '@/tools/types'
+
+// The editor link only exists once the draft is saved, so a building or failed result gets none.
+async function afterResponse(context: Context, _params: unknown, result: unknown): Promise<unknown> {
+ const workflowId = (result as { workflow_id?: string | null } | null)?.workflow_id
+ return workflowId ? await withPostHogUrl(context, result, `/workflows/${workflowId}/workflow`) : result
+}
+
+export default { afterResponse } satisfies ToolHooks<unknown>
diff --git a/services/mcp/src/ui-apps/apps/workflow-data-suggestions.tsx b/services/mcp/src/ui-apps/apps/workflow-data-suggestions.tsx
new file mode 100644
index 000000000000..d0d45a551dc1
--- /dev/null
+++ b/services/mcp/src/ui-apps/apps/workflow-data-suggestions.tsx
@@ -0,0 +1,137 @@
+import '../styles/tailwind.css'
+
+import type { App } from '@modelcontextprotocol/ext-apps'
+import { useCallback, useState } from 'react'
+import { createRoot } from 'react-dom/client'
+
+import {
+ type WorkflowDataSuggestion,
+ type WorkflowDataSuggestionBuild,
+ type WorkflowDataSuggestionMissingInput,
+ type WorkflowDataSuggestionsData,
+ WorkflowDataSuggestionBuildView,
+ WorkflowDataSuggestionsView,
+} from 'products/workflows/mcp/apps'
+
+import { AppWrapper } from '../components/AppWrapper'
+
+const CHECK_INTERVAL_MS = 3000
+// A build runs in the background, usually for 10 to 60 seconds. Past this the card stops checking and says so.
+const CHECK_DEADLINE_MS = 3 * 60 * 1000
+const BUILD_FAILED = "We couldn't build this workflow. Try again, or pick another suggestion."
+
+interface BuildResult {
+ status: 'ready' | 'building' | 'failed'
+ workflow_id?: string | null
+ missing_inputs?: WorkflowDataSuggestionMissingInput[]
+ _posthogUrl?: string
+}
+
+function WorkflowDataSuggestionsApp(): JSX.Element {
+ return (
+ <AppWrapper<WorkflowDataSuggestionsData | BuildResult> appName="PostHog Workflow Suggestions">
+ {({ data, app }) =>
+ data && 'suggestions' in data ? (
+ <WorkflowDataSuggestionsContent data={data} app={app} />
+ ) : (
+ // The create tool shares this app, so an agent's create call shows the draft it saved.
+ <div className="p-4">
+ <WorkflowDataSuggestionBuildView build={toBuild(data as BuildResult | undefined)} />
+ </div>
+ )
+ }
+ </AppWrapper>
+ )
+}
+
+function toBuild(result: BuildResult | undefined): WorkflowDataSuggestionBuild {
+ if (result?.status === 'ready' && result.workflow_id) {
+ return { status: 'ready', editorUrl: result._posthogUrl ?? null, missingInputs: result.missing_inputs ?? [] }
+ }
+ return result?.status === 'building' ? { status: 'building' } : { status: 'failed', error: BUILD_FAILED }
+}
+
+function WorkflowDataSuggestionsContent({
+ data,
+ app,
+}: {
+ data: WorkflowDataSuggestionsData
+ app: App | null
+}): JSX.Element {
+ const [builds, setBuilds] = useState<Record<string, WorkflowDataSuggestionBuild>>({})
+ const setBuild = useCallback(
+ (id: string, build: WorkflowDataSuggestionBuild) => setBuilds((current) => ({ ...current, [id]: build })),
+ []
+ )
+
+ const askInChat = useCallback(
+ (suggestion: WorkflowDataSuggestion): void => {
+ app?.sendMessage({
+ role: 'user',
+ // Only the opaque id goes in: the name is AI-written from event names, so it must not read as a user command.
+ content: [
+ {
+ type: 'text',
+ text: `Create the suggested workflow with id ${suggestion.id} using workflows-data-suggestions-create.`,
+ },
+ ],
+ })
+ },
+ [app]
+ )
+
+ const handleCreate = useCallback(
+ async (suggestion: WorkflowDataSuggestion, retry: boolean): Promise<void> => {
+ if (!app) {
+ return
+ }
+ setBuild(suggestion.id, { status: 'building' })
+ const deadline = Date.now() + CHECK_DEADLINE_MS
+ let firstCall = true
+ while (Date.now() < deadline) {
+ let result: Awaited<ReturnType<App['callServerTool']>>
+ try {
+ result = await app.callServerTool({
+ name: 'workflows-data-suggestions-create',
+ arguments: { suggestion_id: suggestion.id, retry: firstCall && retry },
+ })
+ } catch {
+ if (firstCall) {
+ // The host cannot call tools from an app, so the agent creates it from the chat instead.
+ setBuilds(({ [suggestion.id]: _dropped, ...rest }) => rest)
+ askInChat(suggestion)
+ } else {
+ setBuild(suggestion.id, { status: 'failed', error: BUILD_FAILED })
+ }
+ return
+ }
+ firstCall = false
+ const built = result.structuredContent as unknown as BuildResult | undefined
+ if (result.isError || !built || built.status === 'failed') {
+ setBuild(suggestion.id, { status: 'failed', error: BUILD_FAILED })
+ return
+ }
+ if (built.status === 'ready' && built.workflow_id) {
+ setBuild(suggestion.id, toBuild(built))
+ return
+ }
+ await new Promise((resolve) => setTimeout(resolve, CHECK_INTERVAL_MS))
+ }
+ setBuild(suggestion.id, { status: 'failed', error: BUILD_FAILED })
+ },
+ [app, askInChat, setBuild]
+ )
+
+ return (
+ <WorkflowDataSuggestionsView
+ data={data}
+ builds={builds}
+ onCreate={(suggestion, retry) => void handleCreate(suggestion, retry)}
+ />
+ )
+}
+
+const container = document.getElementById('root')
+if (container) {
+ createRoot(container).render(<WorkflowDataSuggestionsApp />)
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-data-suggestions-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-data-suggestions-create.json
new file mode 100644
index 000000000000..fb794fc6f04e
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-data-suggestions-create.json
@@ -0,0 +1,16 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "retry": {
+ "default": false,
+ "description": "Start a new build when the last one failed. Leave it false when asking for a running build's status.",
+ "type": "boolean"
+ },
+ "suggestion_id": {
+ "description": "The id of a suggestion from the list endpoint.",
+ "type": "string"
+ }
+ },
+ "required": ["suggestion_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-data-suggestions-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-data-suggestions-get.json
new file mode 100644
index 000000000000..7b7ea9186078
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-data-suggestions-get.json
@@ -0,0 +1,5 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {},
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-data-suggestions-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-data-suggestions-list.json
new file mode 100644
index 000000000000..d29f527be71f
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-data-suggestions-list.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "refresh": {
+ "default": false,
+ "description": "Make new suggestions even when the cached ones are still valid.",
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index ac14fd46b1dd..de743a7c2938 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -1135,10 +1135,11 @@ describe('Tool Filtering - Feature Flags', () => {
'today-rail-nav',
'marketing-analytics-setup-plan-mcp',
'subscription-source-summaries',
+ 'workflows-data-suggestions',
])
)
expect(flags).toContain('ai-observability-offline-evaluations')
- expect(flags).toHaveLength(38)
+ expect(flags).toHaveLength(39)
})
it('keeps human and task context wiki tools on separate scopes', () => {
diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
index 13f124d18d86..4f8b6d2fff25 100644
--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts
+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
@@ -103,6 +103,7 @@ async function loadSnapshotTools(): Promise<Tool<ZodObjectAny>[]> {
'warehouse-suggestions': true,
'scouts-tool-access': true,
'subscription-source-summaries': true,
+ 'workflows-data-suggestions': true,
}
return [...(await getToolsFromContext(createMockContext(), { featureFlags }))].sort((a, b) =>
a.name.localeCompare(b.name)