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): add batch-workflow MCP tools (#61001)

Harley Alexanderaaed68c2b816
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index d0561b15d905..a583c84d8af5 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -11,6 +11,7 @@ from django.db import DatabaseError
from django.db.models import OuterRef, Prefetch, QuerySet, Subquery, prefetch_related_objects
import structlog
+from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_view
from loginas.utils import is_impersonated_session
from prometheus_client import Counter
@@ -1144,6 +1145,12 @@ class CohortSerializer(serializers.ModelSerializer):
@extend_schema_view(
list=extend_schema(
parameters=[
+ OpenApiParameter(
+ name="hide_behavioral_cohorts",
+ type=OpenApiTypes.BOOL,
+ location=OpenApiParameter.QUERY,
+ description="Set true to exclude behavioral (event-based) cohorts, which can't be used in feature flags or batch workflow audiences.",
+ ),
OpenApiParameter(
name="basic",
type=bool,
diff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.ts
index 960b99a96ca3..8e2f512c494e 100644
--- a/products/cohorts/frontend/generated/api.schemas.ts
+++ b/products/cohorts/frontend/generated/api.schemas.ts
@@ -315,6 +315,10 @@ export type CohortsListParams = {
* Return a basic payload that omits the heavy `filters`, `query`, and `groups` fields. Useful for pickers that only need id/name/count.
*/
basic?: boolean
+ /**
+ * Set true to exclude behavioral (event-based) cohorts, which can't be used in feature flags or batch workflow audiences.
+ */
+ hide_behavioral_cohorts?: boolean
/**
* Number of results to return per page.
*/
diff --git a/products/cohorts/mcp/tools.yaml b/products/cohorts/mcp/tools.yaml
index bb2c7100b376..5889ab2e97b7 100644
--- a/products/cohorts/mcp/tools.yaml
+++ b/products/cohorts/mcp/tools.yaml
@@ -92,6 +92,8 @@ tools:
cast: string-int
offset:
cast: string-int
+ hide_behavioral_cohorts:
+ description: Set true to exclude behavioral (event-based) cohorts — not usable in batch workflow audiences.
ui_app: cohort-list
response:
include:
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index e94aec63f1cd..5ffb82e05f72 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -31,7 +31,9 @@ from posthog.cdp.validation import (
InputsSerializer,
generate_template_bytecode,
)
-from posthog.models import Team
+from posthog.event_usage import EventSource, get_event_source
+from posthog.models import Cohort, Team
+from posthog.models.cohort.util import get_all_cohort_dependencies
from posthog.plugins.plugin_server_api import create_hog_flow_invocation_test, create_hog_flow_scheduled_invocation
from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
@@ -145,6 +147,46 @@ class HogFlowActionSerializer(serializers.Serializer):
self.initial_data = data
return super().to_internal_value(data)
+ def _should_enforce_audience_guard(self, is_draft) -> bool:
+ # Non-draft saves always validate. Drafts stay lenient only for the web UI builder (users save
+ # incomplete graphs while building); programmatic callers (MCP, posthog-code, API) send complete
+ # graphs, so enforce even on their drafts and fail fast at create time.
+ if not is_draft:
+ return True
+ request = self.context.get("request")
+ return request is None or get_event_source(request) != EventSource.WEB
+
+ def _reject_behavioral_cohorts_in_audience(self, properties) -> None:
+ # Batch/schedule audiences resolve offline by precalculated membership and can't evaluate event
+ # behavior the way it's intended; the UI hides behavioral cohorts from the audience picker. Mirror
+ # that for API/MCP callers. Mirrors the feature-flag guard in posthog/api/cohort.py.
+ if not isinstance(properties, list):
+ return
+ cohort_ids = [
+ p["value"]
+ for p in properties
+ if isinstance(p, dict) and p.get("type") == "cohort" and p.get("value") is not None
+ ]
+ if not cohort_ids:
+ return
+ project_id = self.context["get_team"]().project_id
+ for cohort_id in cohort_ids:
+ try:
+ cohort = Cohort.objects.get(pk=cohort_id, team__project_id=project_id, deleted=False)
+ except (Cohort.DoesNotExist, ValueError, TypeError):
+ continue # missing/invalid cohort surfaces during audience resolution, not here
+ for dep in [cohort, *get_all_cohort_dependencies(cohort)]:
+ if any(p.type == "behavioral" for p in dep.properties.flat):
+ raise serializers.ValidationError(
+ {
+ "filters": (
+ f"Cohort '{dep.name}' targets event behavior, which batch/schedule audiences "
+ "can't evaluate. Use a static or property-based cohort, or an event trigger "
+ "for behavioral targeting."
+ )
+ }
+ )
+
def validate(self, data):
is_draft = self.context.get("is_draft")
@@ -166,8 +208,8 @@ class HogFlowActionSerializer(serializers.Serializer):
serializer.is_valid(raise_exception=True)
data["config"]["filters"] = serializer.validated_data
elif data.get("config", {}).get("type") == "batch":
+ filters = data.get("config", {}).get("filters", {})
if not is_draft:
- filters = data.get("config", {}).get("filters", {})
if not filters:
raise serializers.ValidationError({"filters": "Filters are required for batch triggers."})
if not isinstance(filters, dict):
@@ -175,10 +217,29 @@ class HogFlowActionSerializer(serializers.Serializer):
properties = filters.get("properties", None)
if properties is not None and not isinstance(properties, list):
raise serializers.ValidationError({"filters": {"properties": "Properties must be an array."}})
+ if self._should_enforce_audience_guard(is_draft) and isinstance(filters, dict):
+ # The audience targets who a person is (properties / cohort membership), not what they did.
+ # Event/action filters are silently dropped by the person-based blast radius (resolving to
+ # "everyone"), so reject them outright — same rejection as a behavioral cohort below, and
+ # enforced together so MCP/API drafts can't slip an event-behavior audience through.
+ if filters.get("events") or filters.get("actions"):
+ raise serializers.ValidationError(
+ {
+ "filters": (
+ "Batch trigger audiences can't filter on event behavior. Use person "
+ "properties or a static/property-based cohort, or an event trigger for "
+ "behavioral targeting."
+ )
+ }
+ )
+ self._reject_behavioral_cohorts_in_audience(filters.get("properties"))
elif data.get("config", {}).get("type") == "schedule":
- # Schedule triggers have no extra validation - the schedule definition
- # lives on a separate HogFlowSchedule row keyed by hog_flow_id.
- pass
+ # The schedule definition lives on a separate HogFlowSchedule row, but a schedule trigger
+ # resolves the same offline audience as batch — guard its cohort refs the same way.
+ if self._should_enforce_audience_guard(is_draft):
+ filters = data.get("config", {}).get("filters", {})
+ if isinstance(filters, dict):
+ self._reject_behavioral_cohorts_in_audience(filters.get("properties"))
else:
if not is_draft:
raise serializers.ValidationError({"config": "Invalid trigger type"})
@@ -320,6 +381,19 @@ class HogFlowScheduleSerializer(serializers.ModelSerializer):
"updated_at",
]
read_only_fields = ["id", "status", "next_run_at", "created_at", "updated_at"]
+ extra_kwargs = {
+ "rrule": {
+ "help_text": (
+ "iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once "
+ "per hour."
+ )
+ },
+ "starts_at": {"help_text": "ISO 8601 datetime the schedule starts from."},
+ "timezone": {"help_text": "IANA timezone for interpreting the RRULE (default 'UTC')."},
+ "variables": {"help_text": "Variable value overrides merged with the workflow defaults on each run."},
+ "status": {"help_text": "active, paused, or completed (set once the RRULE's COUNT/UNTIL is exhausted)."},
+ "next_run_at": {"help_text": "Next scheduled fire time, computed by the scheduler."},
+ }
def validate(self, data):
# For partial updates, fall back to instance values
@@ -442,6 +516,15 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
help_text="Ordered action nodes. Exactly one type='trigger' required. Typically one type='exit' too.",
)
variables = HogFlowVariableSerializer(required=False, help_text="Workflow vars (key, type, default). Total <5KB.")
+ schedules = HogFlowScheduleSerializer(
+ many=True,
+ read_only=True,
+ help_text=(
+ "Recurring schedules attached to this workflow (read-only here; manage via the schedules sub-resource). "
+ "A batch/schedule workflow only fires when it's active AND has an active schedule. Empty for "
+ "non-scheduled workflows."
+ ),
+ )
def to_internal_value(self, data):
status = data.get("status")
@@ -471,6 +554,7 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
"abort_action",
"variables",
"billable_action_types",
+ "schedules",
]
read_only_fields = [
"id",
@@ -481,6 +565,7 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
"trigger", # Derived from the trigger action in the actions array
"abort_action",
"billable_action_types", # Computed field, not user-editable
+ "schedules", # Managed via the schedules sub-resource, surfaced read-only here
]
def validate(self, data):
@@ -588,14 +673,36 @@ class HogFlowFilterSet(FilterSet):
@extend_schema(extensions={"x-product": "workflows"})
class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, viewsets.ModelViewSet):
scope_object = "hog_flow"
- scope_object_read_actions = ["list", "retrieve", "logs", "metrics", "metrics_totals"]
- scope_object_write_actions = ["create", "update", "partial_update", "destroy", "invocations"]
+ scope_object_read_actions = ["list", "retrieve", "logs", "metrics", "metrics_totals", "user_blast_radius"]
+ scope_object_write_actions = [
+ "create",
+ "update",
+ "partial_update",
+ "destroy",
+ "invocations",
+ "schedule_detail",
+ "bulk_delete",
+ ]
queryset = HogFlow.objects.all()
filter_backends = [DjangoFilterBackend]
filterset_class = HogFlowFilterSet
log_source = "hog_flow"
app_source = "hog_flow"
+ def dangerously_get_required_scopes(self, request, view) -> Optional[list[str]]:
+ # Dual-method custom actions need method-aware scopes — the action-name-based read/write
+ # lists above can't distinguish GET (read) from POST (write) on the same action. Without
+ # this, these actions declare no scope and reject all personal-API-key (MCP) access.
+ if self.action in ("batch_jobs", "schedules"):
+ return ["hog_flow:read"] if request.method in ("GET", "HEAD", "OPTIONS") else ["hog_flow:write"]
+ # Sizing an audience runs a person/group count over caller-supplied filters — that's person-data
+ # access, so require person:read on top of workflow read. Without it a hog_flow:read-only token
+ # could use this as a person-existence oracle (e.g. "does email X exist?"). The web builder uses
+ # session auth, so live sizing while editing is unaffected.
+ if self.action == "user_blast_radius":
+ return ["hog_flow:read", "person:read"]
+ return None
+
def get_serializer_class(self) -> type[BaseSerializer]:
return HogFlowMinimalSerializer if self.action == "list" else HogFlowSerializer
@@ -654,27 +761,26 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie
logger.warning("Failed to capture hog_flow_created event", error=str(e))
def perform_update(self, serializer):
- # Guardrails for MCP callers (gated on x-posthog-client: mcp; the frontend and raw API
- # are unaffected). We check the raw request payload, not serializer.validated_data —
- # HogFlowSerializer.validate injects derived fields like 'trigger' and
- # 'billable_action_types' which would otherwise make every status-only PATCH look like
- # an edit.
+ # Guardrails for MCP/LLM callers (gated on x-posthog-client: mcp; the frontend and raw API are
+ # unaffected). We check the raw request payload, not serializer.validated_data — HogFlowSerializer.validate
+ # injects derived fields like 'trigger' and 'billable_action_types' which would otherwise make every
+ # status-only PATCH look like a mixed edit.
if self._is_mcp_request(self.request):
keys = set(self.request.data.keys())
has_status = "status" in keys
has_non_status = bool(keys - {"status"})
- # 1. Live workflows can't be edited. Status-only PATCHes (i.e. the lifecycle
- # tools) pass through.
+ # Active workflows are read-only via MCP for now: edits can break runs already scheduled or in flight,
+ # and there's no revision history to roll back. Status-only PATCHes (the lifecycle tools) pass through.
if serializer.instance.status == HogFlow.State.ACTIVE and has_non_status:
raise exceptions.ValidationError(
- "You can't edit an enabled (active) workflow via MCP. "
- "Disable it first with workflows-disable, then make your changes."
+ "Editing an active workflow isn't supported via MCP yet — changes can break runs already "
+ "scheduled or in flight, and there's no revision history to roll back. Don't disable and "
+ "re-enable it to work around this. If you need different behavior, create a new draft workflow."
)
- # 2. Status changes must go through the dedicated lifecycle tools, which send
- # status-only PATCHes. Mixed payloads are rejected so MCP can't sneak a status
- # transition through workflows-update.
+ # Status transitions must go through the dedicated lifecycle tools (status-only PATCHes); a mixed
+ # status + field payload is rejected so MCP can't sneak a transition through a field update.
if has_status and has_non_status:
raise exceptions.ValidationError(
"Status changes via MCP must use workflows-enable / workflows-disable / "
@@ -774,7 +880,11 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie
return Response({"deleted": deleted_count})
- @action(detail=True, methods=["GET", "POST"])
+ @extend_schema(methods=["GET"], responses=HogFlowBatchJobSerializer(many=True))
+ @extend_schema(methods=["POST"], request=HogFlowBatchJobSerializer, responses=HogFlowBatchJobSerializer)
+ # GET returns a bare list (no pagination) and ignores the viewset's HogFlow filterset; disable both so the
+ # generated schema matches the actual response shape.
+ @action(detail=True, methods=["GET", "POST"], pagination_class=None, filter_backends=[])
def batch_jobs(self, request: Request, *args, **kwargs):
try:
hog_flow = self.get_object()
@@ -782,6 +892,12 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie
raise exceptions.NotFound(f"Workflow {kwargs.get('pk')} not found")
if request.method == "POST":
+ # A batch run sends real messages, so only fire for an enabled workflow. The scheduler applies the
+ # same gate (see internal_process_due_schedules) and the UI disables the manual trigger for non-active
+ # workflows; enforce it here too so API/MCP callers can't start a run the consumer would only drop.
+ if hog_flow.status != HogFlow.State.ACTIVE:
+ raise exceptions.ValidationError("Workflow must be active to run a batch. Enable it first.")
+
serializer = HogFlowBatchJobSerializer(
data={**request.data, "hog_flow": hog_flow.id}, context={**self.get_serializer_context()}
)
@@ -795,8 +911,11 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie
serializer = HogFlowBatchJobSerializer(batch_jobs, many=True)
return Response(serializer.data)
- @extend_schema(responses=HogFlowScheduleSerializer(many=True))
- @action(detail=True, methods=["GET", "POST"])
+ @extend_schema(methods=["GET"], responses=HogFlowScheduleSerializer(many=True))
+ @extend_schema(methods=["POST"], request=HogFlowScheduleSerializer, responses=HogFlowScheduleSerializer)
+ # GET returns a bare list (no pagination) and ignores the viewset's HogFlow filterset; disable both so the
+ # generated schema matches the actual response shape.
+ @action(detail=True, methods=["GET", "POST"], pagination_class=None, filter_backends=[])
def schedules(self, request: Request, *args, **kwargs):
hog_flow = self.get_object()
@@ -810,7 +929,17 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie
serializer = HogFlowScheduleSerializer(schedules, many=True)
return Response(serializer.data)
- @extend_schema(parameters=[OpenApiParameter("schedule_id", str, OpenApiParameter.PATH)])
+ @extend_schema(
+ methods=["PATCH"],
+ request=HogFlowScheduleSerializer,
+ responses=HogFlowScheduleSerializer,
+ parameters=[OpenApiParameter("schedule_id", str, OpenApiParameter.PATH)],
+ )
+ @extend_schema(
+ methods=["DELETE"],
+ responses={204: None},
+ parameters=[OpenApiParameter("schedule_id", str, OpenApiParameter.PATH)],
+ )
@action(detail=True, methods=["PATCH", "DELETE"], url_path="schedules/(?P<schedule_id>[^/.]+)")
def schedule_detail(self, request: Request, schedule_id=None, *args, **kwargs):
hog_flow = self.get_object()
diff --git a/products/workflows/backend/api/hog_flow_batch_job.py b/products/workflows/backend/api/hog_flow_batch_job.py
index 215f2f89f8a6..34f10ca25970 100644
--- a/products/workflows/backend/api/hog_flow_batch_job.py
+++ b/products/workflows/backend/api/hog_flow_batch_job.py
@@ -29,6 +29,19 @@ class HogFlowBatchJobSerializer(serializers.ModelSerializer):
"created_by",
"updated_at",
]
+ extra_kwargs = {
+ "status": {
+ "help_text": (
+ "Not currently tracked — stays at its initial value. Use the workflow logs/metrics "
+ "endpoints for run outcome."
+ )
+ },
+ "hog_flow": {"help_text": "ID of the workflow this batch run belongs to."},
+ "filters": {
+ "help_text": "Audience snapshot the run fanned out to, taken from the workflow's batch trigger filters."
+ },
+ "variables": {"help_text": "Variable value overrides applied to this run."},
+ }
def create(self, validated_data: dict, *args, **kwargs) -> HogFlowBatchJob:
request = self.context["request"]
diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.py
index 79031c9d7071..a19976bb26c9 100644
--- a/products/workflows/backend/api/test/test_hog_flow.py
+++ b/products/workflows/backend/api/test/test_hog_flow.py
@@ -8,7 +8,9 @@ from rest_framework import status
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from posthog.cdp.templates.slack.template_slack import template as template_slack
-from posthog.models import Organization, Team, User
+from posthog.models import Cohort, Organization, Team, User
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
@@ -725,6 +727,7 @@ class TestHogFlowAPI(APIBaseTest):
return flow_id
def test_mcp_cannot_modify_active_workflow(self):
+ # Active workflows are read-only via MCP for now — editing risks breaking already-scheduled runs.
flow_id = self._create_active_hog_flow()
response = self.client.patch(
f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
@@ -732,7 +735,7 @@ class TestHogFlowAPI(APIBaseTest):
HTTP_X_POSTHOG_CLIENT="mcp",
)
assert response.status_code == 400, response.json()
- assert "enabled (active) workflow via MCP" in response.json()["detail"]
+ assert "active workflow isn't supported via MCP" in response.json()["detail"]
@parameterized.expand([("disable_to_draft", "draft"), ("archive", "archived")])
def test_mcp_can_disable_active_workflow(self, _name, target_status):
@@ -795,6 +798,8 @@ class TestHogFlowAPI(APIBaseTest):
assert response.json()["status"] == "active"
def test_mcp_cannot_mix_status_with_other_field_updates(self):
+ # Status changes must route through the lifecycle tools — a mixed status + field PATCH is rejected
+ # (here on a draft, so it's the status-mixing guard rather than the active-workflow read-only guard).
hog_flow, _ = self._create_hog_flow_with_action(
{"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}}
)
@@ -1010,6 +1015,142 @@ class TestHogFlowAPI(APIBaseTest):
"type": "validation_error",
}
+ @parameterized.expand(
+ [
+ ("events", {"events": [{"id": "$pageview", "type": "events"}]}),
+ ("actions", {"actions": [{"id": "5", "type": "actions"}]}),
+ ]
+ )
+ def test_hog_flow_batch_trigger_rejects_event_behavior_filters(self, _name, extra_filters):
+ trigger_action = {
+ "id": "trigger_node",
+ "name": "trigger_1",
+ "type": "trigger",
+ "config": {"type": "batch", "filters": {"properties": [], **extra_filters}},
+ }
+ hog_flow = {"name": "Test Batch Flow", "status": "active", "actions": [trigger_action]}
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+ assert response.status_code == 400, response.json()
+ assert "event" in response.json()["detail"].lower()
+
+ def test_hog_flow_batch_trigger_event_filters_rejected_for_mcp_draft(self):
+ # Same draft discriminator as behavioral cohorts: enforced for programmatic callers, lenient for the UI.
+ trigger_action = {
+ "id": "trigger_node",
+ "name": "trigger_1",
+ "type": "trigger",
+ "config": {
+ "type": "batch",
+ "filters": {"properties": [], "events": [{"id": "$pageview", "type": "events"}]},
+ },
+ }
+ hog_flow = {"name": "Test Batch Flow", "status": "draft", "actions": [trigger_action]}
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow, HTTP_X_POSTHOG_CLIENT="mcp")
+ assert response.status_code == 400, response.json()
+ assert "event" in response.json()["detail"].lower()
+
+ def test_hog_flow_batch_trigger_allows_empty_properties_audience(self):
+ # Empty properties = broadcast to everyone, a legitimate batch audience — must not be rejected.
+ trigger_action = {
+ "id": "trigger_node",
+ "name": "trigger_1",
+ "type": "trigger",
+ "config": {
+ "type": "batch",
+ "filters": {"properties": []},
+ },
+ }
+ hog_flow = {"name": "Test Batch Flow", "status": "active", "actions": [trigger_action]}
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+ assert response.status_code == 201, response.json()
+
+ def _make_cohort(self, *, behavioral=False, static=False, nested_cohort_id=None) -> Cohort:
+ if behavioral:
+ properties = {
+ "type": "OR",
+ "values": [
+ {
+ "type": "OR",
+ "values": [
+ {
+ "key": "$pageview",
+ "type": "behavioral",
+ "value": "performed_event",
+ "event_type": "events",
+ "time_value": 30,
+ "time_interval": "day",
+ }
+ ],
+ }
+ ],
+ }
+ elif nested_cohort_id is not None:
+ properties = {
+ "type": "OR",
+ "values": [{"type": "OR", "values": [{"key": "id", "type": "cohort", "value": nested_cohort_id}]}],
+ }
+ else: # property-based dynamic
+ properties = {
+ "type": "OR",
+ "values": [
+ {
+ "type": "OR",
+ "values": [{"key": "email", "type": "person", "value": "[email protected]", "operator": "exact"}],
+ }
+ ],
+ }
+ filters = {} if static else {"properties": properties}
+ return Cohort.objects.create(team=self.team, name="c", filters=filters, is_static=static)
+
+ def _post_batch_with_cohort(self, cohort_id: int, *, status: str = "active", trigger_type: str = "batch", **extra):
+ trigger_action = {
+ "id": "trigger_node",
+ "name": "trigger_1",
+ "type": "trigger",
+ "config": {
+ "type": trigger_type,
+ "filters": {"properties": [{"key": "id", "type": "cohort", "value": cohort_id, "operator": "in"}]},
+ },
+ }
+ hog_flow = {"name": "Test Batch Flow", "status": status, "actions": [trigger_action]}
+ return self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow, **extra)
+
+ @parameterized.expand(["batch", "schedule"])
+ def test_hog_flow_audience_rejects_behavioral_cohort(self, trigger_type: str):
+ cohort = self._make_cohort(behavioral=True)
+ response = self._post_batch_with_cohort(cohort.pk, trigger_type=trigger_type)
+ assert response.status_code == 400, response.json()
+ assert "behavior" in response.json()["detail"].lower()
+
+ def test_hog_flow_batch_trigger_rejects_nested_behavioral_cohort(self):
+ behavioral = self._make_cohort(behavioral=True)
+ wrapper = self._make_cohort(nested_cohort_id=behavioral.pk)
+ response = self._post_batch_with_cohort(wrapper.pk)
+ assert response.status_code == 400, response.json()
+ assert "behavior" in response.json()["detail"].lower()
+
+ @parameterized.expand([("static", {"static": True}), ("property-based", {})])
+ def test_hog_flow_batch_trigger_allows_non_behavioral_cohort(self, _name, cohort_kwargs):
+ cohort = self._make_cohort(**cohort_kwargs)
+ response = self._post_batch_with_cohort(cohort.pk)
+ assert response.status_code == 201, response.json()
+
+ def test_hog_flow_batch_trigger_behavioral_cohort_rejected_for_mcp_draft(self):
+ # Draft is lenient for the UI builder but enforced for programmatic (MCP) callers.
+ cohort = self._make_cohort(behavioral=True)
+ response = self._post_batch_with_cohort(cohort.pk, status="draft", HTTP_X_POSTHOG_CLIENT="mcp")
+ assert response.status_code == 400, response.json()
+ assert "behavior" in response.json()["detail"].lower()
+
+ def test_hog_flow_batch_trigger_behavioral_cohort_allowed_for_web_draft(self):
+ # Web UI must be able to save incomplete draft graphs without the guard firing.
+ cohort = self._make_cohort(behavioral=True)
+ response = self._post_batch_with_cohort(cohort.pk, status="draft")
+ assert response.status_code == 201, response.json()
+
def test_hog_flow_user_blast_radius_requires_filters(self):
with patch("products.workflows.backend.api.hog_flow.get_user_blast_radius") as mock_get_user_blast_radius:
response = self.client.post(f"/api/projects/{self.team.id}/hog_flows/user_blast_radius", {})
@@ -1032,6 +1173,41 @@ class TestHogFlowAPI(APIBaseTest):
assert response.status_code == 200, response.json()
assert response.json() == {"affected": 4, "total": 10}
+ def test_user_blast_radius_personal_api_key_requires_person_read_scope(self):
+ # Sizing an audience queries person data, so a hog_flow:read-only token must NOT be able to use
+ # this as a person-count oracle — person:read is also required.
+ key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="hog_flow only", user=self.user, secure_value=hash_key_value(key), scopes=["hog_flow:read"]
+ )
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/user_blast_radius",
+ {"filters": {"properties": []}},
+ headers={"authorization": f"Bearer {key}"},
+ )
+ assert response.status_code == 403, response.json()
+ assert "person:read" in response.json().get("detail", "")
+
+ def test_user_blast_radius_personal_api_key_with_person_read_scope_allowed(self):
+ key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="hog_flow + person",
+ user=self.user,
+ secure_value=hash_key_value(key),
+ scopes=["hog_flow:read", "person:read"],
+ )
+ with patch("products.workflows.backend.api.hog_flow.get_user_blast_radius") as mock_get_user_blast_radius:
+ from products.feature_flags.backend.user_blast_radius import BlastRadiusResult # noqa: PLC0415
+
+ mock_get_user_blast_radius.return_value = BlastRadiusResult(affected=1, total=10)
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/user_blast_radius",
+ {"filters": {"properties": []}},
+ headers={"authorization": f"Bearer {key}"},
+ )
+ assert response.status_code == 200, response.json()
+ assert response.json() == {"affected": 1, "total": 10}
+
def test_billable_action_types_computed_correctly(self):
"""Test that billable_action_types is computed correctly and cannot be overridden by clients"""
trigger_action = {
@@ -1180,15 +1356,7 @@ class TestHogFlowAPI(APIBaseTest):
"products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"
)
def test_post_hog_flow_batch_jobs_endpoint_creates_job(self, mock_create_invocation):
- hog_flow, _ = self._create_hog_flow_with_action(
- {
- "template_id": "template-webhook",
- "inputs": {"url": {"value": "https://example.com"}},
- }
- )
- create_response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
- assert create_response.status_code == 201, create_response.json()
- flow_id = create_response.json()["id"]
+ flow_id = self._create_active_hog_flow()
batch_job_data = {
"variables": [{"key": "first_name", "value": "Test"}],
@@ -1202,6 +1370,22 @@ class TestHogFlowAPI(APIBaseTest):
assert response.json()["status"] == "queued"
mock_create_invocation.assert_called_once()
+ def test_post_hog_flow_batch_jobs_endpoint_rejects_non_active_workflow(self):
+ # A batch run is gated on an enabled workflow — a draft (or archived) one can't start a broadcast.
+ hog_flow, _ = self._create_hog_flow_with_action(
+ {"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}}
+ )
+ create_response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+ assert create_response.status_code == 201, create_response.json()
+ flow_id = create_response.json()["id"]
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/batch_jobs",
+ {"variables": [{"key": "first_name", "value": "Test"}]},
+ )
+ assert response.status_code == 400, response.json()
+ assert "active" in response.json()["detail"].lower()
+
def test_post_hog_flow_batch_jobs_endpoint_nonexistent_flow(self):
batch_job_data = {"variables": [{"key": "first_name", "value": "Test"}]}
@@ -1213,26 +1397,9 @@ class TestHogFlowAPI(APIBaseTest):
"products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"
)
def test_get_hog_flow_batch_jobs_only_returns_jobs_for_flow(self, mock_create_invocation):
- hog_flow, _ = self._create_hog_flow_with_action(
- {
- "template_id": "template-webhook",
- "inputs": {"url": {"value": "https://example.com"}},
- }
- )
- create_response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
- assert create_response.status_code == 201, create_response.json()
- flow_id = create_response.json()["id"]
-
- # Create another flow
- hog_flow_2, _ = self._create_hog_flow_with_action(
- {
- "template_id": "template-webhook",
- "inputs": {"url": {"value": "https://example2.com"}},
- }
- )
- create_response_2 = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow_2)
- assert create_response_2.status_code == 201, create_response_2.json()
- flow_id_2 = create_response_2.json()["id"]
+ # Both must be active — the batch_jobs POST is gated on an enabled workflow.
+ flow_id = self._create_active_hog_flow()
+ flow_id_2 = self._create_active_hog_flow()
# Create batch jobs for both flows
batch_job_data_1 = {"variables": [{"key": "first_name", "value": "Test1"}]}
diff --git a/products/workflows/backend/test/test_hog_flow_schedule.py b/products/workflows/backend/test/test_hog_flow_schedule.py
index 9eb6b0d137d6..013b7d3fe87b 100644
--- a/products/workflows/backend/test/test_hog_flow_schedule.py
+++ b/products/workflows/backend/test/test_hog_flow_schedule.py
@@ -146,6 +146,25 @@ class TestHogFlowScheduleAPI(APIBaseTest):
assert schedule.status == "paused"
assert schedule.next_run_at is None
+ def test_workflow_get_includes_nested_schedules(self):
+ workflow = self._create_batch_workflow()
+ self.client.post(self._schedules_url(workflow["id"]), SCHEDULE_DATA)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{workflow['id']}/")
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert "schedules" in data
+ assert len(data["schedules"]) == 1
+ assert data["schedules"][0]["rrule"] == SCHEDULE_DATA["rrule"]
+ assert data["schedules"][0]["status"] == "active"
+
+ def test_workflow_get_includes_empty_schedules_when_none(self):
+ workflow = self._create_batch_workflow()
+
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{workflow['id']}/")
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["schedules"] == []
+
def test_delete_schedule(self):
workflow = self._create_batch_workflow()
create_response = self.client.post(self._schedules_url(workflow["id"]), SCHEDULE_DATA)
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 07b08b72447c..888723642350 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -382,6 +382,48 @@ export interface HogFlowActionApi {
output_variable?: unknown
}
+/**
+ * * `active` - Active
+ * `paused` - Paused
+ * `completed` - Completed
+ */
+export type HogFlowScheduleStatusEnumApi =
+ (typeof HogFlowScheduleStatusEnumApi)[keyof typeof HogFlowScheduleStatusEnumApi]
+
+export const HogFlowScheduleStatusEnumApi = {
+ Active: 'active',
+ Paused: 'paused',
+ Completed: 'completed',
+} as const
+
+export interface HogFlowScheduleApi {
+ readonly id: string
+ /** iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour. */
+ rrule: string
+ /** ISO 8601 datetime the schedule starts from. */
+ starts_at: string
+ /**
+ * IANA timezone for interpreting the RRULE (default 'UTC').
+ * @maxLength 64
+ */
+ timezone?: string
+ /** Variable value overrides merged with the workflow defaults on each run. */
+ variables?: unknown
+ /** active, paused, or completed (set once the RRULE's COUNT/UNTIL is exhausted).
+
+ * `active` - Active
+ * `paused` - Paused
+ * `completed` - Completed */
+ readonly status: HogFlowScheduleStatusEnumApi
+ /**
+ * Next scheduled fire time, computed by the scheduler.
+ * @nullable
+ */
+ readonly next_run_at: string | null
+ readonly created_at: string
+ readonly updated_at: string
+}
+
export interface HogFlowApi {
readonly id: string
/**
@@ -423,6 +465,8 @@ export interface HogFlowApi {
/** Workflow vars (key, type, default). Total <5KB. */
variables?: HogFlowApiVariablesItem[]
readonly billable_action_types: unknown
+ /** Recurring schedules attached to this workflow (read-only here; manage via the schedules sub-resource). A batch/schedule workflow only fires when it's active AND has an active schedule. Empty for non-scheduled workflows. */
+ readonly schedules: readonly HogFlowScheduleApi[]
}
/**
@@ -471,6 +515,50 @@ export interface PatchedHogFlowApi {
/** Workflow vars (key, type, default). Total <5KB. */
variables?: PatchedHogFlowApiVariablesItem[]
readonly billable_action_types?: unknown
+ /** Recurring schedules attached to this workflow (read-only here; manage via the schedules sub-resource). A batch/schedule workflow only fires when it's active AND has an active schedule. Empty for non-scheduled workflows. */
+ readonly schedules?: readonly HogFlowScheduleApi[]
+}
+
+/**
+ * * `waiting` - Waiting
+ * `queued` - Queued
+ * `active` - Active
+ * `completed` - Completed
+ * `cancelled` - Cancelled
+ * `failed` - Failed
+ */
+export type HogFlowBatchJobStatusEnumApi =
+ (typeof HogFlowBatchJobStatusEnumApi)[keyof typeof HogFlowBatchJobStatusEnumApi]
+
+export const HogFlowBatchJobStatusEnumApi = {
+ Waiting: 'waiting',
+ Queued: 'queued',
+ Active: 'active',
+ Completed: 'completed',
+ Cancelled: 'cancelled',
+ Failed: 'failed',
+} as const
+
+export interface HogFlowBatchJobApi {
+ readonly id: string
+ /** Not currently tracked — stays at its initial value. Use the workflow logs/metrics endpoints for run outcome.
+
+ * `waiting` - Waiting
+ * `queued` - Queued
+ * `active` - Active
+ * `completed` - Completed
+ * `cancelled` - Cancelled
+ * `failed` - Failed */
+ status?: HogFlowBatchJobStatusEnumApi
+ /** ID of the workflow this batch run belongs to. */
+ hog_flow: string
+ /** Audience snapshot the run fanned out to, taken from the workflow's batch trigger filters. */
+ filters?: unknown
+ /** Variable value overrides applied to this run. */
+ variables?: unknown
+ readonly created_at: string
+ readonly created_by: UserBasicApi
+ readonly updated_at: string
}
/**
@@ -505,41 +593,32 @@ export interface AppMetricsTotalsResponseApi {
totals: AppMetricsTotalsResponseApiTotals
}
-/**
- * * `active` - Active
- * `paused` - Paused
- * `completed` - Completed
- */
-export type HogFlowScheduleStatusEnumApi =
- (typeof HogFlowScheduleStatusEnumApi)[keyof typeof HogFlowScheduleStatusEnumApi]
-
-export const HogFlowScheduleStatusEnumApi = {
- Active: 'active',
- Paused: 'paused',
- Completed: 'completed',
-} as const
-
-export interface HogFlowScheduleApi {
- readonly id: string
- rrule: string
- starts_at: string
- /** @maxLength 64 */
+export interface PatchedHogFlowScheduleApi {
+ readonly id?: string
+ /** iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour. */
+ rrule?: string
+ /** ISO 8601 datetime the schedule starts from. */
+ starts_at?: string
+ /**
+ * IANA timezone for interpreting the RRULE (default 'UTC').
+ * @maxLength 64
+ */
timezone?: string
+ /** Variable value overrides merged with the workflow defaults on each run. */
variables?: unknown
- readonly status: HogFlowScheduleStatusEnumApi
- /** @nullable */
- readonly next_run_at: string | null
- readonly created_at: string
- readonly updated_at: string
-}
+ /** active, paused, or completed (set once the RRULE's COUNT/UNTIL is exhausted).
-export interface PaginatedHogFlowScheduleListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: HogFlowScheduleApi[]
+ * `active` - Active
+ * `paused` - Paused
+ * `completed` - Completed */
+ readonly status?: HogFlowScheduleStatusEnumApi
+ /**
+ * Next scheduled fire time, computed by the scheduler.
+ * @nullable
+ */
+ readonly next_run_at?: string | null
+ readonly created_at?: string
+ readonly updated_at?: string
}
/**
@@ -791,62 +870,3 @@ export const HogFlowsMetricsTotalsRetrieveInterval = {
Day: 'day',
Week: 'week',
} as const
-
-export type HogFlowsSchedulesListParams = {
- created_at?: string
- created_by?: number
- id?: string
- /**
- * Number of results to return per page.
- */
- limit?: number
- /**
- * The initial index from which to return the results.
- */
- offset?: number
- /**
- * * `draft` - Draft
- * `active` - Active
- * `archived` - Archived
- */
- status?: HogFlowsSchedulesListStatus
- updated_at?: string
-}
-
-export type HogFlowsSchedulesListStatus = (typeof HogFlowsSchedulesListStatus)[keyof typeof HogFlowsSchedulesListStatus]
-
-export const HogFlowsSchedulesListStatus = {
- Active: 'active',
- Archived: 'archived',
- Draft: 'draft',
-} as const
-
-export type HogFlowsSchedulesCreateParams = {
- created_at?: string
- created_by?: number
- id?: string
- /**
- * Number of results to return per page.
- */
- limit?: number
- /**
- * The initial index from which to return the results.
- */
- offset?: number
- /**
- * * `draft` - Draft
- * `active` - Active
- * `archived` - Archived
- */
- status?: HogFlowsSchedulesCreateStatus
- updated_at?: string
-}
-
-export type HogFlowsSchedulesCreateStatus =
- (typeof HogFlowsSchedulesCreateStatus)[keyof typeof HogFlowsSchedulesCreateStatus]
-
-export const HogFlowsSchedulesCreateStatus = {
- Active: 'active',
- Archived: 'archived',
- Draft: 'draft',
-} as const
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 13f9fbc195f1..5da2b8854471 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -14,7 +14,9 @@ import type {
BlastRadiusApi,
BlastRadiusRequestApi,
HogFlowApi,
+ HogFlowBatchJobApi,
HogFlowInvocationApi,
+ HogFlowScheduleApi,
HogFlowTemplateApi,
HogFlowTemplatesListParams,
HogFlowTemplatesLogsRetrieveParams,
@@ -22,12 +24,10 @@ import type {
HogFlowsLogsRetrieveParams,
HogFlowsMetricsRetrieveParams,
HogFlowsMetricsTotalsRetrieveParams,
- HogFlowsSchedulesCreateParams,
- HogFlowsSchedulesListParams,
PaginatedHogFlowMinimalListApi,
- PaginatedHogFlowScheduleListApi,
PaginatedHogFlowTemplateListApi,
PatchedHogFlowApi,
+ PatchedHogFlowScheduleApi,
PatchedHogFlowTemplateApi,
} from './api.schemas'
@@ -310,16 +310,16 @@ export const hogFlowsDestroy = async (projectId: string, id: string, options?: R
})
}
-export const getHogFlowsBatchJobsRetrieveUrl = (projectId: string, id: string) => {
+export const getHogFlowsBatchJobsListUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/hog_flows/${id}/batch_jobs/`
}
-export const hogFlowsBatchJobsRetrieve = async (
+export const hogFlowsBatchJobsList = async (
projectId: string,
id: string,
options?: RequestInit
-): Promise<HogFlowApi> => {
- return apiMutator<HogFlowApi>(getHogFlowsBatchJobsRetrieveUrl(projectId, id), {
+): Promise<HogFlowBatchJobApi[]> => {
+ return apiMutator<HogFlowBatchJobApi[]>(getHogFlowsBatchJobsListUrl(projectId, id), {
...options,
method: 'GET',
})
@@ -332,14 +332,14 @@ export const getHogFlowsBatchJobsCreateUrl = (projectId: string, id: string) =>
export const hogFlowsBatchJobsCreate = async (
projectId: string,
id: string,
- hogFlowApi: NonReadonly<HogFlowApi>,
+ hogFlowBatchJobApi: NonReadonly<HogFlowBatchJobApi>,
options?: RequestInit
-): Promise<HogFlowApi> => {
- return apiMutator<HogFlowApi>(getHogFlowsBatchJobsCreateUrl(projectId, id), {
+): Promise<HogFlowBatchJobApi> => {
+ return apiMutator<HogFlowBatchJobApi>(getHogFlowsBatchJobsCreateUrl(projectId, id), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(hogFlowApi),
+ body: JSON.stringify(hogFlowBatchJobApi),
})
}
@@ -453,66 +453,36 @@ export const hogFlowsMetricsTotalsRetrieve = async (
})
}
-export const getHogFlowsSchedulesListUrl = (projectId: string, id: string, params?: HogFlowsSchedulesListParams) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : value.toString())
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/hog_flows/${id}/schedules/?${stringifiedParams}`
- : `/api/projects/${projectId}/hog_flows/${id}/schedules/`
+export const getHogFlowsSchedulesListUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/hog_flows/${id}/schedules/`
}
export const hogFlowsSchedulesList = async (
projectId: string,
id: string,
- params?: HogFlowsSchedulesListParams,
options?: RequestInit
-): Promise<PaginatedHogFlowScheduleListApi> => {
- return apiMutator<PaginatedHogFlowScheduleListApi>(getHogFlowsSchedulesListUrl(projectId, id, params), {
+): Promise<HogFlowScheduleApi[]> => {
+ return apiMutator<HogFlowScheduleApi[]>(getHogFlowsSchedulesListUrl(projectId, id), {
...options,
method: 'GET',
})
}
-export const getHogFlowsSchedulesCreateUrl = (
- projectId: string,
- id: string,
- params?: HogFlowsSchedulesCreateParams
-) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : value.toString())
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/hog_flows/${id}/schedules/?${stringifiedParams}`
- : `/api/projects/${projectId}/hog_flows/${id}/schedules/`
+export const getHogFlowsSchedulesCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/hog_flows/${id}/schedules/`
}
export const hogFlowsSchedulesCreate = async (
projectId: string,
id: string,
- hogFlowApi: NonReadonly<HogFlowApi>,
- params?: HogFlowsSchedulesCreateParams,
+ hogFlowScheduleApi: NonReadonly<HogFlowScheduleApi>,
options?: RequestInit
-): Promise<PaginatedHogFlowScheduleListApi> => {
- return apiMutator<PaginatedHogFlowScheduleListApi>(getHogFlowsSchedulesCreateUrl(projectId, id, params), {
+): Promise<HogFlowScheduleApi> => {
+ return apiMutator<HogFlowScheduleApi>(getHogFlowsSchedulesCreateUrl(projectId, id), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(hogFlowApi),
+ body: JSON.stringify(hogFlowScheduleApi),
})
}
@@ -524,14 +494,14 @@ export const hogFlowsSchedulesPartialUpdate = async (
projectId: string,
id: string,
scheduleId: string,
- patchedHogFlowApi?: NonReadonly<PatchedHogFlowApi>,
+ patchedHogFlowScheduleApi?: NonReadonly<PatchedHogFlowScheduleApi>,
options?: RequestInit
-): Promise<HogFlowApi> => {
- return apiMutator<HogFlowApi>(getHogFlowsSchedulesPartialUpdateUrl(projectId, id, scheduleId), {
+): Promise<HogFlowScheduleApi> => {
+ return apiMutator<HogFlowScheduleApi>(getHogFlowsSchedulesPartialUpdateUrl(projectId, id, scheduleId), {
...options,
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(patchedHogFlowApi),
+ body: JSON.stringify(patchedHogFlowScheduleApi),
})
}
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index 7e343d90d90c..10ab9fd350c6 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -825,160 +825,22 @@ export const HogFlowsPartialUpdateBody = /* @__PURE__ */ zod.object({
.describe('Workflow vars (key, type, default). Total <5KB.'),
})
-export const hogFlowsBatchJobsCreateBodyNameMax = 400
-
-export const hogFlowsBatchJobsCreateBodyDescriptionDefault = ``
-export const hogFlowsBatchJobsCreateBodyTriggerMaskingOneTtlMin = 60
-export const hogFlowsBatchJobsCreateBodyTriggerMaskingOneTtlMax = 94608000
-
-export const hogFlowsBatchJobsCreateBodyActionsItemNameMax = 400
-
-export const hogFlowsBatchJobsCreateBodyActionsItemDescriptionDefault = ``
-export const hogFlowsBatchJobsCreateBodyActionsItemFiltersOneSourceDefault = `events`
-export const hogFlowsBatchJobsCreateBodyActionsItemTypeMax = 100
-
export const HogFlowsBatchJobsCreateBody = /* @__PURE__ */ zod.object({
- name: zod.string().max(hogFlowsBatchJobsCreateBodyNameMax).nullish().describe('Workflow name.'),
- description: zod.string().default(hogFlowsBatchJobsCreateBodyDescriptionDefault).describe('Optional description.'),
status: zod
- .enum(['draft', 'active', 'archived'])
- .describe('\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived')
- .optional()
- .describe(
- 'draft (no execution), active (live), archived (disabled).\n\n\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived'
- ),
- trigger_masking: zod
- .union([
- zod.object({
- ttl: zod
- .number()
- .min(hogFlowsBatchJobsCreateBodyTriggerMaskingOneTtlMin)
- .max(hogFlowsBatchJobsCreateBodyTriggerMaskingOneTtlMax)
- .nullish()
- .describe('Hash TTL in seconds (60 to ~94M \/ 3y).'),
- threshold: zod.number().nullish().describe('Min matching events before triggering (k-anonymity).'),
- hash: zod.string().describe("HogQL template, e.g. '{person.properties.email}'."),
- bytecode: zod.unknown().optional().describe('Auto-compiled from hash. Do not set.'),
- }),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Optional dedup: {hash: <HogQL template>, ttl: <seconds, 60-94608000>, threshold?: <int>}. Server compiles bytecode from hash. Omit to disable.'
- ),
- conversion: zod
- .unknown()
- .optional()
- .describe(
- 'Conversion goal: {filters: [<cond>, ...], window_minutes}. <cond>: {key, value, operator, type: event|person|group}. Empty filters = any event in window. Required for exit_on_conversion \/ exit_on_trigger_not_matched_or_conversion. bytecode compiled server-side.'
- ),
- exit_condition: zod
- .enum([
- 'exit_on_conversion',
- 'exit_on_trigger_not_matched',
- 'exit_on_trigger_not_matched_or_conversion',
- 'exit_only_at_end',
- ])
+ .enum(['waiting', 'queued', 'active', 'completed', 'cancelled', 'failed'])
.describe(
- '\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End'
- )
- .optional()
- .describe(
- "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"
- ),
- edges: zod
- .array(
- zod.object({
- to: zod.string().describe('Target action id.'),
- type: zod
- .enum(['continue', 'branch'])
- .describe('\* `continue` - continue\n\* `branch` - branch')
- .describe(
- "continue: fall-through (sequential or the no-match path of conditional_branch). branch: requires 'index' matching config.conditions[index].\n\n\* `continue` - continue\n\* `branch` - branch"
- ),
- index: zod
- .number()
- .optional()
- .describe(
- "Required for type='branch'. Index into config.conditions on conditional_branch \/ wait_until_condition."
- ),
- from: zod.string().describe('Source action id.'),
- })
+ '\* `waiting` - Waiting\n\* `queued` - Queued\n\* `active` - Active\n\* `completed` - Completed\n\* `cancelled` - Cancelled\n\* `failed` - Failed'
)
.optional()
.describe(
- "Graph edges: [{from, to, type: 'continue'|'branch', index?}]. 'continue' = fall-through (sequential, or no-match path of conditional_branch). 'branch' requires 'index': matches config.conditions[index] on conditional_branch \/ wait_until_condition. Every non-exit action needs a reachable next action ('No next action found' otherwise)."
+ 'Not currently tracked — stays at its initial value. Use the workflow logs\/metrics endpoints for run outcome.\n\n\* `waiting` - Waiting\n\* `queued` - Queued\n\* `active` - Active\n\* `completed` - Completed\n\* `cancelled` - Cancelled\n\* `failed` - Failed'
),
- actions: zod
- .array(
- zod.object({
- id: zod.string().describe('Unique node ID within the workflow.'),
- name: zod.string().max(hogFlowsBatchJobsCreateBodyActionsItemNameMax).describe('Display name.'),
- description: zod
- .string()
- .default(hogFlowsBatchJobsCreateBodyActionsItemDescriptionDefault)
- .describe('Optional description.'),
- on_error: zod
- .union([
- zod
- .enum(['continue', 'abort', 'complete', 'branch'])
- .describe(
- '\* `continue` - continue\n\* `abort` - abort\n\* `complete` - complete\n\* `branch` - branch'
- ),
- zod.null(),
- ])
- .optional()
- .describe(
- 'On failure: continue (skip), abort (stop), complete (mark done), branch (follow error edge).\n\n\* `continue` - continue\n\* `abort` - abort\n\* `complete` - complete\n\* `branch` - branch'
- ),
- created_at: zod.number().optional().describe('Created at (epoch ms). Frontend-managed.'),
- updated_at: zod.number().optional().describe('Updated at (epoch ms). Frontend-managed.'),
- filters: zod
- .union([
- zod.object({
- source: zod
- .enum(['events', 'person-updates', 'data-warehouse-table'])
- .describe(
- '\* `events` - events\n\* `person-updates` - person-updates\n\* `data-warehouse-table` - data-warehouse-table'
- )
- .default(hogFlowsBatchJobsCreateBodyActionsItemFiltersOneSourceDefault),
- actions: zod.array(zod.record(zod.string(), zod.unknown())).optional(),
- events: zod.array(zod.record(zod.string(), zod.unknown())).optional(),
- data_warehouse: zod.array(zod.record(zod.string(), zod.unknown())).optional(),
- properties: zod.array(zod.record(zod.string(), zod.unknown())).optional(),
- bytecode: zod.unknown().optional(),
- transpiled: zod.unknown().optional(),
- filter_test_accounts: zod.boolean().optional(),
- bytecode_error: zod.string().optional(),
- }),
- zod.null(),
- ])
- .optional()
- .describe('Property filters gating this action.'),
- type: zod
- .string()
- .max(hogFlowsBatchJobsCreateBodyActionsItemTypeMax)
- .describe(
- 'trigger | function | function_email | function_sms | function_push | delay | conditional_branch | wait_until_condition | wait_until_time_window | random_cohort_branch | exit.'
- ),
- config: zod
- .unknown()
- .describe(
- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. wait_until_condition: {condition: {filters}, max_wait_duration: <duration>} (same rules as delay). exit: {reason}."
- ),
- output_variable: zod
- .unknown()
- .optional()
- .describe('Output variable definition for downstream actions.'),
- })
- )
- .describe("Ordered action nodes. Exactly one type='trigger' required. Typically one type='exit' too."),
- variables: zod
- .array(
- zod.record(zod.string(), zod.string()).describe('Variable: {key, type: string|number|boolean, default}.')
- )
+ hog_flow: zod.uuid().describe('ID of the workflow this batch run belongs to.'),
+ filters: zod
+ .unknown()
.optional()
- .describe('Workflow vars (key, type, default). Total <5KB.'),
+ .describe("Audience snapshot the run fanned out to, taken from the workflow's batch trigger filters."),
+ variables: zod.unknown().optional().describe('Variable value overrides applied to this run.'),
})
export const hogFlowsInvocationsCreateBodyConfigurationOneNameMax = 400
@@ -1001,6 +863,8 @@ export const hogFlowsInvocationsCreateBodyConfigurationOneActionsItemDescription
export const hogFlowsInvocationsCreateBodyConfigurationOneActionsItemFiltersOneSourceDefault = `events`
export const hogFlowsInvocationsCreateBodyConfigurationOneActionsItemTypeMax = 100
+export const hogFlowsInvocationsCreateBodyConfigurationOneSchedulesItemTimezoneMax = 64
+
export const hogFlowsInvocationsCreateBodyMockAsyncFunctionsDefault = true
export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({
@@ -1210,6 +1074,44 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('Workflow vars (key, type, default). Total <5KB.'),
billable_action_types: zod.unknown(),
+ schedules: zod
+ .array(
+ zod.object({
+ id: zod.uuid(),
+ rrule: zod
+ .string()
+ .describe(
+ "iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour."
+ ),
+ starts_at: zod.iso
+ .datetime({ offset: true })
+ .describe('ISO 8601 datetime the schedule starts from.'),
+ timezone: zod
+ .string()
+ .max(hogFlowsInvocationsCreateBodyConfigurationOneSchedulesItemTimezoneMax)
+ .optional()
+ .describe("IANA timezone for interpreting the RRULE (default 'UTC')."),
+ variables: zod
+ .unknown()
+ .optional()
+ .describe('Variable value overrides merged with the workflow defaults on each run.'),
+ status: zod
+ .enum(['active', 'paused', 'completed'])
+ .describe('\* `active` - Active\n\* `paused` - Paused\n\* `completed` - Completed')
+ .describe(
+ "active, paused, or completed (set once the RRULE's COUNT\/UNTIL is exhausted).\n\n\* `active` - Active\n\* `paused` - Paused\n\* `completed` - Completed"
+ ),
+ next_run_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('Next scheduled fire time, computed by the scheduler.'),
+ created_at: zod.iso.datetime({ offset: true }),
+ updated_at: zod.iso.datetime({ offset: true }),
+ })
+ )
+ .describe(
+ "Recurring schedules attached to this workflow (read-only here; manage via the schedules sub-resource). A batch\/schedule workflow only fires when it's active AND has an active schedule. Empty for non-scheduled workflows."
+ ),
})
.optional()
.describe('Optional override; omit to use saved definition.'),
@@ -1224,320 +1126,45 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({
current_action_id: zod.string().optional().describe('Start from this action ID instead of the trigger.'),
})
-export const hogFlowsSchedulesCreateBodyNameMax = 400
-
-export const hogFlowsSchedulesCreateBodyDescriptionDefault = ``
-export const hogFlowsSchedulesCreateBodyTriggerMaskingOneTtlMin = 60
-export const hogFlowsSchedulesCreateBodyTriggerMaskingOneTtlMax = 94608000
-
-export const hogFlowsSchedulesCreateBodyActionsItemNameMax = 400
-
-export const hogFlowsSchedulesCreateBodyActionsItemDescriptionDefault = ``
-export const hogFlowsSchedulesCreateBodyActionsItemFiltersOneSourceDefault = `events`
-export const hogFlowsSchedulesCreateBodyActionsItemTypeMax = 100
+export const hogFlowsSchedulesCreateBodyTimezoneMax = 64
export const HogFlowsSchedulesCreateBody = /* @__PURE__ */ zod.object({
- name: zod.string().max(hogFlowsSchedulesCreateBodyNameMax).nullish().describe('Workflow name.'),
- description: zod.string().default(hogFlowsSchedulesCreateBodyDescriptionDefault).describe('Optional description.'),
- status: zod
- .enum(['draft', 'active', 'archived'])
- .describe('\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived')
- .optional()
- .describe(
- 'draft (no execution), active (live), archived (disabled).\n\n\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived'
- ),
- trigger_masking: zod
- .union([
- zod.object({
- ttl: zod
- .number()
- .min(hogFlowsSchedulesCreateBodyTriggerMaskingOneTtlMin)
- .max(hogFlowsSchedulesCreateBodyTriggerMaskingOneTtlMax)
- .nullish()
- .describe('Hash TTL in seconds (60 to ~94M \/ 3y).'),
- threshold: zod.number().nullish().describe('Min matching events before triggering (k-anonymity).'),
- hash: zod.string().describe("HogQL template, e.g. '{person.properties.email}'."),
- bytecode: zod.unknown().optional().describe('Auto-compiled from hash. Do not set.'),
- }),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Optional dedup: {hash: <HogQL template>, ttl: <seconds, 60-94608000>, threshold?: <int>}. Server compiles bytecode from hash. Omit to disable.'
- ),
- conversion: zod
- .unknown()
- .optional()
- .describe(
- 'Conversion goal: {filters: [<cond>, ...], window_minutes}. <cond>: {key, value, operator, type: event|person|group}. Empty filters = any event in window. Required for exit_on_conversion \/ exit_on_trigger_not_matched_or_conversion. bytecode compiled server-side.'
- ),
- exit_condition: zod
- .enum([
- 'exit_on_conversion',
- 'exit_on_trigger_not_matched',
- 'exit_on_trigger_not_matched_or_conversion',
- 'exit_only_at_end',
- ])
- .describe(
- '\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End'
- )
- .optional()
+ rrule: zod
+ .string()
.describe(
- "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"
+ "iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour."
),
- edges: zod
- .array(
- zod.object({
- to: zod.string().describe('Target action id.'),
- type: zod
- .enum(['continue', 'branch'])
- .describe('\* `continue` - continue\n\* `branch` - branch')
- .describe(
- "continue: fall-through (sequential or the no-match path of conditional_branch). branch: requires 'index' matching config.conditions[index].\n\n\* `continue` - continue\n\* `branch` - branch"
- ),
- index: zod
- .number()
- .optional()
- .describe(
- "Required for type='branch'. Index into config.conditions on conditional_branch \/ wait_until_condition."
- ),
- from: zod.string().describe('Source action id.'),
- })
- )
+ starts_at: zod.iso.datetime({ offset: true }).describe('ISO 8601 datetime the schedule starts from.'),
+ timezone: zod
+ .string()
+ .max(hogFlowsSchedulesCreateBodyTimezoneMax)
.optional()
- .describe(
- "Graph edges: [{from, to, type: 'continue'|'branch', index?}]. 'continue' = fall-through (sequential, or no-match path of conditional_branch). 'branch' requires 'index': matches config.conditions[index] on conditional_branch \/ wait_until_condition. Every non-exit action needs a reachable next action ('No next action found' otherwise)."
- ),
- actions: zod
- .array(
- zod.object({
- id: zod.string().describe('Unique node ID within the workflow.'),
- name: zod.string().max(hogFlowsSchedulesCreateBodyActionsItemNameMax).describe('Display name.'),
- description: zod
- .string()
- .default(hogFlowsSchedulesCreateBodyActionsItemDescriptionDefault)
- .describe('Optional description.'),
- on_error: zod
- .union([
- zod
- .enum(['continue', 'abort', 'complete', 'branch'])
- .describe(
- '\* `continue` - continue\n\* `abort` - abort\n\* `complete` - complete\n\* `branch` - branch'
- ),
- zod.null(),
- ])
- .optional()
- .describe(
- 'On failure: continue (skip), abort (stop), complete (mark done), branch (follow error edge).\n\n\* `continue` - continue\n\* `abort` - abort\n\* `complete` - complete\n\* `branch` - branch'
- ),
- created_at: zod.number().optional().describe('Created at (epoch ms). Frontend-managed.'),
- updated_at: zod.number().optional().describe('Updated at (epoch ms). Frontend-managed.'),
- filters: zod
- .union([
- zod.object({
- source: zod
- .enum(['events', 'person-updates', 'data-warehouse-table'])
- .describe(
- '\* `events` - events\n\* `person-updates` - person-updates\n\* `data-warehouse-table` - data-warehouse-table'
- )
- .default(hogFlowsSchedulesCreateBodyActionsItemFiltersOneSourceDefault),
- actions: zod.array(zod.record(zod.string(), zod.unknown())).optional(),
- events: zod.array(zod.record(zod.string(), zod.unknown())).optional(),
- data_warehouse: zod.array(zod.record(zod.string(), zod.unknown())).optional(),
- properties: zod.array(zod.record(zod.string(), zod.unknown())).optional(),
- bytecode: zod.unknown().optional(),
- transpiled: zod.unknown().optional(),
- filter_test_accounts: zod.boolean().optional(),
- bytecode_error: zod.string().optional(),
- }),
- zod.null(),
- ])
- .optional()
- .describe('Property filters gating this action.'),
- type: zod
- .string()
- .max(hogFlowsSchedulesCreateBodyActionsItemTypeMax)
- .describe(
- 'trigger | function | function_email | function_sms | function_push | delay | conditional_branch | wait_until_condition | wait_until_time_window | random_cohort_branch | exit.'
- ),
- config: zod
- .unknown()
- .describe(
- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. wait_until_condition: {condition: {filters}, max_wait_duration: <duration>} (same rules as delay). exit: {reason}."
- ),
- output_variable: zod
- .unknown()
- .optional()
- .describe('Output variable definition for downstream actions.'),
- })
- )
- .describe("Ordered action nodes. Exactly one type='trigger' required. Typically one type='exit' too."),
+ .describe("IANA timezone for interpreting the RRULE (default 'UTC')."),
variables: zod
- .array(
- zod.record(zod.string(), zod.string()).describe('Variable: {key, type: string|number|boolean, default}.')
- )
+ .unknown()
.optional()
- .describe('Workflow vars (key, type, default). Total <5KB.'),
+ .describe('Variable value overrides merged with the workflow defaults on each run.'),
})
-export const hogFlowsSchedulesPartialUpdateBodyNameMax = 400
-
-export const hogFlowsSchedulesPartialUpdateBodyDescriptionDefault = ``
-export const hogFlowsSchedulesPartialUpdateBodyTriggerMaskingOneTtlMin = 60
-export const hogFlowsSchedulesPartialUpdateBodyTriggerMaskingOneTtlMax = 94608000
-
-export const hogFlowsSchedulesPartialUpdateBodyActionsItemNameMax = 400
-
-export const hogFlowsSchedulesPartialUpdateBodyActionsItemDescriptionDefault = ``
-export const hogFlowsSchedulesPartialUpdateBodyActionsItemFiltersOneSourceDefault = `events`
-export const hogFlowsSchedulesPartialUpdateBodyActionsItemTypeMax = 100
+export const hogFlowsSchedulesPartialUpdateBodyTimezoneMax = 64
export const HogFlowsSchedulesPartialUpdateBody = /* @__PURE__ */ zod.object({
- name: zod.string().max(hogFlowsSchedulesPartialUpdateBodyNameMax).nullish().describe('Workflow name.'),
- description: zod
+ rrule: zod
.string()
- .default(hogFlowsSchedulesPartialUpdateBodyDescriptionDefault)
- .describe('Optional description.'),
- status: zod
- .enum(['draft', 'active', 'archived'])
- .describe('\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived')
- .optional()
- .describe(
- 'draft (no execution), active (live), archived (disabled).\n\n\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived'
- ),
- trigger_masking: zod
- .union([
- zod.object({
- ttl: zod
- .number()
- .min(hogFlowsSchedulesPartialUpdateBodyTriggerMaskingOneTtlMin)
- .max(hogFlowsSchedulesPartialUpdateBodyTriggerMaskingOneTtlMax)
- .nullish()
- .describe('Hash TTL in seconds (60 to ~94M \/ 3y).'),
- threshold: zod.number().nullish().describe('Min matching events before triggering (k-anonymity).'),
- hash: zod.string().describe("HogQL template, e.g. '{person.properties.email}'."),
- bytecode: zod.unknown().optional().describe('Auto-compiled from hash. Do not set.'),
- }),
- zod.null(),
- ])
.optional()
.describe(
- 'Optional dedup: {hash: <HogQL template>, ttl: <seconds, 60-94608000>, threshold?: <int>}. Server compiles bytecode from hash. Omit to disable.'
- ),
- conversion: zod
- .unknown()
- .optional()
- .describe(
- 'Conversion goal: {filters: [<cond>, ...], window_minutes}. <cond>: {key, value, operator, type: event|person|group}. Empty filters = any event in window. Required for exit_on_conversion \/ exit_on_trigger_not_matched_or_conversion. bytecode compiled server-side.'
+ "iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour."
),
- exit_condition: zod
- .enum([
- 'exit_on_conversion',
- 'exit_on_trigger_not_matched',
- 'exit_on_trigger_not_matched_or_conversion',
- 'exit_only_at_end',
- ])
- .describe(
- '\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End'
- )
- .optional()
- .describe(
- "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"
- ),
- edges: zod
- .array(
- zod.object({
- to: zod.string().describe('Target action id.'),
- type: zod
- .enum(['continue', 'branch'])
- .describe('\* `continue` - continue\n\* `branch` - branch')
- .describe(
- "continue: fall-through (sequential or the no-match path of conditional_branch). branch: requires 'index' matching config.conditions[index].\n\n\* `continue` - continue\n\* `branch` - branch"
- ),
- index: zod
- .number()
- .optional()
- .describe(
- "Required for type='branch'. Index into config.conditions on conditional_branch \/ wait_until_condition."
- ),
- from: zod.string().describe('Source action id.'),
- })
- )
- .optional()
- .describe(
- "Graph edges: [{from, to, type: 'continue'|'branch', index?}]. 'continue' = fall-through (sequential, or no-match path of conditional_branch). 'branch' requires 'index': matches config.conditions[index] on conditional_branch \/ wait_until_condition. Every non-exit action needs a reachable next action ('No next action found' otherwise)."
- ),
- actions: zod
- .array(
- zod.object({
- id: zod.string().describe('Unique node ID within the workflow.'),
- name: zod.string().max(hogFlowsSchedulesPartialUpdateBodyActionsItemNameMax).describe('Display name.'),
- description: zod
- .string()
- .default(hogFlowsSchedulesPartialUpdateBodyActionsItemDescriptionDefault)
- .describe('Optional description.'),
- on_error: zod
- .union([
- zod
- .enum(['continue', 'abort', 'complete', 'branch'])
- .describe(
- '\* `continue` - continue\n\* `abort` - abort\n\* `complete` - complete\n\* `branch` - branch'
- ),
- zod.null(),
- ])
- .optional()
- .describe(
- 'On failure: continue (skip), abort (stop), complete (mark done), branch (follow error edge).\n\n\* `continue` - continue\n\* `abort` - abort\n\* `complete` - complete\n\* `branch` - branch'
- ),
- created_at: zod.number().optional().describe('Created at (epoch ms). Frontend-managed.'),
- updated_at: zod.number().optional().describe('Updated at (epoch ms). Frontend-managed.'),
- filters: zod
- .union([
- zod.object({
- source: zod
- .enum(['events', 'person-updates', 'data-warehouse-table'])
- .describe(
- '\* `events` - events\n\* `person-updates` - person-updates\n\* `data-warehouse-table` - data-warehouse-table'
- )
- .default(hogFlowsSchedulesPartialUpdateBodyActionsItemFiltersOneSourceDefault),
- actions: zod.array(zod.record(zod.string(), zod.unknown())).optional(),
- events: zod.array(zod.record(zod.string(), zod.unknown())).optional(),
- data_warehouse: zod.array(zod.record(zod.string(), zod.unknown())).optional(),
- properties: zod.array(zod.record(zod.string(), zod.unknown())).optional(),
- bytecode: zod.unknown().optional(),
- transpiled: zod.unknown().optional(),
- filter_test_accounts: zod.boolean().optional(),
- bytecode_error: zod.string().optional(),
- }),
- zod.null(),
- ])
- .optional()
- .describe('Property filters gating this action.'),
- type: zod
- .string()
- .max(hogFlowsSchedulesPartialUpdateBodyActionsItemTypeMax)
- .describe(
- 'trigger | function | function_email | function_sms | function_push | delay | conditional_branch | wait_until_condition | wait_until_time_window | random_cohort_branch | exit.'
- ),
- config: zod
- .unknown()
- .describe(
- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. wait_until_condition: {condition: {filters}, max_wait_duration: <duration>} (same rules as delay). exit: {reason}."
- ),
- output_variable: zod
- .unknown()
- .optional()
- .describe('Output variable definition for downstream actions.'),
- })
- )
+ starts_at: zod.iso.datetime({ offset: true }).optional().describe('ISO 8601 datetime the schedule starts from.'),
+ timezone: zod
+ .string()
+ .max(hogFlowsSchedulesPartialUpdateBodyTimezoneMax)
.optional()
- .describe("Ordered action nodes. Exactly one type='trigger' required. Typically one type='exit' too."),
+ .describe("IANA timezone for interpreting the RRULE (default 'UTC')."),
variables: zod
- .array(
- zod.record(zod.string(), zod.string()).describe('Variable: {key, type: string|number|boolean, default}.')
- )
+ .unknown()
.optional()
- .describe('Workflow vars (key, type, default). Total <5KB.'),
+ .describe('Variable value overrides merged with the workflow defaults on each run.'),
})
export const hogFlowsBulkDeleteCreateBodyNameMax = 400
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index 353188d333af..64498a81c5b2 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -39,9 +39,6 @@ tools:
hog-flows-batch-jobs-create:
operation: hog_flows_batch_jobs_create
enabled: false
- hog-flows-batch-jobs-retrieve:
- operation: hog_flows_batch_jobs_retrieve
- enabled: false
hog-flows-bulk-delete-create:
operation: hog_flows_bulk_delete_create
enabled: false
@@ -98,9 +95,6 @@ tools:
hog-flows-schedules-list:
operation: hog_flows_schedules_list
enabled: false
- hog-flows-schedules-partial-update:
- operation: hog_flows_schedules_partial_update
- enabled: false
hog-flows-update:
operation: hog_flows_update
enabled: false
@@ -128,10 +122,17 @@ tools:
enrich_url: hog-{id}
title: Create workflow
description: >
- Create a workflow. Requires an actions array with exactly one type='trigger' (config sets trigger type:
- event|webhook|manual|batch|schedule|tracking_pixel). Other action types:
- function/function_email/function_sms/function_push (CDP template), delay (e.g. '30m'), conditional_branch,
- wait_until_condition. Connect via edges. Defaults to status='draft'; set 'active' to enable.
+ Create a workflow. Needs an actions array with exactly one type='trigger' (config.type:
+ event|webhook|manual|batch|tracking_pixel) plus action nodes —
+ function/function_email/function_sms/function_push, delay (e.g. '30m'), conditional_branch,
+ wait_until_condition — connected by edges. Created as a draft; activate with workflows-enable. 'batch' =
+ broadcast to an audience, one run per matching person (emails/messages). The audience is
+ config.filters.properties: person-property conditions ({type:'person',key,value,operator}) and/or cohort
+ references ({type:'cohort',key:'id',value:<id>,operator:'in'}). Prefer inline person-property conditions or
+ a dynamic (filter-based) cohort via cohorts-create — these re-evaluate as people qualify; a static cohort is
+ a frozen list, use only when given an explicit set. Behavioral (event-based) cohorts are rejected — for 'did
+ event X', use an 'event' trigger instead. A batch workflow fires only once enabled and a recurring schedule
+ is attached (workflows-schedule-create).
ui_app: workflow
workflows-get:
operation: hog_flows_retrieve
@@ -146,7 +147,8 @@ tools:
title: Get workflow
description: >
Get a specific workflow by ID. Returns the full workflow definition including trigger, edges, actions, exit
- condition, and variables.
+ condition, variables, and any recurring 'schedules' (read-only here). For a batch workflow, check
+ status=='active' plus an active entry in 'schedules' to confirm it will actually fire.
ui_app: workflow
workflows-list:
operation: hog_flows_list
@@ -163,6 +165,21 @@ tools:
List all workflows in the project. Returns workflows with their name, description, status
(draft/active/archived), version, trigger configuration, and timestamps.
ui_app: workflow-list
+ workflows-list-batch-jobs:
+ operation: hog_flows_batch_jobs_list
+ enabled: true
+ scopes:
+ - hog_flow:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List workflow batch runs
+ description: >
+ List past batch runs for a workflow (both one-off broadcasts and schedule-triggered runs). Each entry shows
+ the audience filters and variable overrides the run used, plus when it was created. The status field is not
+ tracked — use workflows-logs / workflows-metrics for the outcome of a run.
workflows-run:
operation: hog_flows_invocations_create
enabled: true
@@ -190,7 +207,25 @@ tools:
idempotent: true
enrich_url: hog-{id}
title: Update workflow
- description: Update a workflow by ID. Use workflows-enable / workflows-disable / workflows-archive to change status.
+ description: >
+ Update a workflow by ID. Draft only — active workflows are read-only via MCP for now (editing risks breaking
+ already-scheduled runs); create a new draft for changes instead. Status changes go through workflows-enable
+ / workflows-disable / workflows-archive. A batch audience is config.filters.properties — person-property
+ conditions and/or cohort references. Prefer person properties or a dynamic (filter-based) cohort, which
+ re-evaluate, over a static frozen-list cohort; behavioral (event-based) cohorts are rejected.
exclude_params:
- status
ui_app: workflow
+ workflows-update-schedule:
+ operation: hog_flows_schedules_partial_update
+ enabled: true
+ scopes:
+ - hog_flow:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Update workflow schedule
+ description: >
+ Update a recurring schedule's RRULE, start time, timezone, or variable overrides. Changing the cadence
+ reschedules the next run. Each firing re-broadcasts to the workflow's current trigger audience.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 01ed05ae93fb..b2feaea66616 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -5807,7 +5807,7 @@
}
},
"workflows-create": {
- "description": "Create a workflow. Requires an actions array with exactly one type='trigger' (config sets trigger type: event|webhook|manual|batch|schedule|tracking_pixel). Other action types: function/function_email/function_sms/function_push (CDP template), delay (e.g. '30m'), conditional_branch, wait_until_condition. Connect via edges. Defaults to status='draft'; set 'active' to enable.",
+ "description": "Create a workflow. Needs an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes — function/function_email/function_sms/function_push, delay (e.g. '30m'), conditional_branch, wait_until_condition — connected by edges. Created as a draft; activate with workflows-enable. 'batch' = broadcast to an audience, one run per matching person (emails/messages). The audience is config.filters.properties: person-property conditions ({type:'person',key,value,operator}) and/or cohort references ({type:'cohort',key:'id',value:<id>,operator:'in'}). Prefer inline person-property conditions or a dynamic (filter-based) cohort via cohorts-create — these re-evaluate as people qualify; a static cohort is a frozen list, use only when given an explicit set. Behavioral (event-based) cohorts are rejected — for 'did event X', use an 'event' trigger instead. A batch workflow fires only once enabled and a recurring schedule is attached (workflows-schedule-create).",
"category": "Workflows",
"feature": "workflows",
"summary": "Create workflow",
@@ -5821,7 +5821,7 @@
}
},
"workflows-get": {
- "description": "Get a specific workflow by ID. Returns the full workflow definition including trigger, edges, actions, exit condition, and variables.",
+ "description": "Get a specific workflow by ID. Returns the full workflow definition including trigger, edges, actions, exit condition, variables, and any recurring 'schedules' (read-only here). For a batch workflow, check status=='active' plus an active entry in 'schedules' to confirm it will actually fire.",
"category": "Workflows",
"feature": "workflows",
"summary": "Get workflow",
@@ -5848,6 +5848,20 @@
"readOnlyHint": true
}
},
+ "workflows-list-batch-jobs": {
+ "description": "List past batch runs for a workflow (both one-off broadcasts and schedule-triggered runs). Each entry shows the audience filters and variable overrides the run used, plus when it was created. The status field is not tracked — use workflows-logs / workflows-metrics for the outcome of a run.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "List workflow batch runs",
+ "title": "List workflow batch runs",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"workflows-run": {
"description": "Test-invoke a saved workflow. Pass test event data via globals (typically {event, person, groups}). Async actions (HTTP/email/SMS) are mocked by default; set mock_async_functions=false to fire real side effects. Optional current_action_id starts from a specific node. Returns the execution trace.",
"category": "Workflows",
@@ -5863,7 +5877,7 @@
}
},
"workflows-update": {
- "description": "Update a workflow by ID. Use workflows-enable / workflows-disable / workflows-archive to change status.",
+ "description": "Update a workflow by ID. Draft only — active workflows are read-only via MCP for now (editing risks breaking already-scheduled runs); create a new draft for changes instead. Status changes go through workflows-enable / workflows-disable / workflows-archive. A batch audience is config.filters.properties — person-property conditions and/or cohort references. Prefer person properties or a dynamic (filter-based) cohort, which re-evaluate, over a static frozen-list cohort; behavioral (event-based) cohorts are rejected.",
"category": "Workflows",
"feature": "workflows",
"summary": "Update workflow",
@@ -5875,5 +5889,19 @@
"openWorldHint": true,
"readOnlyHint": false
}
+ },
+ "workflows-update-schedule": {
+ "description": "Update a recurring schedule's RRULE, start time, timezone, or variable overrides. Changing the cadence reschedules the next run. Each firing re-broadcasts to the workflow's current trigger audience.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Update workflow schedule",
+ "title": "Update workflow schedule",
+ "required_scopes": ["hog_flow:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
}
}
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 9015b5b88456..33805b909e26 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6175,30 +6175,30 @@
"readOnlyHint": false
}
},
- "workflows-create": {
- "description": "Create a workflow. Requires an actions array with exactly one type='trigger' (config sets trigger type: event|webhook|manual|batch|schedule|tracking_pixel). Other action types: function/function_email/function_sms/function_push (CDP template), delay (e.g. '30m'), conditional_branch, wait_until_condition. Connect via edges. Defaults to status='draft'; set 'active' to enable.",
+ "workflows-blast-radius": {
+ "description": "Count how many users a batch workflow's audience matches (person/cohort, not event behavior). Always run this BEFORE run-batch / schedule-create. Then STOP and get the user's explicit confirmation: tell them the exact count and that running will send real messages to that many people. Do not proceed to run-batch / schedule-create until they say yes.",
"category": "Workflows",
"feature": "workflows",
- "summary": "Create workflow",
- "title": "Create workflow",
- "required_scopes": ["hog_flow:write"],
+ "summary": "Size workflow audience",
+ "title": "Size workflow audience",
+ "required_scopes": ["hog_flow:read", "person:read"],
"annotations": {
"destructiveHint": false,
- "idempotentHint": false,
+ "idempotentHint": true,
"openWorldHint": true,
- "readOnlyHint": false
+ "readOnlyHint": true
}
},
- "workflows-disable": {
- "description": "Disable / deactivate a live workflow and stop processing events. Confirm with the user before invoking.",
+ "workflows-create": {
+ "description": "Create a workflow. Needs an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes — function/function_email/function_sms/function_push, delay (e.g. '30m'), conditional_branch, wait_until_condition — connected by edges. Created as a draft; activate with workflows-enable. 'batch' = broadcast to an audience, one run per matching person (emails/messages). The audience is config.filters.properties: person-property conditions ({type:'person',key,value,operator}) and/or cohort references ({type:'cohort',key:'id',value:<id>,operator:'in'}). Prefer inline person-property conditions or a dynamic (filter-based) cohort via cohorts-create — these re-evaluate as people qualify; a static cohort is a frozen list, use only when given an explicit set. Behavioral (event-based) cohorts are rejected — for 'did event X', use an 'event' trigger instead. A batch workflow fires only once enabled and a recurring schedule is attached (workflows-schedule-create).",
"category": "Workflows",
"feature": "workflows",
- "summary": "Disable workflow",
- "title": "Disable workflow",
+ "summary": "Create workflow",
+ "title": "Create workflow",
"required_scopes": ["hog_flow:write"],
"annotations": {
- "destructiveHint": true,
- "idempotentHint": true,
+ "destructiveHint": false,
+ "idempotentHint": false,
"openWorldHint": true,
"readOnlyHint": false
}
@@ -6218,7 +6218,7 @@
}
},
"workflows-get": {
- "description": "Get a specific workflow by ID. Returns the full workflow definition including trigger, edges, actions, exit condition, and variables.",
+ "description": "Get a specific workflow by ID. Returns the full workflow definition including trigger, edges, actions, exit condition, variables, and any recurring 'schedules' (read-only here). For a batch workflow, check status=='active' plus an active entry in 'schedules' to confirm it will actually fire.",
"category": "Workflows",
"feature": "workflows",
"summary": "Get workflow",
@@ -6245,6 +6245,20 @@
"readOnlyHint": true
}
},
+ "workflows-list-batch-jobs": {
+ "description": "List past batch runs for a workflow (both one-off broadcasts and schedule-triggered runs). Each entry shows the audience filters and variable overrides the run used, plus when it was created. The status field is not tracked — use workflows-logs / workflows-metrics for the outcome of a run.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "List workflow batch runs",
+ "title": "List workflow batch runs",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"workflows-run": {
"description": "Test-invoke a saved workflow. Pass test event data via globals (typically {event, person, groups}). Async actions (HTTP/email/SMS) are mocked by default; set mock_async_functions=false to fire real side effects. Optional current_action_id starts from a specific node. Returns the execution trace.",
"category": "Workflows",
@@ -6259,8 +6273,36 @@
"readOnlyHint": false
}
},
+ "workflows-run-batch": {
+ "description": "Broadcast a batch workflow to its matching users NOW — sends real messages/webhooks, not a test. Workflow must be enabled. STOP before calling: show the user the audience size from workflows-blast-radius and get their explicit confirmation in a separate turn — never size and fire in one step. Requires acknowledged_affected_count from workflows-blast-radius; rejects on drift or over the cap.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Run batch workflow",
+ "title": "Run batch workflow",
+ "required_scopes": ["hog_flow:write", "person:read"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "workflows-schedule-create": {
+ "description": "Attach a recurring RRULE schedule to a batch workflow. The workflow must already be active (enable it first). Each run broadcasts real messages to the trigger audience — STOP and get the user's explicit confirmation first, then pass acknowledged_affected_count from workflows-blast-radius.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Schedule workflow runs",
+ "title": "Schedule workflow runs",
+ "required_scopes": ["hog_flow:write", "person:read"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"workflows-update": {
- "description": "Update a workflow by ID. Use workflows-enable / workflows-disable / workflows-archive to change status.",
+ "description": "Update a workflow by ID. Draft only — active workflows are read-only via MCP for now (editing risks breaking already-scheduled runs); create a new draft for changes instead. Status changes go through workflows-enable / workflows-disable / workflows-archive. A batch audience is config.filters.properties — person-property conditions and/or cohort references. Prefer person properties or a dynamic (filter-based) cohort, which re-evaluate, over a static frozen-list cohort; behavioral (event-based) cohorts are rejected.",
"category": "Workflows",
"feature": "workflows",
"summary": "Update workflow",
@@ -6272,5 +6314,19 @@
"openWorldHint": true,
"readOnlyHint": false
}
+ },
+ "workflows-update-schedule": {
+ "description": "Update a recurring schedule's RRULE, start time, timezone, or variable overrides. Changing the cadence reschedules the next run. Each firing re-broadcasts to the workflow's current trigger audience.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Update workflow schedule",
+ "title": "Update workflow schedule",
+ "required_scopes": ["hog_flow:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
}
}
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index d50ba2c3c06e..26beba4eaad1 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -466,31 +466,59 @@
"readOnlyHint": false
}
},
- "workflows-disable": {
- "description": "Disable / deactivate a live workflow and stop processing events. Confirm with the user before invoking.",
+ "workflows-archive": {
+ "description": "Archive a draft or disabled workflow.",
"category": "Workflows",
"feature": "workflows",
- "summary": "Disable workflow",
- "title": "Disable workflow",
+ "summary": "Archive workflow",
+ "title": "Archive workflow",
"required_scopes": ["hog_flow:write"],
"annotations": {
- "destructiveHint": true,
+ "destructiveHint": false,
"idempotentHint": true,
"openWorldHint": true,
"readOnlyHint": false
}
},
- "workflows-archive": {
- "description": "Archive a draft or disabled workflow.",
+ "workflows-blast-radius": {
+ "description": "Count how many users a batch workflow's audience matches (person/cohort, not event behavior). Always run this BEFORE run-batch / schedule-create. Then STOP and get the user's explicit confirmation: tell them the exact count and that running will send real messages to that many people. Do not proceed to run-batch / schedule-create until they say yes.",
"category": "Workflows",
"feature": "workflows",
- "summary": "Archive workflow",
- "title": "Archive workflow",
- "required_scopes": ["hog_flow:write"],
+ "summary": "Size workflow audience",
+ "title": "Size workflow audience",
+ "required_scopes": ["hog_flow:read", "person:read"],
"annotations": {
"destructiveHint": false,
"idempotentHint": true,
"openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "workflows-run-batch": {
+ "description": "Broadcast a batch workflow to its matching users NOW — sends real messages/webhooks, not a test. Workflow must be enabled. STOP before calling: show the user the audience size from workflows-blast-radius and get their explicit confirmation in a separate turn — never size and fire in one step. Requires acknowledged_affected_count from workflows-blast-radius; rejects on drift or over the cap.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Run batch workflow",
+ "title": "Run batch workflow",
+ "required_scopes": ["hog_flow:write", "person:read"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "workflows-schedule-create": {
+ "description": "Attach a recurring RRULE schedule to a batch workflow. The workflow must already be active (enable it first). Each run broadcasts real messages to the trigger audience — STOP and get the user's explicit confirmation first, then pass acknowledged_affected_count from workflows-blast-radius.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Schedule workflow runs",
+ "title": "Schedule workflow runs",
+ "required_scopes": ["hog_flow:write", "person:read"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
"readOnlyHint": false
}
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3c1dab402d69..b3559ec32e47 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -18413,6 +18413,48 @@ export namespace Schemas {
output_variable?: unknown;
}
+ /**
+ * * `active` - Active
+ * `paused` - Paused
+ * `completed` - Completed
+ */
+ export type HogFlowScheduleStatusEnum = typeof HogFlowScheduleStatusEnum[keyof typeof HogFlowScheduleStatusEnum];
+
+
+ export const HogFlowScheduleStatusEnum = {
+ Active: 'active',
+ Paused: 'paused',
+ Completed: 'completed',
+ } as const;
+
+ export interface HogFlowSchedule {
+ readonly id: string;
+ /** iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour. */
+ rrule: string;
+ /** ISO 8601 datetime the schedule starts from. */
+ starts_at: string;
+ /**
+ * IANA timezone for interpreting the RRULE (default 'UTC').
+ * @maxLength 64
+ */
+ timezone?: string;
+ /** Variable value overrides merged with the workflow defaults on each run. */
+ variables?: unknown;
+ /** active, paused, or completed (set once the RRULE's COUNT/UNTIL is exhausted).
+
+ * `active` - Active
+ * `paused` - Paused
+ * `completed` - Completed */
+ readonly status: HogFlowScheduleStatusEnum;
+ /**
+ * Next scheduled fire time, computed by the scheduler.
+ * @nullable
+ */
+ readonly next_run_at: string | null;
+ readonly created_at: string;
+ readonly updated_at: string;
+ }
+
export interface HogFlow {
readonly id: string;
/**
@@ -18454,6 +18496,50 @@ export namespace Schemas {
/** Workflow vars (key, type, default). Total <5KB. */
variables?: HogFlowVariablesItem[];
readonly billable_action_types: unknown;
+ /** Recurring schedules attached to this workflow (read-only here; manage via the schedules sub-resource). A batch/schedule workflow only fires when it's active AND has an active schedule. Empty for non-scheduled workflows. */
+ readonly schedules: readonly HogFlowSchedule[];
+ }
+
+ /**
+ * * `waiting` - Waiting
+ * `queued` - Queued
+ * `active` - Active
+ * `completed` - Completed
+ * `cancelled` - Cancelled
+ * `failed` - Failed
+ */
+ export type HogFlowBatchJobStatusEnum = typeof HogFlowBatchJobStatusEnum[keyof typeof HogFlowBatchJobStatusEnum];
+
+
+ export const HogFlowBatchJobStatusEnum = {
+ Waiting: 'waiting',
+ Queued: 'queued',
+ Active: 'active',
+ Completed: 'completed',
+ Cancelled: 'cancelled',
+ Failed: 'failed',
+ } as const;
+
+ export interface HogFlowBatchJob {
+ readonly id: string;
+ /** Not currently tracked — stays at its initial value. Use the workflow logs/metrics endpoints for run outcome.
+
+ * `waiting` - Waiting
+ * `queued` - Queued
+ * `active` - Active
+ * `completed` - Completed
+ * `cancelled` - Cancelled
+ * `failed` - Failed */
+ status?: HogFlowBatchJobStatusEnum;
+ /** ID of the workflow this batch run belongs to. */
+ hog_flow: string;
+ /** Audience snapshot the run fanned out to, taken from the workflow's batch trigger filters. */
+ filters?: unknown;
+ /** Variable value overrides applied to this run. */
+ variables?: unknown;
+ readonly created_at: string;
+ readonly created_by: UserBasic;
+ readonly updated_at: string;
}
/**
@@ -18494,34 +18580,6 @@ export namespace Schemas {
readonly billable_action_types: unknown;
}
- /**
- * * `active` - Active
- * `paused` - Paused
- * `completed` - Completed
- */
- export type HogFlowScheduleStatusEnum = typeof HogFlowScheduleStatusEnum[keyof typeof HogFlowScheduleStatusEnum];
-
-
- export const HogFlowScheduleStatusEnum = {
- Active: 'active',
- Paused: 'paused',
- Completed: 'completed',
- } as const;
-
- export interface HogFlowSchedule {
- readonly id: string;
- rrule: string;
- starts_at: string;
- /** @maxLength 64 */
- timezone?: string;
- variables?: unknown;
- readonly status: HogFlowScheduleStatusEnum;
- /** @nullable */
- readonly next_run_at: string | null;
- readonly created_at: string;
- readonly updated_at: string;
- }
-
/**
* @nullable
*/
@@ -23216,15 +23274,6 @@ export namespace Schemas {
results: HogFlowMinimal[];
}
- export interface PaginatedHogFlowScheduleList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: HogFlowSchedule[];
- }
-
export interface PaginatedHogFlowTemplateList {
count: number;
/** @nullable */
@@ -28522,6 +28571,36 @@ export namespace Schemas {
/** Workflow vars (key, type, default). Total <5KB. */
variables?: PatchedHogFlowVariablesItem[];
readonly billable_action_types?: unknown;
+ /** Recurring schedules attached to this workflow (read-only here; manage via the schedules sub-resource). A batch/schedule workflow only fires when it's active AND has an active schedule. Empty for non-scheduled workflows. */
+ readonly schedules?: readonly HogFlowSchedule[];
+ }
+
+ export interface PatchedHogFlowSchedule {
+ readonly id?: string;
+ /** iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour. */
+ rrule?: string;
+ /** ISO 8601 datetime the schedule starts from. */
+ starts_at?: string;
+ /**
+ * IANA timezone for interpreting the RRULE (default 'UTC').
+ * @maxLength 64
+ */
+ timezone?: string;
+ /** Variable value overrides merged with the workflow defaults on each run. */
+ variables?: unknown;
+ /** active, paused, or completed (set once the RRULE's COUNT/UNTIL is exhausted).
+
+ * `active` - Active
+ * `paused` - Paused
+ * `completed` - Completed */
+ readonly status?: HogFlowScheduleStatusEnum;
+ /**
+ * Next scheduled fire time, computed by the scheduler.
+ * @nullable
+ */
+ readonly next_run_at?: string | null;
+ readonly created_at?: string;
+ readonly updated_at?: string;
}
/**
@@ -41341,66 +41420,6 @@ export namespace Schemas {
Week: 'week',
} as const;
- export type EnvironmentsHogFlowsSchedulesListParams = {
- created_at?: string;
- created_by?: number;
- id?: string;
- /**
- * Number of results to return per page.
- */
- limit?: number;
- /**
- * The initial index from which to return the results.
- */
- offset?: number;
- /**
- * * `draft` - Draft
- * `active` - Active
- * `archived` - Archived
- */
- status?: EnvironmentsHogFlowsSchedulesListStatus;
- updated_at?: string;
- };
-
- export type EnvironmentsHogFlowsSchedulesListStatus = typeof EnvironmentsHogFlowsSchedulesListStatus[keyof typeof EnvironmentsHogFlowsSchedulesListStatus];
-
-
- export const EnvironmentsHogFlowsSchedulesListStatus = {
- Active: 'active',
- Archived: 'archived',
- Draft: 'draft',
- } as const;
-
- export type EnvironmentsHogFlowsSchedulesCreateParams = {
- created_at?: string;
- created_by?: number;
- id?: string;
- /**
- * Number of results to return per page.
- */
- limit?: number;
- /**
- * The initial index from which to return the results.
- */
- offset?: number;
- /**
- * * `draft` - Draft
- * `active` - Active
- * `archived` - Archived
- */
- status?: EnvironmentsHogFlowsSchedulesCreateStatus;
- updated_at?: string;
- };
-
- export type EnvironmentsHogFlowsSchedulesCreateStatus = typeof EnvironmentsHogFlowsSchedulesCreateStatus[keyof typeof EnvironmentsHogFlowsSchedulesCreateStatus];
-
-
- export const EnvironmentsHogFlowsSchedulesCreateStatus = {
- Active: 'active',
- Archived: 'archived',
- Draft: 'draft',
- } as const;
-
export type EnvironmentsHogFunctionsListParams = {
created_at?: string;
created_by?: number;
@@ -44853,6 +44872,10 @@ export namespace Schemas {
* Return a basic payload that omits the heavy `filters`, `query`, and `groups` fields. Useful for pickers that only need id/name/count.
*/
basic?: boolean;
+ /**
+ * Set true to exclude behavioral (event-based) cohorts, which can't be used in feature flags or batch workflow audiences.
+ */
+ hide_behavioral_cohorts?: boolean;
/**
* Number of results to return per page.
*/
@@ -46771,66 +46794,6 @@ export namespace Schemas {
Week: 'week',
} as const;
- export type HogFlowsSchedulesListParams = {
- created_at?: string;
- created_by?: number;
- id?: string;
- /**
- * Number of results to return per page.
- */
- limit?: number;
- /**
- * The initial index from which to return the results.
- */
- offset?: number;
- /**
- * * `draft` - Draft
- * `active` - Active
- * `archived` - Archived
- */
- status?: HogFlowsSchedulesListStatus;
- updated_at?: string;
- };
-
- export type HogFlowsSchedulesListStatus = typeof HogFlowsSchedulesListStatus[keyof typeof HogFlowsSchedulesListStatus];
-
-
- export const HogFlowsSchedulesListStatus = {
- Active: 'active',
- Archived: 'archived',
- Draft: 'draft',
- } as const;
-
- export type HogFlowsSchedulesCreateParams = {
- created_at?: string;
- created_by?: number;
- id?: string;
- /**
- * Number of results to return per page.
- */
- limit?: number;
- /**
- * The initial index from which to return the results.
- */
- offset?: number;
- /**
- * * `draft` - Draft
- * `active` - Active
- * `archived` - Archived
- */
- status?: HogFlowsSchedulesCreateStatus;
- updated_at?: string;
- };
-
- export type HogFlowsSchedulesCreateStatus = typeof HogFlowsSchedulesCreateStatus[keyof typeof HogFlowsSchedulesCreateStatus];
-
-
- export const HogFlowsSchedulesCreateStatus = {
- Active: 'active',
- Archived: 'archived',
- Draft: 'draft',
- } as const;
-
export type HogFunctionTemplatesListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/cohorts/api.ts b/services/mcp/src/generated/cohorts/api.ts
index 0c0850e0ac94..0025720438bb 100644
--- a/services/mcp/src/generated/cohorts/api.ts
+++ b/services/mcp/src/generated/cohorts/api.ts
@@ -23,6 +23,12 @@ export const CohortsListQueryParams = /* @__PURE__ */ zod.object({
.describe(
'Return a basic payload that omits the heavy `filters`, `query`, and `groups` fields. Useful for pickers that only need id/name/count.'
),
+ hide_behavioral_cohorts: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Set true to exclude behavioral (event-based) cohorts, which can't be used in feature flags or batch workflow audiences."
+ ),
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
})
diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.ts
index 07b1e407cca1..b6f6c3a640f6 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 7 enabled ops
+ * PostHog API - MCP 9 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -360,6 +360,15 @@ export const HogFlowsPartialUpdateBody = /* @__PURE__ */ zod.object({
.describe('Workflow vars (key, type, default). Total <5KB.'),
})
+export const HogFlowsBatchJobsListParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this hog flow.'),
+ 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 HogFlowsInvocationsCreateParams = /* @__PURE__ */ zod.object({
id: zod.string().describe('A UUID string identifying this hog flow.'),
project_id: zod
@@ -457,3 +466,34 @@ export const HogFlowsMetricsRetrieveQueryParams = /* @__PURE__ */ zod.object({
kind: zod.string().min(1).optional().describe("Comma-separated metric kinds to filter by, e.g. 'success,failure'."),
name: zod.string().min(1).optional().describe('Comma-separated metric names to filter by.'),
})
+
+export const HogFlowsSchedulesPartialUpdateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this hog flow.'),
+ 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/."
+ ),
+ schedule_id: zod.string(),
+})
+
+export const hogFlowsSchedulesPartialUpdateBodyTimezoneMax = 64
+
+export const HogFlowsSchedulesPartialUpdateBody = /* @__PURE__ */ zod.object({
+ rrule: zod
+ .string()
+ .optional()
+ .describe(
+ "iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour."
+ ),
+ starts_at: zod.iso.datetime({ offset: true }).optional().describe('ISO 8601 datetime the schedule starts from.'),
+ timezone: zod
+ .string()
+ .max(hogFlowsSchedulesPartialUpdateBodyTimezoneMax)
+ .optional()
+ .describe("IANA timezone for interpreting the RRULE (default 'UTC')."),
+ variables: zod
+ .unknown()
+ .optional()
+ .describe('Variable value overrides merged with the workflow defaults on each run.'),
+})
diff --git a/services/mcp/src/tools/generated/cohorts.ts b/services/mcp/src/tools/generated/cohorts.ts
index 004b21468832..7e516f6cd87d 100644
--- a/services/mcp/src/tools/generated/cohorts.ts
+++ b/services/mcp/src/tools/generated/cohorts.ts
@@ -82,6 +82,9 @@ const cohortsCreate = (): ToolBase<typeof CohortsCreateSchema, WithPostHogUrl<Sc
const CohortsListSchema = CohortsListQueryParams.extend({
limit: z.preprocess(castStringToInt, CohortsListQueryParams.shape['limit']).optional(),
offset: z.preprocess(castStringToInt, CohortsListQueryParams.shape['offset']).optional(),
+ hide_behavioral_cohorts: CohortsListQueryParams.shape['hide_behavioral_cohorts'].describe(
+ 'Set true to exclude behavioral (event-based) cohorts — not usable in batch workflow audiences.'
+ ),
})
const cohortsList = (): ToolBase<typeof CohortsListSchema, WithPostHogUrl<Schemas.PaginatedCohortList>> =>
@@ -95,6 +98,7 @@ const cohortsList = (): ToolBase<typeof CohortsListSchema, WithPostHogUrl<Schema
path: `/api/projects/${encodeURIComponent(String(projectId))}/cohorts/`,
query: {
basic: params.basic,
+ hide_behavioral_cohorts: params.hide_behavioral_cohorts,
limit: params.limit,
offset: params.offset,
},
diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.ts
index 1ad64d58e826..950b1f8c59f1 100644
--- a/services/mcp/src/tools/generated/workflows.ts
+++ b/services/mcp/src/tools/generated/workflows.ts
@@ -3,6 +3,7 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import {
+ HogFlowsBatchJobsListParams,
HogFlowsCreateBody,
HogFlowsInvocationsCreateBody,
HogFlowsInvocationsCreateParams,
@@ -14,6 +15,8 @@ import {
HogFlowsPartialUpdateBody,
HogFlowsPartialUpdateParams,
HogFlowsRetrieveParams,
+ HogFlowsSchedulesPartialUpdateBody,
+ HogFlowsSchedulesPartialUpdateParams,
} from '@/generated/workflows/api'
import { withUiApp } from '@/resources/ui-apps'
import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
@@ -156,6 +159,24 @@ const workflowsList = (): ToolBase<typeof WorkflowsListSchema, WithPostHogUrl<Sc
},
})
+const WorkflowsListBatchJobsSchema = HogFlowsBatchJobsListParams.omit({ project_id: true })
+
+const workflowsListBatchJobs = (): ToolBase<
+ typeof WorkflowsListBatchJobsSchema,
+ WithPostHogUrl<Schemas.HogFlowBatchJob[]>
+> => ({
+ name: 'workflows-list-batch-jobs',
+ schema: WorkflowsListBatchJobsSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsListBatchJobsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.HogFlowBatchJob[]>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/batch_jobs/`,
+ })
+ return await withPostHogUrl(context, result, '/pipeline/destinations')
+ },
+})
+
const WorkflowsRunSchema = HogFlowsInvocationsCreateParams.omit({ project_id: true }).extend(
HogFlowsInvocationsCreateBody.shape
)
@@ -228,12 +249,45 @@ const workflowsUpdate = (): ToolBase<typeof WorkflowsUpdateSchema, WithPostHogUr
},
})
+const WorkflowsUpdateScheduleSchema = HogFlowsSchedulesPartialUpdateParams.omit({ project_id: true }).extend(
+ HogFlowsSchedulesPartialUpdateBody.shape
+)
+
+const workflowsUpdateSchedule = (): ToolBase<typeof WorkflowsUpdateScheduleSchema, Schemas.HogFlowSchedule> => ({
+ name: 'workflows-update-schedule',
+ schema: WorkflowsUpdateScheduleSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsUpdateScheduleSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.rrule !== undefined) {
+ body['rrule'] = params.rrule
+ }
+ if (params.starts_at !== undefined) {
+ body['starts_at'] = params.starts_at
+ }
+ if (params.timezone !== undefined) {
+ body['timezone'] = params.timezone
+ }
+ if (params.variables !== undefined) {
+ body['variables'] = params.variables
+ }
+ const result = await context.api.request<Schemas.HogFlowSchedule>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/schedules/${encodeURIComponent(String(params.schedule_id))}/`,
+ body,
+ })
+ return result
+ },
+})
+
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'hog-flows-logs-retrieve': hogFlowsLogsRetrieve,
'hog-flows-metrics-retrieve': hogFlowsMetricsRetrieve,
'workflows-create': workflowsCreate,
'workflows-get': workflowsGet,
'workflows-list': workflowsList,
+ 'workflows-list-batch-jobs': workflowsListBatchJobs,
'workflows-run': workflowsRun,
'workflows-update': workflowsUpdate,
+ 'workflows-update-schedule': workflowsUpdateSchedule,
}
diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.ts
index c9aeffd9310a..89987aebd2be 100644
--- a/services/mcp/src/tools/index.ts
+++ b/services/mcp/src/tools/index.ts
@@ -39,8 +39,12 @@ import {
getToolDefinition,
} from './toolDefinitions'
import type { Context, Tool, ToolBase, ZodObjectAny } from './types'
-// Workflows (lifecycle — CRUD lives in generated/workflows.ts)
-import { workflowsArchive, workflowsDisable, workflowsEnable } from './workflows/lifecycle'
+// Workflows (batch — orchestration over existing REST endpoints with a blast-radius guard)
+import { workflowsBlastRadius, workflowsRunBatch, workflowsScheduleCreate } from './workflows/batch'
+// Workflows (lifecycle — CRUD lives in generated/workflows.ts). workflows-disable is intentionally
+// not registered: editing active workflows is blocked, and exposing disable invited a
+// disable→edit→enable workaround. The factory stays in lifecycle.ts for easy re-enable.
+import { workflowsArchive, workflowsEnable } from './workflows/lifecycle'
// Map of tool names to tool factory functions
export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {
@@ -88,8 +92,13 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {
// Workflows lifecycle (thin wrappers over hog_flows_partial_update so MCP gets
// an idiomatic enable/disable/archive surface without three new REST endpoints).
'workflows-enable': workflowsEnable,
- 'workflows-disable': workflowsDisable,
'workflows-archive': workflowsArchive,
+
+ // Workflows batch (hand-rolled: blast-radius sizing + echo-back guard before fan-out,
+ // composing the existing user_blast_radius / batch_jobs / schedules endpoints).
+ 'workflows-blast-radius': workflowsBlastRadius,
+ 'workflows-run-batch': workflowsRunBatch,
+ 'workflows-schedule-create': workflowsScheduleCreate,
}
export const getToolsFromContext = async (
diff --git a/services/mcp/src/tools/workflows/batch.ts b/services/mcp/src/tools/workflows/batch.ts
new file mode 100644
index 000000000000..1896e2309187
--- /dev/null
+++ b/services/mcp/src/tools/workflows/batch.ts
@@ -0,0 +1,182 @@
+import { z } from 'zod'
+
+import type { Context, ToolBase } from '@/tools/types'
+
+/**
+ * Mirrors `CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE` in nodejs/src/cdp/config.ts — the cap the batch
+ * consumer enforces by silently truncating the fan-out. We reject past it here so MCP callers get an
+ * explicit error instead of an under-the-hood partial run. Keep the two values in sync.
+ */
+export const BATCH_WORKFLOW_MAX_AUDIENCE_SIZE = 5000
+
+type BlastRadius = { affected: number; total: number }
+
+type WorkflowTrigger = { type?: string; filters?: unknown }
+
+async function fetchWorkflow(
+ context: Context,
+ projectId: string,
+ workflowId: string
+): Promise<{ status: string | undefined; trigger: WorkflowTrigger }> {
+ const workflow = await context.api.request<{ status?: string; trigger?: unknown }>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(workflowId))}/`,
+ })
+ return { status: workflow.status, trigger: (workflow.trigger ?? {}) as WorkflowTrigger }
+}
+
+function triggerFilters(trigger: WorkflowTrigger): unknown {
+ return trigger.filters ?? { properties: [] }
+}
+
+async function sizeAudience(context: Context, projectId: string, filters: unknown): Promise<BlastRadius> {
+ return await context.api.request<BlastRadius>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/user_blast_radius/`,
+ body: { filters },
+ })
+}
+
+/**
+ * Echo-back guard: the caller must have sized the audience with workflows-blast-radius and surfaced the
+ * number to the user. We recompute it here and reject on drift or over-cap before any fan-out.
+ */
+function assertAcknowledged(affected: number, acknowledged: number): void {
+ if (affected !== acknowledged) {
+ throw new Error(
+ `Audience size is now ${affected} users (you acknowledged ${acknowledged}). Re-check with ` +
+ `workflows-blast-radius and confirm the new count with the user before running.`
+ )
+ }
+ if (affected > BATCH_WORKFLOW_MAX_AUDIENCE_SIZE) {
+ throw new Error(
+ `Audience of ${affected} users exceeds the ${BATCH_WORKFLOW_MAX_AUDIENCE_SIZE}-user cap. Narrow the ` +
+ `workflow's batch trigger filters to reduce the audience, then try again.`
+ )
+ }
+}
+
+const BlastRadiusSchema = z.object({
+ workflow_id: z.string().describe('ID of the workflow whose batch-trigger audience to size.'),
+})
+
+export const workflowsBlastRadius = (): ToolBase<typeof BlastRadiusSchema, BlastRadius> => ({
+ name: 'workflows-blast-radius',
+ schema: BlastRadiusSchema,
+ handler: async (context, params) => {
+ const projectId = await context.stateManager.getProjectId()
+ const { trigger } = await fetchWorkflow(context, projectId, params.workflow_id)
+ return await sizeAudience(context, projectId, triggerFilters(trigger))
+ },
+})
+
+const RunBatchSchema = z.object({
+ workflow_id: z.string().describe('ID of the batch workflow to run now.'),
+ acknowledged_affected_count: z
+ .number()
+ .int()
+ .describe(
+ 'The affected-user count from workflows-blast-radius that you showed the user AND they explicitly ' +
+ 'confirmed before you called this — never size and fire in one step. Rejected if it no longer ' +
+ 'matches the current audience, forcing a re-check.'
+ ),
+ variables: z
+ .record(z.string(), z.unknown())
+ .optional()
+ .describe('Optional {key: value} variable overrides for this run; defaults to the workflow definition.'),
+})
+
+export const workflowsRunBatch = (): ToolBase<typeof RunBatchSchema, unknown> => ({
+ name: 'workflows-run-batch',
+ schema: RunBatchSchema,
+ handler: async (context, params) => {
+ const projectId = await context.stateManager.getProjectId()
+ const { status, trigger } = await fetchWorkflow(context, projectId, params.workflow_id)
+
+ if (trigger.type !== 'batch') {
+ throw new Error(
+ `workflows-run-batch only applies to workflows with a 'batch' trigger (this one is ` +
+ `'${trigger.type ?? 'unknown'}'). Use workflows-run to test-invoke, or a schedule for recurring runs.`
+ )
+ }
+
+ if (status !== 'active') {
+ throw new Error(
+ `Workflow is not active (status '${status ?? 'unknown'}') — a batch run sends real messages, so the ` +
+ `workflow must be enabled first with workflows-enable.`
+ )
+ }
+
+ const filters = triggerFilters(trigger)
+ const { affected } = await sizeAudience(context, projectId, filters)
+ assertAcknowledged(affected, params.acknowledged_affected_count)
+
+ return await context.api.request({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.workflow_id))}/batch_jobs/`,
+ body: { filters, ...(params.variables !== undefined ? { variables: params.variables } : {}) },
+ })
+ },
+})
+
+const ScheduleCreateSchema = z.object({
+ workflow_id: z.string().describe('ID of the batch workflow to attach the recurring schedule to.'),
+ rrule: z
+ .string()
+ .describe("iCalendar RRULE (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour."),
+ starts_at: z.string().describe('ISO 8601 datetime the schedule starts from.'),
+ timezone: z.string().optional().describe("IANA timezone for the RRULE (default 'UTC')."),
+ acknowledged_affected_count: z
+ .number()
+ .int()
+ .describe(
+ 'The affected-user count from workflows-blast-radius that you showed the user AND they explicitly ' +
+ 'confirmed before scheduling. Each firing re-broadcasts to the audience at that time; rejected if it ' +
+ 'no longer matches.'
+ ),
+ variables: z
+ .record(z.string(), z.unknown())
+ .optional()
+ .describe('Optional {key: value} variable overrides merged with the workflow defaults on each run.'),
+})
+
+export const workflowsScheduleCreate = (): ToolBase<typeof ScheduleCreateSchema, unknown> => ({
+ name: 'workflows-schedule-create',
+ schema: ScheduleCreateSchema,
+ handler: async (context, params) => {
+ const projectId = await context.stateManager.getProjectId()
+ const { status, trigger } = await fetchWorkflow(context, projectId, params.workflow_id)
+
+ if (trigger.type !== 'batch') {
+ throw new Error(
+ `workflows-schedule-create only applies to workflows with a 'batch' trigger (this one is ` +
+ `'${trigger.type ?? 'unknown'}').`
+ )
+ }
+
+ // Require the workflow to be active before scheduling. A draft's trigger can still be edited, so
+ // scheduling a draft would let the audience be broadened after you acknowledged it (the scheduler
+ // uses the trigger's filters at fire time). An active workflow's trigger can't be edited via MCP,
+ // so the acknowledged audience is locked in.
+ if (status !== 'active') {
+ throw new Error(
+ `Workflow is not active (status '${status ?? 'unknown'}') — enable it with workflows-enable before ` +
+ `scheduling. Scheduling a draft would let the audience change after you sized it.`
+ )
+ }
+
+ const { affected } = await sizeAudience(context, projectId, triggerFilters(trigger))
+ assertAcknowledged(affected, params.acknowledged_affected_count)
+
+ return await context.api.request({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.workflow_id))}/schedules/`,
+ body: {
+ rrule: params.rrule,
+ starts_at: params.starts_at,
+ ...(params.timezone !== undefined ? { timezone: params.timezone } : {}),
+ ...(params.variables !== undefined ? { variables: params.variables } : {}),
+ },
+ })
+ },
+})
diff --git a/services/mcp/tests/tools/workflows.integration.test.ts b/services/mcp/tests/tools/workflows.integration.test.ts
index d7a1d7db527a..60bf178cb165 100644
--- a/services/mcp/tests/tools/workflows.integration.test.ts
+++ b/services/mcp/tests/tools/workflows.integration.test.ts
@@ -12,6 +12,7 @@ import {
} from '@/shared/test-utils'
import { GENERATED_TOOLS } from '@/tools/generated/workflows'
import type { Context } from '@/tools/types'
+import { workflowsBlastRadius, workflowsRunBatch, workflowsScheduleCreate } from '@/tools/workflows/batch'
import { workflowsArchive, workflowsDisable, workflowsEnable } from '@/tools/workflows/lifecycle'
describe('Workflows', { concurrent: false }, () => {
@@ -26,6 +27,11 @@ describe('Workflows', { concurrent: false }, () => {
const enableTool = workflowsEnable()
const disableTool = workflowsDisable()
const archiveTool = workflowsArchive()
+ const blastRadiusTool = workflowsBlastRadius()
+ const runBatchTool = workflowsRunBatch()
+ const scheduleCreateTool = workflowsScheduleCreate()
+ const listBatchJobsTool = GENERATED_TOOLS['workflows-list-batch-jobs']!()
+ const updateScheduleTool = GENERATED_TOOLS['workflows-update-schedule']!()
const createdWorkflowIds: string[] = []
@@ -82,6 +88,34 @@ describe('Workflows', { concurrent: false }, () => {
}
}
+ // A batch-trigger workflow (empty properties = audience is all persons). Drafts are fine for
+ // these tests — the echo-back guard lives in the MCP handler, not the API.
+ function makeBatchWorkflowParams(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ const ts = Date.now()
+ return makeWorkflowParams({
+ actions: [
+ {
+ id: 'trigger_node',
+ name: 'Trigger',
+ type: 'trigger',
+ created_at: ts,
+ updated_at: ts,
+ config: { type: 'batch', filters: { properties: [] } },
+ },
+ {
+ id: 'exit_node',
+ name: 'Exit',
+ type: 'exit',
+ created_at: ts,
+ updated_at: ts,
+ config: { reason: 'Default exit' },
+ },
+ ],
+ edges: [{ from: 'trigger_node', to: 'exit_node', type: 'continue' }],
+ ...overrides,
+ })
+ }
+
describe('workflows-list tool', () => {
it('should list workflows and return paginated structure', async () => {
const result = await listTool.handler(context, {})
@@ -252,10 +286,77 @@ describe('Workflows', { concurrent: false }, () => {
})
await expect(createTool.handler(context, params)).rejects.toThrow()
})
+
+ it('should reject a batch audience that references a behavioral cohort', async () => {
+ const projectId = await context.stateManager.getProjectId()
+ const cohortPath = `/api/projects/${encodeURIComponent(String(projectId))}/cohorts/`
+ const cohort = await context.api.request<{ id: number }>({
+ method: 'POST',
+ path: cohortPath,
+ body: {
+ name: `mcp-test-behavioral-${generateUniqueKey('cohort')}`,
+ filters: {
+ properties: {
+ type: 'OR',
+ values: [
+ {
+ type: 'OR',
+ values: [
+ {
+ key: '$pageview',
+ type: 'behavioral',
+ value: 'performed_event',
+ event_type: 'events',
+ time_value: 30,
+ time_interval: 'day',
+ },
+ ],
+ },
+ ],
+ },
+ },
+ },
+ })
+
+ try {
+ const ts = Date.now()
+ const params = makeBatchWorkflowParams({
+ actions: [
+ {
+ id: 'trigger_node',
+ name: 'Trigger',
+ type: 'trigger',
+ created_at: ts,
+ updated_at: ts,
+ config: {
+ type: 'batch',
+ filters: {
+ properties: [{ key: 'id', type: 'cohort', value: cohort.id, operator: 'in' }],
+ },
+ },
+ },
+ {
+ id: 'exit_node',
+ name: 'Exit',
+ type: 'exit',
+ created_at: ts,
+ updated_at: ts,
+ config: { reason: 'Default exit' },
+ },
+ ],
+ })
+ // MCP requests are non-web, so the guard fires even on a draft save.
+ await expect(createTool.handler(context, params)).rejects.toThrow(/behavior/i)
+ } finally {
+ await context.api
+ .request({ method: 'PATCH', path: `${cohortPath}${cohort.id}/`, body: { deleted: true } })
+ .catch(() => {})
+ }
+ })
})
describe('workflows-update tool', () => {
- it('should partially update a workflow name', async () => {
+ it('should partially update a draft workflow name', async () => {
const created = parseToolResponse(await createTool.handler(context, makeWorkflowParams()))
createdWorkflowIds.push(created.id)
@@ -266,6 +367,16 @@ describe('Workflows', { concurrent: false }, () => {
expect(renamed.id).toBe(created.id)
expect(renamed.name).toBe('mcp-test-renamed')
})
+
+ it('should refuse editing an active workflow via MCP', async () => {
+ const created = parseToolResponse(await createTool.handler(context, makeWorkflowParams()))
+ createdWorkflowIds.push(created.id)
+ await enableTool.handler(context, { id: created.id })
+
+ await expect(
+ updateTool.handler(context, { id: created.id, name: 'mcp-test-active-rename' })
+ ).rejects.toThrow(/active workflow isn't supported via MCP/)
+ })
})
// workflows-run hits the invocations endpoint, which forwards to the CDP plugin
@@ -328,4 +439,119 @@ describe('Workflows', { concurrent: false }, () => {
expect(archived.status).toBe('archived')
})
})
+
+ describe('workflows-blast-radius tool', () => {
+ it('sizes the batch trigger audience for a workflow', async () => {
+ const created = parseToolResponse(await createTool.handler(context, makeBatchWorkflowParams()))
+ createdWorkflowIds.push(created.id)
+
+ const { affected, total } = parseToolResponse(
+ await blastRadiusTool.handler(context, { workflow_id: created.id })
+ )
+
+ expect(typeof affected).toBe('number')
+ expect(typeof total).toBe('number')
+ expect(affected).toBeLessThanOrEqual(total)
+ })
+
+ it('throws for a non-existent workflow', async () => {
+ await expect(blastRadiusTool.handler(context, { workflow_id: crypto.randomUUID() })).rejects.toThrow()
+ })
+ })
+
+ describe('workflows-run-batch tool', () => {
+ it('rejects a stale acknowledged count without firing, surfacing the fresh count', async () => {
+ const created = parseToolResponse(await createTool.handler(context, makeBatchWorkflowParams()))
+ createdWorkflowIds.push(created.id)
+ // Must be active or the run-batch active-guard fires before the echo-back check.
+ await enableTool.handler(context, { id: created.id })
+
+ const { affected } = parseToolResponse(await blastRadiusTool.handler(context, { workflow_id: created.id }))
+
+ await expect(
+ runBatchTool.handler(context, { workflow_id: created.id, acknowledged_affected_count: affected + 1 })
+ ).rejects.toThrow(String(affected))
+ })
+
+ it('rejects a workflow whose trigger is not a batch trigger', async () => {
+ // makeWorkflowParams() builds an event-trigger workflow.
+ const created = parseToolResponse(await createTool.handler(context, makeWorkflowParams()))
+ createdWorkflowIds.push(created.id)
+
+ await expect(
+ runBatchTool.handler(context, { workflow_id: created.id, acknowledged_affected_count: 0 })
+ ).rejects.toThrow(/batch/)
+ })
+
+ // The happy path (matching count → POST batch_jobs) forwards to the CDP plugin server
+ // (CDP_API_URL), which isn't running in MCP CI — see the workflows-run note above. Fire-path
+ // coverage lives in the backend test and the unit handler test
+ // (tests/unit/workflows-batch-handlers.test.ts).
+ })
+
+ describe('workflows schedule tools', () => {
+ it('creates a schedule, surfaces it on workflows-get, and updates it', async () => {
+ const created = parseToolResponse(await createTool.handler(context, makeBatchWorkflowParams()))
+ createdWorkflowIds.push(created.id)
+ await enableTool.handler(context, { id: created.id })
+
+ const { affected } = parseToolResponse(await blastRadiusTool.handler(context, { workflow_id: created.id }))
+
+ const schedule = parseToolResponse(
+ await scheduleCreateTool.handler(context, {
+ workflow_id: created.id,
+ rrule: 'FREQ=DAILY;INTERVAL=1',
+ starts_at: new Date().toISOString(),
+ timezone: 'UTC',
+ acknowledged_affected_count: affected,
+ })
+ )
+ expect(schedule.id).toBeTypeOf('string')
+ expect(schedule.rrule).toBe('FREQ=DAILY;INTERVAL=1')
+
+ // The schedule is surfaced inline on the workflow (no separate list tool).
+ const workflow = parseToolResponse(await getTool.handler(context, { id: created.id }))
+ expect(Array.isArray(workflow.schedules)).toBe(true)
+ expect(workflow.schedules.map((s: any) => s.id)).toContain(schedule.id)
+
+ const updated = parseToolResponse(
+ await updateScheduleTool.handler(context, {
+ id: created.id,
+ schedule_id: schedule.id,
+ rrule: 'FREQ=WEEKLY;INTERVAL=1',
+ })
+ )
+ expect(updated.rrule).toBe('FREQ=WEEKLY;INTERVAL=1')
+ })
+
+ it('rejects schedule creation when the acknowledged count is stale', async () => {
+ const created = parseToolResponse(await createTool.handler(context, makeBatchWorkflowParams()))
+ createdWorkflowIds.push(created.id)
+ await enableTool.handler(context, { id: created.id })
+
+ const { affected } = parseToolResponse(await blastRadiusTool.handler(context, { workflow_id: created.id }))
+
+ await expect(
+ scheduleCreateTool.handler(context, {
+ workflow_id: created.id,
+ rrule: 'FREQ=DAILY;INTERVAL=1',
+ starts_at: new Date().toISOString(),
+ acknowledged_affected_count: affected + 1,
+ })
+ ).rejects.toThrow(String(affected))
+ })
+ })
+
+ describe('workflows-list-batch-jobs tool', () => {
+ it('returns the batch runs for a workflow', async () => {
+ const created = parseToolResponse(await createTool.handler(context, makeBatchWorkflowParams()))
+ createdWorkflowIds.push(created.id)
+
+ // The bare-array response is enriched via withPostHogUrl (spread into an object with a
+ // _posthogUrl key), same as other bare-array list tools — so it's an object, not an array.
+ const jobs = parseToolResponse(await listBatchJobsTool.handler(context, { id: created.id }))
+ expect(jobs).toBeTypeOf('object')
+ expect(jobs).toHaveProperty('_posthogUrl')
+ })
+ })
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json
index 55e911877b6b..275fc29b5981 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json
@@ -5,6 +5,10 @@
"description": "Return a basic payload that omits the heavy `filters`, `query`, and `groups` fields. Useful for pickers that only need id/name/count.",
"type": "boolean"
},
+ "hide_behavioral_cohorts": {
+ "description": "Set true to exclude behavioral (event-based) cohorts — not usable in batch workflow audiences.",
+ "type": "boolean"
+ },
"limit": {
"description": "Number of results to return per page.",
"type": "number"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/workflows-blast-radius.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/workflows-blast-radius.json
new file mode 100644
index 000000000000..ab59e5ce611c
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/workflows-blast-radius.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "workflow_id": {
+ "description": "ID of the workflow whose batch-trigger audience to size.",
+ "type": "string"
+ }
+ },
+ "required": ["workflow_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-disable.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/workflows-list-batch-jobs.json
similarity index 100%
rename from services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-disable.json
rename to services/mcp/tests/unit/__snapshots__/tool-schemas/common/workflows-list-batch-jobs.json
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/workflows-run-batch.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/workflows-run-batch.json
new file mode 100644
index 000000000000..2ff799760615
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/workflows-run-batch.json
@@ -0,0 +1,25 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "acknowledged_affected_count": {
+ "description": "The affected-user count from workflows-blast-radius that you showed the user. Rejected if it no longer matches the current audience, forcing a re-check.",
+ "maximum": 9007199254740991,
+ "minimum": -9007199254740991,
+ "type": "integer"
+ },
+ "variables": {
+ "additionalProperties": {},
+ "description": "Optional {key: value} variable overrides for this run; defaults to the workflow definition.",
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ "workflow_id": {
+ "description": "ID of the batch workflow to run now.",
+ "type": "string"
+ }
+ },
+ "required": ["workflow_id", "acknowledged_affected_count"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/workflows-schedule-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/workflows-schedule-create.json
new file mode 100644
index 000000000000..c97e920bdeb4
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/workflows-schedule-create.json
@@ -0,0 +1,37 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "acknowledged_affected_count": {
+ "description": "Required for a batch (audience) workflow: the current affected-user count from workflows-blast-radius that you showed the user. Each firing re-broadcasts to the audience at that time; rejected if it no longer matches. Not needed for a 'schedule' trigger (person-less — no audience).",
+ "maximum": 9007199254740991,
+ "minimum": -9007199254740991,
+ "type": "integer"
+ },
+ "rrule": {
+ "description": "iCalendar RRULE (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour.",
+ "type": "string"
+ },
+ "starts_at": {
+ "description": "ISO 8601 datetime the schedule starts from.",
+ "type": "string"
+ },
+ "timezone": {
+ "description": "IANA timezone for the RRULE (default 'UTC').",
+ "type": "string"
+ },
+ "variables": {
+ "additionalProperties": {},
+ "description": "Optional {key: value} variable overrides merged with the workflow defaults on each run.",
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ "workflow_id": {
+ "description": "ID of the batch or schedule workflow to attach the schedule to.",
+ "type": "string"
+ }
+ },
+ "required": ["workflow_id", "rrule", "starts_at"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/workflows-update-schedule.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/workflows-update-schedule.json
new file mode 100644
index 000000000000..1b38f21dc18e
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/workflows-update-schedule.json
@@ -0,0 +1,32 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this hog flow.",
+ "type": "string"
+ },
+ "rrule": {
+ "description": "iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour.",
+ "type": "string"
+ },
+ "schedule_id": {
+ "type": "string"
+ },
+ "starts_at": {
+ "description": "ISO 8601 datetime the schedule starts from.",
+ "format": "date-time",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
+ "timezone": {
+ "description": "IANA timezone for interpreting the RRULE (default 'UTC').",
+ "maxLength": 64,
+ "type": "string"
+ },
+ "variables": {
+ "description": "Variable value overrides merged with the workflow defaults on each run."
+ }
+ },
+ "required": ["id", "schedule_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-blast-radius.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-blast-radius.json
new file mode 100644
index 000000000000..ab59e5ce611c
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-blast-radius.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "workflow_id": {
+ "description": "ID of the workflow whose batch-trigger audience to size.",
+ "type": "string"
+ }
+ },
+ "required": ["workflow_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-batch-jobs.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-batch-jobs.json
new file mode 100644
index 000000000000..6c38f5b9f257
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-batch-jobs.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this hog flow.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-run-batch.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-run-batch.json
new file mode 100644
index 000000000000..a1f4ab6eda0b
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-run-batch.json
@@ -0,0 +1,25 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "acknowledged_affected_count": {
+ "description": "The affected-user count from workflows-blast-radius that you showed the user AND they explicitly confirmed before you called this — never size and fire in one step. Rejected if it no longer matches the current audience, forcing a re-check.",
+ "maximum": 9007199254740991,
+ "minimum": -9007199254740991,
+ "type": "integer"
+ },
+ "variables": {
+ "additionalProperties": {},
+ "description": "Optional {key: value} variable overrides for this run; defaults to the workflow definition.",
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ "workflow_id": {
+ "description": "ID of the batch workflow to run now.",
+ "type": "string"
+ }
+ },
+ "required": ["workflow_id", "acknowledged_affected_count"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-schedule-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-schedule-create.json
new file mode 100644
index 000000000000..78c8278f7ad2
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-schedule-create.json
@@ -0,0 +1,37 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "acknowledged_affected_count": {
+ "description": "The affected-user count from workflows-blast-radius that you showed the user AND they explicitly confirmed before scheduling. Each firing re-broadcasts to the audience at that time; rejected if it no longer matches.",
+ "maximum": 9007199254740991,
+ "minimum": -9007199254740991,
+ "type": "integer"
+ },
+ "rrule": {
+ "description": "iCalendar RRULE (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour.",
+ "type": "string"
+ },
+ "starts_at": {
+ "description": "ISO 8601 datetime the schedule starts from.",
+ "type": "string"
+ },
+ "timezone": {
+ "description": "IANA timezone for the RRULE (default 'UTC').",
+ "type": "string"
+ },
+ "variables": {
+ "additionalProperties": {},
+ "description": "Optional {key: value} variable overrides merged with the workflow defaults on each run.",
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ "workflow_id": {
+ "description": "ID of the batch workflow to attach the recurring schedule to.",
+ "type": "string"
+ }
+ },
+ "required": ["workflow_id", "rrule", "starts_at", "acknowledged_affected_count"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-schedule.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-schedule.json
new file mode 100644
index 000000000000..1b38f21dc18e
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-schedule.json
@@ -0,0 +1,32 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this hog flow.",
+ "type": "string"
+ },
+ "rrule": {
+ "description": "iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour.",
+ "type": "string"
+ },
+ "schedule_id": {
+ "type": "string"
+ },
+ "starts_at": {
+ "description": "ISO 8601 datetime the schedule starts from.",
+ "format": "date-time",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
+ "timezone": {
+ "description": "IANA timezone for interpreting the RRULE (default 'UTC').",
+ "maxLength": 64,
+ "type": "string"
+ },
+ "variables": {
+ "description": "Variable value overrides merged with the workflow defaults on each run."
+ }
+ },
+ "required": ["id", "schedule_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/workflows-batch-handlers.test.ts b/services/mcp/tests/unit/workflows-batch-handlers.test.ts
new file mode 100644
index 000000000000..66b77af9681d
--- /dev/null
+++ b/services/mcp/tests/unit/workflows-batch-handlers.test.ts
@@ -0,0 +1,256 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { Context } from '@/tools/types'
+import {
+ BATCH_WORKFLOW_MAX_AUDIENCE_SIZE,
+ workflowsBlastRadius,
+ workflowsRunBatch,
+ workflowsScheduleCreate,
+} from '@/tools/workflows/batch'
+
+interface RequestArgs {
+ method: string
+ path: string
+ body?: Record<string, unknown>
+}
+
+const BATCH_FILTERS = { properties: [{ key: 'email', value: 'is_set', type: 'person' }] }
+
+/**
+ * Mock context whose api.request dispatches by method+path:
+ * - GET .../hog_flows/{id}/ -> the workflow (with the given trigger)
+ * - POST .../hog_flows/user_blast_radius/ -> the given blast radius
+ * - POST .../batch_jobs/ or .../schedules/ -> echoes the created resource
+ */
+function createMockContext(opts: {
+ trigger: unknown
+ blastRadius: { affected: number; total: number }
+ status?: string
+}): { context: Context; request: ReturnType<typeof vi.fn> } {
+ const request = vi.fn(async ({ method, path }: RequestArgs) => {
+ if (method === 'GET' && /\/hog_flows\/[^/]+\/$/.test(path)) {
+ return { id: 'wf-1', status: opts.status ?? 'active', trigger: opts.trigger }
+ }
+ if (method === 'POST' && path.endsWith('/user_blast_radius/')) {
+ return opts.blastRadius
+ }
+ if (method === 'POST' && path.endsWith('/batch_jobs/')) {
+ return { id: 'batch-1', status: 'queued' }
+ }
+ if (method === 'POST' && path.endsWith('/schedules/')) {
+ return { id: 'sched-1', status: 'active' }
+ }
+ throw new Error(`unexpected request: ${method} ${path}`)
+ })
+
+ const context = {
+ api: { request },
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('1') },
+ } as unknown as Context
+
+ return { context, request }
+}
+
+function calls(request: ReturnType<typeof vi.fn>): RequestArgs[] {
+ return request.mock.calls.map((c) => c[0] as RequestArgs)
+}
+
+const blastRadiusTool = workflowsBlastRadius()
+const runBatchTool = workflowsRunBatch()
+const scheduleCreateTool = workflowsScheduleCreate()
+
+describe('workflows batch handlers', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ describe('workflows-blast-radius', () => {
+ it('resolves the workflow trigger filters and sizes them, returning the count', async () => {
+ const { context, request } = createMockContext({
+ trigger: { type: 'batch', filters: BATCH_FILTERS },
+ blastRadius: { affected: 42, total: 100 },
+ })
+
+ const result = await blastRadiusTool.handler(context, { workflow_id: 'wf-1' })
+
+ const c = calls(request)
+ expect(c[0]).toMatchObject({ method: 'GET', path: '/api/projects/1/hog_flows/wf-1/' })
+ expect(c[1]).toMatchObject({
+ method: 'POST',
+ path: '/api/projects/1/hog_flows/user_blast_radius/',
+ body: { filters: BATCH_FILTERS },
+ })
+ expect(result).toEqual({ affected: 42, total: 100 })
+ })
+ })
+
+ describe('workflows-run-batch', () => {
+ it('fires the batch job with the trigger filters when the acknowledged count matches', async () => {
+ const { context, request } = createMockContext({
+ trigger: { type: 'batch', filters: BATCH_FILTERS },
+ blastRadius: { affected: 10, total: 100 },
+ })
+
+ const result = await runBatchTool.handler(context, {
+ workflow_id: 'wf-1',
+ acknowledged_affected_count: 10,
+ variables: { plan: 'pro' },
+ })
+
+ const batchCall = calls(request).find((c) => c.path.endsWith('/batch_jobs/'))
+ expect(batchCall).toMatchObject({
+ method: 'POST',
+ path: '/api/projects/1/hog_flows/wf-1/batch_jobs/',
+ body: { filters: BATCH_FILTERS, variables: { plan: 'pro' } },
+ })
+ expect(result).toMatchObject({ id: 'batch-1' })
+ })
+
+ it('omits variables from the body when none are given', async () => {
+ const { context, request } = createMockContext({
+ trigger: { type: 'batch', filters: BATCH_FILTERS },
+ blastRadius: { affected: 10, total: 100 },
+ })
+
+ await runBatchTool.handler(context, { workflow_id: 'wf-1', acknowledged_affected_count: 10 })
+
+ const batchCall = calls(request).find((c) => c.path.endsWith('/batch_jobs/'))
+ expect(batchCall!.body).toEqual({ filters: BATCH_FILTERS })
+ })
+
+ it('rejects and does not fire when the acknowledged count is stale, surfacing the fresh count', async () => {
+ const { context, request } = createMockContext({
+ trigger: { type: 'batch', filters: BATCH_FILTERS },
+ blastRadius: { affected: 25, total: 100 },
+ })
+
+ await expect(
+ runBatchTool.handler(context, { workflow_id: 'wf-1', acknowledged_affected_count: 10 })
+ ).rejects.toThrow(/25/)
+ expect(calls(request).some((c) => c.path.endsWith('/batch_jobs/'))).toBe(false)
+ })
+
+ it('rejects and does not fire when the audience exceeds the cap', async () => {
+ const { context, request } = createMockContext({
+ trigger: { type: 'batch', filters: BATCH_FILTERS },
+ blastRadius: { affected: BATCH_WORKFLOW_MAX_AUDIENCE_SIZE + 1, total: 1_000_000 },
+ })
+
+ await expect(
+ runBatchTool.handler(context, {
+ workflow_id: 'wf-1',
+ acknowledged_affected_count: BATCH_WORKFLOW_MAX_AUDIENCE_SIZE + 1,
+ })
+ ).rejects.toThrow(new RegExp(String(BATCH_WORKFLOW_MAX_AUDIENCE_SIZE)))
+ expect(calls(request).some((c) => c.path.endsWith('/batch_jobs/'))).toBe(false)
+ })
+
+ it('rejects workflows whose trigger is not a batch trigger', async () => {
+ const { context, request } = createMockContext({
+ trigger: { type: 'event', filters: BATCH_FILTERS },
+ blastRadius: { affected: 10, total: 100 },
+ })
+
+ await expect(
+ runBatchTool.handler(context, { workflow_id: 'wf-1', acknowledged_affected_count: 10 })
+ ).rejects.toThrow(/batch/)
+ expect(calls(request).some((c) => c.path.endsWith('/batch_jobs/'))).toBe(false)
+ })
+
+ it('rejects a workflow that is not active, without firing', async () => {
+ const { context, request } = createMockContext({
+ trigger: { type: 'batch', filters: BATCH_FILTERS },
+ blastRadius: { affected: 10, total: 100 },
+ status: 'draft',
+ })
+
+ await expect(
+ runBatchTool.handler(context, { workflow_id: 'wf-1', acknowledged_affected_count: 10 })
+ ).rejects.toThrow(/enable/i)
+ expect(calls(request).some((c) => c.path.endsWith('/batch_jobs/'))).toBe(false)
+ })
+ })
+
+ describe('workflows-schedule-create', () => {
+ it('creates the schedule for a batch trigger when the acknowledged count matches', async () => {
+ const { context, request } = createMockContext({
+ trigger: { type: 'batch', filters: BATCH_FILTERS },
+ blastRadius: { affected: 3, total: 100 },
+ })
+
+ const result = await scheduleCreateTool.handler(context, {
+ workflow_id: 'wf-1',
+ rrule: 'FREQ=DAILY;INTERVAL=1',
+ starts_at: '2026-06-01T00:00:00Z',
+ timezone: 'UTC',
+ acknowledged_affected_count: 3,
+ variables: { plan: 'pro' },
+ })
+
+ const schedCall = calls(request).find((c) => c.path.endsWith('/schedules/'))
+ expect(schedCall).toMatchObject({
+ method: 'POST',
+ path: '/api/projects/1/hog_flows/wf-1/schedules/',
+ body: {
+ rrule: 'FREQ=DAILY;INTERVAL=1',
+ starts_at: '2026-06-01T00:00:00Z',
+ timezone: 'UTC',
+ variables: { plan: 'pro' },
+ },
+ })
+ expect(result).toMatchObject({ id: 'sched-1' })
+ })
+
+ it('rejects a stale acknowledged count on a batch trigger without creating the schedule', async () => {
+ const { context, request } = createMockContext({
+ trigger: { type: 'batch', filters: BATCH_FILTERS },
+ blastRadius: { affected: 50, total: 100 },
+ })
+
+ await expect(
+ scheduleCreateTool.handler(context, {
+ workflow_id: 'wf-1',
+ rrule: 'FREQ=DAILY;INTERVAL=1',
+ starts_at: '2026-06-01T00:00:00Z',
+ acknowledged_affected_count: 3,
+ })
+ ).rejects.toThrow(/50/)
+ expect(calls(request).some((c) => c.path.endsWith('/schedules/'))).toBe(false)
+ })
+
+ it('rejects scheduling a draft (non-active) workflow without creating the schedule', async () => {
+ const { context, request } = createMockContext({
+ trigger: { type: 'batch', filters: BATCH_FILTERS },
+ blastRadius: { affected: 3, total: 100 },
+ status: 'draft',
+ })
+
+ await expect(
+ scheduleCreateTool.handler(context, {
+ workflow_id: 'wf-1',
+ rrule: 'FREQ=DAILY;INTERVAL=1',
+ starts_at: '2026-06-01T00:00:00Z',
+ acknowledged_affected_count: 3,
+ })
+ ).rejects.toThrow(/active/i)
+ expect(calls(request).some((c) => c.path.endsWith('/schedules/'))).toBe(false)
+ })
+
+ it('rejects a non-batch trigger (schedule trigger no longer supported)', async () => {
+ const { context, request } = createMockContext({
+ trigger: { type: 'schedule' },
+ blastRadius: { affected: 1, total: 1 },
+ })
+
+ await expect(
+ scheduleCreateTool.handler(context, {
+ workflow_id: 'wf-1',
+ rrule: 'FREQ=DAILY;INTERVAL=1',
+ starts_at: '2026-06-01T00:00:00Z',
+ acknowledged_affected_count: 1,
+ })
+ ).rejects.toThrow(/batch/)
+ expect(calls(request).some((c) => c.path.endsWith('/schedules/'))).toBe(false)
+ })
+ })
+})