:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): draft, test, publish cycle behind the workflows-revisions flag + MCP (#70823)
Harley Alexander9998824633c2
diff --git a/hogli.yaml b/hogli.yamlindex 5eb8039a020a..339cb8693f38 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -799,8 +799,8 @@ quality:"$@"description: Format CSS/SCSS filesformat:js:- cmd: pnpm oxlint --fix --fix-suggestions --quiet "$@" && pnpm exec oxfmt --no-error-on-unmatched-pattern- "$@"+ cmd: pnpm oxlint --fix --fix-suggestions --quiet --no-error-on-unmatched-pattern+ "$@" && pnpm exec oxfmt --no-error-on-unmatched-pattern "$@"description: Format JavaScript/TypeScript files (frontend)format:nodejs:cmd: pnpm --dir nodejs exec eslint --fix "$@" && pnpm --dir nodejs exec prettierdiff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex 291e9c84e648..3efa13b4df35 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -362,7 +362,12 @@ export class CdpApi {const { clickhouse_event, mock_async_functions, configuration, invocation_id } = req.bodylet { globals } = req.body- logger.info('⚡️', 'Received invocation', { id, team_id, body: req.body })+ // Redact configuration: it carries function inputs (auth headers, API keys) that must not land in logs+ logger.info('⚡️', 'Received invocation', {+ id,+ team_id,+ body: { ...req.body, configuration: configuration ? '[redacted]' : undefined },+ })const invocationID = invocation_id ?? new UUIDT().toString()@@ -529,7 +534,12 @@ export class CdpApi {const { id, team_id } = req.paramsconst { clickhouse_event, configuration, invocation_id, current_action_id, mock_async_functions } = req.body- logger.info('⚡️', 'Received hogflow invocation', { id, team_id, body: req.body })+ // Redact configuration: it carries action inputs (auth headers, API keys) that must not land in logs+ logger.info('⚡️', 'Received hogflow invocation', {+ id,+ team_id,+ body: { ...req.body, configuration: configuration ? '[redacted]' : undefined },+ })const invocationID = invocation_id ?? new UUIDT().toString()diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 4cee628be7b9..fb82bb9eea26 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -258,6 +258,11 @@ field_with_masked_contents: dict[AuditableScope, list[str]] = {"ExternalDataSource": ["job_inputs",],+ "HogFlow": [+ # Full content snapshot including action inputs (auth headers, API keys) — record that a+ # draft was staged/published/discarded, never its contents.+ "draft",+ ],"OrganizationDomain": ["_scim_bearer_token","verification_challenge",diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex bf301f9a5570..6580325cf08e 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -56,6 +56,7 @@ from posthog.models.filters import Filterfrom posthog.plugins.plugin_server_api import (create_hog_flow_invocation_test,create_hog_flow_scheduled_invocation,+ get_hog_flow_in_flight_count,rerun_hog_invocations,)from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin@@ -95,6 +96,7 @@ from products.workflows.backend.services.batch_audience import (get_batch_audience_person_ids,use_workflows_batch_audience_query,)+from products.workflows.backend.services.revisions import use_workflows_revisionsfrom products.workflows.backend.utils.batch_trigger_limit import get_hogflow_batch_trigger_limitfrom products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrule@@ -104,14 +106,29 @@ logger = structlog.get_logger(__name__)# (nodejs/src/cdp/services/hogflows/actions/delay.ts) that throws at runtime on mismatch.DELAY_DURATION_REGEX = re.compile(r"^\d*\.?\d+[dhm]$")-# 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. Shared by the plain update path and the graph endpoint.+# Active workflows are read-only via MCP unless the workflows-revisions flag routes edits to the+# draft (see perform_update / graph): edits can break runs already scheduled or in flight, and+# there's no revision history to roll back. Shared by the plain update path and the graph endpoint.MCP_ACTIVE_EDIT_REJECTION = ("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. If you need different ""behavior, create a new draft workflow.")+# The content of a workflow: everything the draft cycle stages and publish promotes, and nothing+# else. Metadata (name, description) and lifecycle (status) always apply to the live row. The draft+# blob is a full snapshot of these fields so publish is a plain copy, not a merge.+DRAFT_CONTENT_FIELDS = (+ "actions",+ "edges",+ "trigger",+ "trigger_masking",+ "conversion",+ "exit_condition",+ "abort_action",+ "variables",+)+# A batch audience is a one-time snapshot of everyone matching the conditions at run time, so each# condition must resolve to a concrete set of persons/groups. Feature flag evaluation is dynamic# (rollout %, distinct_id hashing, super-conditions, holdouts) and has no such fixed membership, so a@@ -928,6 +945,24 @@ class HogFlowSerializer(HogFlowMinimalSerializer):),)+ draft = serializers.JSONField(+ read_only=True,+ help_text=(+ "Staged content changes awaiting publish — a full snapshot of the workflow's actions, edges and "+ "settings. Null when there's nothing staged. Test it with a use_draft test run, then promote it "+ "with the publish endpoint or throw it away with discard_draft."+ ),+ )+ draft_updated_at = serializers.DateTimeField(+ read_only=True,+ allow_null=True,+ help_text=(+ "When the draft was last written; null when there's no staged draft. Pass this to publish (and as "+ "base_updated_at on further draft edits) so a concurrent editor's changes aren't clobbered — a "+ "mismatch returns 409."+ ),+ )+def to_internal_value(self, data):status = data.get("status")if status is None and self.instance:@@ -970,6 +1005,8 @@ class HogFlowSerializer(HogFlowMinimalSerializer):"billable_action_types","schedules","user_access_level",+ "draft",+ "draft_updated_at",]read_only_fields = ["id",@@ -982,6 +1019,8 @@ class HogFlowSerializer(HogFlowMinimalSerializer):"billable_action_types", # Computed field, not user-editable"schedules", # Managed via the schedules sub-resource, surfaced read-only here"user_access_level",+ "draft", # Written by draft routing (see perform_update / graph), never directly+ "draft_updated_at",]def validate(self, data):@@ -1227,6 +1266,51 @@ class HogFlowInvocationSerializer(serializers.Serializer):"returns the next action id."),)+ use_draft = serializers.BooleanField(+ default=False,+ write_only=True,+ help_text=(+ "Test the workflow's staged draft instead of its live config. Requires an open draft; "+ "can't be combined with an explicit configuration override."+ ),+ )+++class HogFlowPublishRequestSerializer(serializers.Serializer):+ confirm = serializers.BooleanField(+ default=False,+ help_text=(+ "False (default) previews the publish: returns how many runs are in flight without changing "+ "anything. True applies the staged draft to the live workflow."+ ),+ )+ draft_updated_at = serializers.DateTimeField(+ required=False,+ help_text=(+ "The draft_updated_at you loaded — required when confirm=true. A mismatch returns 409, so you "+ "never publish a draft someone else has changed since you read it."+ ),+ )+++class HogFlowPublishResponseSerializer(serializers.Serializer):+ published = serializers.BooleanField(help_text="Whether the draft was applied to the live workflow.")+ in_flight_runs = serializers.IntegerField(+ allow_null=True,+ help_text=(+ "Runs currently in flight (parked on waits/delays or executing) that will follow the new config "+ "once published. Null when the count is unavailable."+ ),+ )+ draft_updated_at = serializers.DateTimeField(+ allow_null=True,+ help_text="Echo of the staged draft's timestamp — pass it back with confirm=true to publish exactly this draft.",+ )+ workflow = HogFlowSerializer(+ required=False,+ allow_null=True,+ help_text="The workflow after publishing (only set when published=true).",+ )class CommaSeparatedListFilter(BaseInFilter, CharFilter):@@ -1280,6 +1364,8 @@ class HogFlowViewSet("bulk_delete","rerun","graph",+ "publish",+ "discard_draft",]queryset = HogFlow.objects.all()pagination_class = HogFlowPagination@@ -1463,15 +1549,12 @@ class HogFlowViewSet(# 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.+ route_to_draft = Falseif self._is_mcp_request(self.request):keys = set(self.request.data.keys())has_status = "status" in keyshas_non_status = bool(keys - {"status"})- # Active workflows are read-only via MCP for now. Status-only PATCHes (lifecycle tools) pass through.- if serializer.instance.status == HogFlow.State.ACTIVE and has_non_status:- raise exceptions.ValidationError(MCP_ACTIVE_EDIT_REJECTION)-# 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:@@ -1480,6 +1563,14 @@ class HogFlowViewSet("workflows-archive — they can't be combined with other field updates.")+ # Content edits on an active workflow stage a draft when the revisions cycle is on for the+ # team; otherwise active workflows stay read-only via MCP. Status-only PATCHes (lifecycle+ # tools) pass through either way, and metadata-only edits apply live once the flag is on.+ if serializer.instance.status == HogFlow.State.ACTIVE and has_non_status:+ if not use_workflows_revisions(self.team):+ raise exceptions.ValidationError(MCP_ACTIVE_EDIT_REJECTION)+ route_to_draft = bool(keys & set(DRAFT_CONTENT_FIELDS))+# TODO(team-workflows): Atomically increment version, insert new object instead of default update behaviorinstance_id = serializer.instance.id@@ -1502,10 +1593,31 @@ class HogFlowViewSet(except HogFlow.DoesNotExist:before_update = None- if base_updated_at and before_update and before_update.updated_at > base_updated_at:+ # Draft edits race against other draft edits, not against the live row (which they don't+ # touch), so the staleness baseline is the draft's own timestamp once a draft exists.+ guard_timestamp = before_update.updated_at if before_update else None+ if route_to_draft and before_update and before_update.draft_updated_at:+ guard_timestamp = before_update.draft_updated_at+ if base_updated_at and guard_timestamp and guard_timestamp > base_updated_at:raise StaleWorkflowUpdateError()- serializer.save()+ if route_to_draft:+ assert before_update is not None+ self._write_draft(serializer.instance, before_update, serializer.validated_data)+ # Metadata in the same payload still applies live. Content (and the fields validate()+ # derives from it — trigger, billable_action_types) must not leak onto the live row:+ # they were computed from the draft's graph.+ remaining = {+ k: v+ for k, v in serializer.validated_data.items()+ if k not in DRAFT_CONTENT_FIELDS and k != "billable_action_types"+ }+ if remaining:+ serializer.validated_data.clear()+ serializer.validated_data.update(remaining)+ serializer.save()+ else:+ serializer.save()log_activity_from_viewset(self, serializer.instance, name=serializer.instance.name, previous=before_update)self._emit_resource_edited(serializer.instance)@@ -1536,6 +1648,23 @@ class HogFlowViewSet(except Exception as e:logger.warning("Failed to capture hog_flow_activated event", error=str(e))+ def _write_draft(self, instance: HogFlow, locked: HogFlow, validated_data: dict) -> None:+ # The draft is always a full content snapshot (live config as the base, staged draft on top,+ # this edit's validated fields last) so publish is a plain copy with no merge logic.+ snapshot = {field: getattr(locked, field) for field in DRAFT_CONTENT_FIELDS}+ # The model's legacy default for actions/edges is `{}`, but the API shape is a list — normalize+ # so publish's re-validation doesn't choke on a snapshot of a never-edited column.+ for field in ("actions", "edges"):+ if not snapshot[field]:+ snapshot[field] = []+ draft = {**snapshot, **(locked.draft or {})}+ for field in DRAFT_CONTENT_FIELDS:+ if field in validated_data:+ draft[field] = validated_data[field]+ instance.draft = draft+ instance.draft_updated_at = timezone.now()+ instance.save(update_fields=["draft", "draft_updated_at"])+@extend_schema(request=HogFlowGraphUpdateSerializer, responses={200: HogFlowSerializer})@action(detail=True, methods=["PATCH"])def graph(self, request: Request, *args, **kwargs):@@ -1553,12 +1682,21 @@ class HogFlowViewSet(# nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)locked = HogFlow.objects.select_for_update().get(pk=instance.pk)+ route_to_draft = Falseif self._is_mcp_request(request) and locked.status == HogFlow.State.ACTIVE:- raise exceptions.ValidationError(MCP_ACTIVE_EDIT_REJECTION)+ if not use_workflows_revisions(self.team):+ raise exceptions.ValidationError(MCP_ACTIVE_EDIT_REJECTION)+ route_to_draft = True++ # Draft edits compose on the staged draft, not on live — a second patch must see the first.+ if route_to_draft and locked.draft:+ base_actions = list(locked.draft.get("actions") or [])+ base_edges = list(locked.draft.get("edges") or [])+ else:+ base_actions = list(locked.actions or [])+ base_edges = list(locked.edges or [])- new_actions, new_edges = apply_graph_operations(- list(locked.actions or []), list(locked.edges or []), operations- )+ new_actions, new_edges = apply_graph_operations(base_actions, base_edges, operations)serializer = self.get_serializer(locked, data={"actions": new_actions, "edges": new_edges}, partial=True)# The surgical endpoint is the one path where structural corruption would be newly introduced,@@ -1568,8 +1706,113 @@ class HogFlowViewSet(# nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)before_update = HogFlow.objects.get(pk=instance.pk)- # save() mutates and returns `locked` in place, so it's the saved HogFlow from here on.+ if route_to_draft:+ self._write_draft(locked, locked, serializer.validated_data)+ else:+ # save() mutates and returns `locked` in place, so it's the saved HogFlow from here on.+ serializer.save()++ log_activity_from_viewset(self, locked, name=locked.name, previous=before_update)+ self._emit_resource_edited(locked)++ return Response(self.get_serializer(locked).data)++ def _get_in_flight_run_count(self, hog_flow: HogFlow) -> Optional[int]:+ # Best-effort: publish must not fail because the counting service is unreachable — the count+ # is advisory ("N runs in flight will follow the new config"), not a gate.+ try:+ res = get_hog_flow_in_flight_count(team_id=self.team_id, hog_flow_id=str(hog_flow.id))+ if res.status_code == 200:+ return res.json().get("count")+ logger.warning(+ "Failed to fetch in-flight run count for workflow",+ hog_flow_id=str(hog_flow.id),+ status_code=res.status_code,+ )+ except Exception:+ logger.warning(+ "Failed to fetch in-flight run count for workflow", hog_flow_id=str(hog_flow.id), exc_info=True+ )+ return None++ @extend_schema(request=HogFlowPublishRequestSerializer, responses={200: HogFlowPublishResponseSerializer})+ @action(detail=True, methods=["POST"])+ def publish(self, request: Request, *args, **kwargs):+ # Promote the staged draft to the live config. Two-step by design: a call without confirm only+ # echoes impact (how many runs are in flight), so callers — especially agents — never publish blind.+ if not use_workflows_revisions(self.team):+ raise exceptions.ValidationError("Publishing drafts isn't enabled for this project yet.")++ param_serializer = HogFlowPublishRequestSerializer(data=request.data)+ param_serializer.is_valid(raise_exception=True)+ confirm = param_serializer.validated_data["confirm"]++ instance = self.get_object()+ if not instance.draft:+ raise exceptions.ValidationError("This workflow has no staged draft to publish.")++ if not confirm:+ return Response(+ {+ "published": False,+ "in_flight_runs": self._get_in_flight_run_count(instance),+ "draft_updated_at": instance.draft_updated_at,+ }+ )++ expected_draft_updated_at = param_serializer.validated_data.get("draft_updated_at")+ if not expected_draft_updated_at:+ raise exceptions.ValidationError(+ {"draft_updated_at": "Required when confirming a publish — pass the draft_updated_at you loaded."}+ )++ with transaction.atomic():+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)+ locked = HogFlow.objects.select_for_update().get(pk=instance.pk)+ if not locked.draft:+ raise exceptions.ValidationError("This workflow has no staged draft to publish.")+ if locked.draft_updated_at != expected_draft_updated_at:+ raise StaleWorkflowUpdateError()++ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)+ before_update = HogFlow.objects.get(pk=instance.pk)+ # The draft goes back through the normal serializer so publish revalidates strictly and+ # recompiles bytecode — a stored blob is never trusted to be execution-ready.+ serializer = self.get_serializer(locked, data=dict(locked.draft), partial=True)+ serializer.is_valid(raise_exception=True)serializer.save()+ locked.draft = None+ locked.draft_updated_at = None+ locked.save(update_fields=["draft", "draft_updated_at"])++ log_activity_from_viewset(self, locked, name=locked.name, previous=before_update)+ self._emit_resource_edited(locked)++ return Response(+ {+ "published": True,+ "in_flight_runs": None,+ "draft_updated_at": None,+ "workflow": self.get_serializer(locked).data,+ }+ )++ @extend_schema(request=None, responses={200: HogFlowSerializer})+ @action(detail=True, methods=["POST"])+ def discard_draft(self, request: Request, *args, **kwargs):+ # Throw away the staged draft. Idempotent: discarding when nothing is staged is a no-op.+ if not use_workflows_revisions(self.team):+ raise exceptions.ValidationError("Drafts aren't enabled for this project yet.")++ instance = self.get_object()+ with transaction.atomic():+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)+ locked = HogFlow.objects.select_for_update().get(pk=instance.pk)+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)+ before_update = HogFlow.objects.get(pk=instance.pk)+ locked.draft = None+ locked.draft_updated_at = None+ locked.save(update_fields=["draft", "draft_updated_at"])log_activity_from_viewset(self, locked, name=locked.name, previous=before_update)self._emit_resource_edited(locked)@@ -1594,10 +1837,22 @@ class HogFlowViewSet(if not serializer.is_valid():return Response(serializer.errors, status=400)+ payload = dict(serializer.validated_data)+ if payload.pop("use_draft", False):+ # The staged draft was validated when written, so it goes to the executor inline exactly+ # like an explicit configuration override — workers never read (or cache) the draft column.+ if payload.get("configuration"):+ raise exceptions.ValidationError(+ {"use_draft": "Pass either use_draft or an explicit configuration override, not both."}+ )+ if not hog_flow or not hog_flow.draft:+ raise exceptions.ValidationError({"use_draft": "This workflow has no staged draft to test."})+ payload["configuration"] = hog_flow.draft+res = create_hog_flow_invocation_test(team_id=self.team_id,hog_flow_id=str(hog_flow.id) if hog_flow else "new",- payload=serializer.validated_data,+ payload=payload,)if res.status_code != 200:diff --git a/products/workflows/backend/api/test/test_hog_flow_draft_publish.py b/products/workflows/backend/api/test/test_hog_flow_draft_publish.pynew file mode 100644index 000000000000..d597ac661846--- /dev/null+++ b/products/workflows/backend/api/test/test_hog_flow_draft_publish.py@@ -0,0 +1,409 @@+from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.cdp.templates.hog_function_template import sync_template_to_db+from posthog.models.activity_logging.activity_log import ActivityLog++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++webhook_template = MOCK_NODE_TEMPLATES[0]++FLAG_PATH = "products.workflows.backend.api.hog_flow.use_workflows_revisions"+++def _trigger_action() -> dict:+ return {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {+ "type": "event",+ "filters": {+ "events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}],+ },+ },+ }+++def _webhook_action(action_id: str = "action_1", url: str = "https://example.com") -> dict:+ return {+ "id": action_id,+ "name": action_id,+ "type": "function",+ "config": {"template_id": "template-webhook", "inputs": {"url": {"value": url}}},+ }+++class TestHogFlowDraftPublish(APIBaseTest):+ def setUp(self):+ super().setUp()+ sync_template_to_db(webhook_template)++ def _create_active_flow(self) -> str:+ hog_flow = {"name": "Test Flow", "actions": [_trigger_action(), _webhook_action()]}+ create = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert create.status_code == 201, create.json()+ flow_id = create.json()["id"]+ activate = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "active"})+ assert activate.status_code == 200, activate.json()+ return flow_id++ def _patch_actions_via_mcp(self, flow_id: str, url: str = "https://changed.example.com"):+ return self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {"actions": [_trigger_action(), _webhook_action(url=url)]},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )++ # ── Draft routing ────────────────────────────────────────────────++ @patch(FLAG_PATH, return_value=True)+ def test_mcp_content_edit_on_active_flow_routes_to_draft(self, _flag):+ flow_id = self._create_active_flow()+ live_actions_before = HogFlow.objects.get(pk=flow_id).actions++ response = self._patch_actions_via_mcp(flow_id)+ assert response.status_code == 200, response.json()++ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.actions == live_actions_before+ assert flow.draft is not None+ assert flow.draft_updated_at is not None+ draft_urls = [a["config"]["inputs"]["url"]["value"] for a in flow.draft["actions"] if a["type"] == "function"]+ assert draft_urls == ["https://changed.example.com"]+ # The response surfaces the draft so callers can see what they staged+ assert response.json()["draft"] is not None++ @patch(FLAG_PATH, return_value=False)+ def test_mcp_content_edit_on_active_flow_rejected_when_flag_off(self, _flag):+ flow_id = self._create_active_flow()+ response = self._patch_actions_via_mcp(flow_id)+ assert response.status_code == 400, response.json()+ assert "active workflow isn't supported via MCP" in response.json()["detail"]++ @patch(FLAG_PATH, return_value=True)+ def test_web_content_edit_on_active_flow_still_applies_live(self, _flag):+ flow_id = self._create_active_flow()+ response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {"actions": [_trigger_action(), _webhook_action(url="https://changed.example.com")]},+ )+ assert response.status_code == 200, response.json()+ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.draft is None+ live_urls = [a["config"]["inputs"]["url"]["value"] for a in flow.actions if a["type"] == "function"]+ assert live_urls == ["https://changed.example.com"]++ @patch(FLAG_PATH, return_value=True)+ def test_mcp_content_edit_on_inactive_flow_applies_live(self, _flag):+ # Disabled/draft-status workflows edit in place — the draft cycle protects in-flight runs only+ hog_flow = {"name": "Test Flow", "actions": [_trigger_action(), _webhook_action()]}+ create = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ flow_id = create.json()["id"]++ response = self._patch_actions_via_mcp(flow_id)+ assert response.status_code == 200, response.json()+ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.draft is None+ live_urls = [a["config"]["inputs"]["url"]["value"] for a in flow.actions if a["type"] == "function"]+ assert live_urls == ["https://changed.example.com"]++ @patch(FLAG_PATH, return_value=True)+ def test_mcp_metadata_edit_on_active_flow_applies_live_without_draft(self, _flag):+ flow_id = self._create_active_flow()+ response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {"name": "Renamed live"},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert response.status_code == 200, response.json()+ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.name == "Renamed live"+ assert flow.draft is None++ @patch(FLAG_PATH, return_value=True)+ def test_mcp_mixed_status_and_content_still_rejected(self, _flag):+ flow_id = self._create_active_flow()+ response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {"status": "draft", "name": "Renamed"},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert response.status_code == 400, response.json()++ @patch(FLAG_PATH, return_value=True)+ def test_stale_draft_edit_is_rejected_with_409(self, _flag):+ flow_id = self._create_active_flow()+ first = self._patch_actions_via_mcp(flow_id)+ assert first.status_code == 200, first.json()++ stale = "2020-01-01T00:00:00Z"+ response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {+ "actions": [_trigger_action(), _webhook_action(url="https://other.example.com")],+ "base_updated_at": stale,+ },+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert response.status_code == 409, response.json()++ # ── Graph patch routing ──────────────────────────────────────────++ @patch(FLAG_PATH, return_value=True)+ def test_mcp_graph_patch_on_active_flow_lands_in_draft(self, _flag):+ flow_id = self._create_active_flow()+ live_actions_before = HogFlow.objects.get(pk=flow_id).actions++ response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",+ {+ "operations": [+ {+ "op": "update_action",+ "id": "action_1",+ "patch": {"config": {"inputs": {"url": {"value": "https://patched.example.com"}}}},+ }+ ]+ },+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert response.status_code == 200, response.json()++ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.actions == live_actions_before+ assert flow.draft is not None+ draft_urls = [a["config"]["inputs"]["url"]["value"] for a in flow.draft["actions"] if a["type"] == "function"]+ assert draft_urls == ["https://patched.example.com"]++ @patch(FLAG_PATH, return_value=True)+ def test_mcp_graph_patch_composes_on_existing_draft(self, _flag):+ # A second surgical patch must apply against the staged draft, not reset it from live+ flow_id = self._create_active_flow()+ first = self._patch_actions_via_mcp(flow_id, url="https://draft-v1.example.com")+ assert first.status_code == 200, first.json()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",+ {+ "operations": [+ {+ "op": "add_action",+ "action": _webhook_action(action_id="action_2", url="https://added.example.com"),+ "edges": [{"from": "action_1", "to": "action_2", "type": "continue"}],+ }+ ]+ },+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert response.status_code == 200, response.json()++ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.draft is not None+ draft_urls = {a["config"]["inputs"]["url"]["value"] for a in flow.draft["actions"] if a["type"] == "function"}+ assert draft_urls == {"https://draft-v1.example.com", "https://added.example.com"}++ @patch(FLAG_PATH, return_value=False)+ def test_mcp_graph_patch_on_active_flow_rejected_when_flag_off(self, _flag):+ flow_id = self._create_active_flow()+ response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",+ {+ "operations": [+ {+ "op": "update_action",+ "id": "action_1",+ "patch": {"config": {"inputs": {"url": {"value": "https://patched.example.com"}}}},+ }+ ]+ },+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert response.status_code == 400, response.json()++ # ── Publish ──────────────────────────────────────────────────────++ def _stage_draft(self, flow_id: str) -> HogFlow:+ with patch(FLAG_PATH, return_value=True):+ response = self._patch_actions_via_mcp(flow_id)+ assert response.status_code == 200, response.json()+ return HogFlow.objects.get(pk=flow_id)++ @patch("products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count")+ @patch(FLAG_PATH, return_value=True)+ def test_publish_without_confirm_returns_impact_only(self, _flag, mock_count):+ mock_count.return_value = MagicMock(status_code=200, json=lambda: {"count": 42})+ flow_id = self._create_active_flow()+ flow = self._stage_draft(flow_id)+ live_actions_before = flow.actions++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish", {})+ assert response.status_code == 200, response.json()+ assert response.json()["in_flight_runs"] == 42+ assert response.json()["draft_updated_at"] is not None++ flow.refresh_from_db()+ assert flow.actions == live_actions_before+ assert flow.draft is not None++ @patch("products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count")+ @patch(FLAG_PATH, return_value=True)+ def test_publish_impact_degrades_to_null_when_count_unavailable(self, _flag, mock_count):+ mock_count.side_effect = Exception("node service down")+ flow_id = self._create_active_flow()+ self._stage_draft(flow_id)++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish", {})+ assert response.status_code == 200, response.json()+ assert response.json()["in_flight_runs"] is None++ @patch(FLAG_PATH, return_value=True)+ def test_publish_with_confirm_promotes_draft_and_clears_it(self, _flag):+ flow_id = self._create_active_flow()+ flow = self._stage_draft(flow_id)+ # Narrow a local, not the attribute — narrowing flow.draft_updated_at here would make the+ # post-publish `is None` assertion unreachable in mypy's eyes (it can't see refresh_from_db)+ staged_at = flow.draft_updated_at+ assert staged_at is not None++ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",+ {"confirm": True, "draft_updated_at": staged_at.isoformat()},+ )+ assert response.status_code == 200, response.json()++ flow.refresh_from_db()+ live_urls = [a["config"]["inputs"]["url"]["value"] for a in flow.actions if a["type"] == "function"]+ assert live_urls == ["https://changed.example.com"]+ assert flow.draft is None+ assert flow.draft_updated_at is None+ # Bytecode is recompiled through the normal serializer path on publish+ trigger = next(a for a in flow.actions if a["type"] == "trigger")+ assert trigger["config"]["filters"].get("bytecode"), "publish must compile trigger filter bytecode"++ @patch(FLAG_PATH, return_value=True)+ def test_publish_with_stale_draft_pointer_is_rejected_with_409(self, _flag):+ flow_id = self._create_active_flow()+ self._stage_draft(flow_id)++ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",+ {"confirm": True, "draft_updated_at": "2020-01-01T00:00:00Z"},+ )+ assert response.status_code == 409, response.json()++ @parameterized.expand(+ [+ ("flag_off", False, True),+ ("no_draft", True, False),+ ]+ )+ def test_publish_rejected(self, _name, flag_on, stage_draft):+ flow_id = self._create_active_flow()+ if stage_draft:+ self._stage_draft(flow_id)+ with patch(FLAG_PATH, return_value=flag_on):+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",+ {"confirm": True, "draft_updated_at": "2026-01-01T00:00:00Z"},+ )+ assert response.status_code == 400, response.json()++ @patch(FLAG_PATH, return_value=True)+ def test_publish_validates_draft_strictly(self, _flag):+ # A draft written by some future lenient path must not promote unvalidated: publish is defensive+ # regardless of who wrote the blob+ flow_id = self._create_active_flow()+ flow = self._stage_draft(flow_id)+ assert flow.draft is not None+ assert flow.draft_updated_at is not None+ flow.draft = {**flow.draft, "actions": [{"id": "bad", "type": "function", "config": {}}]}+ flow.save(update_fields=["draft"])++ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",+ {"confirm": True, "draft_updated_at": flow.draft_updated_at.isoformat()},+ )+ assert response.status_code == 400, response.json()++ flow.refresh_from_db()+ live_urls = [a["config"]["inputs"]["url"]["value"] for a in flow.actions if a["type"] == "function"]+ assert live_urls == ["https://example.com"], "a failed publish must leave the live config untouched"++ # ── Discard ──────────────────────────────────────────────────────++ @patch(FLAG_PATH, return_value=True)+ def test_discard_draft_clears_it(self, _flag):+ flow_id = self._create_active_flow()+ self._stage_draft(flow_id)++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/discard_draft", {})+ assert response.status_code == 200, response.json()++ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.draft is None+ assert flow.draft_updated_at is None++ # ── Test-run from draft ──────────────────────────────────────────++ @patch("products.workflows.backend.api.hog_flow.create_hog_flow_invocation_test")+ @patch(FLAG_PATH, return_value=True)+ def test_invocation_with_use_draft_sends_draft_as_configuration(self, _flag, mock_invoke):+ mock_invoke.return_value = MagicMock(status_code=200, json=lambda: {"status": "success"})+ flow_id = self._create_active_flow()+ self._stage_draft(flow_id)++ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/invocations",+ {"use_draft": True, "globals": {"event": {"event": "$pageview", "properties": {}}}},+ )+ assert response.status_code == 200, response.json()++ payload = mock_invoke.call_args.kwargs["payload"]+ sent_urls = [+ a["config"]["inputs"]["url"]["value"]+ for a in payload["configuration"]["actions"]+ if a["type"] == "function"+ ]+ assert sent_urls == ["https://changed.example.com"]++ @patch(FLAG_PATH, return_value=True)+ def test_invocation_with_use_draft_and_no_draft_is_rejected(self, _flag):+ flow_id = self._create_active_flow()+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/invocations",+ {"use_draft": True, "globals": {"event": {"event": "$pageview", "properties": {}}}},+ )+ assert response.status_code == 400, response.json()++ # ── Serializer exposure ──────────────────────────────────────────++ @patch(FLAG_PATH, return_value=True)+ def test_get_surfaces_open_draft(self, _flag):+ flow_id = self._create_active_flow()+ self._stage_draft(flow_id)++ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}")+ assert response.status_code == 200, response.json()+ assert response.json()["draft"] is not None+ assert response.json()["draft_updated_at"] is not None++ @patch(FLAG_PATH, return_value=True)+ def test_draft_contents_are_masked_in_activity_log(self, _flag):+ flow_id = self._create_active_flow()+ self._stage_draft(flow_id)++ entry = ActivityLog.objects.filter(scope="HogFlow", item_id=flow_id).order_by("-created_at").first()+ assert entry is not None+ detail = entry.detail+ assert detail is not None+ draft_changes = [c for c in detail["changes"] if c["field"] == "draft"]+ assert draft_changes, detail["changes"]+ for change in draft_changes:+ # Draft snapshots carry action inputs (auth headers, API keys) — contents must never+ # land in team-readable activity rows, only the fact that the draft changed.+ assert change.get("before") in (None, "masked")+ assert change.get("after") in (None, "masked")diff --git a/products/workflows/backend/models/hog_flow/hog_flow.py b/products/workflows/backend/models/hog_flow/hog_flow.pyindex 70682199fe40..0f0727154cd6 100644--- a/products/workflows/backend/models/hog_flow/hog_flow.py+++ b/products/workflows/backend/models/hog_flow/hog_flow.py@@ -95,7 +95,10 @@ class HogFlow(UUIDTModel):@receiver(post_save, sender=HogFlow)-def hog_flow_saved(sender, instance: HogFlow, created, **kwargs):+def hog_flow_saved(sender, instance: HogFlow, created, update_fields=None, **kwargs):+ # Draft columns don't affect live execution, so workers don't need a config reload for them.+ if update_fields and set(update_fields) <= {"draft", "draft_updated_at"}:+ returnreload_hog_flows_on_workers(team_id=instance.team_id, hog_flow_ids=[str(instance.id)])diff --git a/products/workflows/backend/services/revisions.py b/products/workflows/backend/services/revisions.pynew file mode 100644index 000000000000..a575b62a72b0--- /dev/null+++ b/products/workflows/backend/services/revisions.py@@ -0,0 +1,37 @@+import structlog+import posthoganalytics++from posthog.models.team.team import Team++logger = structlog.get_logger(__name__)++WORKFLOWS_REVISIONS_FLAG = "workflows-revisions"+++def use_workflows_revisions(team: Team) -> bool:+ """Gates the draft → test → publish cycle on active workflows; off means today's behavior+ (active workflows are read-only via MCP).++ A raised exception (Redis/HyperCache blip, network glitch, SDK bug) is treated as "flag off" —+ the rejection path is the safe fallback, making the flag a kill switch for the whole cycle.+ """+ try:+ return bool(+ posthoganalytics.feature_enabled(+ WORKFLOWS_REVISIONS_FLAG,+ str(team.uuid),+ groups={"organization": str(team.organization_id), "project": str(team.id)},+ group_properties={+ "organization": {"id": str(team.organization_id)},+ "project": {"id": str(team.id)},+ },+ )+ )+ except Exception:+ logger.warning(+ "workflows.revisions.feature_flag_check_failed_defaulting_off",+ team_id=team.id,+ flag=WORKFLOWS_REVISIONS_FLAG,+ exc_info=True,+ )+ return Falsediff --git a/products/workflows/backend/test/test_hog_flow.py b/products/workflows/backend/test/test_hog_flow.pyindex 9dfd1fafaf0c..9c87d74f42cb 100644--- a/products/workflows/backend/test/test_hog_flow.py+++ b/products/workflows/backend/test/test_hog_flow.py@@ -22,6 +22,18 @@ class TestHogFlow(TestCase):hog_flow = HogFlow.objects.create(name="Test Flow", team=self.team)mock_reload.assert_called_once_with(team_id=self.team.id, hog_flow_ids=[str(hog_flow.id)])+ @patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")+ def test_draft_only_save_skips_worker_reload(self, mock_reload):+ hog_flow = HogFlow.objects.create(name="Test Flow", team=self.team)+ mock_reload.reset_mock()++ hog_flow.draft = {"name": "Draft name"}+ hog_flow.save(update_fields=["draft", "draft_updated_at"])+ mock_reload.assert_not_called()++ hog_flow.save(update_fields=["draft", "name"])+ mock_reload.assert_called_once_with(team_id=self.team.id, hog_flow_ids=[str(hog_flow.id)])+@patch("products.workflows.backend.tasks.hog_flows.refresh_affected_hog_flows.delay")def test_action_saved_receiver(self, mock_refresh):action = Action.objects.create(team=self.team, name="Test Action")diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex d1cd7e4769ee..9a5ca4f32ca1 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -526,6 +526,13 @@ export interface HogFlowApi {* @nullable*/readonly user_access_level: string | null+ /** Staged content changes awaiting publish — a full snapshot of the workflow's actions, edges and settings. Null when there's nothing staged. Test it with a use_draft test run, then promote it with the publish endpoint or throw it away with discard_draft. */+ readonly draft: unknown+ /**+ * When the draft was last written; null when there's no staged draft. Pass this to publish (and as base_updated_at on further draft edits) so a concurrent editor's changes aren't clobbered — a mismatch returns 409.+ * @nullable+ */+ readonly draft_updated_at: string | null}/**@@ -584,6 +591,13 @@ export interface PatchedHogFlowApi {* @nullable*/readonly user_access_level?: string | null+ /** Staged content changes awaiting publish — a full snapshot of the workflow's actions, edges and settings. Null when there's nothing staged. Test it with a use_draft test run, then promote it with the publish endpoint or throw it away with discard_draft. */+ readonly draft?: unknown+ /**+ * When the draft was last written; null when there's no staged draft. Pass this to publish (and as base_updated_at on further draft edits) so a concurrent editor's changes aren't clobbered — a mismatch returns 409.+ * @nullable+ */+ readonly draft_updated_at?: string | null}export interface MessageAssetApi {@@ -759,6 +773,8 @@ export interface HogFlowInvocationApi {mock_async_functions?: boolean/** Start execution from this action ID instead of the trigger. Each test run executes a single node and returns the next action id. */current_action_id?: string+ /** Test the workflow's staged draft instead of its live config. Requires an open draft; can't be combined with an explicit configuration override. */+ use_draft?: boolean}export interface AppMetricSeriesApi {@@ -777,6 +793,30 @@ export interface AppMetricsTotalsResponseApi {totals: AppMetricsTotalsResponseApiTotals}+export interface HogFlowPublishRequestApi {+ /** False (default) previews the publish: returns how many runs are in flight without changing anything. True applies the staged draft to the live workflow. */+ confirm?: boolean+ /** The draft_updated_at you loaded — required when confirm=true. A mismatch returns 409, so you never publish a draft someone else has changed since you read it. */+ draft_updated_at?: string+}++export interface HogFlowPublishResponseApi {+ /** Whether the draft was applied to the live workflow. */+ published: boolean+ /**+ * Runs currently in flight (parked on waits/delays or executing) that will follow the new config once published. Null when the count is unavailable.+ * @nullable+ */+ in_flight_runs: number | null+ /**+ * Echo of the staged draft's timestamp — pass it back with confirm=true to publish exactly this draft.+ * @nullable+ */+ draft_updated_at: string | null+ /** The workflow after publishing (only set when published=true). */+ workflow?: HogFlowApi | null+}+/*** * `running` - running* * `succeeded` - succeededdiff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.tsindex 5d91adc52eef..ed111d9229f1 100644--- a/products/workflows/frontend/generated/api.ts+++ b/products/workflows/frontend/generated/api.ts@@ -16,6 +16,8 @@ import type {HogFlowApi,HogFlowBatchJobApi,HogFlowInvocationApi,+ HogFlowPublishRequestApi,+ HogFlowPublishResponseApi,HogFlowScheduleApi,HogFlowTemplateApi,HogFlowTemplatesListParams,@@ -414,6 +416,21 @@ export const hogFlowsBatchJobsCreate = async (})}+export const getHogFlowsDiscardDraftCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/hog_flows/${id}/discard_draft/`+}++export const hogFlowsDiscardDraftCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<HogFlowApi> => {+ return apiMutator<HogFlowApi>(getHogFlowsDiscardDraftCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getHogFlowsGraphPartialUpdateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/hog_flows/${id}/graph/`}@@ -593,6 +610,24 @@ export const hogFlowsMetricsTotalsRetrieve = async (})}+export const getHogFlowsPublishCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/hog_flows/${id}/publish/`+}++export const hogFlowsPublishCreate = async (+ projectId: string,+ id: string,+ hogFlowPublishRequestApi?: HogFlowPublishRequestApi,+ options?: RequestInit+): Promise<HogFlowPublishResponseApi> => {+ return apiMutator<HogFlowPublishResponseApi>(getHogFlowsPublishCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(hogFlowPublishRequestApi),+ })+}+export const getHogFlowsRerunCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/hog_flows/${id}/rerun/`}diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex 8f24a9bd4149..6c3f9732fb25 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -1492,6 +1492,7 @@ export const hogFlowsInvocationsCreateBodyConfigurationOneActionsItemConfigTwoEvexport const hogFlowsInvocationsCreateBodyConfigurationOneSchedulesItemTimezoneMax = 64export const hogFlowsInvocationsCreateBodyMockAsyncFunctionsDefault = true+export const hogFlowsInvocationsCreateBodyUseDraftDefault = falseexport const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({configuration: zod@@ -1910,6 +1911,17 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({.string().nullable().describe('The effective access level the user has for this object'),+ draft: zod+ .unknown()+ .describe(+ "Staged content changes awaiting publish — a full snapshot of the workflow's actions, edges and settings. Null when there's nothing staged. Test it with a use_draft test run, then promote it with the publish endpoint or throw it away with discard_draft."+ ),+ draft_updated_at: zod.iso+ .datetime({ offset: true })+ .nullable()+ .describe(+ "When the draft was last written; null when there's no staged draft. Pass this to publish (and as base_updated_at on further draft edits) so a concurrent editor's changes aren't clobbered — a mismatch returns 409."+ ),}).describe('Mixin for serializers to add user access control fields').optional()@@ -1928,6 +1940,29 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({.describe('Start execution from this action ID instead of the trigger. Each test run executes a single node and returns the next action id.'),+ use_draft: zod+ .boolean()+ .default(hogFlowsInvocationsCreateBodyUseDraftDefault)+ .describe(+ "Test the workflow's staged draft instead of its live config. Requires an open draft; can't be combined with an explicit configuration override."+ ),+})++export const hogFlowsPublishCreateBodyConfirmDefault = false++export const HogFlowsPublishCreateBody = /* @__PURE__ */ zod.object({+ confirm: zod+ .boolean()+ .default(hogFlowsPublishCreateBodyConfirmDefault)+ .describe(+ 'False (default) previews the publish: returns how many runs are in flight without changing anything. True applies the staged draft to the live workflow.'+ ),+ draft_updated_at: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'The draft_updated_at you loaded — required when confirm=true. A mismatch returns 409, so you never publish a draft someone else has changed since you read it.'+ ),})/**diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yamlindex b9cd1f031e6d..129f74a2cd7c 100644--- a/products/workflows/mcp/tools.yaml+++ b/products/workflows/mcp/tools.yaml@@ -54,6 +54,9 @@ tools:hog-flows-destroy:operation: hog_flows_destroyenabled: false+ hog-flows-discard-draft-create:+ operation: hog_flows_discard_draft_create+ enabled: falsehog-flows-invocations-create:operation: hog_flows_invocations_createenabled: false@@ -63,6 +66,9 @@ tools:hog-flows-partial-update:operation: hog_flows_partial_updateenabled: false+ hog-flows-publish-create:+ operation: hog_flows_publish_create+ enabled: falsehog-flows-rerun-create:operation: hog_flows_rerun_createenabled: false@@ -106,20 +112,35 @@ tools:title: Create workflowdescription: >Create a workflow. It is created as a draft and does NOT run until enabled: test it with workflows-test-run- first, then enable (workflows-enable) only with the user's explicit approval — enabling is a one-way door,- since live workflows can't be edited over MCP. Provide an actions array with exactly one type='trigger'- (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes- (function/function_email/function_sms, delay, conditional_branch, wait_until_condition, ...) connected by- edges. Read the building-workflows skill for node shapes before composing: a node that mismatches the- per-type schema saves but breaks the visual editor. Two traps that save but break: (1) a conditional_branch- condition needs a 'filters' wrapper — {filters:{properties:[...]}}, not {properties:[...]} on the condition;- omitting it passes save but the editor flags it and the branch won't evaluate your condition. (2) Never- hand-author bytecode anywhere; send properties/hash and the server compiles it. A 'batch' trigger broadcasts- to an audience (config.filters.properties: person-property conditions and/or cohort references), one run per- matching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with+ first, then enable (workflows-enable) only with the user's explicit approval — from then on it runs on real+ people, and further content edits stage as a draft you must publish (workflows-publish) to take effect.+ Provide an actions array with exactly one type='trigger' (config.type:+ event|webhook|manual|batch|tracking_pixel) plus action nodes (function/function_email/function_sms, delay,+ conditional_branch, wait_until_condition, ...) connected by edges. Read the building-workflows skill for+ node shapes before composing: a node that mismatches the per-type schema saves but breaks the visual editor.+ Two traps that save but break: (1) a conditional_branch condition needs a 'filters' wrapper —+ {filters:{properties:[...]}}, not {properties:[...]} on the condition; omitting it passes save but the+ editor flags it and the branch won't evaluate your condition. (2) Never hand-author bytecode anywhere; send+ properties/hash and the server compiles it. A 'batch' trigger broadcasts to an audience+ (config.filters.properties: person-property conditions and/or cohort references), one run per matching+ person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule withworkflows-schedule-create. Behavioral targeting ('did event X at least N times over the last M days') isunsupported; reject it and explain why.ui_app: workflow+ workflows-discard-draft:+ operation: hog_flows_discard_draft_create+ enabled: true+ scopes:+ - hog_flow:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Discard workflow draft+ description: >+ Throw away a workflow's staged draft without touching the live config. Idempotent — discarding when nothing+ is staged is a no-op. Returns the workflow.+ ui_app: workflowworkflows-get:operation: hog_flows_retrieveenabled: true@@ -134,7 +155,9 @@ tools:description: >Get a specific workflow by ID. Returns the full workflow definition including trigger, edges, actions, exitcondition, 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.+ status=='active' plus an active entry in 'schedules' to confirm it will actually fire. On an active+ workflow, 'draft' holds staged content changes awaiting workflows-publish (null when nothing is staged) —+ the live config in actions/edges is what's running.ui_app: workflowworkflows-get-invocation:operation: hog_flows_invocation_result_retrieve@@ -242,16 +265,36 @@ tools:input_schema: WorkflowGraphPatchSchematitle: Patch workflow graphdescription: >- Surgically edit a draft workflow's graph by sending a small, ordered list of operations instead of resending- every action and edge. Prefer this over workflows-update for any change to an existing draft — to tweak one- node's config use update_action with a deep-merge patch (e.g. change just an email subject), and use- add_action / remove_action / add_edge / remove_edge / replace_action_edges for structural changes. Reference- nodes and edges by id. Operations apply atomically: the graph is read, the ops applied in order, the result- fully validated (dangling edges, branch indexes, single trigger), and saved only if valid — otherwise- nothing changes. Draft only — active workflows are read-only via MCP. The full updated workflow is returned,- so you don't need to re-fetch before the next edit. When adding or editing a conditional_branch, each- condition needs a 'filters' wrapper: {filters:{properties:[...]}}, not {properties:[...]} on the condition.- Re-test the changed path with workflows-test-run after patching.+ Surgically edit a workflow's graph by sending a small, ordered list of operations instead of resending every+ action and edge. Prefer this over workflows-update for any graph change — to tweak one node's config use+ update_action with a deep-merge patch (e.g. change just an email subject), and use add_action /+ remove_action / add_edge / remove_edge / replace_action_edges for structural changes. Reference nodes and+ edges by id. Operations apply atomically: the graph is read, the ops applied in order, the result fully+ validated (dangling edges, branch indexes, single trigger), and saved only if valid — otherwise nothing+ changes. On an active workflow, patches stage a draft instead of changing what's running: the first patch+ copies the live graph into the draft, later patches compose onto it, and nothing reaches real people until+ workflows-publish. A rejection saying active workflows can't be edited means draft editing isn't enabled for+ this project yet — then a live change means recreating the workflow as a new draft. The full updated+ workflow is returned, so you don't need to re-fetch before the next edit. When adding or editing a+ conditional_branch, each condition needs a 'filters' wrapper: {filters:{properties:[...]}}, not+ {properties:[...]} on the condition. Re-test the changed path with workflows-test-run after patching.+ workflows-publish:+ operation: hog_flows_publish_create+ enabled: true+ scopes:+ - hog_flow:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: false+ title: Publish workflow draft+ description: >+ Apply a workflow's staged draft to its live config. Two-step: call without confirm first — it returns+ in_flight_runs (people mid-flow who will follow the new config once published) and draft_updated_at,+ changing nothing. Echo that impact to the user and get their go-ahead, then call again with confirm=true and+ that exact draft_updated_at; a 409 means the draft changed since you read it, so re-read and re-confirm.+ Publish revalidates the draft fully and recompiles it, so an invalid draft is rejected with the reason and+ the live config stays untouched. Test the draft first with workflows-test-run (use_draft=true).workflows-stats:operation: hog_flows_metrics_retrieveenabled: true@@ -285,7 +328,8 @@ tools:To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the actionafter them, since delays are not simulated. Pass test 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. Returns the step's execution trace.+ effects. Returns the step's execution trace. Set use_draft=true to test a workflow's staged draft instead of+ its live config — always do this before workflows-publish.exclude_params:- configurationworkflows-update:@@ -303,9 +347,10 @@ tools:Fallback editor. Prefer workflows-patch-graph for graph changes: it sends only the delta, is structurallyvalidated, and returns the full updated graph. Reach for workflows-update for top-level metadata a patchcan't express (name, description, exit_condition), or as an escape hatch to replace the whole workflow when- you can't get workflows-patch-graph to land a change. Draft only: active workflows are read-only via MCP- (editing risks breaking already-scheduled runs), so create a new draft to change a live one. Status changes- go through workflows-enable / workflows-archive.+ you can't get workflows-patch-graph to land a change. On an active workflow, content fields stage a draft+ (published with workflows-publish) while name/description apply immediately; a rejection saying active+ workflows can't be edited means draft editing isn't enabled for this project yet — then a live change means+ recreating the workflow as a new draft. Status changes go through workflows-enable / workflows-archive.exclude_params:- statusui_app: workflowdiff --git a/products/workflows/skills/building-workflows/SKILL.md b/products/workflows/skills/building-workflows/SKILL.mdindex 8a489068f21e..b98607162621 100644--- a/products/workflows/skills/building-workflows/SKILL.md+++ b/products/workflows/skills/building-workflows/SKILL.md@@ -17,8 +17,8 @@ Work the workflow through these stages. Don't jump straight to enabling it.2. **Create as a draft.** `workflows-create`. Every workflow is created `draft`; it does not execute yet.3. **Test-run it.** `workflows-test-run` runs **one step at a time**. Start at the first step (omit `current_action_id`, or point it at the trigger) with sample `globals` (`{event, person, groups}`); the result includes the next step's id (`nextActionId`). Feed that back as `current_action_id` and run again, walking step by step to the end. Skip `delay` nodes by jumping to the action after them (delays aren't simulated). Async side effects (HTTP/email/SMS) are mocked unless you set `mock_async_functions=false`. Read each step's trace to confirm the path taken.4. **Read logs while iterating.** `workflows-logs` shows the per-step execution trace (levels DEBUG to ERROR). This is how you see _why_ a step skipped, branched, or errored.-5. **Edit the draft, then re-test.** Patch the graph with `workflows-patch-graph` (see [Editing a draft](#editing-a-draft)). **Every edit invalidates your earlier test** — re-run the affected path before moving on. Drafts only; active workflows are read-only over MCP.-6. **Enable (one-way door, needs the user's explicit sign-off).** `workflows-enable` flips it to `active` and an **event/webhook/manual** trigger starts firing on matching activity. You can't edit a live workflow over MCP (to change it you recreate it as a new draft), so treat enabling as effectively irreversible: finish testing, then get the user's explicit go before enabling. Don't enable on your own initiative.+5. **Edit, then re-test.** Patch the graph with `workflows-patch-graph` (see [Editing a draft](#editing-a-draft)). **Every edit invalidates your earlier test** — re-run the affected path before moving on. On a draft workflow, edits apply directly; on an active one they stage a draft (see [Changing a live workflow](#changing-a-live-workflow)).+6. **Enable (needs the user's explicit sign-off).** `workflows-enable` flips it to `active` and an **event/webhook/manual** trigger starts firing on matching activity. From then on it runs on real people, and every change goes through the draft → test → publish cycle before taking effect — so finish testing, then get the user's explicit go before enabling. Don't enable on your own initiative.7. **Dispatch (batch/schedule only).** A `batch` workflow does **not** fire on enable alone. Send a one-off broadcast with `workflows-run-batch`, or attach a recurring schedule with `workflows-schedule-create`. Confirm with `workflows-get` that `status=='active'` _and_ its read-only `schedules` field has an active entry.8. **Monitor.** Drill down: `workflows-global-stats` (which workflows are failing) to `workflows-stats` (one workflow's trend) to `workflows-list-invocations` (who it failed for) to `workflows-get-invocation` (the triggering payload) to `workflows-logs` (the failing step).@@ -36,7 +36,16 @@ Email templates follow the same rule: edit a template's design with **`workflows## Changing a live workflow-Active workflows cannot be edited over MCP. **To change a live workflow, create a new draft** (`workflows-create`) with the updated graph, test it, and enable it. If the user wants to edit a live workflow in place, tell them that isn't supported yet and offer the new-draft path.+Editing an active workflow stages a **draft** instead of changing what's running: nothing reaches real people until you publish. Work the cycle:++1. **Edit.** `workflows-patch-graph` (or `workflows-update` for content fields) on the active workflow writes to its draft — the first edit copies the live graph into the draft, later edits compose onto it. `workflows-get` shows the staged draft in `draft`; the live config stays in `actions`/`edges`. Metadata (name, description) applies live immediately.+2. **Test the draft.** `workflows-test-run` with `use_draft=true` executes the staged draft instead of the live config. Re-test every path you changed.+3. **Publish deliberately.** `workflows-publish` without `confirm` returns `in_flight_runs` — people currently mid-flow (parked on waits/delays) who will follow the new config — plus `draft_updated_at`. **Echo that impact to the user and get their go-ahead**, then call again with `confirm=true` and that exact `draft_updated_at`. A 409 means the draft changed since you read it: re-read, re-confirm. Publish revalidates everything, so an invalid draft is rejected and live config stays untouched.+4. **Or bail.** `workflows-discard-draft` throws the staged draft away.++In-flight runs follow the live config: once published, people mid-flow continue from their current step on the new version. Steps they already passed don't re-run.++If an edit is rejected with "editing an active workflow isn't supported", draft editing isn't enabled for this project yet — then a live change means recreating the workflow as a new draft (`workflows-create`), testing it, and enabling it as a replacement.## What the server owns, never send itdiff --git a/products/workflows/skills/building-workflows/references/lifecycle-and-debugging.md b/products/workflows/skills/building-workflows/references/lifecycle-and-debugging.mdindex 3c0878fa395e..891a5dffed9c 100644--- a/products/workflows/skills/building-workflows/references/lifecycle-and-debugging.md+++ b/products/workflows/skills/building-workflows/references/lifecycle-and-debugging.md@@ -7,16 +7,18 @@ The MCP tools for the workflows product, grouped by job. The lifecycle that stri**Author & lifecycle**- `workflows-create` — create a workflow. Always created as a `draft`.-- `workflows-patch-graph` — **the way to edit a draft's graph.** An ordered, id-addressed op list (`update_action`, `add_action`, `remove_action`, `add_edge`, `remove_edge`, `replace_action_edges`) applied atomically; `update_action` deep-merges (a `null` leaf deletes a key). Returns the full updated graph, so no re-fetch. **Drafts only.**-- `workflows-update` — **fallback editor.** Top-level metadata a graph patch can't express (renaming), or an escape hatch to replace the whole workflow when `workflows-patch-graph` won't land a change. **Drafts only**; active workflows are read-only over MCP, so to change a live one create a new draft.-- `workflows-enable` — draft → `active`. **One-way door:** you can't edit a live workflow (only recreate it as a draft), so test first and get the user's explicit approval before enabling.+- `workflows-patch-graph` — **the way to edit a workflow's graph.** An ordered, id-addressed op list (`update_action`, `add_action`, `remove_action`, `add_edge`, `remove_edge`, `replace_action_edges`) applied atomically; `update_action` deep-merges (a `null` leaf deletes a key). Returns the full updated graph, so no re-fetch. On an active workflow, patches stage a draft (published with `workflows-publish`) instead of changing what's running.+- `workflows-update` — **fallback editor.** Top-level metadata a graph patch can't express (renaming), or an escape hatch to replace the whole workflow when `workflows-patch-graph` won't land a change. On an active workflow, content fields stage a draft; name/description apply live.+- `workflows-enable` — draft → `active`. It starts running on real people, so test first and get the user's explicit approval before enabling. Later changes stage as drafts and take effect only on publish.+- `workflows-publish` — apply an active workflow's staged draft to its live config. Call without `confirm` first: it echoes `in_flight_runs` + `draft_updated_at` and changes nothing. Get the user's go-ahead, then confirm with that exact `draft_updated_at` (409 = draft changed under you; re-read).+- `workflows-discard-draft` — throw the staged draft away; live config untouched. Idempotent.- `workflows-archive` — retire a workflow.-- `workflows-get` — full definition: trigger, edges, actions, exit condition, variables, and read-only `schedules` (any recurring schedules attached to the workflow; there's no separate list-schedules tool).+- `workflows-get` — full definition: trigger, edges, actions, exit condition, variables, staged `draft`/`draft_updated_at` (null when nothing staged), and read-only `schedules` (any recurring schedules attached to the workflow; there's no separate list-schedules tool).- `workflows-list` — all workflows with name, status, version, trigger, timestamps.**Test & inspect**-- `workflows-test-run` — runs **one step at a time**, it does not traverse the whole graph in one call. Omit `current_action_id` (or set it to the trigger) to run the first step; the result gives you `nextActionId`, which you pass as `current_action_id` on the next call. Walk the workflow step by step this way; to test a specific branch, set `current_action_id` to that node. Skip `delay` nodes by jumping to the action after them (delays aren't simulated). Pass test data via `globals` (`{event, person, groups}`). Async actions (HTTP/email/SMS) mocked by default; `mock_async_functions=false` fires real side effects. Returns the step's execution trace.+- `workflows-test-run` — runs **one step at a time**, it does not traverse the whole graph in one call. Omit `current_action_id` (or set it to the trigger) to run the first step; the result gives you `nextActionId`, which you pass as `current_action_id` on the next call. Walk the workflow step by step this way; to test a specific branch, set `current_action_id` to that node. Skip `delay` nodes by jumping to the action after them (delays aren't simulated). Pass test data via `globals` (`{event, person, groups}`). Async actions (HTTP/email/SMS) mocked by default; `mock_async_functions=false` fires real side effects. Returns the step's execution trace. `use_draft=true` tests an active workflow's staged draft instead of its live config — always do this before `workflows-publish`.- `workflows-logs` — execution log entries (timestamp, level DEBUG/LOG/INFO/WARN/ERROR, message). Filter by level, text, time range, limit.**Batch & schedules**diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 14aa139c60bd..574fe79db775 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -9284,7 +9284,7 @@"feature_flag": "engineering-analytics"},"workflows-create": {- "description": "Create a workflow. It is created as a draft and does NOT run until enabled: test it with workflows-test-run first, then enable (workflows-enable) only with the user's explicit approval — enabling is a one-way door, since live workflows can't be edited over MCP. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes (function/function_email/function_sms, delay, conditional_branch, wait_until_condition, ...) connected by edges. Read the building-workflows skill for node shapes before composing: a node that mismatches the per-type schema saves but breaks the visual editor. Two traps that save but break: (1) a conditional_branch condition needs a 'filters' wrapper — {filters:{properties:[...]}}, not {properties:[...]} on the condition; omitting it passes save but the editor flags it and the branch won't evaluate your condition. (2) Never hand-author bytecode anywhere; send properties/hash and the server compiles it. A 'batch' trigger broadcasts to an audience (config.filters.properties: person-property conditions and/or cohort references), one run per matching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with workflows-schedule-create. Behavioral targeting ('did event X at least N times over the last M days') is unsupported; reject it and explain why.",+ "description": "Create a workflow. It is created as a draft and does NOT run until enabled: test it with workflows-test-run first, then enable (workflows-enable) only with the user's explicit approval — from then on it runs on real people, and further content edits stage as a draft you must publish (workflows-publish) to take effect. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes (function/function_email/function_sms, delay, conditional_branch, wait_until_condition, ...) connected by edges. Read the building-workflows skill for node shapes before composing: a node that mismatches the per-type schema saves but breaks the visual editor. Two traps that save but break: (1) a conditional_branch condition needs a 'filters' wrapper — {filters:{properties:[...]}}, not {properties:[...]} on the condition; omitting it passes save but the editor flags it and the branch won't evaluate your condition. (2) Never hand-author bytecode anywhere; send properties/hash and the server compiles it. A 'batch' trigger broadcasts to an audience (config.filters.properties: person-property conditions and/or cohort references), one run per matching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with workflows-schedule-create. Behavioral targeting ('did event X at least N times over the last M days') is unsupported; reject it and explain why.","category": "Workflows","feature": "workflows","summary": "Create workflow",@@ -9311,8 +9311,22 @@"readOnlyHint": false}},+ "workflows-discard-draft": {+ "description": "Throw away a workflow's staged draft without touching the live config. Idempotent — discarding when nothing is staged is a no-op. Returns the workflow.",+ "category": "Workflows",+ "feature": "workflows",+ "summary": "Discard workflow draft",+ "title": "Discard workflow draft",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"workflows-get": {- "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.",+ "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. On an active workflow, 'draft' holds staged content changes awaiting workflows-publish (null when nothing is staged) — the live config in actions/edges is what's running.","category": "Workflows","feature": "workflows","summary": "Get workflow",@@ -9452,7 +9466,7 @@}},"workflows-patch-graph": {- "description": "Surgically edit a draft workflow's graph by sending a small, ordered list of operations instead of resending every action and edge. Prefer this over workflows-update for any change to an existing draft — to tweak one node's config use update_action with a deep-merge patch (e.g. change just an email subject), and use add_action / remove_action / add_edge / remove_edge / replace_action_edges for structural changes. Reference nodes and edges by id. Operations apply atomically: the graph is read, the ops applied in order, the result fully validated (dangling edges, branch indexes, single trigger), and saved only if valid — otherwise nothing changes. Draft only — active workflows are read-only via MCP. The full updated workflow is returned, so you don't need to re-fetch before the next edit. When adding or editing a conditional_branch, each condition needs a 'filters' wrapper: {filters:{properties:[...]}}, not {properties:[...]} on the condition. Re-test the changed path with workflows-test-run after patching.",+ "description": "Surgically edit a workflow's graph by sending a small, ordered list of operations instead of resending every action and edge. Prefer this over workflows-update for any graph change — to tweak one node's config use update_action with a deep-merge patch (e.g. change just an email subject), and use add_action / remove_action / add_edge / remove_edge / replace_action_edges for structural changes. Reference nodes and edges by id. Operations apply atomically: the graph is read, the ops applied in order, the result fully validated (dangling edges, branch indexes, single trigger), and saved only if valid — otherwise nothing changes. On an active workflow, patches stage a draft instead of changing what's running: the first patch copies the live graph into the draft, later patches compose onto it, and nothing reaches real people until workflows-publish. A rejection saying active workflows can't be edited means draft editing isn't enabled for this project yet — then a live change means recreating the workflow as a new draft. The full updated workflow is returned, so you don't need to re-fetch before the next edit. When adding or editing a conditional_branch, each condition needs a 'filters' wrapper: {filters:{properties:[...]}}, not {properties:[...]} on the condition. Re-test the changed path with workflows-test-run after patching.","category": "Workflows","feature": "workflows","summary": "Patch workflow graph",@@ -9465,6 +9479,20 @@"readOnlyHint": false}},+ "workflows-publish": {+ "description": "Apply a workflow's staged draft to its live config. Two-step: call without confirm first — it returns in_flight_runs (people mid-flow who will follow the new config once published) and draft_updated_at, changing nothing. Echo that impact to the user and get their go-ahead, then call again with confirm=true and that exact draft_updated_at; a 409 means the draft changed since you read it, so re-read and re-confirm. Publish revalidates the draft fully and recompiles it, so an invalid draft is rejected with the reason and the live config stays untouched. Test the draft first with workflows-test-run (use_draft=true).",+ "category": "Workflows",+ "feature": "workflows",+ "summary": "Publish workflow draft",+ "title": "Publish workflow draft",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"workflows-show-email-template": {"description": "Render an email template as an inline preview for the user. Call after creating or updating a template, and whenever the user asks to see one. The response carries the final rendered html — read it before describing the result. For fetching a template to edit it, use workflows-get-email-template.","category": "Workflows",@@ -9494,7 +9522,7 @@}},"workflows-test-run": {- "description": "Test-invoke a workflow one node at a time; it does NOT traverse the full graph in one call. The result includes nextActionId. To verify a path end to end, chain calls: start at the trigger (omit current_action_id), then pass the returned nextActionId as current_action_id on the next call, and repeat. To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the action after them, since delays are not simulated. Pass test 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. Returns the step's execution trace.",+ "description": "Test-invoke a workflow one node at a time; it does NOT traverse the full graph in one call. The result includes nextActionId. To verify a path end to end, chain calls: start at the trigger (omit current_action_id), then pass the returned nextActionId as current_action_id on the next call, and repeat. To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the action after them, since delays are not simulated. Pass test 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. Returns the step's execution trace. Set use_draft=true to test a workflow's staged draft instead of its live config — always do this before workflows-publish.","category": "Workflows","feature": "workflows","summary": "Test-run workflow",@@ -9508,7 +9536,7 @@}},"workflows-update": {- "description": "Fallback editor. Prefer workflows-patch-graph for graph changes: it sends only the delta, is structurally validated, and returns the full updated graph. Reach for workflows-update for top-level metadata a patch can't express (name, description, exit_condition), or as an escape hatch to replace the whole workflow when you can't get workflows-patch-graph to land a change. Draft only: active workflows are read-only via MCP (editing risks breaking already-scheduled runs), so create a new draft to change a live one. Status changes go through workflows-enable / workflows-archive.",+ "description": "Fallback editor. Prefer workflows-patch-graph for graph changes: it sends only the delta, is structurally validated, and returns the full updated graph. Reach for workflows-update for top-level metadata a patch can't express (name, description, exit_condition), or as an escape hatch to replace the whole workflow when you can't get workflows-patch-graph to land a change. On an active workflow, content fields stage a draft (published with workflows-publish) while name/description apply immediately; a rejection saying active workflows can't be edited means draft editing isn't enabled for this project yet — then a live change means recreating the workflow as a new draft. Status changes go through workflows-enable / workflows-archive.","category": "Workflows","feature": "workflows","summary": "Update workflow",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 970069872fbf..c433ffd696de 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -9834,7 +9834,7 @@}},"workflows-create": {- "description": "Create a workflow. It is created as a draft and does NOT run until enabled: test it with workflows-test-run first, then enable (workflows-enable) only with the user's explicit approval — enabling is a one-way door, since live workflows can't be edited over MCP. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes (function/function_email/function_sms, delay, conditional_branch, wait_until_condition, ...) connected by edges. Read the building-workflows skill for node shapes before composing: a node that mismatches the per-type schema saves but breaks the visual editor. Two traps that save but break: (1) a conditional_branch condition needs a 'filters' wrapper — {filters:{properties:[...]}}, not {properties:[...]} on the condition; omitting it passes save but the editor flags it and the branch won't evaluate your condition. (2) Never hand-author bytecode anywhere; send properties/hash and the server compiles it. A 'batch' trigger broadcasts to an audience (config.filters.properties: person-property conditions and/or cohort references), one run per matching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with workflows-schedule-create. Behavioral targeting ('did event X at least N times over the last M days') is unsupported; reject it and explain why.",+ "description": "Create a workflow. It is created as a draft and does NOT run until enabled: test it with workflows-test-run first, then enable (workflows-enable) only with the user's explicit approval — from then on it runs on real people, and further content edits stage as a draft you must publish (workflows-publish) to take effect. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes (function/function_email/function_sms, delay, conditional_branch, wait_until_condition, ...) connected by edges. Read the building-workflows skill for node shapes before composing: a node that mismatches the per-type schema saves but breaks the visual editor. Two traps that save but break: (1) a conditional_branch condition needs a 'filters' wrapper — {filters:{properties:[...]}}, not {properties:[...]} on the condition; omitting it passes save but the editor flags it and the branch won't evaluate your condition. (2) Never hand-author bytecode anywhere; send properties/hash and the server compiles it. A 'batch' trigger broadcasts to an audience (config.filters.properties: person-property conditions and/or cohort references), one run per matching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with workflows-schedule-create. Behavioral targeting ('did event X at least N times over the last M days') is unsupported; reject it and explain why.","category": "Workflows","feature": "workflows","summary": "Create workflow",@@ -9861,8 +9861,22 @@"readOnlyHint": false}},+ "workflows-discard-draft": {+ "description": "Throw away a workflow's staged draft without touching the live config. Idempotent — discarding when nothing is staged is a no-op. Returns the workflow.",+ "category": "Workflows",+ "feature": "workflows",+ "summary": "Discard workflow draft",+ "title": "Discard workflow draft",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"workflows-enable": {- "description": "Enable / activate a draft workflow and start processing events. One-way door: a live workflow can't be edited over MCP (to change it you recreate it as a new draft), so test it first and get the user's explicit approval before invoking. Don't enable on your own initiative.",+ "description": "Enable / activate a draft workflow and start processing events. From then on it runs on real people: test it first with workflows-test-run and get the user's explicit approval before invoking - don't enable on your own initiative. Once live, content edits stage as a draft you publish with workflows-publish; if draft editing isn't enabled for the project yet, a live change means recreating the workflow as a new draft.","category": "Workflows","feature": "workflows","summary": "Enable workflow",@@ -9876,7 +9890,7 @@}},"workflows-get": {- "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.",+ "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. On an active workflow, 'draft' holds staged content changes awaiting workflows-publish (null when nothing is staged) — the live config in actions/edges is what's running.","category": "Workflows","feature": "workflows","summary": "Get workflow",@@ -10016,7 +10030,7 @@}},"workflows-patch-graph": {- "description": "Surgically edit a draft workflow's graph by sending a small, ordered list of operations instead of resending every action and edge. Prefer this over workflows-update for any change to an existing draft — to tweak one node's config use update_action with a deep-merge patch (e.g. change just an email subject), and use add_action / remove_action / add_edge / remove_edge / replace_action_edges for structural changes. Reference nodes and edges by id. Operations apply atomically: the graph is read, the ops applied in order, the result fully validated (dangling edges, branch indexes, single trigger), and saved only if valid — otherwise nothing changes. Draft only — active workflows are read-only via MCP. The full updated workflow is returned, so you don't need to re-fetch before the next edit. When adding or editing a conditional_branch, each condition needs a 'filters' wrapper: {filters:{properties:[...]}}, not {properties:[...]} on the condition. Re-test the changed path with workflows-test-run after patching.",+ "description": "Surgically edit a workflow's graph by sending a small, ordered list of operations instead of resending every action and edge. Prefer this over workflows-update for any graph change — to tweak one node's config use update_action with a deep-merge patch (e.g. change just an email subject), and use add_action / remove_action / add_edge / remove_edge / replace_action_edges for structural changes. Reference nodes and edges by id. Operations apply atomically: the graph is read, the ops applied in order, the result fully validated (dangling edges, branch indexes, single trigger), and saved only if valid — otherwise nothing changes. On an active workflow, patches stage a draft instead of changing what's running: the first patch copies the live graph into the draft, later patches compose onto it, and nothing reaches real people until workflows-publish. A rejection saying active workflows can't be edited means draft editing isn't enabled for this project yet — then a live change means recreating the workflow as a new draft. The full updated workflow is returned, so you don't need to re-fetch before the next edit. When adding or editing a conditional_branch, each condition needs a 'filters' wrapper: {filters:{properties:[...]}}, not {properties:[...]} on the condition. Re-test the changed path with workflows-test-run after patching.","category": "Workflows","feature": "workflows","summary": "Patch workflow graph",@@ -10029,6 +10043,20 @@"readOnlyHint": false}},+ "workflows-publish": {+ "description": "Apply a workflow's staged draft to its live config. Two-step: call without confirm first — it returns in_flight_runs (people mid-flow who will follow the new config once published) and draft_updated_at, changing nothing. Echo that impact to the user and get their go-ahead, then call again with confirm=true and that exact draft_updated_at; a 409 means the draft changed since you read it, so re-read and re-confirm. Publish revalidates the draft fully and recompiles it, so an invalid draft is rejected with the reason and the live config stays untouched. Test the draft first with workflows-test-run (use_draft=true).",+ "category": "Workflows",+ "feature": "workflows",+ "summary": "Publish workflow draft",+ "title": "Publish workflow draft",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true,+ "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",@@ -10086,7 +10114,7 @@}},"workflows-test-run": {- "description": "Test-invoke a workflow one node at a time; it does NOT traverse the full graph in one call. The result includes nextActionId. To verify a path end to end, chain calls: start at the trigger (omit current_action_id), then pass the returned nextActionId as current_action_id on the next call, and repeat. To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the action after them, since delays are not simulated. Pass test 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. Returns the step's execution trace.",+ "description": "Test-invoke a workflow one node at a time; it does NOT traverse the full graph in one call. The result includes nextActionId. To verify a path end to end, chain calls: start at the trigger (omit current_action_id), then pass the returned nextActionId as current_action_id on the next call, and repeat. To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the action after them, since delays are not simulated. Pass test 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. Returns the step's execution trace. Set use_draft=true to test a workflow's staged draft instead of its live config — always do this before workflows-publish.","category": "Workflows","feature": "workflows","summary": "Test-run workflow",@@ -10100,7 +10128,7 @@}},"workflows-update": {- "description": "Fallback editor. Prefer workflows-patch-graph for graph changes: it sends only the delta, is structurally validated, and returns the full updated graph. Reach for workflows-update for top-level metadata a patch can't express (name, description, exit_condition), or as an escape hatch to replace the whole workflow when you can't get workflows-patch-graph to land a change. Draft only: active workflows are read-only via MCP (editing risks breaking already-scheduled runs), so create a new draft to change a live one. Status changes go through workflows-enable / workflows-archive.",+ "description": "Fallback editor. Prefer workflows-patch-graph for graph changes: it sends only the delta, is structurally validated, and returns the full updated graph. Reach for workflows-update for top-level metadata a patch can't express (name, description, exit_condition), or as an escape hatch to replace the whole workflow when you can't get workflows-patch-graph to land a change. On an active workflow, content fields stage a draft (published with workflows-publish) while name/description apply immediately; a rejection saying active workflows can't be edited means draft editing isn't enabled for this project yet — then a live change means recreating the workflow as a new draft. Status changes go through workflows-enable / workflows-archive.","category": "Workflows","feature": "workflows","summary": "Update workflow",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex b458947a585a..61a84b3015a3 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -620,7 +620,7 @@}},"workflows-enable": {- "description": "Enable / activate a draft workflow and start processing events. One-way door: a live workflow can't be edited over MCP (to change it you recreate it as a new draft), so test it first and get the user's explicit approval before invoking. Don't enable on your own initiative.",+ "description": "Enable / activate a draft workflow and start processing events. From then on it runs on real people: test it first with workflows-test-run and get the user's explicit approval before invoking - don't enable on your own initiative. Once live, content edits stage as a draft you publish with workflows-publish; if draft editing isn't enabled for the project yet, a live change means recreating the workflow as a new draft.","category": "Workflows","feature": "workflows","summary": "Enable workflow",diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 422762847777..9bd62c820dfe 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -882,7 +882,7 @@"properties": {"id": {"type": "string",- "description": "The workflow (HogFlow) id to edit. Draft only — active workflows are read-only via MCP."+ "description": "The workflow (HogFlow) id to edit."},"operations": {"minItems": 1,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex cbcefa9964d2..a171febec8c4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -28618,6 +28618,13 @@ export namespace Schemas {* @nullable*/readonly user_access_level: string | null;+ /** Staged content changes awaiting publish — a full snapshot of the workflow's actions, edges and settings. Null when there's nothing staged. Test it with a use_draft test run, then promote it with the publish endpoint or throw it away with discard_draft. */+ readonly draft: unknown;+ /**+ * When the draft was last written; null when there's no staged draft. Pass this to publish (and as base_updated_at on further draft edits) so a concurrent editor's changes aren't clobbered — a mismatch returns 409.+ * @nullable+ */+ readonly draft_updated_at: string | null;}/**@@ -28718,6 +28725,8 @@ export namespace Schemas {mock_async_functions?: boolean;/** Start execution from this action ID instead of the trigger. Each test run executes a single node and returns the next action id. */current_action_id?: string;+ /** Test the workflow's staged draft instead of its live config. Requires an open draft; can't be combined with an explicit configuration override. */+ use_draft?: boolean;}/**@@ -28750,6 +28759,30 @@ export namespace Schemas {readonly user_access_level: string | null;}+ export interface HogFlowPublishRequest {+ /** False (default) previews the publish: returns how many runs are in flight without changing anything. True applies the staged draft to the live workflow. */+ confirm?: boolean;+ /** The draft_updated_at you loaded — required when confirm=true. A mismatch returns 409, so you never publish a draft someone else has changed since you read it. */+ draft_updated_at?: string;+ }++ export interface HogFlowPublishResponse {+ /** Whether the draft was applied to the live workflow. */+ published: boolean;+ /**+ * Runs currently in flight (parked on waits/delays or executing) that will follow the new config once published. Null when the count is unavailable.+ * @nullable+ */+ in_flight_runs: number | null;+ /**+ * Echo of the staged draft's timestamp — pass it back with confirm=true to publish exactly this draft.+ * @nullable+ */+ draft_updated_at: string | null;+ /** The workflow after publishing (only set when published=true). */+ workflow?: HogFlow | null;+ }+/*** @nullable*/@@ -43035,6 +43068,13 @@ export namespace Schemas {* @nullable*/readonly user_access_level?: string | null;+ /** Staged content changes awaiting publish — a full snapshot of the workflow's actions, edges and settings. Null when there's nothing staged. Test it with a use_draft test run, then promote it with the publish endpoint or throw it away with discard_draft. */+ readonly draft?: unknown;+ /**+ * When the draft was last written; null when there's no staged draft. Pass this to publish (and as base_updated_at on further draft edits) so a concurrent editor's changes aren't clobbered — a mismatch returns 409.+ * @nullable+ */+ readonly draft_updated_at?: string | null;}export interface PatchedHogFlowGraphUpdate {diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.tsindex 720ed6947217..0b3642ca3526 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 13 enabled ops+ * PostHog API - MCP 15 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -709,6 +709,15 @@ export const HogFlowsBatchJobsListParams = /* @__PURE__ */ zod.object({),})+export const HogFlowsDiscardDraftCreateParams = /* @__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 HogFlowsGraphPartialUpdateParams = /* @__PURE__ */ zod.object({id: zod.string().describe('A UUID string identifying this hog flow.'),project_id: zod@@ -868,6 +877,7 @@ export const HogFlowsInvocationsCreateParams = /* @__PURE__ */ zod.object({})export const hogFlowsInvocationsCreateBodyMockAsyncFunctionsDefault = true+export const hogFlowsInvocationsCreateBodyUseDraftDefault = falseexport const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({globals: zod@@ -884,6 +894,12 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({.describe('Start execution from this action ID instead of the trigger. Each test run executes a single node and returns the next action id.'),+ use_draft: zod+ .boolean()+ .default(hogFlowsInvocationsCreateBodyUseDraftDefault)+ .describe(+ "Test the workflow's staged draft instead of its live config. Requires an open draft; can't be combined with an explicit configuration override."+ ),})export const HogFlowsLogsRetrieveParams = /* @__PURE__ */ zod.object({@@ -961,6 +977,32 @@ export const HogFlowsMetricsRetrieveQueryParams = /* @__PURE__ */ zod.object({name: zod.string().min(1).optional().describe('Comma-separated metric names to filter by.'),})+export const HogFlowsPublishCreateParams = /* @__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 hogFlowsPublishCreateBodyConfirmDefault = false++export const HogFlowsPublishCreateBody = /* @__PURE__ */ zod.object({+ confirm: zod+ .boolean()+ .default(hogFlowsPublishCreateBodyConfirmDefault)+ .describe(+ 'False (default) previews the publish: returns how many runs are in flight without changing anything. True applies the staged draft to the live workflow.'+ ),+ draft_updated_at: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'The draft_updated_at you loaded — required when confirm=true. A mismatch returns 409, so you never publish a draft someone else has changed since you read it.'+ ),+})+export const HogFlowsSchedulesPartialUpdateParams = /* @__PURE__ */ zod.object({id: zod.string().describe('A UUID string identifying this hog flow.'),project_id: zoddiff --git a/services/mcp/src/hono/cache/RedisCache.ts b/services/mcp/src/hono/cache/RedisCache.tsindex 105bd01d2060..2af747650723 100644--- a/services/mcp/src/hono/cache/RedisCache.ts+++ b/services/mcp/src/hono/cache/RedisCache.ts@@ -24,7 +24,12 @@ export class RedisCache<T extends Record<string, any>> extends ScopedCache<T> {private ttl: numberprivate prefix: CachePrefix- constructor(scope: string, redis: RedisLike, prefix: CachePrefix = 'token', ttlSeconds: number = DEFAULT_TTL_SECONDS) {+ constructor(+ scope: string,+ redis: RedisLike,+ prefix: CachePrefix = 'token',+ ttlSeconds: number = DEFAULT_TTL_SECONDS+ ) {super(scope)this.redis = redisthis.prefix = prefixdiff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex 8b3bc76054d8..2ac3d86421c1 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -499,7 +499,7 @@ const WorkflowGraphOperationSchema = z.discriminatedUnion('op', [])export const WorkflowGraphPatchSchema = z.object({- id: z.string().describe('The workflow (HogFlow) id to edit. Draft only — active workflows are read-only via MCP.'),+ id: z.string().describe('The workflow (HogFlow) id to edit.'),operations: z.array(WorkflowGraphOperationSchema).min(1)diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.tsindex cf4f32e9a5df..573e2d7df381 100644--- a/services/mcp/src/tools/generated/workflows.ts+++ b/services/mcp/src/tools/generated/workflows.ts@@ -5,6 +5,7 @@ import type { Schemas } from '@/api/generated'import {HogFlowsBatchJobsListParams,HogFlowsCreateBody,+ HogFlowsDiscardDraftCreateParams,HogFlowsInvocationResultRetrieveParams,HogFlowsInvocationResultsRetrieveParams,HogFlowsInvocationResultsRetrieveQueryParams,@@ -18,6 +19,8 @@ import {HogFlowsMetricsRetrieveQueryParams,HogFlowsPartialUpdateBody,HogFlowsPartialUpdateParams,+ HogFlowsPublishCreateBody,+ HogFlowsPublishCreateParams,HogFlowsRetrieveParams,HogFlowsSchedulesPartialUpdateBody,HogFlowsSchedulesPartialUpdateParams,@@ -72,6 +75,22 @@ const workflowsCreate = (): ToolBase<typeof WorkflowsCreateSchema, WithPostHogUr},})+const WorkflowsDiscardDraftSchema = HogFlowsDiscardDraftCreateParams.omit({ project_id: true })++const workflowsDiscardDraft = (): ToolBase<typeof WorkflowsDiscardDraftSchema, Schemas.HogFlow> =>+ withUiApp('workflow', {+ name: 'workflows-discard-draft',+ schema: WorkflowsDiscardDraftSchema,+ handler: async (context: Context, params: z.infer<typeof WorkflowsDiscardDraftSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.HogFlow>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/discard_draft/`,+ })+ return result+ },+ })+const WorkflowsGetSchema = HogFlowsRetrieveParams.omit({ project_id: true })const workflowsGet = (): ToolBase<typeof WorkflowsGetSchema, WithPostHogUrl<Schemas.HogFlow>> =>@@ -241,6 +260,31 @@ const workflowsPatchGraph = (): ToolBase<typeof WorkflowsPatchGraphSchema, Schem},})+const WorkflowsPublishSchema = HogFlowsPublishCreateParams.omit({ project_id: true }).extend(+ HogFlowsPublishCreateBody.shape+)++const workflowsPublish = (): ToolBase<typeof WorkflowsPublishSchema, Schemas.HogFlowPublishResponse> => ({+ name: 'workflows-publish',+ schema: WorkflowsPublishSchema,+ handler: async (context: Context, params: z.infer<typeof WorkflowsPublishSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.confirm !== undefined) {+ body['confirm'] = params.confirm+ }+ if (params.draft_updated_at !== undefined) {+ body['draft_updated_at'] = params.draft_updated_at+ }+ const result = await context.api.request<Schemas.HogFlowPublishResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/publish/`,+ body,+ })+ return result+ },+})+const WorkflowsStatsSchema = HogFlowsMetricsRetrieveParams.omit({ project_id: true }).extend(HogFlowsMetricsRetrieveQueryParams.shape)@@ -286,6 +330,9 @@ const workflowsTestRun = (): ToolBase<typeof WorkflowsTestRunSchema, unknown> =>if (params.current_action_id !== undefined) {body['current_action_id'] = params.current_action_id}+ if (params.use_draft !== undefined) {+ body['use_draft'] = params.use_draft+ }const result = await context.api.request<unknown>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/invocations/`,@@ -372,6 +419,7 @@ const workflowsUpdateSchedule = (): ToolBase<typeof WorkflowsUpdateScheduleSchemexport const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'workflows-create': workflowsCreate,+ 'workflows-discard-draft': workflowsDiscardDraft,'workflows-get': workflowsGet,'workflows-get-invocation': workflowsGetInvocation,'workflows-global-stats': workflowsGlobalStats,@@ -380,6 +428,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'workflows-list-invocations': workflowsListInvocations,'workflows-logs': workflowsLogs,'workflows-patch-graph': workflowsPatchGraph,+ 'workflows-publish': workflowsPublish,'workflows-stats': workflowsStats,'workflows-test-run': workflowsTestRun,'workflows-update': workflowsUpdate,diff --git a/services/mcp/src/ui-apps/lib/index.ts b/services/mcp/src/ui-apps/lib/index.tsindex e552a93d8ace..23c3a6bec177 100644--- a/services/mcp/src/ui-apps/lib/index.ts+++ b/services/mcp/src/ui-apps/lib/index.ts@@ -3,4 +3,11 @@ export { DescriptionList, type DescriptionListProps, type DescriptionListItem }export { ListDetailView, type ListDetailViewProps } from './ListDetailView'export { emptyStateIllustration, type EmptyStateIllustrationType } from './illustrations/emptyStateIllustrations'export { cn, formatDate } from './utils'-export { CHART_COLORS, CHART_THEME, FUNNEL_COLOR, LIFECYCLE_COLORS, colorAt, lifecycleColor } from '../components/charts/theme'+export {+ CHART_COLORS,+ CHART_THEME,+ FUNNEL_COLOR,+ LIFECYCLE_COLORS,+ colorAt,+ lifecycleColor,+} from '../components/charts/theme'diff --git a/services/mcp/tests/hono/redis-cache.test.ts b/services/mcp/tests/hono/redis-cache.test.tsindex 8736aa88a186..21fe8543ea30 100644--- a/services/mcp/tests/hono/redis-cache.test.ts+++ b/services/mcp/tests/hono/redis-cache.test.ts@@ -82,7 +82,12 @@ describe('RedisCache', () => {describe('set', () => {it('should store JSON-serialized values with scoped key', async () => {await cache.set('region', 'eu')- expect(mockRedis.set).toHaveBeenCalledWith('mcp:token:test-user-hash:region', '"eu"', 'EX', 7 * 24 * 60 * 60)+ expect(mockRedis.set).toHaveBeenCalledWith(+ 'mcp:token:test-user-hash:region',+ '"eu"',+ 'EX',+ 7 * 24 * 60 * 60+ )})it('should isolate different users', async () => {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-discard-draft.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-discard-draft.jsonnew file mode 100644index 000000000000..6c38f5b9f257--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-discard-draft.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-patch-graph.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-graph.jsonindex 82ece5196011..e4effc369f81 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-graph.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-graph.json@@ -2,7 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"id": {- "description": "The workflow (HogFlow) id to edit. Draft only — active workflows are read-only via MCP.",+ "description": "The workflow (HogFlow) id to edit.","type": "string"},"operations": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-publish.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-publish.jsonnew file mode 100644index 000000000000..f3ef60141a3f--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-publish.json@@ -0,0 +1,22 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "confirm": {+ "default": false,+ "description": "False (default) previews the publish: returns how many runs are in flight without changing anything. True applies the staged draft to the live workflow.",+ "type": "boolean"+ },+ "draft_updated_at": {+ "description": "The draft_updated_at you loaded — required when confirm=true. A mismatch returns 409, so you never publish a draft someone else has changed since you read it.",+ "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"+ },+ "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-test-run.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-test-run.jsonindex 9056741f39d8..95d2f727f61d 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-test-run.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-test-run.json@@ -21,6 +21,11 @@"default": true,"description": "True (default) mocks HTTP/email/SMS. False fires real side effects.","type": "boolean"+ },+ "use_draft": {+ "default": false,+ "description": "Test the workflow's staged draft instead of its live config. Requires an open draft; can't be combined with an explicit configuration override.",+ "type": "boolean"}},"required": ["id"],diff --git a/services/mcp/tests/unit/query-wrapper-factory.test.ts b/services/mcp/tests/unit/query-wrapper-factory.test.tsindex 83ff30a7edc0..01c3d4e7d832 100644--- a/services/mcp/tests/unit/query-wrapper-factory.test.ts+++ b/services/mcp/tests/unit/query-wrapper-factory.test.ts@@ -366,17 +366,14 @@ describe('createQueryWrapper filterTestAccounts project default', () => {expect(runQuery.mock.calls[0]![0].query.filterTestAccounts).toBe(expected)})- it.each(['false', 'true'])(- 'rejects the string %j rather than coercing it to a boolean',- (stringValue) => {- const tool = createQueryWrapper({ name: 'test', schema: makeSchema(false), kind: 'TrendsQuery' })()-- // The generated schemas use z.coerce.boolean(), which would turn "false"- // into true; the stripped replacement must be a strict boolean so a- // malformed value is rejected instead of silently flipping filtering.- expect(tool.schema.safeParse({ series, filterTestAccounts: stringValue }).success).toBe(false)- }- )+ it.each(['false', 'true'])('rejects the string %j rather than coercing it to a boolean', (stringValue) => {+ const tool = createQueryWrapper({ name: 'test', schema: makeSchema(false), kind: 'TrendsQuery' })()++ // The generated schemas use z.coerce.boolean(), which would turn "false"+ // into true; the stripped replacement must be a strict boolean so a+ // malformed value is rejected instead of silently flipping filtering.+ expect(tool.schema.safeParse({ series, filterTestAccounts: stringValue }).success).toBe(false)+ })it('does not inject the field into schemas that lack it', async () => {const runQuery = vi.fn().mockResolvedValue({ results: [] })