Skip to content

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

feat(workflows): graph partial updates via MCP (#63583)

Harley Alexander48d445be1306
diff --git a/products/workflows/backend/api/graph_operations.py b/products/workflows/backend/api/graph_operations.py
new file mode 100644
index 000000000000..897b948e981c
--- /dev/null
+++ b/products/workflows/backend/api/graph_operations.py
@@ -0,0 +1,104 @@
+from copy import deepcopy
+from typing import NoReturn
+
+from rest_framework import serializers
+
+# Surgical, id-addressed edits to a workflow graph (actions + edges). The caller sends a small,
+# ordered list of operations instead of re-transmitting the whole graph; these are applied to the
+# stored actions/edges and the result is validated + saved by the serializer. Pure functions here —
+# no DB, no validation of config (that's HogFlowSerializer's job) and no structural validation
+# (that's validate_graph) — so they're cheap to unit-test exhaustively.
+
+
+def _deep_merge(target: dict, patch: dict) -> dict:
+ """Recursively merge `patch` into `target`. A null leaf deletes the key; a dict merges into a
+ dict; anything else replaces. Lets a caller change config.inputs.subject without resending the
+ rest of config."""
+ for key, value in patch.items():
+ if value is None:
+ target.pop(key, None)
+ elif isinstance(value, dict) and isinstance(target.get(key), dict):
+ _deep_merge(target[key], value)
+ else:
+ target[key] = value
+ return target
+
+
+def _edges_match(a: dict, b: dict) -> bool:
+ return (
+ a.get("from") == b.get("from")
+ and a.get("to") == b.get("to")
+ and a.get("type") == b.get("type")
+ and a.get("index") == b.get("index")
+ )
+
+
+def _fail(message: str) -> NoReturn:
+ raise serializers.ValidationError({"operations": message})
+
+
+def apply_graph_operations(
+ actions: list[dict], edges: list[dict], operations: list[dict]
+) -> tuple[list[dict], list[dict]]:
+ """Apply the ordered operations to copies of `actions`/`edges` and return the new graph. Does not
+ mutate the inputs. Raises ValidationError on operations that can't be applied (unknown id, missing
+ edge, duplicate id). Structural validity of the result is the caller's responsibility."""
+ actions = deepcopy(actions)
+ edges = deepcopy(edges)
+ actions_by_id = {a.get("id"): a for a in actions}
+
+ for op in operations:
+ kind = op["op"]
+
+ if kind == "update_action":
+ action = actions_by_id.get(op["id"])
+ if action is None:
+ _fail(f"update_action: action '{op['id']}' not found")
+ _deep_merge(action, op["patch"])
+
+ elif kind == "add_action":
+ new_action = op["action"]
+ new_id = new_action.get("id")
+ if not new_id:
+ _fail("add_action: action is missing an 'id'")
+ if new_id in actions_by_id:
+ _fail(f"add_action: action id '{new_id}' already exists")
+ actions.append(new_action)
+ actions_by_id[new_id] = new_action
+
+ elif kind == "remove_action":
+ target_id = op["id"]
+ if target_id not in actions_by_id:
+ _fail(f"remove_action: action '{target_id}' not found")
+ # Reroute incoming edges to the removed node's first outgoer, then drop edges touching it
+ # — mirrors the web builder's onNodesDelete so a removed middle node doesn't orphan its tail.
+ outgoers = [e["to"] for e in edges if e.get("from") == target_id]
+ first_outgoer = outgoers[0] if outgoers else None
+ if first_outgoer is not None:
+ for edge in edges:
+ if edge.get("to") == target_id:
+ edge["to"] = first_outgoer
+ edges = [e for e in edges if e.get("from") != target_id and e.get("to") != target_id]
+ actions = [a for a in actions if a.get("id") != target_id]
+ del actions_by_id[target_id]
+
+ elif kind == "add_edge":
+ edges.append(dict(op["edge"]))
+
+ elif kind == "remove_edge":
+ target_edge = op["edge"]
+ remaining = [e for e in edges if not _edges_match(e, target_edge)]
+ if len(remaining) == len(edges):
+ _fail("remove_edge: no matching edge found")
+ edges = remaining
+
+ elif kind == "replace_action_edges":
+ target_id = op["id"]
+ if target_id not in actions_by_id:
+ _fail(f"replace_action_edges: action '{target_id}' not found")
+ # Replace only the node's *outgoing* edges (the rewire-branches use case). Incoming edges are
+ # left intact so a caller who sends just the new branches can't accidentally orphan the node.
+ edges = [e for e in edges if e.get("from") != target_id]
+ edges.extend(dict(e) for e in op["edges"])
+
+ return actions, edges
diff --git a/products/workflows/backend/api/graph_validation.py b/products/workflows/backend/api/graph_validation.py
new file mode 100644
index 000000000000..c415bc431af2
--- /dev/null
+++ b/products/workflows/backend/api/graph_validation.py
@@ -0,0 +1,114 @@
+from collections import deque
+from typing import Optional
+
+from rest_framework import serializers
+
+# Action types that fan out via `branch` edges, and the config array each branch `index` points into.
+# A branch edge's `index` must fall in [0, branch_count). Types not listed support no branch edges.
+# Mirrors the frontend branch-edge model (getBranchLabel / StepConditionalBranch / StepRandomCohortBranch
+# in products/workflows/frontend/Workflows/hogflows): conditional_branch has one branch per condition,
+# random_cohort_branch one per cohort, wait_until_condition exactly one (the condition-met path, index 0),
+# each alongside a single `continue` fall-through/timeout edge.
+
+
+def _branch_slot_count(action: dict) -> int:
+ config = action.get("config") or {}
+ action_type = action.get("type")
+ if action_type == "conditional_branch":
+ return len(config.get("conditions") or [])
+ if action_type == "random_cohort_branch":
+ return len(config.get("cohorts") or [])
+ if action_type == "wait_until_condition":
+ return 1
+ return 0
+
+
+def validate_graph(actions: list[dict], edges: list[dict], abort_action: Optional[str] = None) -> list[str]:
+ """Structural validation of the workflow graph. Raises ValidationError on hard errors that would
+ break execution at runtime ('No next action found' and friends); returns a list of non-fatal
+ warnings (e.g. unreachable nodes) for the caller to surface. Complements the per-action and
+ whole-flow checks in HogFlowSerializer — those validate config; this validates the graph wiring."""
+ errors: list[str] = []
+
+ action_ids = [a.get("id") for a in actions]
+ actions_by_id = {a.get("id"): a for a in actions}
+
+ # Unique action ids — surgical edits reference nodes by id, so collisions are ambiguous.
+ duplicate_ids = sorted({aid for aid in action_ids if action_ids.count(aid) > 1 and aid is not None})
+ if duplicate_ids:
+ errors.append(f"Duplicate action id(s): {', '.join(duplicate_ids)}. Action ids must be unique.")
+
+ # Exactly one trigger.
+ trigger_ids = [a.get("id") for a in actions if a.get("type") == "trigger"]
+ if len(trigger_ids) != 1:
+ errors.append(f"Exactly one trigger action is required (found {len(trigger_ids)}).")
+
+ # Every edge endpoint references a real action.
+ seen_branch_keys: set[tuple] = set()
+ for edge in edges:
+ src, dst, edge_type = edge.get("from"), edge.get("to"), edge.get("type")
+ if src not in actions_by_id:
+ errors.append(f"Edge references unknown source action '{src}'.")
+ if dst not in actions_by_id:
+ errors.append(f"Edge references unknown target action '{dst}'.")
+
+ if edge_type == "branch":
+ index = edge.get("index")
+ if index is None:
+ errors.append(f"Branch edge from '{src}' is missing 'index'.")
+ elif src in actions_by_id:
+ slot_count = _branch_slot_count(actions_by_id[src])
+ if slot_count == 0:
+ errors.append(
+ f"Action '{src}' (type {actions_by_id[src].get('type')}) does not support branch edges."
+ )
+ elif not (0 <= index < slot_count):
+ errors.append(f"Branch edge from '{src}' has index {index} out of range [0, {slot_count}).")
+ else:
+ key = (src, index)
+ if key in seen_branch_keys:
+ errors.append(f"Duplicate branch edge from '{src}' with index {index}.")
+ seen_branch_keys.add(key)
+
+ # abort_action, when set, must point at a real action.
+ if abort_action and abort_action not in actions_by_id:
+ errors.append(f"abort_action references unknown action '{abort_action}'.")
+
+ if errors:
+ raise serializers.ValidationError({"graph": errors})
+
+ return _reachability_warnings(action_ids, actions_by_id, edges, trigger_ids)
+
+
+def _reachability_warnings(
+ action_ids: list[Optional[str]], actions_by_id: dict, edges: list[dict], trigger_ids: list[Optional[str]]
+) -> list[str]:
+ # A workflow always runs from its single trigger, so any action you can't reach by following edges
+ # from the trigger is dead — it'll never execute. We surface that as a warning (not an error: a
+ # half-wired draft is legitimate mid-build). Needs exactly one trigger to have a well-defined start.
+ if len(trigger_ids) != 1:
+ return []
+
+ # Adjacency list: action id -> list of action ids its outgoing edges point to.
+ adjacency: dict[Optional[str], list[Optional[str]]] = {aid: [] for aid in action_ids}
+ for edge in edges:
+ src = edge.get("from")
+ if src in adjacency:
+ adjacency[src].append(edge.get("to"))
+
+ # Breadth-first walk from the trigger, collecting every node we can get to. The `reachable` set
+ # both records the answer and prevents us from re-processing a node (so cycles terminate).
+ reachable: set[Optional[str]] = set()
+ queue: deque = deque([trigger_ids[0]])
+ while queue:
+ node = queue.popleft()
+ if node in reachable:
+ continue
+ reachable.add(node)
+ queue.extend(adjacency.get(node, []))
+
+ # Anything defined in the graph but never visited by the walk is unreachable.
+ unreachable = sorted(str(aid) for aid in actions_by_id if aid not in reachable)
+ if unreachable:
+ return [f"Action(s) not reachable from the trigger: {', '.join(unreachable)}."]
+ return []
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 6796c0b1469a..096624376c03 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -4,6 +4,7 @@ import uuid as uuid_mod
from datetime import timedelta
from typing import Optional, cast
+from django.db import transaction
from django.db.models import QuerySet
from django.utils import timezone
@@ -56,6 +57,8 @@ from products.feature_flags.backend.user_blast_radius import (
get_user_blast_radius,
get_user_blast_radius_persons,
)
+from products.workflows.backend.api.graph_operations import apply_graph_operations
+from products.workflows.backend.api.graph_validation import validate_graph
from products.workflows.backend.api.hog_flow_batch_job import HogFlowBatchJobSerializer
from products.workflows.backend.models.hog_flow.hog_flow import BILLABLE_ACTION_TYPES, HogFlow
from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob
@@ -68,6 +71,14 @@ 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.
+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."
+)
+
def _should_validate_strictly(context: dict, is_draft: Optional[bool]) -> bool:
# Non-draft saves always validate fully. Drafts stay lenient for the web UI builder (which saves
@@ -328,21 +339,38 @@ class HogFlowActionSerializer(serializers.Serializer):
if single_condition:
conditions = [single_condition]
+ is_conditional_branch = data.get("type") == "conditional_branch"
if conditions:
for condition in conditions:
filters = condition.get("filters")
- if filters is not None:
- if "events" in filters:
- if strict:
- raise serializers.ValidationError("Event filters are not allowed in conditionals")
- else:
- serializer = HogFunctionFiltersSerializer(data=filters, context=self.context)
- if not strict:
- if serializer.is_valid():
- condition["filters"] = serializer.validated_data
- else:
- serializer.is_valid(raise_exception=True)
+ if filters is None:
+ # A conditional_branch condition without a 'filters' wrapper (e.g. a bare {properties: [...]})
+ # has nothing to compile, so it silently becomes always-false and the branch never matches.
+ # Reject it for strict callers with a fixable message; web-builder drafts stay lenient
+ # (incomplete mid-edit). wait_until_condition waits on `events` instead, so a null condition
+ # filter is legitimate there — only enforce this for conditional_branch.
+ if strict and is_conditional_branch:
+ raise serializers.ValidationError(
+ {
+ "config": (
+ "Each conditional_branch condition must wrap its filters in a 'filters' key, e.g. "
+ "{conditions: [{filters: {properties: [...]}}]} (same shape as a trigger's "
+ "filters). A condition without 'filters' compiles to always-false and never matches."
+ )
+ }
+ )
+ continue
+ if "events" in filters:
+ if strict:
+ raise serializers.ValidationError("Event filters are not allowed in conditionals")
+ else:
+ serializer = HogFunctionFiltersSerializer(data=filters, context=self.context)
+ if not strict:
+ if serializer.is_valid():
condition["filters"] = serializer.validated_data
+ else:
+ serializer.is_valid(raise_exception=True)
+ condition["filters"] = serializer.validated_data
if data.get("type") == "wait_until_condition":
wait_events = data.get("config", {}).get("events") or []
@@ -665,6 +693,33 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
# (e.g. a cohort reference) fails at create rather than being silently stored.
strict = _should_validate_strictly(self.context, self.context.get("is_draft"))
+ # Graph wiring (dangling edges, branch-index range, abort_action, reachability) is enforced only on
+ # the surgical /graph endpoint (which sets enforce_graph_structure and builds a clean graph by
+ # construction). On every other save it's advisory: existing workflows carry pre-existing structural
+ # corruption (stale branch edges from removed conditions, legacy null endpoints), and a normal edit —
+ # even an unrelated one — must not be blocked by graph state the caller didn't introduce. We log it
+ # for telemetry instead. The web builder's incomplete drafts (not strict) skip the check entirely.
+ enforce_graph = self.context.get("enforce_graph_structure", False)
+ if strict or enforce_graph:
+ edges = data.get("edges", instance.edges if instance else [])
+ try:
+ warnings = validate_graph(actions, edges, abort_action=instance.abort_action if instance else None)
+ except serializers.ValidationError as exc:
+ if enforce_graph:
+ raise
+ graph_errors = exc.detail.get("graph", []) if isinstance(exc.detail, dict) else [exc.detail]
+ for error in graph_errors:
+ logger.warning(
+ "hog_flow_graph_structural_error",
+ error=str(error),
+ hog_flow_id=str(instance.id) if instance else None,
+ )
+ warnings = []
+ for warning in warnings:
+ logger.info(
+ "hog_flow_graph_warning", warning=warning, hog_flow_id=str(instance.id) if instance else None
+ )
+
conversion = data.get("conversion")
if conversion is not None:
filters = conversion.get("filters")
@@ -730,6 +785,87 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
return super().update(instance, validated_data)
+GRAPH_OPERATION_TYPES = [
+ "update_action",
+ "add_action",
+ "remove_action",
+ "add_edge",
+ "remove_edge",
+ "replace_action_edges",
+]
+
+# Per-op required fields, validated in HogFlowGraphOperationSerializer.validate so a malformed op is
+# rejected before any are applied (the whole batch is atomic).
+_GRAPH_OPERATION_REQUIRED_FIELDS: dict[str, list[str]] = {
+ "update_action": ["id", "patch"],
+ "add_action": ["action"],
+ "remove_action": ["id"],
+ "add_edge": ["edge"],
+ "remove_edge": ["edge"],
+ "replace_action_edges": ["id", "edges"],
+}
+
+
+class HogFlowGraphOperationSerializer(serializers.Serializer):
+ op = serializers.ChoiceField(
+ choices=GRAPH_OPERATION_TYPES,
+ help_text=(
+ "Graph edit. update_action {id, patch}: deep-merge patch into the action's fields (a null leaf "
+ "deletes that key) — the surgical path for tweaking one config value. add_action {action}: append "
+ "a full action node. remove_action {id}: delete a node and reconnect its incoming edges to its "
+ "first outgoer. add_edge {edge} / remove_edge {edge}: add or delete one edge. "
+ "replace_action_edges {id, edges}: replace this action's outgoing edges with the given set "
+ "(use when adding/removing branch conditions); incoming edges are left intact."
+ ),
+ )
+ id = serializers.CharField(
+ required=False, help_text="Action id. Required for update_action, remove_action, replace_action_edges."
+ )
+ patch = serializers.JSONField(
+ required=False,
+ help_text=(
+ "update_action only. Partial action fields, deep-merged into the existing action; a null leaf "
+ "deletes that key. e.g. {config: {inputs: {subject: {value: 'Hi'}}}} changes only that input."
+ ),
+ )
+ action = serializers.JSONField(
+ required=False,
+ help_text="add_action only. A full action node {id, name, type, config, ...}; same shape as in actions.",
+ )
+ edge = HogFlowEdgeSerializer(
+ required=False, help_text="add_edge / remove_edge only. The edge {from, to, type, index?}."
+ )
+ edges = serializers.ListField(
+ child=HogFlowEdgeSerializer(),
+ required=False,
+ help_text="replace_action_edges only. The complete set of the action's outgoing edges; incoming edges are preserved.",
+ )
+
+ def validate(self, data):
+ op = data["op"]
+ missing = [field for field in _GRAPH_OPERATION_REQUIRED_FIELDS[op] if data.get(field) is None]
+ if missing:
+ raise serializers.ValidationError(f"op '{op}' requires: {', '.join(missing)}")
+ if op == "update_action" and not isinstance(data.get("patch"), dict):
+ raise serializers.ValidationError("update_action 'patch' must be an object")
+ if op == "add_action" and not isinstance(data.get("action"), dict):
+ raise serializers.ValidationError("add_action 'action' must be an object")
+ return data
+
+
+class HogFlowGraphUpdateSerializer(serializers.Serializer):
+ operations = serializers.ListField(
+ child=HogFlowGraphOperationSerializer(),
+ allow_empty=False,
+ help_text=(
+ "Ordered graph edits applied atomically to a draft workflow: the stored graph is read, the ops "
+ "are applied in order, the result is fully validated, and it's saved only if valid — otherwise the "
+ "workflow is unchanged. Reference nodes/edges by id so you never resend the whole graph. The full "
+ "updated workflow is returned."
+ ),
+ )
+
+
class HogFlowInvocationSerializer(serializers.Serializer):
configuration = HogFlowSerializer(
write_only=True, required=False, help_text="Optional override; omit to use saved definition."
@@ -743,7 +879,12 @@ class HogFlowInvocationSerializer(serializers.Serializer):
help_text="True (default) mocks HTTP/email/SMS. False fires real side effects.",
)
current_action_id = serializers.CharField(
- write_only=True, required=False, help_text="Start from this action ID instead of the trigger."
+ write_only=True,
+ required=False,
+ help_text=(
+ "Start execution from this action ID instead of the trigger. Each test run executes a single node and "
+ "returns the next action id."
+ ),
)
@@ -784,6 +925,7 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie
"invocations",
"schedule_detail",
"bulk_delete",
+ "graph",
]
queryset = HogFlow.objects.all()
pagination_class = HogFlowPagination
@@ -895,14 +1037,9 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie
has_status = "status" in keys
has_non_status = bool(keys - {"status"})
- # Active workflows are read-only via MCP for now: edits can break runs already scheduled or in flight,
- # and there's no revision history to roll back. Status-only PATCHes (the lifecycle tools) pass through.
+ # 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(
- "Editing an active workflow isn't supported via MCP yet — changes can break runs already "
- "scheduled or in flight, and there's no revision history to roll back. Don't disable and "
- "re-enable it to work around this. If you need different behavior, create a new draft workflow."
- )
+ 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.
@@ -951,6 +1088,45 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie
except Exception as e:
logger.warning("Failed to capture hog_flow_activated event", error=str(e))
+ @extend_schema(request=HogFlowGraphUpdateSerializer, responses={200: HogFlowSerializer})
+ @action(detail=True, methods=["PATCH"])
+ def graph(self, request: Request, *args, **kwargs):
+ # Surgical graph editing: apply a small, id-addressed op list to the stored graph instead of
+ # re-transmitting every action and edge. Reads, applies, validates, and saves atomically so a
+ # rejected batch leaves the workflow untouched (and concurrent edits can't interleave).
+ op_serializer = HogFlowGraphUpdateSerializer(data=request.data)
+ op_serializer.is_valid(raise_exception=True)
+ operations = op_serializer.validated_data["operations"]
+
+ # Authorize + team-scope via the normal lookup, then re-read FOR UPDATE inside the transaction.
+ instance = self.get_object()
+
+ with transaction.atomic():
+ # nosemgrep: semgrep.rules.idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)
+ locked = HogFlow.objects.select_for_update().get(pk=instance.pk)
+
+ if self._is_mcp_request(request) and locked.status == HogFlow.State.ACTIVE:
+ raise exceptions.ValidationError(MCP_ACTIVE_EDIT_REJECTION)
+
+ new_actions, new_edges = apply_graph_operations(
+ list(locked.actions or []), list(locked.edges or []), 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,
+ # so it enforces graph validation as a hard error (unlike the lenient full-save path).
+ serializer.context["enforce_graph_structure"] = True
+ serializer.is_valid(raise_exception=True)
+
+ # nosemgrep: semgrep.rules.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.
+ serializer.save()
+
+ log_activity_from_viewset(self, locked, name=locked.name, previous=before_update)
+
+ return Response(self.get_serializer(locked).data)
+
@extend_schema(request=HogFlowInvocationSerializer, responses={200: _FallbackSerializer})
@action(detail=True, methods=["POST"])
def invocations(self, request: Request, *args, **kwargs):
diff --git a/products/workflows/backend/api/test/test_graph_validation.py b/products/workflows/backend/api/test/test_graph_validation.py
new file mode 100644
index 000000000000..2a5dd99b87dd
--- /dev/null
+++ b/products/workflows/backend/api/test/test_graph_validation.py
@@ -0,0 +1,228 @@
+import pytest
+from unittest import TestCase
+
+from parameterized import parameterized
+from rest_framework import serializers
+
+from products.workflows.backend.api.graph_operations import apply_graph_operations
+from products.workflows.backend.api.graph_validation import validate_graph
+
+TRIGGER = {"id": "t", "name": "trigger", "type": "trigger", "config": {"type": "event"}}
+EXIT = {"id": "x", "name": "exit", "type": "exit", "config": {}}
+
+
+def _fn(action_id: str) -> dict:
+ return {"id": action_id, "name": action_id, "type": "function", "config": {}}
+
+
+def _cond(action_id: str, n_conditions: int) -> dict:
+ return {
+ "id": action_id,
+ "name": action_id,
+ "type": "conditional_branch",
+ "config": {"conditions": [{"filters": {}} for _ in range(n_conditions)]},
+ }
+
+
+def _edge(frm: str, to: str, edge_type: str = "continue", index: int | None = None) -> dict:
+ edge: dict = {"from": frm, "to": to, "type": edge_type}
+ if index is not None:
+ edge["index"] = index
+ return edge
+
+
+def _graph_errors(actions, edges, abort_action=None) -> str:
+ with pytest.raises(serializers.ValidationError) as exc:
+ validate_graph(actions, edges, abort_action=abort_action)
+ return str(exc.value.detail)
+
+
+class TestValidateGraph(TestCase):
+ def test_valid_linear_graph_passes_with_no_warnings(self):
+ actions = [TRIGGER, _fn("a"), EXIT]
+ edges = [_edge("t", "a"), _edge("a", "x")]
+ assert validate_graph(actions, edges) == []
+
+ def test_duplicate_action_id_raises(self):
+ actions = [TRIGGER, _fn("a"), _fn("a"), EXIT]
+ assert "Duplicate action id" in _graph_errors(actions, [])
+
+ @parameterized.expand([("zero", []), ("two", [TRIGGER, dict(TRIGGER, id="t2")])])
+ def test_trigger_count_must_be_one(self, _name, trigger_actions):
+ actions = [*trigger_actions, _fn("a")] if trigger_actions else [_fn("a")]
+ assert "Exactly one trigger action is required" in _graph_errors(actions, [])
+
+ def test_edge_with_unknown_source_raises(self):
+ actions = [TRIGGER, _fn("a")]
+ assert "unknown source action 'ghost'" in _graph_errors(actions, [_edge("ghost", "a")])
+
+ def test_edge_with_unknown_target_raises(self):
+ actions = [TRIGGER, _fn("a")]
+ assert "unknown target action 'ghost'" in _graph_errors(actions, [_edge("a", "ghost")])
+
+ def test_branch_edge_on_non_branching_action_raises(self):
+ actions = [TRIGGER, _fn("a"), EXIT]
+ assert "does not support branch edges" in _graph_errors(actions, [_edge("a", "x", "branch", index=0)])
+
+ def test_branch_edge_missing_index_raises(self):
+ actions = [TRIGGER, _cond("c", 2), EXIT]
+ assert "missing 'index'" in _graph_errors(actions, [_edge("c", "x", "branch")])
+
+ def test_branch_edge_index_out_of_range_raises(self):
+ actions = [TRIGGER, _cond("c", 2), EXIT]
+ assert "out of range [0, 2)" in _graph_errors(actions, [_edge("c", "x", "branch", index=2)])
+
+ def test_duplicate_branch_index_raises(self):
+ actions = [TRIGGER, _cond("c", 2), _fn("a"), EXIT]
+ edges = [_edge("c", "a", "branch", index=0), _edge("c", "x", "branch", index=0)]
+ assert "Duplicate branch edge" in _graph_errors(actions, edges)
+
+ def test_abort_action_unknown_raises(self):
+ actions = [TRIGGER, _fn("a")]
+ assert "abort_action references unknown action 'ghost'" in _graph_errors(actions, [], abort_action="ghost")
+
+ def test_abort_action_known_passes(self):
+ actions = [TRIGGER, _fn("a")]
+ edges = [_edge("t", "a")]
+ assert validate_graph(actions, edges, abort_action="a") == []
+
+ def test_valid_branch_graph_passes(self):
+ actions = [TRIGGER, _cond("c", 2), _fn("a"), _fn("b"), EXIT]
+ edges = [
+ _edge("t", "c"),
+ _edge("c", "a", "branch", index=0),
+ _edge("c", "b", "branch", index=1),
+ _edge("c", "x"), # no-match fall-through
+ _edge("a", "x"),
+ _edge("b", "x"),
+ ]
+ assert validate_graph(actions, edges) == []
+
+ def test_wait_until_condition_allows_index_zero_only(self):
+ wait = {"id": "w", "name": "w", "type": "wait_until_condition", "config": {"condition": {"filters": {}}}}
+ actions = [TRIGGER, wait, EXIT]
+ edges = [_edge("t", "w"), _edge("w", "x", "branch", index=0), _edge("w", "x")]
+ assert validate_graph(actions, edges) == []
+ assert "out of range [0, 1)" in _graph_errors(actions, [_edge("t", "w"), _edge("w", "x", "branch", index=1)])
+
+ def test_unreachable_node_returns_warning_not_error(self):
+ actions = [TRIGGER, _fn("a"), _fn("orphan"), EXIT]
+ edges = [_edge("t", "a"), _edge("a", "x")]
+ warnings = validate_graph(actions, edges)
+ assert len(warnings) == 1
+ assert "not reachable from the trigger" in warnings[0]
+ assert "orphan" in warnings[0]
+
+
+class TestApplyGraphOperations(TestCase):
+ def test_update_action_deep_merges_config(self):
+ actions = [
+ TRIGGER,
+ {
+ "id": "a",
+ "name": "a",
+ "type": "function",
+ "config": {"inputs": {"url": {"value": "old"}, "keep": {"value": "v"}}},
+ },
+ ]
+ ops = [{"op": "update_action", "id": "a", "patch": {"config": {"inputs": {"url": {"value": "new"}}}}}]
+ new_actions, _ = apply_graph_operations(actions, [], ops)
+ a = next(x for x in new_actions if x["id"] == "a")
+ assert a["config"]["inputs"]["url"]["value"] == "new"
+ assert a["config"]["inputs"]["keep"]["value"] == "v" # untouched sibling preserved
+
+ def test_update_action_null_leaf_deletes_key(self):
+ actions = [TRIGGER, {"id": "a", "name": "a", "type": "function", "config": {"x": 1, "y": 2}}]
+ ops = [{"op": "update_action", "id": "a", "patch": {"config": {"x": None}}}]
+ new_actions, _ = apply_graph_operations(actions, [], ops)
+ a = next(x for x in new_actions if x["id"] == "a")
+ assert a["config"] == {"y": 2}
+
+ def test_update_action_not_found_raises(self):
+ with pytest.raises(serializers.ValidationError) as exc:
+ apply_graph_operations([TRIGGER], [], [{"op": "update_action", "id": "ghost", "patch": {}}])
+ assert "not found" in str(exc.value.detail)
+
+ def test_add_action_appends(self):
+ new_actions, _ = apply_graph_operations([TRIGGER], [], [{"op": "add_action", "action": _fn("a")}])
+ assert [x["id"] for x in new_actions] == ["t", "a"]
+
+ def test_add_action_duplicate_id_raises(self):
+ with pytest.raises(serializers.ValidationError) as exc:
+ apply_graph_operations([TRIGGER, _fn("a")], [], [{"op": "add_action", "action": _fn("a")}])
+ assert "already exists" in str(exc.value.detail)
+
+ def test_add_action_missing_id_raises(self):
+ with pytest.raises(serializers.ValidationError) as exc:
+ apply_graph_operations(
+ [TRIGGER], [], [{"op": "add_action", "action": {"name": "x", "type": "function", "config": {}}}]
+ )
+ assert "missing an 'id'" in str(exc.value.detail)
+
+ def test_remove_action_reroutes_incoming_to_first_outgoer(self):
+ # t -> a -> x ; removing a should reconnect t -> x
+ actions = [TRIGGER, _fn("a"), EXIT]
+ edges = [_edge("t", "a"), _edge("a", "x")]
+ new_actions, new_edges = apply_graph_operations(actions, edges, [{"op": "remove_action", "id": "a"}])
+ assert [x["id"] for x in new_actions] == ["t", "x"]
+ assert new_edges == [_edge("t", "x")]
+
+ def test_remove_action_not_found_raises(self):
+ with pytest.raises(serializers.ValidationError) as exc:
+ apply_graph_operations([TRIGGER], [], [{"op": "remove_action", "id": "ghost"}])
+ assert "not found" in str(exc.value.detail)
+
+ def test_add_edge_appends(self):
+ _, new_edges = apply_graph_operations([TRIGGER, _fn("a")], [], [{"op": "add_edge", "edge": _edge("t", "a")}])
+ assert new_edges == [_edge("t", "a")]
+
+ def test_remove_edge_removes_matching(self):
+ edges = [_edge("t", "a"), _edge("a", "x")]
+ _, new_edges = apply_graph_operations(
+ [TRIGGER, _fn("a"), EXIT], edges, [{"op": "remove_edge", "edge": _edge("t", "a")}]
+ )
+ assert new_edges == [_edge("a", "x")]
+
+ def test_remove_edge_no_match_raises(self):
+ with pytest.raises(serializers.ValidationError) as exc:
+ apply_graph_operations([TRIGGER, _fn("a")], [], [{"op": "remove_edge", "edge": _edge("t", "a")}])
+ assert "no matching edge" in str(exc.value.detail)
+
+ def test_replace_action_edges_swaps_outgoing_and_preserves_incoming(self):
+ # c has old outgoing branch edges; replace with a fresh set. The incoming t->c edge is left intact
+ # so editing a node's branches can't orphan it when the caller only sends outgoing edges.
+ actions = [TRIGGER, _cond("c", 2), _fn("a"), _fn("b"), EXIT]
+ edges = [_edge("t", "c"), _edge("c", "a", "branch", index=0), _edge("c", "x")]
+ ops = [
+ {
+ "op": "replace_action_edges",
+ "id": "c",
+ "edges": [_edge("c", "a", "branch", index=0), _edge("c", "b", "branch", index=1)],
+ }
+ ]
+ _, new_edges = apply_graph_operations(actions, edges, ops)
+ # incoming edge preserved
+ assert _edge("t", "c") in new_edges
+ # old outgoing replaced by the new set
+ assert _edge("c", "x") not in new_edges
+ assert _edge("c", "b", "branch", index=1) in new_edges
+
+ def test_replace_action_edges_unknown_id_raises(self):
+ with pytest.raises(serializers.ValidationError) as exc:
+ apply_graph_operations([TRIGGER], [], [{"op": "replace_action_edges", "id": "ghost", "edges": []}])
+ assert "not found" in str(exc.value.detail)
+
+ def test_operations_apply_in_order(self):
+ # add an action, then update it in the same batch
+ ops = [
+ {"op": "add_action", "action": _fn("a")},
+ {"op": "update_action", "id": "a", "patch": {"name": "renamed"}},
+ ]
+ new_actions, _ = apply_graph_operations([TRIGGER], [], ops)
+ assert next(x for x in new_actions if x["id"] == "a")["name"] == "renamed"
+
+ def test_does_not_mutate_input(self):
+ actions = [TRIGGER, _fn("a")]
+ edges = [_edge("t", "a")]
+ apply_graph_operations(actions, edges, [{"op": "update_action", "id": "a", "patch": {"name": "x"}}])
+ assert actions[1]["name"] == "a" # original untouched
diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.py
index 3983230e4a1f..d86fcc55245c 100644
--- a/products/workflows/backend/api/test/test_hog_flow.py
+++ b/products/workflows/backend/api/test/test_hog_flow.py
@@ -453,6 +453,54 @@ class TestHogFlowAPI(APIBaseTest):
assert "bytecode" in conditions[0]["filters"], conditions[0]["filters"]
assert conditions[0]["filters"]["bytecode"] == ["_H", 1, 32, "custom_event", 32, "event", 1, 1, 11]
+ def test_hog_flow_conditional_branch_condition_missing_filters_rejected(self):
+ # A bare {properties: [...]} (no 'filters' wrapper) compiles to always-false; reject it in strict mode.
+ conditional_action = {
+ "id": "cond_1",
+ "name": "cond_1",
+ "type": "conditional_branch",
+ "config": {
+ "conditions": [
+ {"properties": [{"key": "plan", "type": "person", "value": "enterprise", "operator": "exact"}]}
+ ]
+ },
+ }
+ trigger_action = {
+ "id": "trigger_node",
+ "name": "trigger_1",
+ "type": "trigger",
+ "config": {
+ "type": "event",
+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},
+ },
+ }
+ hog_flow = {"name": "Test Flow", "status": "active", "actions": [trigger_action, conditional_action]}
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+ assert response.status_code == 400, response.json()
+ assert "filters" in response.json()["detail"]
+
+ def test_hog_flow_conditional_branch_missing_filters_allowed_for_web_draft(self):
+ # Web-builder drafts stay lenient — an incomplete condition mid-edit must still save.
+ conditional_action = {
+ "id": "cond_1",
+ "name": "cond_1",
+ "type": "conditional_branch",
+ "config": {"conditions": [{"properties": []}]},
+ }
+ trigger_action = {
+ "id": "trigger_node",
+ "name": "trigger_1",
+ "type": "trigger",
+ "config": {
+ "type": "event",
+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},
+ },
+ }
+ # Default test client uses session auth → EventSource.WEB → lenient draft validation.
+ hog_flow = {"name": "Test Flow", "status": "draft", "actions": [trigger_action, conditional_action]}
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+ assert response.status_code == 201, response.json()
+
def test_hog_flow_single_condition_field(self):
trigger_action = {
"id": "trigger_node",
@@ -1013,6 +1061,169 @@ class TestHogFlowAPI(APIBaseTest):
assert response.status_code == 400, response.json()
assert response.json()["attr"] == "edges"
+ def _create_draft_flow_with_graph(self) -> str:
+ # trigger -> action_1 (webhook) -> exit, created as a draft so the graph endpoint can edit it.
+ trigger = {
+ "id": "trigger_node",
+ "name": "trigger_1",
+ "type": "trigger",
+ "config": {
+ "type": "event",
+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},
+ },
+ }
+ action = {
+ "id": "action_1",
+ "name": "action_1",
+ "type": "function",
+ "config": {"template_id": "template-webhook", "inputs": {"url": {"value": "https://old.example.com"}}},
+ }
+ exit_action = {"id": "exit_1", "name": "exit_1", "type": "exit", "config": {}}
+ flow = {
+ "name": "Test Flow",
+ "status": "draft",
+ "actions": [trigger, action, exit_action],
+ "edges": [
+ {"from": "trigger_node", "to": "action_1", "type": "continue"},
+ {"from": "action_1", "to": "exit_1", "type": "continue"},
+ ],
+ }
+ create = self.client.post(f"/api/projects/{self.team.id}/hog_flows", flow)
+ assert create.status_code == 201, create.json()
+ return create.json()["id"]
+
+ def _patch_graph(self, flow_id: str, operations: list[dict], **extra):
+ return self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {"operations": operations},
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ **extra,
+ )
+
+ def test_graph_update_action_changes_single_field(self):
+ flow_id = self._create_draft_flow_with_graph()
+ response = self._patch_graph(
+ flow_id,
+ [
+ {
+ "op": "update_action",
+ "id": "action_1",
+ "patch": {"config": {"inputs": {"url": {"value": "https://new.example.com"}}}},
+ }
+ ],
+ )
+ assert response.status_code == 200, response.json()
+ actions = {a["id"]: a for a in response.json()["actions"]}
+ assert actions["action_1"]["config"]["inputs"]["url"]["value"] == "https://new.example.com"
+ # The rest of the graph is intact.
+ assert actions["trigger_node"]["type"] == "trigger"
+ assert "exit_1" in actions
+
+ def test_graph_response_echoes_full_graph(self):
+ flow_id = self._create_draft_flow_with_graph()
+ response = self._patch_graph(flow_id, [{"op": "update_action", "id": "action_1", "patch": {"name": "renamed"}}])
+ assert response.status_code == 200, response.json()
+ body = response.json()
+ assert {"actions", "edges", "trigger"} <= set(body.keys())
+ assert len(body["actions"]) == 3
+ assert body["edges"] == [
+ {"from": "trigger_node", "to": "action_1", "type": "continue"},
+ {"from": "action_1", "to": "exit_1", "type": "continue"},
+ ]
+
+ def test_graph_remove_action_reconnects_edges(self):
+ flow_id = self._create_draft_flow_with_graph()
+ response = self._patch_graph(flow_id, [{"op": "remove_action", "id": "action_1"}])
+ assert response.status_code == 200, response.json()
+ body = response.json()
+ assert sorted(a["id"] for a in body["actions"]) == ["exit_1", "trigger_node"]
+ assert body["edges"] == [{"from": "trigger_node", "to": "exit_1", "type": "continue"}]
+
+ def test_graph_dangling_edge_rejected_with_no_partial_write(self):
+ flow_id = self._create_draft_flow_with_graph()
+ response = self._patch_graph(
+ flow_id, [{"op": "add_edge", "edge": {"from": "action_1", "to": "ghost", "type": "continue"}}]
+ )
+ assert response.status_code == 400, response.json()
+ assert "unknown target action 'ghost'" in str(response.json())
+ # Atomicity: the workflow's edges are unchanged on disk.
+ flow = HogFlow.objects.get(pk=flow_id)
+ assert flow.edges == [
+ {"from": "trigger_node", "to": "action_1", "type": "continue"},
+ {"from": "action_1", "to": "exit_1", "type": "continue"},
+ ]
+
+ def test_graph_empty_operations_rejected(self):
+ flow_id = self._create_draft_flow_with_graph()
+ response = self._patch_graph(flow_id, [])
+ assert response.status_code == 400, response.json()
+
+ def test_graph_mcp_cannot_edit_active_workflow(self):
+ flow_id = self._create_active_hog_flow()
+ response = self._patch_graph(flow_id, [{"op": "update_action", "id": "action_1", "patch": {"name": "x"}}])
+ assert response.status_code == 400, response.json()
+ assert "active workflow isn't supported via MCP" in response.json()["detail"]
+
+ def test_graph_non_mcp_can_edit_active_workflow(self):
+ flow_id = self._create_active_hog_flow()
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {"operations": [{"op": "update_action", "id": "action_1", "patch": {"name": "Renamed via UI"}}]},
+ )
+ assert response.status_code == 200, response.json()
+ assert {a["id"]: a for a in response.json()["actions"]}["action_1"]["name"] == "Renamed via UI"
+
+ def _flow_with_dangling_edge(self, status: str) -> dict:
+ # A structurally-invalid graph: an edge pointing at an action that doesn't exist. Mirrors the
+ # pre-existing corruption real workflows carry (stale edges from removed nodes/conditions).
+ return {
+ "name": "Dangling Flow",
+ "status": status,
+ "actions": [
+ {
+ "id": "trigger_node",
+ "name": "t",
+ "type": "trigger",
+ "config": {
+ "type": "event",
+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},
+ },
+ },
+ {"id": "exit_1", "name": "exit", "type": "exit", "config": {}},
+ ],
+ "edges": [
+ {"from": "trigger_node", "to": "exit_1", "type": "continue"},
+ {"from": "trigger_node", "to": "ghost", "type": "continue"},
+ ],
+ }
+
+ def test_create_active_flow_with_invalid_graph_is_lenient(self):
+ # Option B: the full create/PATCH path no longer hard-blocks on graph structure — only the surgical
+ # /graph endpoint enforces. A dangling edge is logged, not rejected, so callers (incl. the web UI on
+ # an active save) aren't trapped by pre-existing corruption.
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", self._flow_with_dangling_edge("active"))
+ assert response.status_code == 201, response.json()
+
+ def test_full_patch_with_invalid_graph_is_lenient(self):
+ create = self.client.post(f"/api/projects/{self.team.id}/hog_flows", self._flow_with_dangling_edge("draft"))
+ assert create.status_code == 201, create.json()
+ flow_id = create.json()["id"]
+ # Re-saving the (already structurally-broken) flow as active must succeed — the user isn't blocked
+ # from editing a workflow whose graph corruption they didn't introduce.
+ response = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "active"})
+ assert response.status_code == 200, response.json()
+ assert HogFlow.objects.get(pk=flow_id).status == "active"
+
+ def test_graph_endpoint_still_enforces_on_draft(self):
+ # The new surgical endpoint is where corruption would be newly introduced, so it stays strict even
+ # though the full-PATCH path is lenient.
+ flow_id = self._create_draft_flow_with_graph()
+ response = self._patch_graph(
+ flow_id, [{"op": "add_edge", "edge": {"from": "action_1", "to": "ghost", "type": "continue"}}]
+ )
+ assert response.status_code == 400, response.json()
+ assert "unknown target action 'ghost'" in str(response.json())
+
def test_can_call_a_test_invocation(self):
hog_flow, _ = self._create_hog_flow_with_action(
{"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}}
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index fe10a3ca058f..9c07aae7d7d5 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -559,6 +559,53 @@ export interface HogFlowBatchJobApi {
readonly updated_at: string
}
+/**
+ * * `update_action` - update_action
+ * * `add_action` - add_action
+ * * `remove_action` - remove_action
+ * * `add_edge` - add_edge
+ * * `remove_edge` - remove_edge
+ * * `replace_action_edges` - replace_action_edges
+ */
+export type HogFlowGraphOperationOpEnumApi =
+ (typeof HogFlowGraphOperationOpEnumApi)[keyof typeof HogFlowGraphOperationOpEnumApi]
+
+export const HogFlowGraphOperationOpEnumApi = {
+ UpdateAction: 'update_action',
+ AddAction: 'add_action',
+ RemoveAction: 'remove_action',
+ AddEdge: 'add_edge',
+ RemoveEdge: 'remove_edge',
+ ReplaceActionEdges: 'replace_action_edges',
+} as const
+
+export interface HogFlowGraphOperationApi {
+ /** Graph edit. update_action {id, patch}: deep-merge patch into the action's fields (a null leaf deletes that key) — the surgical path for tweaking one config value. add_action {action}: append a full action node. remove_action {id}: delete a node and reconnect its incoming edges to its first outgoer. add_edge {edge} / remove_edge {edge}: add or delete one edge. replace_action_edges {id, edges}: replace this action's outgoing edges with the given set (use when adding/removing branch conditions); incoming edges are left intact.
+ *
+ * * `update_action` - update_action
+ * * `add_action` - add_action
+ * * `remove_action` - remove_action
+ * * `add_edge` - add_edge
+ * * `remove_edge` - remove_edge
+ * * `replace_action_edges` - replace_action_edges */
+ op: HogFlowGraphOperationOpEnumApi
+ /** Action id. Required for update_action, remove_action, replace_action_edges. */
+ id?: string
+ /** update_action only. Partial action fields, deep-merged into the existing action; a null leaf deletes that key. e.g. {config: {inputs: {subject: {value: 'Hi'}}}} changes only that input. */
+ patch?: unknown
+ /** add_action only. A full action node {id, name, type, config, ...}; same shape as in actions. */
+ action?: unknown
+ /** add_edge / remove_edge only. The edge {from, to, type, index?}. */
+ edge?: HogFlowEdgeApi
+ /** replace_action_edges only. The complete set of the action's outgoing edges; incoming edges are preserved. */
+ edges?: HogFlowEdgeApi[]
+}
+
+export interface PatchedHogFlowGraphUpdateApi {
+ /** Ordered graph edits applied atomically to a draft workflow: the stored graph is read, the ops are applied in order, the result is fully validated, and it's saved only if valid — otherwise the workflow is unchanged. Reference nodes/edges by id so you never resend the whole graph. The full updated workflow is returned. */
+ operations?: HogFlowGraphOperationApi[]
+}
+
export interface HogInvocationResultApi {
invocation_id: string
status: string
@@ -614,7 +661,7 @@ export interface HogFlowInvocationApi {
globals?: HogFlowInvocationApiGlobals
/** True (default) mocks HTTP/email/SMS. False fires real side effects. */
mock_async_functions?: boolean
- /** Start from this action ID instead of the trigger. */
+ /** 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
}
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index a793eb4090e4..f477f6acfd17 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -31,6 +31,7 @@ import type {
PaginatedHogFlowMinimalListApi,
PaginatedHogFlowTemplateListApi,
PatchedHogFlowApi,
+ PatchedHogFlowGraphUpdateApi,
PatchedHogFlowScheduleApi,
PatchedHogFlowTemplateApi,
WorkflowStatsRowApi,
@@ -348,6 +349,24 @@ export const hogFlowsBatchJobsCreate = async (
})
}
+export const getHogFlowsGraphPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/hog_flows/${id}/graph/`
+}
+
+export const hogFlowsGraphPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedHogFlowGraphUpdateApi?: PatchedHogFlowGraphUpdateApi,
+ options?: RequestInit
+): Promise<HogFlowApi> => {
+ return apiMutator<HogFlowApi>(getHogFlowsGraphPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedHogFlowGraphUpdateApi),
+ })
+}
+
export const getHogFlowsInvocationResultsRetrieveUrl = (
projectId: string,
id: string,
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index 1267d50b1525..5328fdab1fe0 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -884,6 +884,91 @@ export const HogFlowsBatchJobsCreateBody = /* @__PURE__ */ zod.object({
variables: zod.unknown().optional().describe('Variable value overrides applied to this run.'),
})
+export const HogFlowsGraphPartialUpdateBody = /* @__PURE__ */ zod.object({
+ operations: zod
+ .array(
+ zod.object({
+ op: zod
+ .enum([
+ 'update_action',
+ 'add_action',
+ 'remove_action',
+ 'add_edge',
+ 'remove_edge',
+ 'replace_action_edges',
+ ])
+ .describe(
+ '\* `update_action` - update_action\n\* `add_action` - add_action\n\* `remove_action` - remove_action\n\* `add_edge` - add_edge\n\* `remove_edge` - remove_edge\n\* `replace_action_edges` - replace_action_edges'
+ )
+ .describe(
+ "Graph edit. update_action {id, patch}: deep-merge patch into the action's fields (a null leaf deletes that key) — the surgical path for tweaking one config value. add_action {action}: append a full action node. remove_action {id}: delete a node and reconnect its incoming edges to its first outgoer. add_edge {edge} \/ remove_edge {edge}: add or delete one edge. replace_action_edges {id, edges}: replace this action's outgoing edges with the given set (use when adding\/removing branch conditions); incoming edges are left intact.\n\n\* `update_action` - update_action\n\* `add_action` - add_action\n\* `remove_action` - remove_action\n\* `add_edge` - add_edge\n\* `remove_edge` - remove_edge\n\* `replace_action_edges` - replace_action_edges"
+ ),
+ id: zod
+ .string()
+ .optional()
+ .describe('Action id. Required for update_action, remove_action, replace_action_edges.'),
+ patch: zod
+ .unknown()
+ .optional()
+ .describe(
+ "update_action only. Partial action fields, deep-merged into the existing action; a null leaf deletes that key. e.g. {config: {inputs: {subject: {value: 'Hi'}}}} changes only that input."
+ ),
+ action: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'add_action only. A full action node {id, name, type, config, ...}; same shape as in actions.'
+ ),
+ edge: zod
+ .object({
+ to: zod.string().describe('Target action id.'),
+ type: zod
+ .enum(['continue', 'branch'])
+ .describe('\* `continue` - continue\n\* `branch` - branch')
+ .describe(
+ "continue: fall-through (sequential or the no-match path of conditional_branch). branch: requires 'index' matching config.conditions[index].\n\n\* `continue` - continue\n\* `branch` - branch"
+ ),
+ index: zod
+ .number()
+ .optional()
+ .describe(
+ "Required for type='branch'. Index into config.conditions on conditional_branch \/ wait_until_condition."
+ ),
+ from: zod.string().describe('Source action id.'),
+ })
+ .optional()
+ .describe('add_edge \/ remove_edge only. The edge {from, to, type, index?}.'),
+ edges: zod
+ .array(
+ zod.object({
+ to: zod.string().describe('Target action id.'),
+ type: zod
+ .enum(['continue', 'branch'])
+ .describe('\* `continue` - continue\n\* `branch` - branch')
+ .describe(
+ "continue: fall-through (sequential or the no-match path of conditional_branch). branch: requires 'index' matching config.conditions[index].\n\n\* `continue` - continue\n\* `branch` - branch"
+ ),
+ index: zod
+ .number()
+ .optional()
+ .describe(
+ "Required for type='branch'. Index into config.conditions on conditional_branch \/ wait_until_condition."
+ ),
+ from: zod.string().describe('Source action id.'),
+ })
+ )
+ .optional()
+ .describe(
+ "replace_action_edges only. The complete set of the action's outgoing edges; incoming edges are preserved."
+ ),
+ })
+ )
+ .optional()
+ .describe(
+ "Ordered graph edits applied atomically to a draft workflow: the stored graph is read, the ops are applied in order, the result is fully validated, and it's saved only if valid — otherwise the workflow is unchanged. Reference nodes\/edges by id so you never resend the whole graph. The full updated workflow is returned."
+ ),
+})
+
export const hogFlowsInvocationsCreateBodyConfigurationOneNameMax = 400
export const hogFlowsInvocationsCreateBodyConfigurationOneDescriptionDefault = ``
@@ -1168,7 +1253,12 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({
.boolean()
.default(hogFlowsInvocationsCreateBodyMockAsyncFunctionsDefault)
.describe('True (default) mocks HTTP\/email\/SMS. False fires real side effects.'),
- current_action_id: zod.string().optional().describe('Start from this action ID instead of the trigger.'),
+ current_action_id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Start execution from this action ID instead of the trigger. Each test run executes a single node and returns the next action id.'
+ ),
})
export const hogFlowsSchedulesCreateBodyTimezoneMax = 64
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index e1db95f5fe5a..74c8a6ed3dee 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -217,6 +217,26 @@ tools:
Retrieve execution logs for a specific workflow by ID. Returns log entries with timestamp, level (DEBUG,
LOG, INFO, WARN, ERROR), and message. Use to debug why a workflow is failing or not producing expected
results. Supports filtering by log level, text search, time range (after/before), and pagination via limit.
+ workflows-patch-graph:
+ operation: hog_flows_graph_partial_update
+ enabled: true
+ scopes:
+ - hog_flow:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ input_schema: WorkflowGraphPatchSchema
+ title: Patch workflow 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.
workflows-stats:
operation: hog_flows_metrics_retrieve
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 3b0f899f54ef..e7c2fc92a841 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -7620,6 +7620,20 @@
"readOnlyHint": false
}
},
+ "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.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Patch workflow graph",
+ "title": "Patch workflow graph",
+ "required_scopes": ["hog_flow:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "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",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index d3871bf3848b..3052f3815ec4 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -8171,6 +8171,20 @@
"readOnlyHint": false
}
},
+ "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.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Patch workflow graph",
+ "title": "Patch workflow graph",
+ "required_scopes": ["hog_flow:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "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",
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index bfda60b6fe5c..7e3096b563ca 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -829,6 +829,194 @@
}
],
"description": "Filter definition. Pick exactly one branch: `data_warehouse` (set `source: \"data_warehouse\"` plus `table_name`/`timestamp_field`/`key_field`) or `events` (HogFunction filter shape with an `events` array)."
+ },
+ "WorkflowGraphPatchSchema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "The workflow (HogFlow) id to edit. Draft only — active workflows are read-only via MCP."
+ },
+ "operations": {
+ "minItems": 1,
+ "type": "array",
+ "items": {
+ "oneOf": [
+ {
+ "type": "object",
+ "properties": {
+ "op": {
+ "type": "string",
+ "const": "update_action"
+ },
+ "id": {
+ "type": "string",
+ "description": "Id of the action to update."
+ },
+ "patch": {
+ "type": "object",
+ "propertyNames": {
+ "type": "string"
+ },
+ "additionalProperties": {},
+ "description": "Partial action fields, deep-merged into the existing action; a null leaf deletes that key. e.g. {config: {inputs: {subject: {value: \"Hi\"}}}} changes only that one input."
+ }
+ },
+ "required": ["op", "id", "patch"]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "op": {
+ "type": "string",
+ "const": "add_action"
+ },
+ "action": {
+ "type": "object",
+ "propertyNames": {
+ "type": "string"
+ },
+ "additionalProperties": {},
+ "description": "A full action node {id, name, type, config, ...}; same shape as entries in the workflow actions array."
+ }
+ },
+ "required": ["op", "action"]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "op": {
+ "type": "string",
+ "const": "remove_action"
+ },
+ "id": {
+ "type": "string",
+ "description": "Id of the action to remove. Its incoming edges reconnect to its first outgoer."
+ }
+ },
+ "required": ["op", "id"]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "op": {
+ "type": "string",
+ "const": "add_edge"
+ },
+ "edge": {
+ "type": "object",
+ "properties": {
+ "from": {
+ "type": "string",
+ "description": "Source action id."
+ },
+ "to": {
+ "type": "string",
+ "description": "Target action id."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["continue", "branch"],
+ "description": "'continue' = fall-through (sequential or no-match path); 'branch' = a condition/cohort branch (needs index)."
+ },
+ "index": {
+ "description": "Required for type=branch: which condition/cohort slot this branch matches (0-based).",
+ "type": "integer",
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991
+ }
+ },
+ "required": ["from", "to", "type"],
+ "description": "The edge to add."
+ }
+ },
+ "required": ["op", "edge"]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "op": {
+ "type": "string",
+ "const": "remove_edge"
+ },
+ "edge": {
+ "type": "object",
+ "properties": {
+ "from": {
+ "type": "string",
+ "description": "Source action id."
+ },
+ "to": {
+ "type": "string",
+ "description": "Target action id."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["continue", "branch"],
+ "description": "'continue' = fall-through (sequential or no-match path); 'branch' = a condition/cohort branch (needs index)."
+ },
+ "index": {
+ "description": "Required for type=branch: which condition/cohort slot this branch matches (0-based).",
+ "type": "integer",
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991
+ }
+ },
+ "required": ["from", "to", "type"],
+ "description": "The edge to remove (matched on from/to/type/index)."
+ }
+ },
+ "required": ["op", "edge"]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "op": {
+ "type": "string",
+ "const": "replace_action_edges"
+ },
+ "id": {
+ "type": "string",
+ "description": "Action id whose outgoing edges are being replaced."
+ },
+ "edges": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "from": {
+ "type": "string",
+ "description": "Source action id."
+ },
+ "to": {
+ "type": "string",
+ "description": "Target action id."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["continue", "branch"],
+ "description": "'continue' = fall-through (sequential or no-match path); 'branch' = a condition/cohort branch (needs index)."
+ },
+ "index": {
+ "description": "Required for type=branch: which condition/cohort slot this branch matches (0-based).",
+ "type": "integer",
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991
+ }
+ },
+ "required": ["from", "to", "type"]
+ },
+ "description": "The complete set of the action's outgoing edges; incoming edges are preserved."
+ }
+ },
+ "required": ["op", "id", "edges"]
+ }
+ ]
+ },
+ "description": "Ordered graph edits applied atomically: the stored graph is read, ops are applied in order, the result is fully validated, and it is saved only if valid — otherwise the workflow is left unchanged. Reference nodes/edges by id so you never resend the whole graph. The full updated workflow is returned."
+ }
+ },
+ "required": ["id", "operations"]
}
}
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 466b3e856cde..bf1454127d88 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -23234,6 +23234,48 @@ export namespace Schemas {
readonly updated_at: string;
}
+ /**
+ * * `update_action` - update_action
+ * * `add_action` - add_action
+ * * `remove_action` - remove_action
+ * * `add_edge` - add_edge
+ * * `remove_edge` - remove_edge
+ * * `replace_action_edges` - replace_action_edges
+ */
+ export type HogFlowGraphOperationOpEnum = typeof HogFlowGraphOperationOpEnum[keyof typeof HogFlowGraphOperationOpEnum];
+
+
+ export const HogFlowGraphOperationOpEnum = {
+ UpdateAction: 'update_action',
+ AddAction: 'add_action',
+ RemoveAction: 'remove_action',
+ AddEdge: 'add_edge',
+ RemoveEdge: 'remove_edge',
+ ReplaceActionEdges: 'replace_action_edges',
+ } as const;
+
+ export interface HogFlowGraphOperation {
+ /** Graph edit. update_action {id, patch}: deep-merge patch into the action's fields (a null leaf deletes that key) — the surgical path for tweaking one config value. add_action {action}: append a full action node. remove_action {id}: delete a node and reconnect its incoming edges to its first outgoer. add_edge {edge} / remove_edge {edge}: add or delete one edge. replace_action_edges {id, edges}: replace this action's outgoing edges with the given set (use when adding/removing branch conditions); incoming edges are left intact.
+ *
+ * * `update_action` - update_action
+ * * `add_action` - add_action
+ * * `remove_action` - remove_action
+ * * `add_edge` - add_edge
+ * * `remove_edge` - remove_edge
+ * * `replace_action_edges` - replace_action_edges */
+ op: HogFlowGraphOperationOpEnum;
+ /** Action id. Required for update_action, remove_action, replace_action_edges. */
+ id?: string;
+ /** update_action only. Partial action fields, deep-merged into the existing action; a null leaf deletes that key. e.g. {config: {inputs: {subject: {value: 'Hi'}}}} changes only that input. */
+ patch?: unknown;
+ /** add_action only. A full action node {id, name, type, config, ...}; same shape as in actions. */
+ action?: unknown;
+ /** add_edge / remove_edge only. The edge {from, to, type, index?}. */
+ edge?: HogFlowEdge;
+ /** replace_action_edges only. The complete set of the action's outgoing edges; incoming edges are preserved. */
+ edges?: HogFlowEdge[];
+ }
+
/**
* Test trigger payload, typically {event, person, groups}.
*/
@@ -23246,7 +23288,7 @@ export namespace Schemas {
globals?: HogFlowInvocationGlobals;
/** True (default) mocks HTTP/email/SMS. False fires real side effects. */
mock_async_functions?: boolean;
- /** Start from this action ID instead of the trigger. */
+ /** 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;
}
@@ -34654,6 +34696,11 @@ export namespace Schemas {
readonly schedules?: readonly HogFlowSchedule[];
}
+ export interface PatchedHogFlowGraphUpdate {
+ /** Ordered graph edits applied atomically to a draft workflow: the stored graph is read, the ops are applied in order, the result is fully validated, and it's saved only if valid — otherwise the workflow is unchanged. Reference nodes/edges by id so you never resend the whole graph. The full updated workflow is returned. */
+ operations?: HogFlowGraphOperation[];
+ }
+
export interface PatchedHogFlowSchedule {
readonly id?: string;
/** iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour. */
diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.ts
index 988cf035500b..60a3d0bb391d 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 12 enabled ops
+ * PostHog API - MCP 13 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -379,6 +379,100 @@ export const HogFlowsBatchJobsListParams = /* @__PURE__ */ zod.object({
),
})
+export const HogFlowsGraphPartialUpdateParams = /* @__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 HogFlowsGraphPartialUpdateBody = /* @__PURE__ */ zod.object({
+ operations: zod
+ .array(
+ zod.object({
+ op: zod
+ .enum([
+ 'update_action',
+ 'add_action',
+ 'remove_action',
+ 'add_edge',
+ 'remove_edge',
+ 'replace_action_edges',
+ ])
+ .describe(
+ '* `update_action` - update_action\n* `add_action` - add_action\n* `remove_action` - remove_action\n* `add_edge` - add_edge\n* `remove_edge` - remove_edge\n* `replace_action_edges` - replace_action_edges'
+ )
+ .describe(
+ "Graph edit. update_action {id, patch}: deep-merge patch into the action's fields (a null leaf deletes that key) — the surgical path for tweaking one config value. add_action {action}: append a full action node. remove_action {id}: delete a node and reconnect its incoming edges to its first outgoer. add_edge {edge} / remove_edge {edge}: add or delete one edge. replace_action_edges {id, edges}: replace this action's outgoing edges with the given set (use when adding/removing branch conditions); incoming edges are left intact.\n\n* `update_action` - update_action\n* `add_action` - add_action\n* `remove_action` - remove_action\n* `add_edge` - add_edge\n* `remove_edge` - remove_edge\n* `replace_action_edges` - replace_action_edges"
+ ),
+ id: zod
+ .string()
+ .optional()
+ .describe('Action id. Required for update_action, remove_action, replace_action_edges.'),
+ patch: zod
+ .unknown()
+ .optional()
+ .describe(
+ "update_action only. Partial action fields, deep-merged into the existing action; a null leaf deletes that key. e.g. {config: {inputs: {subject: {value: 'Hi'}}}} changes only that input."
+ ),
+ action: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'add_action only. A full action node {id, name, type, config, ...}; same shape as in actions.'
+ ),
+ edge: zod
+ .object({
+ to: zod.string().describe('Target action id.'),
+ type: zod
+ .enum(['continue', 'branch'])
+ .describe('* `continue` - continue\n* `branch` - branch')
+ .describe(
+ "continue: fall-through (sequential or the no-match path of conditional_branch). branch: requires 'index' matching config.conditions[index].\n\n* `continue` - continue\n* `branch` - branch"
+ ),
+ index: zod
+ .number()
+ .optional()
+ .describe(
+ "Required for type='branch'. Index into config.conditions on conditional_branch / wait_until_condition."
+ ),
+ from: zod.string().describe('Source action id.'),
+ })
+ .optional()
+ .describe('add_edge / remove_edge only. The edge {from, to, type, index?}.'),
+ edges: zod
+ .array(
+ zod.object({
+ to: zod.string().describe('Target action id.'),
+ type: zod
+ .enum(['continue', 'branch'])
+ .describe('* `continue` - continue\n* `branch` - branch')
+ .describe(
+ "continue: fall-through (sequential or the no-match path of conditional_branch). branch: requires 'index' matching config.conditions[index].\n\n* `continue` - continue\n* `branch` - branch"
+ ),
+ index: zod
+ .number()
+ .optional()
+ .describe(
+ "Required for type='branch'. Index into config.conditions on conditional_branch / wait_until_condition."
+ ),
+ from: zod.string().describe('Source action id.'),
+ })
+ )
+ .optional()
+ .describe(
+ "replace_action_edges only. The complete set of the action's outgoing edges; incoming edges are preserved."
+ ),
+ })
+ )
+ .optional()
+ .describe(
+ "Ordered graph edits applied atomically to a draft workflow: the stored graph is read, the ops are applied in order, the result is fully validated, and it's saved only if valid — otherwise the workflow is unchanged. Reference nodes/edges by id so you never resend the whole graph. The full updated workflow is returned."
+ ),
+})
+
export const HogFlowsInvocationResultsRetrieveParams = /* @__PURE__ */ zod.object({
id: zod.string().describe('A UUID string identifying this hog flow.'),
project_id: zod
@@ -454,7 +548,12 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({
.boolean()
.default(hogFlowsInvocationsCreateBodyMockAsyncFunctionsDefault)
.describe('True (default) mocks HTTP/email/SMS. False fires real side effects.'),
- current_action_id: zod.string().optional().describe('Start from this action ID instead of the trigger.'),
+ current_action_id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Start execution from this action ID instead of the trigger. Each test run executes a single node and returns the next action id.'
+ ),
})
export const HogFlowsLogsRetrieveParams = /* @__PURE__ */ zod.object({
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 69cc9949f78f..504a07fa807d 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -396,6 +396,73 @@ export function validateDistinctIdPersonIdExclusive(
}
}
+const WorkflowGraphEdgeSchema = z.object({
+ from: z.string().describe('Source action id.'),
+ to: z.string().describe('Target action id.'),
+ type: z
+ .enum(['continue', 'branch'])
+ .describe(
+ "'continue' = fall-through (sequential or no-match path); 'branch' = a condition/cohort branch (needs index)."
+ ),
+ index: z
+ .number()
+ .int()
+ .optional()
+ .describe('Required for type=branch: which condition/cohort slot this branch matches (0-based).'),
+})
+
+const WorkflowGraphOperationSchema = z.discriminatedUnion('op', [
+ z.object({
+ op: z.literal('update_action'),
+ id: z.string().describe('Id of the action to update.'),
+ patch: z
+ .record(z.string(), z.unknown())
+ .describe(
+ 'Partial action fields, deep-merged into the existing action; a null leaf deletes that key. ' +
+ 'e.g. {config: {inputs: {subject: {value: "Hi"}}}} changes only that one input.'
+ ),
+ }),
+ z.object({
+ op: z.literal('add_action'),
+ action: z
+ .record(z.string(), z.unknown())
+ .describe(
+ 'A full action node {id, name, type, config, ...}; same shape as entries in the workflow actions array.'
+ ),
+ }),
+ z.object({
+ op: z.literal('remove_action'),
+ id: z.string().describe('Id of the action to remove. Its incoming edges reconnect to its first outgoer.'),
+ }),
+ z.object({
+ op: z.literal('add_edge'),
+ edge: WorkflowGraphEdgeSchema.describe('The edge to add.'),
+ }),
+ z.object({
+ op: z.literal('remove_edge'),
+ edge: WorkflowGraphEdgeSchema.describe('The edge to remove (matched on from/to/type/index).'),
+ }),
+ z.object({
+ op: z.literal('replace_action_edges'),
+ id: z.string().describe('Action id whose outgoing edges are being replaced.'),
+ edges: z
+ .array(WorkflowGraphEdgeSchema)
+ .describe("The complete set of the action's outgoing edges; incoming edges are preserved."),
+ }),
+])
+
+export const WorkflowGraphPatchSchema = z.object({
+ id: z.string().describe('The workflow (HogFlow) id to edit. Draft only — active workflows are read-only via MCP.'),
+ operations: z
+ .array(WorkflowGraphOperationSchema)
+ .min(1)
+ .describe(
+ 'Ordered graph edits applied atomically: the stored graph is read, ops are applied in order, the result ' +
+ 'is fully validated, and it is saved only if valid — otherwise the workflow is left unchanged. Reference ' +
+ 'nodes/edges by id so you never resend the whole graph. The full updated workflow is returned.'
+ ),
+})
+
// Surgical edits to an email template's Unlayer design — one discriminated op per change, addressed by
// the stable block id. Mirrors DesignOperationSerializer; kept as a hand-authored discriminated union so
// the LLM sees exactly which fields each op needs (the auto-generated PATCH schema flattens them all to
diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.ts
index 22d09c5eb041..cf4f32e9a5df 100644
--- a/services/mcp/src/tools/generated/workflows.ts
+++ b/services/mcp/src/tools/generated/workflows.ts
@@ -23,6 +23,7 @@ import {
HogFlowsSchedulesPartialUpdateParams,
} from '@/generated/workflows/api'
import { withUiApp } from '@/resources/ui-apps'
+import { WorkflowGraphPatchSchema } from '@/schema/tool-inputs'
import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
@@ -222,6 +223,24 @@ const workflowsLogs = (): ToolBase<typeof WorkflowsLogsSchema, unknown> => ({
},
})
+const WorkflowsPatchGraphSchema = WorkflowGraphPatchSchema
+
+const workflowsPatchGraph = (): ToolBase<typeof WorkflowsPatchGraphSchema, Schemas.HogFlow> => ({
+ name: 'workflows-patch-graph',
+ schema: WorkflowsPatchGraphSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsPatchGraphSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const parsedParams = WorkflowsPatchGraphSchema.parse(params)
+ const { id, ...body } = parsedParams
+ const result = await context.api.request<Schemas.HogFlow>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(id))}/graph/`,
+ body,
+ })
+ return result
+ },
+})
+
const WorkflowsStatsSchema = HogFlowsMetricsRetrieveParams.omit({ project_id: true }).extend(
HogFlowsMetricsRetrieveQueryParams.shape
)
@@ -360,6 +379,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'workflows-list-batch-jobs': workflowsListBatchJobs,
'workflows-list-invocations': workflowsListInvocations,
'workflows-logs': workflowsLogs,
+ 'workflows-patch-graph': workflowsPatchGraph,
'workflows-stats': workflowsStats,
'workflows-test-run': workflowsTestRun,
'workflows-update': workflowsUpdate,
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.json
new file mode 100644
index 000000000000..82ece5196011
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-graph.json
@@ -0,0 +1,189 @@
+{
+ "$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.",
+ "type": "string"
+ },
+ "operations": {
+ "description": "Ordered graph edits applied atomically: the stored graph is read, ops are applied in order, the result is fully validated, and it is saved only if valid — otherwise the workflow is left unchanged. Reference nodes/edges by id so you never resend the whole graph. The full updated workflow is returned.",
+ "items": {
+ "oneOf": [
+ {
+ "properties": {
+ "id": {
+ "description": "Id of the action to update.",
+ "type": "string"
+ },
+ "op": {
+ "const": "update_action",
+ "type": "string"
+ },
+ "patch": {
+ "additionalProperties": {},
+ "description": "Partial action fields, deep-merged into the existing action; a null leaf deletes that key. e.g. {config: {inputs: {subject: {value: \"Hi\"}}}} changes only that one input.",
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ }
+ },
+ "required": ["op", "id", "patch"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "action": {
+ "additionalProperties": {},
+ "description": "A full action node {id, name, type, config, ...}; same shape as entries in the workflow actions array.",
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ "op": {
+ "const": "add_action",
+ "type": "string"
+ }
+ },
+ "required": ["op", "action"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "id": {
+ "description": "Id of the action to remove. Its incoming edges reconnect to its first outgoer.",
+ "type": "string"
+ },
+ "op": {
+ "const": "remove_action",
+ "type": "string"
+ }
+ },
+ "required": ["op", "id"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "edge": {
+ "description": "The edge to add.",
+ "properties": {
+ "from": {
+ "description": "Source action id.",
+ "type": "string"
+ },
+ "index": {
+ "description": "Required for type=branch: which condition/cohort slot this branch matches (0-based).",
+ "maximum": 9007199254740991,
+ "minimum": -9007199254740991,
+ "type": "integer"
+ },
+ "to": {
+ "description": "Target action id.",
+ "type": "string"
+ },
+ "type": {
+ "description": "'continue' = fall-through (sequential or no-match path); 'branch' = a condition/cohort branch (needs index).",
+ "enum": ["continue", "branch"],
+ "type": "string"
+ }
+ },
+ "required": ["from", "to", "type"],
+ "type": "object"
+ },
+ "op": {
+ "const": "add_edge",
+ "type": "string"
+ }
+ },
+ "required": ["op", "edge"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "edge": {
+ "description": "The edge to remove (matched on from/to/type/index).",
+ "properties": {
+ "from": {
+ "description": "Source action id.",
+ "type": "string"
+ },
+ "index": {
+ "description": "Required for type=branch: which condition/cohort slot this branch matches (0-based).",
+ "maximum": 9007199254740991,
+ "minimum": -9007199254740991,
+ "type": "integer"
+ },
+ "to": {
+ "description": "Target action id.",
+ "type": "string"
+ },
+ "type": {
+ "description": "'continue' = fall-through (sequential or no-match path); 'branch' = a condition/cohort branch (needs index).",
+ "enum": ["continue", "branch"],
+ "type": "string"
+ }
+ },
+ "required": ["from", "to", "type"],
+ "type": "object"
+ },
+ "op": {
+ "const": "remove_edge",
+ "type": "string"
+ }
+ },
+ "required": ["op", "edge"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "edges": {
+ "description": "The complete set of the action's outgoing edges; incoming edges are preserved.",
+ "items": {
+ "properties": {
+ "from": {
+ "description": "Source action id.",
+ "type": "string"
+ },
+ "index": {
+ "description": "Required for type=branch: which condition/cohort slot this branch matches (0-based).",
+ "maximum": 9007199254740991,
+ "minimum": -9007199254740991,
+ "type": "integer"
+ },
+ "to": {
+ "description": "Target action id.",
+ "type": "string"
+ },
+ "type": {
+ "description": "'continue' = fall-through (sequential or no-match path); 'branch' = a condition/cohort branch (needs index).",
+ "enum": ["continue", "branch"],
+ "type": "string"
+ }
+ },
+ "required": ["from", "to", "type"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "id": {
+ "description": "Action id whose outgoing edges are being replaced.",
+ "type": "string"
+ },
+ "op": {
+ "const": "replace_action_edges",
+ "type": "string"
+ }
+ },
+ "required": ["op", "id", "edges"],
+ "type": "object"
+ }
+ ]
+ },
+ "minItems": 1,
+ "type": "array"
+ }
+ },
+ "required": ["id", "operations"],
+ "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.json
index 6e1f336a725d..9056741f39d8 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
@@ -2,7 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"current_action_id": {
- "description": "Start from this action ID instead of the trigger.",
+ "description": "Start execution from this action ID instead of the trigger. Each test run executes a single node and returns the next action id.",
"type": "string"
},
"globals": {