Skip to content

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

feat(workflows): add invocation debugging MCP tools and align names (#61655)

Harley Alexander64c5a4efdd39
diff --git a/posthog/api/app_metrics2.py b/posthog/api/app_metrics2.py
index fc7d81565a47..6353bc65d9b6 100644
--- a/posthog/api/app_metrics2.py
+++ b/posthog/api/app_metrics2.py
@@ -242,6 +242,56 @@ def fetch_app_metric_totals(
return AppMetricsTotalsResponse(totals=totals)
+def fetch_app_metric_totals_by_source(
+ team_id: int,
+ app_source: str,
+ after: Optional[datetime] = None,
+ before: Optional[datetime] = None,
+ name: Optional[list[str]] = None,
+) -> dict[str, dict[str, int]]:
+ """Per-`app_source_id` metric totals for a whole team in one grouped query.
+
+ Unlike `fetch_app_metric_totals` (single object), this drops the `app_source_id`
+ filter and groups by it, so callers get counts for every object at once — e.g. a
+ failure overview across all workflows. Returns `{app_source_id: {metric_name: count}}`.
+ """
+ name = name or ["succeeded", "failed"]
+
+ # Convert to UTC before formatting — the naive string is read as UTC by toDateTime64, so a
+ # team-timezone-aware bound would otherwise shift the window by the team's offset.
+ clickhouse_kwargs: dict[str, Any] = {
+ "team_id": team_id,
+ "app_source": app_source,
+ "after": after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S") if after else None,
+ "before": before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S") if before else None,
+ "name": name,
+ }
+
+ clickhouse_query = f"""
+ SELECT
+ app_source_id,
+ metric_name,
+ sum(count) as count
+ FROM app_metrics2
+ WHERE team_id = %(team_id)s
+ AND app_source = %(app_source)s
+ {"AND timestamp >= toDateTime64(%(after)s, 6)" if after else ""}
+ {"AND timestamp <= toDateTime64(%(before)s, 6)" if before else ""}
+ AND metric_name IN %(name)s
+ GROUP BY app_source_id, metric_name
+ """
+
+ results = sync_execute(clickhouse_query, clickhouse_kwargs)
+
+ if not isinstance(results, list):
+ raise ValueError("Unexpected results from ClickHouse")
+
+ totals: dict[str, dict[str, int]] = {}
+ for app_source_id, metric_name, count in results:
+ totals.setdefault(app_source_id, {})[metric_name] = count
+ return totals
+
+
class AppMetricsMixin(viewsets.GenericViewSet):
app_source: str # Should be set by the inheriting class
diff --git a/posthog/api/hog_invocation_results.py b/posthog/api/hog_invocation_results.py
new file mode 100644
index 000000000000..3b208ba4e7ca
--- /dev/null
+++ b/posthog/api/hog_invocation_results.py
@@ -0,0 +1,271 @@
+import gzip
+import json
+import base64
+import dataclasses
+from datetime import UTC, datetime
+from typing import Any, Optional, cast
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import extend_schema_field
+from rest_framework import serializers
+from rest_framework_dataclasses.serializers import DataclassSerializer
+
+from posthog.schema import ProductKey
+
+from posthog.clickhouse.client.execute import sync_execute
+from posthog.clickhouse.query_tagging import Feature, tag_queries
+
+FUNCTION_KIND_TO_PRODUCT_KEY: dict[str, ProductKey] = {
+ "hog_function": ProductKey.PIPELINE_DESTINATIONS,
+ "hog_flow": ProductKey.WORKFLOWS,
+}
+
+
+def tag_invocation_results_query(function_kind: str) -> None:
+ product_key = FUNCTION_KIND_TO_PRODUCT_KEY.get(function_kind, ProductKey.PIPELINE_DESTINATIONS)
+ tag_queries(product=product_key, feature=Feature.QUERY)
+
+
+# Per-invocation lifecycle rows (start/finish/retries) collapse to the latest
+# `version`. The argMax aliases are deliberately NOT named after their source
+# columns: ClickHouse's analyzer resolves a name in WHERE/HAVING to a same-named
+# SELECT alias (prefer_column_name_to_alias=0), so reusing e.g. `status` would
+# turn `WHERE status = …` into `argMax(status) = …` (aggregate-in-WHERE error).
+# We collapse in a subquery, then filter the raw columns in the inner WHERE and
+# the aggregated `latest_*` columns in the outer WHERE. Column order is matched
+# positionally against HogInvocationResult when building the dataclass.
+_COLLAPSED_AGGREGATES = """
+ invocation_id,
+ argMax(status, version) AS latest_status,
+ argMax(error_kind, version) AS latest_error_kind,
+ argMax(error_message, version) AS latest_error_message,
+ argMax(distinct_id, version) AS latest_distinct_id,
+ argMax(person_id, version) AS latest_person_id,
+ min(scheduled_at) AS latest_scheduled_at,
+ argMax(started_at, version) AS latest_started_at,
+ argMax(finished_at, version) AS latest_finished_at,
+ argMax(duration_ms, version) AS latest_duration_ms,
+ argMax(attempts, version) AS latest_attempts,
+ argMax(is_retry, version) AS latest_is_retry,
+ argMax(is_deleted, version) AS latest_is_deleted
+""".strip()
+
+# Outer projection, in HogInvocationResult field order.
+_OUTER_COLUMNS = """
+ invocation_id,
+ latest_status,
+ latest_error_kind,
+ latest_error_message,
+ latest_distinct_id,
+ latest_person_id,
+ latest_scheduled_at,
+ latest_started_at,
+ latest_finished_at,
+ latest_duration_ms,
+ latest_attempts,
+ latest_is_retry
+""".strip()
+
+
[email protected](frozen=True)
+class HogInvocationResult:
+ invocation_id: str
+ status: str
+ error_kind: str
+ error_message: str
+ distinct_id: str
+ person_id: str
+ scheduled_at: datetime
+ started_at: Optional[datetime]
+ finished_at: Optional[datetime]
+ duration_ms: Optional[int]
+ attempts: int
+ is_retry: bool
+
+
[email protected](frozen=True)
+class HogInvocationResultDetail(HogInvocationResult):
+ # The triggering payload (event/person/groups) the run executed against, decoded from the
+ # stored gzip+base64 blob into a JSON object so callers get structured data directly. Shape
+ # is caller-defined and unbounded.
+ invocation_globals: dict[str, Any]
+
+
+def _decode_invocation_globals(stored: str) -> dict[str, Any]:
+ """Decode the stored invocation_globals into a JSON object.
+
+ The producer gzip-compresses then base64-encodes the payload (see the Node
+ hog-invocation-results service). Legacy rows predate compression and are stored
+ as raw JSON, detected by a leading '{'. A decode failure degrades to an empty
+ object so one malformed row can't 500 the whole request.
+ """
+ if not stored:
+ return {}
+ try:
+ decoded = stored if stored.startswith("{") else gzip.decompress(base64.b64decode(stored)).decode("utf-8")
+ parsed = json.loads(decoded)
+ except (ValueError, OSError, EOFError):
+ return {}
+ return parsed if isinstance(parsed, dict) else {}
+
+
+class HogInvocationResultSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = HogInvocationResult
+
+
+@extend_schema_field(OpenApiTypes.OBJECT)
+class InvocationGlobalsField(serializers.JSONField):
+ pass
+
+
+class HogInvocationResultDetailSerializer(DataclassSerializer):
+ invocation_globals = InvocationGlobalsField(
+ help_text="The triggering payload (event/person/groups) the run executed against, as a JSON object."
+ )
+
+ class Meta:
+ dataclass = HogInvocationResultDetail
+
+
+class HogInvocationResultsRequestSerializer(serializers.Serializer):
+ status = serializers.CharField(
+ required=False,
+ help_text="Comma-separated invocation statuses to include, e.g. 'failed' or 'success,failed'.",
+ )
+ distinct_id = serializers.CharField(
+ required=False,
+ help_text="Only return invocations triggered for this distinct_id (the person the run executed for).",
+ )
+ after = serializers.CharField(
+ required=False,
+ default="-7d",
+ help_text="Start of the time range, matched on scheduled time. Relative ('-7d', '-24h') or ISO 8601. "
+ "Defaults to -7d — bounds the ClickHouse partition scan, so widen it explicitly for older runs.",
+ )
+ before = serializers.CharField(
+ required=False,
+ help_text="End of the time range, matched on scheduled time. Same format as 'after'. Defaults to now.",
+ )
+ limit = serializers.IntegerField(
+ required=False,
+ default=50,
+ max_value=500,
+ min_value=1,
+ help_text="Maximum number of invocations to return (1-500, default 50).",
+ )
+
+
+def _build_invocation(row: tuple, detail: bool) -> Any:
+ common = {
+ "invocation_id": row[0],
+ "status": row[1],
+ "error_kind": row[2],
+ "error_message": row[3],
+ "distinct_id": row[4],
+ "person_id": row[5],
+ "scheduled_at": row[6],
+ "started_at": row[7],
+ "finished_at": row[8],
+ "duration_ms": row[9],
+ "attempts": row[10],
+ "is_retry": bool(row[11]),
+ }
+ if detail:
+ return HogInvocationResultDetail(**common, invocation_globals=_decode_invocation_globals(row[12]))
+ return HogInvocationResult(**common)
+
+
+def fetch_hog_invocation_results(
+ team_id: int,
+ function_kind: str,
+ function_id: str,
+ limit: int,
+ status: Optional[list[str]] = None,
+ distinct_id: Optional[str] = None,
+ after: Optional[datetime] = None,
+ before: Optional[datetime] = None,
+) -> list[HogInvocationResult]:
+ """List a function's invocations, each collapsed to its latest lifecycle state."""
+ where = [
+ "team_id = %(team_id)s",
+ "function_kind = %(function_kind)s",
+ "function_id = %(function_id)s",
+ ]
+ kwargs: dict[str, Any] = {
+ "team_id": team_id,
+ "function_kind": function_kind,
+ "function_id": function_id,
+ "limit": limit,
+ }
+
+ # distinct_id is invocation identity — stable across lifecycle rows — so filter
+ # it pre-aggregation on the raw column. status changes start→finish, so it's
+ # filtered post-collapse on the aggregated `latest_status` in the outer WHERE.
+ if distinct_id:
+ where.append("distinct_id = %(distinct_id)s")
+ kwargs["distinct_id"] = distinct_id
+ # `after`/`before` come in as team-timezone-aware datetimes; convert to UTC before formatting so
+ # the naive string matches the UTC `scheduled_at` column (toDateTime64 reads it as UTC). Skipping
+ # this shifts the window by the team's offset — wrong for short windows on non-UTC teams.
+ if after:
+ where.append("scheduled_at >= toDateTime64(%(after)s, 6)")
+ kwargs["after"] = after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")
+ if before:
+ where.append("scheduled_at <= toDateTime64(%(before)s, 6)")
+ kwargs["before"] = before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")
+
+ outer_where = ["latest_is_deleted = 0"]
+ if status:
+ outer_where.append("latest_status IN %(statuses)s")
+ kwargs["statuses"] = status
+
+ query = f"""
+ SELECT {_OUTER_COLUMNS}
+ FROM (
+ SELECT {_COLLAPSED_AGGREGATES}
+ FROM hog_invocation_results
+ WHERE {" AND ".join(where)}
+ GROUP BY invocation_id
+ )
+ WHERE {" AND ".join(outer_where)}
+ ORDER BY latest_scheduled_at DESC
+ LIMIT %(limit)s
+ """
+
+ results = cast(list, sync_execute(query, kwargs))
+ return [_build_invocation(row, detail=False) for row in results]
+
+
+def fetch_hog_invocation_result(
+ team_id: int,
+ function_kind: str,
+ function_id: str,
+ invocation_id: str,
+) -> Optional[HogInvocationResultDetail]:
+ """Fetch a single invocation by id, including its triggering payload."""
+ kwargs = {
+ "team_id": team_id,
+ "function_kind": function_kind,
+ "function_id": function_id,
+ "invocation_id": invocation_id,
+ }
+ query = f"""
+ SELECT {_OUTER_COLUMNS}, latest_invocation_globals
+ FROM (
+ SELECT {_COLLAPSED_AGGREGATES},
+ argMax(invocation_globals, version) AS latest_invocation_globals
+ FROM hog_invocation_results
+ WHERE team_id = %(team_id)s
+ AND function_kind = %(function_kind)s
+ AND function_id = %(function_id)s
+ AND invocation_id = %(invocation_id)s
+ GROUP BY invocation_id
+ )
+ WHERE latest_is_deleted = 0
+ """
+
+ results = cast(list, sync_execute(query, kwargs))
+ if not results:
+ return None
+ return _build_invocation(results[0], detail=True)
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 9d6aaf119850..f8dc3cb12b6c 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -18,8 +18,18 @@ from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.serializers import BaseSerializer
-from posthog.api.app_metrics2 import AppMetricsMixin
+from posthog.schema import ProductKey
+
+from posthog.api.app_metrics2 import AppMetricsMixin, fetch_app_metric_totals_by_source
from posthog.api.documentation import _FallbackSerializer
+from posthog.api.hog_invocation_results import (
+ HogInvocationResultDetailSerializer,
+ HogInvocationResultSerializer,
+ HogInvocationResultsRequestSerializer,
+ fetch_hog_invocation_result,
+ fetch_hog_invocation_results,
+ tag_invocation_results_query,
+)
from posthog.api.log_entries import LogEntryMixin
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
@@ -31,9 +41,11 @@ from posthog.cdp.validation import (
InputsSerializer,
generate_template_bytecode,
)
+from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.event_usage import EventSource, get_event_source
from posthog.models import Team
from posthog.plugins.plugin_server_api import create_hog_flow_invocation_test, create_hog_flow_scheduled_invocation
+from posthog.utils import relative_date_parse_with_delta_mapping
from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
from products.cohorts.backend.models.cohort import Cohort
@@ -68,6 +80,24 @@ class BlastRadiusSerializer(serializers.Serializer):
total = serializers.IntegerField(help_text="Total number of users")
+class WorkflowGlobalStatsRequestSerializer(serializers.Serializer):
+ after = serializers.CharField(
+ required=False,
+ default="-7d",
+ help_text="Start of the window, matched on metric time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d.",
+ )
+ before = serializers.CharField(
+ required=False,
+ help_text="End of the window. Same format as 'after'. Defaults to now.",
+ )
+
+
+class WorkflowStatsRowSerializer(serializers.Serializer):
+ workflow_id = serializers.CharField(help_text="The workflow these counts are for.")
+ succeeded = serializers.IntegerField(help_text="Successful invocations in the window.")
+ failed = serializers.IntegerField(help_text="Failed invocations in the window.")
+
+
class HogFlowConfigFunctionInputsSerializer(serializers.Serializer):
inputs_schema = serializers.ListField(child=InputsSchemaItemSerializer(), required=False)
inputs = InputsSerializer(required=False)
@@ -674,7 +704,15 @@ class HogFlowFilterSet(FilterSet):
@extend_schema(extensions={"x-product": "workflows"})
class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, viewsets.ModelViewSet):
scope_object = "hog_flow"
- scope_object_read_actions = ["list", "retrieve", "logs", "metrics", "metrics_totals", "user_blast_radius"]
+ scope_object_read_actions = [
+ "list",
+ "retrieve",
+ "logs",
+ "metrics",
+ "metrics_totals",
+ "metrics_global",
+ "user_blast_radius",
+ ]
scope_object_write_actions = [
"create",
"update",
@@ -689,6 +727,7 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie
filterset_class = HogFlowFilterSet
log_source = "hog_flow"
app_source = "hog_flow"
+ function_kind = "hog_flow"
def dangerously_get_required_scopes(self, request, view) -> Optional[list[str]]:
# Dual-method custom actions need method-aware scopes — the action-name-based read/write
@@ -702,6 +741,12 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie
# session auth, so live sizing while editing is unaffected.
if self.action == "user_blast_radius":
return ["hog_flow:read", "person:read"]
+ # Invocation inspection returns distinct_id / person_id and the raw triggering payload
+ # (invocation_globals: event/person/groups), so it's person-data access — require person:read
+ # on top of workflow read, same as user_blast_radius. A hog_flow:read-only token must not be
+ # able to enumerate who a workflow ran for.
+ if self.action in ("invocation_results", "invocation_result"):
+ return ["hog_flow:read", "person:read"]
# A test invocation resolves the event's $groups into real group properties server-side, so a
# hog_flow:write-only token could branch on group_0.properties and read the returned logs/variables
# as a group-property oracle. Require group:read on top. The web builder uses session auth, so
@@ -740,7 +785,7 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie
if self._is_mcp_request(self.request) and serializer.validated_data.get("status") == HogFlow.State.ACTIVE:
raise exceptions.ValidationError(
"You can't one-shot active workflows via MCP. "
- "Create as draft, test with workflows-run, then enable with workflows-enable."
+ "Create as draft, test with workflows-test-run, then enable with workflows-enable."
)
serializer.save()
@@ -871,6 +916,111 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie
return Response(BlastRadiusSerializer(result).data)
+ @extend_schema(
+ operation_id="hog_flows_invocation_results_retrieve",
+ parameters=[HogInvocationResultsRequestSerializer],
+ responses=HogInvocationResultSerializer(many=True),
+ )
+ @action(detail=True, methods=["GET"], pagination_class=None, filter_backends=[])
+ def invocation_results(self, request: Request, *args, **kwargs):
+ obj = self.get_object()
+ tag_invocation_results_query(self.function_kind)
+
+ param_serializer = HogInvocationResultsRequestSerializer(data=request.query_params)
+ param_serializer.is_valid(raise_exception=True)
+ params = param_serializer.validated_data
+
+ after_date = None
+ before_date = None
+ if params.get("after"):
+ after_date, _, _ = relative_date_parse_with_delta_mapping(params["after"], self.team.timezone_info)
+ if params.get("before"):
+ before_date, _, _ = relative_date_parse_with_delta_mapping(params["before"], self.team.timezone_info)
+
+ data = fetch_hog_invocation_results(
+ team_id=self.team_id,
+ function_kind=self.function_kind,
+ function_id=str(obj.id),
+ limit=params["limit"],
+ status=params["status"].split(",") if params.get("status") else None,
+ distinct_id=params.get("distinct_id"),
+ after=after_date,
+ before=before_date,
+ )
+ return Response(HogInvocationResultSerializer(data, many=True).data)
+
+ @extend_schema(
+ operation_id="hog_flows_invocation_result_retrieve",
+ parameters=[OpenApiParameter("invocation_id", str, OpenApiParameter.PATH)],
+ responses=HogInvocationResultDetailSerializer,
+ )
+ @action(
+ detail=True,
+ methods=["GET"],
+ url_path="invocation_results/(?P<invocation_id>[^/.]+)",
+ filter_backends=[],
+ )
+ def invocation_result(self, request: Request, *args, **kwargs):
+ obj = self.get_object()
+ tag_invocation_results_query(self.function_kind)
+
+ data = fetch_hog_invocation_result(
+ team_id=self.team_id,
+ function_kind=self.function_kind,
+ function_id=str(obj.id),
+ invocation_id=kwargs["invocation_id"],
+ )
+ if data is None:
+ raise exceptions.NotFound("Invocation not found.")
+ return Response(HogInvocationResultDetailSerializer(data).data)
+
+ @extend_schema(
+ operation_id="hog_flows_metrics_global_retrieve",
+ parameters=[WorkflowGlobalStatsRequestSerializer],
+ responses=WorkflowStatsRowSerializer(many=True),
+ )
+ @action(detail=False, methods=["GET"], pagination_class=None, filter_backends=[], url_path="metrics/global")
+ def metrics_global(self, request: Request, *args, **kwargs):
+ param_serializer = WorkflowGlobalStatsRequestSerializer(data=request.query_params)
+ param_serializer.is_valid(raise_exception=True)
+ params = param_serializer.validated_data
+
+ tag_queries(product=ProductKey.WORKFLOWS, feature=Feature.QUERY)
+
+ after_date, _, _ = relative_date_parse_with_delta_mapping(params["after"], self.team.timezone_info)
+ before_date = None
+ if params.get("before"):
+ before_date, _, _ = relative_date_parse_with_delta_mapping(params["before"], self.team.timezone_info)
+
+ totals = fetch_app_metric_totals_by_source(
+ team_id=self.team_id,
+ app_source=self.app_source,
+ after=after_date,
+ before=before_date,
+ )
+ # The ClickHouse query is only team-scoped, so intersect with the workflows the caller can
+ # actually see. Keeps the aggregate consistent with workflows-list/-get access control (hog
+ # flows aren't an access-control resource today, so this is a no-op now but won't silently
+ # become a bypass if they become one), and drops orphaned metrics for since-deleted workflows.
+ accessible_ids = {
+ str(pk)
+ for pk in self.user_access_control.filter_queryset_by_access_level(self.get_queryset()).values_list(
+ "id", flat=True
+ )
+ }
+ rows: list[dict[str, object]] = [
+ {
+ "workflow_id": workflow_id,
+ "succeeded": counts.get("succeeded", 0),
+ "failed": counts.get("failed", 0),
+ }
+ for workflow_id, counts in totals.items()
+ if workflow_id in accessible_ids
+ ]
+ # Surface the most-failing workflows first — this is the at-a-glance triage view.
+ rows.sort(key=lambda row: cast(int, row["failed"]), reverse=True)
+ return Response(WorkflowStatsRowSerializer(rows, many=True).data)
+
@action(methods=["POST"], detail=False)
def bulk_delete(self, request: Request, **kwargs):
ids = request.data.get("ids", [])
diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.py
index 43f6674f3ef0..209e5a1e91f1 100644
--- a/products/workflows/backend/api/test/test_hog_flow.py
+++ b/products/workflows/backend/api/test/test_hog_flow.py
@@ -1,6 +1,7 @@
+from datetime import UTC, datetime, timedelta
from typing import Optional
-from posthog.test.base import APIBaseTest
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -11,6 +12,7 @@ from posthog.cdp.templates.slack.template_slack import template as template_slac
from posthog.models import Organization, Team, User
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.test.fixtures import create_app_metric2
from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
from products.cohorts.backend.models.cohort import Cohort
@@ -1998,3 +2000,102 @@ class TestHogFlowAPI(APIBaseTest):
assert response.status_code == expected_status, response.json()
if expected_error:
assert response.json()["detail"] == expected_error
+
+
+class TestHogFlowGlobalStats(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.flow_a = HogFlow.objects.create(team=self.team, name="Flow A")
+ self.flow_b = HogFlow.objects.create(team=self.team, name="Flow B")
+
+ def _global(self, params=None):
+ return self.client.get(f"/api/projects/{self.team.id}/hog_flows/metrics/global/", params)
+
+ def _seed(self, workflow_id, *, succeeded=0, failed=0, timestamp=None, team_id=None, app_source="hog_flow"):
+ tid = team_id or self.team.pk
+ if succeeded:
+ create_app_metric2(
+ team_id=tid,
+ app_source=app_source,
+ app_source_id=str(workflow_id),
+ metric_kind="success",
+ metric_name="succeeded",
+ count=succeeded,
+ timestamp=timestamp,
+ )
+ if failed:
+ create_app_metric2(
+ team_id=tid,
+ app_source=app_source,
+ app_source_id=str(workflow_id),
+ metric_kind="failure",
+ metric_name="failed",
+ count=failed,
+ timestamp=timestamp,
+ )
+
+ def test_returns_empty_when_no_metrics(self):
+ res = self._global()
+ assert res.status_code == status.HTTP_200_OK
+ assert res.json() == []
+
+ def test_aggregates_per_workflow_sorted_most_failing_first(self):
+ self._seed(self.flow_a.id, succeeded=3, failed=1)
+ self._seed(self.flow_b.id, succeeded=5, failed=4)
+ rows = self._global().json()
+ by_id = {r["workflow_id"]: r for r in rows}
+ assert by_id[str(self.flow_a.id)] == {"workflow_id": str(self.flow_a.id), "succeeded": 3, "failed": 1}
+ assert by_id[str(self.flow_b.id)] == {"workflow_id": str(self.flow_b.id), "succeeded": 5, "failed": 4}
+ # Most-failing first.
+ assert rows[0]["workflow_id"] == str(self.flow_b.id)
+
+ def test_time_window_filter(self):
+ now = datetime.now(tz=UTC)
+ self._seed(self.flow_a.id, failed=4, timestamp=now)
+ self._seed(self.flow_a.id, failed=9, timestamp=now - timedelta(days=30))
+ recent = {r["workflow_id"]: r for r in self._global({"after": "-7d"}).json()}
+ assert recent[str(self.flow_a.id)]["failed"] == 4
+ wide = {r["workflow_id"]: r for r in self._global({"after": "-60d"}).json()}
+ assert wide[str(self.flow_a.id)]["failed"] == 13
+
+ def test_after_filter_respects_team_timezone(self):
+ # PT is UTC-7 in June, so after='2026-06-08T00:00:00' resolves to 07:00 UTC. The 06:00 UTC
+ # row must fall outside the window and the 08:00 UTC row inside — a naive bound read as
+ # 00:00 UTC would count both.
+ self.team.timezone = "America/Los_Angeles"
+ self.team.save()
+ self._seed(self.flow_a.id, failed=1, timestamp=datetime(2026, 6, 8, 6, 0, 0, tzinfo=UTC))
+ self._seed(self.flow_a.id, failed=1, timestamp=datetime(2026, 6, 8, 8, 0, 0, tzinfo=UTC))
+ rows = self._global({"after": "2026-06-08T00:00:00", "before": "2026-06-09T00:00:00"}).json()
+ assert {r["workflow_id"]: r["failed"] for r in rows} == {str(self.flow_a.id): 1}
+
+ def test_isolated_from_other_team_and_app_source(self):
+ self._seed(self.flow_a.id, succeeded=2)
+ # Same id but a hog_function metric, and another team — neither must leak in.
+ self._seed(self.flow_a.id, succeeded=7, app_source="hog_function")
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ self._seed(self.flow_a.id, succeeded=99, team_id=other_team.pk)
+ rows = self._global().json()
+ assert {r["workflow_id"]: r["succeeded"] for r in rows} == {str(self.flow_a.id): 2}
+
+ def test_excludes_metrics_for_workflows_not_in_queryset(self):
+ # Metrics are intersected with workflows the caller can see, so a row for an id that isn't a
+ # live workflow (e.g. since-deleted, or one the caller can't access) must not leak in.
+ self._seed(self.flow_a.id, failed=2)
+ self._seed("00000000-0000-0000-0000-000000000000", failed=9)
+ rows = self._global().json()
+ assert {r["workflow_id"] for r in rows} == {str(self.flow_a.id)}
+
+ def test_personal_api_key_hog_flow_read_only_allowed(self):
+ # Aggregate counts carry no person data, so hog_flow:read alone is sufficient (no person:read).
+ self._seed(self.flow_a.id, failed=1)
+ key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="hog_flow only", user=self.user, secure_value=hash_key_value(key), scopes=["hog_flow:read"]
+ )
+ res = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/metrics/global/",
+ headers={"authorization": f"Bearer {key}"},
+ )
+ assert res.status_code == status.HTTP_200_OK, res.json()
+ assert {r["workflow_id"] for r in res.json()} == {str(self.flow_a.id)}
diff --git a/products/workflows/backend/api/test/test_hog_flow_invocation_results.py b/products/workflows/backend/api/test/test_hog_flow_invocation_results.py
new file mode 100644
index 000000000000..8c79a4f3e06a
--- /dev/null
+++ b/products/workflows/backend/api/test/test_hog_flow_invocation_results.py
@@ -0,0 +1,269 @@
+import gzip
+import json
+import base64
+from datetime import UTC, datetime, timedelta
+from typing import Any, Optional
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.clickhouse.client.execute import sync_execute
+from posthog.models.hog_invocation_results.sql import INSERT_HOG_INVOCATION_RESULT_SQL
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
+
+
+def create_hog_invocation_result(
+ team_id: int,
+ function_id: str,
+ invocation_id: str,
+ *,
+ function_kind: str = "hog_flow",
+ invocation_status: str = "success",
+ version: int = 1,
+ is_deleted: int = 0,
+ distinct_id: str = "user-1",
+ person_id: str = "person-1",
+ error_kind: str = "",
+ error_message: str = "",
+ scheduled_at: Optional[datetime] = None,
+ started_at: Optional[datetime] = None,
+ finished_at: Optional[datetime] = None,
+ duration_ms: Optional[int] = 12,
+ attempts: int = 1,
+ is_retry: int = 0,
+ invocation_globals: str = "{}",
+) -> None:
+ # Default to "now" so rows land inside the endpoint's default -7d window.
+ scheduled = scheduled_at or datetime.now(tz=UTC)
+ params: dict[str, Any] = {
+ "team_id": team_id,
+ "function_kind": function_kind,
+ "function_id": function_id,
+ "invocation_id": invocation_id,
+ "parent_run_id": "",
+ "status": invocation_status,
+ "attempts": attempts,
+ "is_retry": is_retry,
+ "scheduled_at": scheduled,
+ "first_scheduled_at": scheduled,
+ "started_at": started_at,
+ "finished_at": finished_at,
+ "duration_ms": duration_ms,
+ "error_kind": error_kind,
+ "error_message": error_message,
+ "event_uuid": "",
+ "distinct_id": distinct_id,
+ "person_id": person_id,
+ "invocation_globals": invocation_globals,
+ "version": version,
+ "is_deleted": is_deleted,
+ }
+ sync_execute(INSERT_HOG_INVOCATION_RESULT_SQL, params)
+
+
+class TestHogFlowInvocationResults(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.hog_flow = HogFlow.objects.create(team=self.team, name="Test Flow")
+
+ def _list(self, params=None):
+ return self.client.get(f"/api/projects/{self.team.id}/hog_flows/{self.hog_flow.id}/invocation_results/", params)
+
+ def _detail(self, invocation_id: str):
+ return self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{self.hog_flow.id}/invocation_results/{invocation_id}/"
+ )
+
+ def _seed(self, invocation_id: str, **kwargs):
+ create_hog_invocation_result(
+ team_id=self.team.pk, function_id=str(self.hog_flow.pk), invocation_id=invocation_id, **kwargs
+ )
+
+ def test_returns_empty_when_no_invocations(self):
+ res = self._list()
+ assert res.status_code == status.HTTP_200_OK
+ assert res.json() == []
+
+ def test_returns_invocation(self):
+ self._seed(
+ "inv-1",
+ invocation_status="failed",
+ error_kind="HogVMError",
+ error_message="boom",
+ distinct_id="user-7",
+ person_id="person-7",
+ finished_at=datetime(2024, 1, 1, 12, 0, 5, tzinfo=UTC),
+ )
+ results = self._list().json()
+ assert len(results) == 1
+ row = results[0]
+ assert row["invocation_id"] == "inv-1"
+ assert row["status"] == "failed"
+ assert row["error_message"] == "boom"
+ assert row["distinct_id"] == "user-7"
+ assert row["person_id"] == "person-7"
+ assert "invocation_globals" not in row
+
+ def test_collapses_lifecycle_rows_to_latest_version(self):
+ # A started row (v1) and a finished row (v2) for the same invocation collapse to the latest.
+ self._seed("inv-1", invocation_status="started", version=1, finished_at=None)
+ self._seed(
+ "inv-1",
+ invocation_status="failed",
+ version=2,
+ error_message="late failure",
+ finished_at=datetime(2024, 1, 1, 12, 0, 9, tzinfo=UTC),
+ )
+ results = self._list().json()
+ assert len(results) == 1
+ assert results[0]["status"] == "failed"
+ assert results[0]["error_message"] == "late failure"
+
+ def test_excludes_deleted_invocations(self):
+ self._seed("inv-1", invocation_status="success", version=1)
+ self._seed("inv-1", invocation_status="success", version=2, is_deleted=1)
+ assert self._list().json() == []
+
+ @parameterized.expand(
+ [
+ ("failed", {"inv-fail"}),
+ ("success,failed", {"inv-ok", "inv-fail"}),
+ ]
+ )
+ def test_filters_by_status(self, status_filter: str, expected_ids: set):
+ self._seed("inv-ok", invocation_status="success")
+ self._seed("inv-fail", invocation_status="failed")
+ results = self._list({"status": status_filter}).json()
+ assert {r["invocation_id"] for r in results} == expected_ids
+
+ def test_filters_by_distinct_id(self):
+ self._seed("inv-1", distinct_id="user-a")
+ self._seed("inv-2", distinct_id="user-b")
+ results = self._list({"distinct_id": "user-a"}).json()
+ assert {r["invocation_id"] for r in results} == {"inv-1"}
+
+ @parameterized.expand(
+ [
+ ({"after": "-15d"}, {"inv-mid", "inv-late"}),
+ ({"after": "-30d", "before": "-5d"}, {"inv-early", "inv-mid"}),
+ ({"after": "-15d", "before": "-5d"}, {"inv-mid"}),
+ ]
+ )
+ def test_filters_by_time_range(self, params: dict, expected_ids: set):
+ # Relative to now, since the endpoint defaults `after` to -7d.
+ now = datetime.now(tz=UTC)
+ self._seed("inv-early", scheduled_at=now - timedelta(days=20))
+ self._seed("inv-mid", scheduled_at=now - timedelta(days=10))
+ self._seed("inv-late", scheduled_at=now - timedelta(days=2))
+ results = self._list(params).json()
+ assert {r["invocation_id"] for r in results} == expected_ids
+
+ def test_default_window_excludes_rows_older_than_7d(self):
+ # No `after` → default -7d window bounds the partition scan, so older runs drop out.
+ now = datetime.now(tz=UTC)
+ self._seed("recent", scheduled_at=now - timedelta(days=2))
+ self._seed("old", scheduled_at=now - timedelta(days=30))
+ results = self._list().json()
+ assert {r["invocation_id"] for r in results} == {"recent"}
+
+ def test_after_filter_respects_team_timezone(self):
+ # PT is UTC-7 in June, so after='2026-06-08T00:00:00' (no offset) resolves to 07:00 UTC.
+ # The row at 06:00 UTC must be excluded and the one at 08:00 UTC included — a naive
+ # conversion that read the bound as 00:00 UTC would wrongly include both.
+ self.team.timezone = "America/Los_Angeles"
+ self.team.save()
+ self._seed("before-bound", scheduled_at=datetime(2026, 6, 8, 6, 0, 0, tzinfo=UTC))
+ self._seed("after-bound", scheduled_at=datetime(2026, 6, 8, 8, 0, 0, tzinfo=UTC))
+ results = self._list({"after": "2026-06-08T00:00:00", "before": "2026-06-09T00:00:00"}).json()
+ assert {r["invocation_id"] for r in results} == {"after-bound"}
+
+ def test_isolated_from_other_flow_and_function_kind(self):
+ self._seed("inv-mine", invocation_status="success")
+ # Same team, but a hog_function invocation and a different flow id must not leak in.
+ create_hog_invocation_result(
+ team_id=self.team.pk,
+ function_id=str(self.hog_flow.pk),
+ invocation_id="inv-fn",
+ function_kind="hog_function",
+ )
+ create_hog_invocation_result(team_id=self.team.pk, function_id="some-other-flow", invocation_id="inv-other")
+ results = self._list().json()
+ assert {r["invocation_id"] for r in results} == {"inv-mine"}
+
+ def test_respects_limit(self):
+ for i in range(5):
+ self._seed(f"inv-{i}")
+ results = self._list({"limit": 2}).json()
+ assert len(results) == 2
+
+ def test_detail_returns_invocation_globals(self):
+ # Legacy rows predate compression and are stored as raw JSON.
+ self._seed("inv-1", invocation_status="failed", invocation_globals='{"event": {"event": "$pageview"}}')
+ res = self._detail("inv-1")
+ assert res.status_code == status.HTTP_200_OK
+ body = res.json()
+ assert body["invocation_id"] == "inv-1"
+ assert body["status"] == "failed"
+ assert body["invocation_globals"] == {"event": {"event": "$pageview"}}
+
+ def test_detail_decodes_gzip_base64_invocation_globals(self):
+ # Current rows are gzip-compressed then base64-encoded by the producer.
+ payload = {"event": {"event": "$pageview"}, "person": {"id": "p1"}, "groups": {}}
+ encoded = base64.b64encode(gzip.compress(json.dumps(payload).encode("utf-8"))).decode("utf-8")
+ self._seed("inv-1", invocation_globals=encoded)
+ body = self._detail("inv-1").json()
+ assert body["invocation_globals"] == payload
+
+ def test_detail_invocation_globals_degrades_to_empty_on_garbage(self):
+ self._seed("inv-1", invocation_globals="not-valid-base64-or-json")
+ assert self._detail("inv-1").json()["invocation_globals"] == {}
+
+ def test_detail_404_for_unknown_invocation(self):
+ assert self._detail("nope").status_code == status.HTTP_404_NOT_FOUND
+
+ def test_personal_api_key_requires_person_read_scope(self):
+ # Invocation inspection exposes distinct_id / person_id and the triggering payload, so a
+ # hog_flow:read-only token must not be able to enumerate who a workflow ran for — person:read
+ # is also required.
+ self._seed("inv-1")
+ key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="hog_flow only", user=self.user, secure_value=hash_key_value(key), scopes=["hog_flow:read"]
+ )
+ headers = {"authorization": f"Bearer {key}"}
+ list_res = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{self.hog_flow.id}/invocation_results/", headers=headers
+ )
+ assert list_res.status_code == 403, list_res.json()
+ assert "person:read" in list_res.json().get("detail", "")
+ detail_res = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{self.hog_flow.id}/invocation_results/inv-1/", headers=headers
+ )
+ assert detail_res.status_code == 403, detail_res.json()
+ assert "person:read" in detail_res.json().get("detail", "")
+
+ def test_personal_api_key_with_person_read_scope_allowed(self):
+ self._seed("inv-1", invocation_globals='{"event": {"event": "$pageview"}}')
+ key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="hog_flow + person",
+ user=self.user,
+ secure_value=hash_key_value(key),
+ scopes=["hog_flow:read", "person:read"],
+ )
+ headers = {"authorization": f"Bearer {key}"}
+ list_res = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{self.hog_flow.id}/invocation_results/", headers=headers
+ )
+ assert list_res.status_code == 200, list_res.json()
+ assert {r["invocation_id"] for r in list_res.json()} == {"inv-1"}
+ detail_res = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{self.hog_flow.id}/invocation_results/inv-1/", headers=headers
+ )
+ assert detail_res.status_code == 200, detail_res.json()
+ assert detail_res.json()["invocation_id"] == "inv-1"
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 888723642350..7b1c6c543e5d 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -561,6 +561,49 @@ export interface HogFlowBatchJobApi {
readonly updated_at: string
}
+export interface HogInvocationResultApi {
+ invocation_id: string
+ status: string
+ error_kind: string
+ error_message: string
+ distinct_id: string
+ person_id: string
+ scheduled_at: string
+ /** @nullable */
+ started_at: string | null
+ /** @nullable */
+ finished_at: string | null
+ /** @nullable */
+ duration_ms: number | null
+ attempts: number
+ is_retry: boolean
+}
+
+/**
+ * The triggering payload (event/person/groups) the run executed against, as a JSON object.
+ */
+export type HogInvocationResultDetailApiInvocationGlobals = { [key: string]: unknown }
+
+export interface HogInvocationResultDetailApi {
+ /** The triggering payload (event/person/groups) the run executed against, as a JSON object. */
+ invocation_globals: HogInvocationResultDetailApiInvocationGlobals
+ invocation_id: string
+ status: string
+ error_kind: string
+ error_message: string
+ distinct_id: string
+ person_id: string
+ scheduled_at: string
+ /** @nullable */
+ started_at: string | null
+ /** @nullable */
+ finished_at: string | null
+ /** @nullable */
+ duration_ms: number | null
+ attempts: number
+ is_retry: boolean
+}
+
/**
* Test trigger payload, typically {event, person, groups}.
*/
@@ -621,6 +664,15 @@ export interface PatchedHogFlowScheduleApi {
readonly updated_at?: string
}
+export interface WorkflowStatsRowApi {
+ /** The workflow these counts are for. */
+ workflow_id: string
+ /** Successful invocations in the window. */
+ succeeded: number
+ /** Failed invocations in the window. */
+ failed: number
+}
+
/**
* Property filters to apply
*/
@@ -715,6 +767,35 @@ export const HogFlowsListStatus = {
Draft: 'draft',
} as const
+export type HogFlowsInvocationResultsRetrieveParams = {
+ /**
+ * Start of the time range, matched on scheduled time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d — bounds the ClickHouse partition scan, so widen it explicitly for older runs.
+ * @minLength 1
+ */
+ after?: string
+ /**
+ * End of the time range, matched on scheduled time. Same format as 'after'. Defaults to now.
+ * @minLength 1
+ */
+ before?: string
+ /**
+ * Only return invocations triggered for this distinct_id (the person the run executed for).
+ * @minLength 1
+ */
+ distinct_id?: string
+ /**
+ * Maximum number of invocations to return (1-500, default 50).
+ * @minimum 1
+ * @maximum 500
+ */
+ limit?: number
+ /**
+ * Comma-separated invocation statuses to include, e.g. 'failed' or 'success,failed'.
+ * @minLength 1
+ */
+ status?: string
+}
+
export type HogFlowsLogsRetrieveParams = {
/**
* Only return entries after this ISO 8601 timestamp.
@@ -870,3 +951,16 @@ export const HogFlowsMetricsTotalsRetrieveInterval = {
Day: 'day',
Week: 'week',
} as const
+
+export type HogFlowsMetricsGlobalRetrieveParams = {
+ /**
+ * Start of the window, matched on metric time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d.
+ * @minLength 1
+ */
+ after?: string
+ /**
+ * End of the window. Same format as 'after'. Defaults to now.
+ * @minLength 1
+ */
+ before?: string
+}
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 5da2b8854471..5d04367b54df 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -20,15 +20,20 @@ import type {
HogFlowTemplateApi,
HogFlowTemplatesListParams,
HogFlowTemplatesLogsRetrieveParams,
+ HogFlowsInvocationResultsRetrieveParams,
HogFlowsListParams,
HogFlowsLogsRetrieveParams,
+ HogFlowsMetricsGlobalRetrieveParams,
HogFlowsMetricsRetrieveParams,
HogFlowsMetricsTotalsRetrieveParams,
+ HogInvocationResultApi,
+ HogInvocationResultDetailApi,
PaginatedHogFlowMinimalListApi,
PaginatedHogFlowTemplateListApi,
PatchedHogFlowApi,
PatchedHogFlowScheduleApi,
PatchedHogFlowTemplateApi,
+ WorkflowStatsRowApi,
} from './api.schemas'
// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
@@ -343,6 +348,57 @@ export const hogFlowsBatchJobsCreate = async (
})
}
+export const getHogFlowsInvocationResultsRetrieveUrl = (
+ projectId: string,
+ id: string,
+ params?: HogFlowsInvocationResultsRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/hog_flows/${id}/invocation_results/?${stringifiedParams}`
+ : `/api/projects/${projectId}/hog_flows/${id}/invocation_results/`
+}
+
+export const hogFlowsInvocationResultsRetrieve = async (
+ projectId: string,
+ id: string,
+ params?: HogFlowsInvocationResultsRetrieveParams,
+ options?: RequestInit
+): Promise<HogInvocationResultApi[]> => {
+ return apiMutator<HogInvocationResultApi[]>(getHogFlowsInvocationResultsRetrieveUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getHogFlowsInvocationResultRetrieveUrl = (projectId: string, id: string, invocationId: string) => {
+ return `/api/projects/${projectId}/hog_flows/${id}/invocation_results/${invocationId}/`
+}
+
+export const hogFlowsInvocationResultRetrieve = async (
+ projectId: string,
+ id: string,
+ invocationId: string,
+ options?: RequestInit
+): Promise<HogInvocationResultDetailApi> => {
+ return apiMutator<HogInvocationResultDetailApi>(
+ getHogFlowsInvocationResultRetrieveUrl(projectId, id, invocationId),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
export const getHogFlowsInvocationsCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/hog_flows/${id}/invocations/`
}
@@ -538,6 +594,36 @@ export const hogFlowsBulkDeleteCreate = async (
})
}
+export const getHogFlowsMetricsGlobalRetrieveUrl = (
+ projectId: string,
+ params?: HogFlowsMetricsGlobalRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/hog_flows/metrics/global/?${stringifiedParams}`
+ : `/api/projects/${projectId}/hog_flows/metrics/global/`
+}
+
+export const hogFlowsMetricsGlobalRetrieve = async (
+ projectId: string,
+ params?: HogFlowsMetricsGlobalRetrieveParams,
+ options?: RequestInit
+): Promise<WorkflowStatsRowApi[]> => {
+ return apiMutator<WorkflowStatsRowApi[]>(getHogFlowsMetricsGlobalRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getHogFlowsUserBlastRadiusCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/hog_flows/user_blast_radius/`
}
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index 64498a81c5b2..c1a8d60d202f 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -51,35 +51,6 @@ tools:
hog-flows-invocations-create:
operation: hog_flows_invocations_create
enabled: false
- hog-flows-logs-retrieve:
- operation: hog_flows_logs_retrieve
- enabled: true
- scopes:
- - hog_flow:read
- annotations:
- readOnly: true
- destructive: false
- idempotent: true
- title: Get workflow logs
- description: >
- 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.
- hog-flows-metrics-retrieve:
- operation: hog_flows_metrics_retrieve
- enabled: true
- scopes:
- - hog_flow:read
- annotations:
- readOnly: true
- destructive: false
- idempotent: true
- title: Get workflow metrics
- description: >
- Retrieve execution metrics for a specific workflow by ID. Returns time-series data showing success and
- failure counts over a configurable interval (hour, day, or week). Use to understand workflow health,
- identify failure spikes, and monitor execution reliability. Supports breakdown by metric kind
- (success/failure) or name, and time range filtering.
hog-flows-metrics-totals-retrieve:
operation: hog_flows_metrics_totals_retrieve
enabled: false
@@ -150,6 +121,38 @@ tools:
condition, variables, and any recurring 'schedules' (read-only here). For a batch workflow, check
status=='active' plus an active entry in 'schedules' to confirm it will actually fire.
ui_app: workflow
+ workflows-get-invocation:
+ operation: hog_flows_invocation_result_retrieve
+ enabled: true
+ scopes:
+ - hog_flow:read
+ - person:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get workflow invocation
+ description: >
+ Get a single workflow invocation by invocation_id, including invocation_globals — the raw triggering payload
+ (event/person/groups) that the run executed against. Use after workflows-list-invocations to inspect exactly
+ what input produced a failure.
+ workflows-global-stats:
+ operation: hog_flows_metrics_global_retrieve
+ enabled: true
+ scopes:
+ - hog_flow:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: Workflow stats overview
+ description: >
+ At-a-glance health across ALL workflows in one call: per-workflow succeeded/failed counts over a window
+ (after/before, default last 7 days), sorted most-failing first. Start here when debugging — find which
+ workflows are failing, then drill into those with workflows-list-invocations (who it failed for) →
+ workflows-get-invocation (the triggering payload) → workflows-logs (the failing step). Avoids scanning every
+ workflow one at a time. For a single workflow's time-series, use workflows-stats.
workflows-list:
operation: hog_flows_list
enabled: true
@@ -179,12 +182,60 @@ tools:
description: >
List past batch runs for a workflow (both one-off broadcasts and schedule-triggered runs). Each entry shows
the audience filters and variable overrides the run used, plus when it was created. The status field is not
- tracked — use workflows-logs / workflows-metrics for the outcome of a run.
- workflows-run:
+ tracked — use workflows-logs / workflows-stats for the outcome of a run.
+ workflows-list-invocations:
+ operation: hog_flows_invocation_results_retrieve
+ enabled: true
+ scopes:
+ - hog_flow:read
+ - person:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List workflow invocations
+ description: >
+ List a workflow's individual invocations (one execution per person/event), each collapsed to its final
+ outcome — status, error_kind/error_message, distinct_id, person_id, timings. This is the per-recipient
+ failure view: filter status=failed to see who it failed for and why. Filter by distinct_id and time range.
+ Distinct from workflows-list-batch-jobs (the dispatch ledger, which has no per-person outcome) — drill from
+ a failed invocation into workflows-logs for the step-by-step trace.
+ workflows-logs:
+ operation: hog_flows_logs_retrieve
+ enabled: true
+ scopes:
+ - hog_flow:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get workflow logs
+ description: >
+ 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-stats:
+ operation: hog_flows_metrics_retrieve
+ enabled: true
+ scopes:
+ - hog_flow:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get workflow stats
+ description: >
+ Execution stats for a single workflow by ID: time-series success/failure counts over a configurable interval
+ (hour, day, or week). Use to inspect one workflow's health — failure spikes and reliability trends. For an
+ at-a-glance view across ALL workflows, call workflows-global-stats first, then drill in here. Supports
+ breakdown by metric kind (success/failure) or name, and time range filtering.
+ workflows-test-run:
operation: hog_flows_invocations_create
enabled: true
scopes:
- hog_flow:write
+ - group:read
annotations:
readOnly: false
destructive: true
@@ -210,9 +261,9 @@ tools:
description: >
Update a workflow by ID. Draft only — active workflows are read-only via MCP for now (editing risks breaking
already-scheduled runs); create a new draft for changes instead. Status changes go through workflows-enable
- / workflows-disable / workflows-archive. A batch audience is config.filters.properties — person-property
- conditions and/or cohort references. Prefer person properties or a dynamic (filter-based) cohort, which
- re-evaluate, over a static frozen-list cohort; behavioral (event-based) cohorts are rejected.
+ / workflows-archive. A batch audience is config.filters.properties — person-property conditions and/or
+ cohort references. Prefer person properties or a dynamic (filter-based) cohort, which re-evaluate, over a
+ static frozen-list cohort; behavioral (event-based) cohorts are rejected.
exclude_params:
- status
ui_app: workflow
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index fe8ae7551cba..efa19392ebc1 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2698,34 +2698,6 @@
},
"feature_flag": "heatmaps-mcp"
},
- "hog-flows-logs-retrieve": {
- "description": "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.",
- "category": "Workflows",
- "feature": "workflows",
- "summary": "Get workflow logs",
- "title": "Get workflow logs",
- "required_scopes": ["hog_flow:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- }
- },
- "hog-flows-metrics-retrieve": {
- "description": "Retrieve execution metrics for a specific workflow by ID. Returns time-series data showing success and failure counts over a configurable interval (hour, day, or week). Use to understand workflow health, identify failure spikes, and monitor execution reliability. Supports breakdown by metric kind (success/failure) or name, and time range filtering.",
- "category": "Workflows",
- "feature": "workflows",
- "summary": "Get workflow metrics",
- "title": "Get workflow metrics",
- "required_scopes": ["hog_flow:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- }
- },
"inbox-reports-list": {
"description": "List signal reports for the current project. A signal report is a cluster of related observations (signals) that PostHog has aggregated into a single issue or trend. Reports surface in the Inbox. Supports filtering by status (potential, candidate, in_progress, pending_input, ready, failed, suppressed), free-text search across title and summary, source_product (e.g. error_tracking, session_replay), and suggested_reviewers (PostHog user UUIDs). Results are paginated and ordered by '-is_suggested_reviewer,status,-updated_at' by default.",
"category": "Signals",
@@ -6470,6 +6442,34 @@
"readOnlyHint": true
}
},
+ "workflows-get-invocation": {
+ "description": "Get a single workflow invocation by invocation_id, including invocation_globals — the raw triggering payload (event/person/groups) that the run executed against. Use after workflows-list-invocations to inspect exactly what input produced a failure.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get workflow invocation",
+ "title": "Get workflow invocation",
+ "required_scopes": ["hog_flow:read", "person:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "workflows-global-stats": {
+ "description": "At-a-glance health across ALL workflows in one call: per-workflow succeeded/failed counts over a window (after/before, default last 7 days), sorted most-failing first. Start here when debugging — find which workflows are failing, then drill into those with workflows-list-invocations (who it failed for) → workflows-get-invocation (the triggering payload) → workflows-logs (the failing step). Avoids scanning every workflow one at a time. For a single workflow's time-series, use workflows-stats.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Workflow stats overview",
+ "title": "Workflow stats overview",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"workflows-list": {
"description": "List all workflows in the project. Returns workflows with their name, description, status (draft/active/archived), version, trigger configuration, and timestamps.",
"category": "Workflows",
@@ -6485,7 +6485,7 @@
}
},
"workflows-list-batch-jobs": {
- "description": "List past batch runs for a workflow (both one-off broadcasts and schedule-triggered runs). Each entry shows the audience filters and variable overrides the run used, plus when it was created. The status field is not tracked — use workflows-logs / workflows-metrics for the outcome of a run.",
+ "description": "List past batch runs for a workflow (both one-off broadcasts and schedule-triggered runs). Each entry shows the audience filters and variable overrides the run used, plus when it was created. The status field is not tracked — use workflows-logs / workflows-stats for the outcome of a run.",
"category": "Workflows",
"feature": "workflows",
"summary": "List workflow batch runs",
@@ -6498,13 +6498,55 @@
"readOnlyHint": true
}
},
- "workflows-run": {
+ "workflows-list-invocations": {
+ "description": "List a workflow's individual invocations (one execution per person/event), each collapsed to its final outcome — status, error_kind/error_message, distinct_id, person_id, timings. This is the per-recipient failure view: filter status=failed to see who it failed for and why. Filter by distinct_id and time range. Distinct from workflows-list-batch-jobs (the dispatch ledger, which has no per-person outcome) — drill from a failed invocation into workflows-logs for the step-by-step trace.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "List workflow invocations",
+ "title": "List workflow invocations",
+ "required_scopes": ["hog_flow:read", "person:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "workflows-logs": {
+ "description": "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.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get workflow logs",
+ "title": "Get workflow logs",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "workflows-stats": {
+ "description": "Execution stats for a single workflow by ID: time-series success/failure counts over a configurable interval (hour, day, or week). Use to inspect one workflow's health — failure spikes and reliability trends. For an at-a-glance view across ALL workflows, call workflows-global-stats first, then drill in here. Supports breakdown by metric kind (success/failure) or name, and time range filtering.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get workflow stats",
+ "title": "Get workflow stats",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "workflows-test-run": {
"description": "Test-invoke a saved workflow. Pass test event data via globals (typically {event, person, groups}). Async actions (HTTP/email/SMS) are mocked by default; set mock_async_functions=false to fire real side effects. Optional current_action_id starts from a specific node. Returns the execution trace.",
"category": "Workflows",
"feature": "workflows",
"summary": "Test-run workflow",
"title": "Test-run workflow",
- "required_scopes": ["hog_flow:write"],
+ "required_scopes": ["hog_flow:write", "group:read"],
"annotations": {
"destructiveHint": true,
"idempotentHint": false,
@@ -6513,7 +6555,7 @@
}
},
"workflows-update": {
- "description": "Update a workflow by ID. Draft only — active workflows are read-only via MCP for now (editing risks breaking already-scheduled runs); create a new draft for changes instead. Status changes go through workflows-enable / workflows-disable / workflows-archive. A batch audience is config.filters.properties — person-property conditions and/or cohort references. Prefer person properties or a dynamic (filter-based) cohort, which re-evaluate, over a static frozen-list cohort; behavioral (event-based) cohorts are rejected.",
+ "description": "Update a workflow by ID. Draft only — active workflows are read-only via MCP for now (editing risks breaking already-scheduled runs); create a new draft for changes instead. Status changes go through workflows-enable / workflows-archive. A batch audience is config.filters.properties — person-property conditions and/or cohort references. Prefer person properties or a dynamic (filter-based) cohort, which re-evaluate, over a static frozen-list cohort; behavioral (event-based) cohorts are rejected.",
"category": "Workflows",
"feature": "workflows",
"summary": "Update workflow",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 2d4ebb2a720d..12708237a662 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2952,34 +2952,6 @@
},
"feature_flag": "heatmaps-mcp"
},
- "hog-flows-logs-retrieve": {
- "description": "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.",
- "category": "Workflows",
- "feature": "workflows",
- "summary": "Get workflow logs",
- "title": "Get workflow logs",
- "required_scopes": ["hog_flow:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- }
- },
- "hog-flows-metrics-retrieve": {
- "description": "Retrieve execution metrics for a specific workflow by ID. Returns time-series data showing success and failure counts over a configurable interval (hour, day, or week). Use to understand workflow health, identify failure spikes, and monitor execution reliability. Supports breakdown by metric kind (success/failure) or name, and time range filtering.",
- "category": "Workflows",
- "feature": "workflows",
- "summary": "Get workflow metrics",
- "title": "Get workflow metrics",
- "required_scopes": ["hog_flow:read"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- }
- },
"inbox-reports-list": {
"description": "List signal reports for the current project. A signal report is a cluster of related observations (signals) that PostHog has aggregated into a single issue or trend. Reports surface in the Inbox. Supports filtering by status (potential, candidate, in_progress, pending_input, ready, failed, suppressed), free-text search across title and summary, source_product (e.g. error_tracking, session_replay), and suggested_reviewers (PostHog user UUIDs). Results are paginated and ordered by '-is_suggested_reviewer,status,-updated_at' by default.",
"category": "Signals",
@@ -6881,6 +6853,34 @@
"readOnlyHint": true
}
},
+ "workflows-get-invocation": {
+ "description": "Get a single workflow invocation by invocation_id, including invocation_globals — the raw triggering payload (event/person/groups) that the run executed against. Use after workflows-list-invocations to inspect exactly what input produced a failure.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get workflow invocation",
+ "title": "Get workflow invocation",
+ "required_scopes": ["hog_flow:read", "person:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "workflows-global-stats": {
+ "description": "At-a-glance health across ALL workflows in one call: per-workflow succeeded/failed counts over a window (after/before, default last 7 days), sorted most-failing first. Start here when debugging — find which workflows are failing, then drill into those with workflows-list-invocations (who it failed for) → workflows-get-invocation (the triggering payload) → workflows-logs (the failing step). Avoids scanning every workflow one at a time. For a single workflow's time-series, use workflows-stats.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Workflow stats overview",
+ "title": "Workflow stats overview",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"workflows-list": {
"description": "List all workflows in the project. Returns workflows with their name, description, status (draft/active/archived), version, trigger configuration, and timestamps.",
"category": "Workflows",
@@ -6896,7 +6896,7 @@
}
},
"workflows-list-batch-jobs": {
- "description": "List past batch runs for a workflow (both one-off broadcasts and schedule-triggered runs). Each entry shows the audience filters and variable overrides the run used, plus when it was created. The status field is not tracked — use workflows-logs / workflows-metrics for the outcome of a run.",
+ "description": "List past batch runs for a workflow (both one-off broadcasts and schedule-triggered runs). Each entry shows the audience filters and variable overrides the run used, plus when it was created. The status field is not tracked — use workflows-logs / workflows-stats for the outcome of a run.",
"category": "Workflows",
"feature": "workflows",
"summary": "List workflow batch runs",
@@ -6909,18 +6909,32 @@
"readOnlyHint": true
}
},
- "workflows-run": {
- "description": "Test-invoke a saved workflow. Pass test event data via globals (typically {event, person, groups}). Async actions (HTTP/email/SMS) are mocked by default; set mock_async_functions=false to fire real side effects. Optional current_action_id starts from a specific node. Returns the execution trace.",
+ "workflows-list-invocations": {
+ "description": "List a workflow's individual invocations (one execution per person/event), each collapsed to its final outcome — status, error_kind/error_message, distinct_id, person_id, timings. This is the per-recipient failure view: filter status=failed to see who it failed for and why. Filter by distinct_id and time range. Distinct from workflows-list-batch-jobs (the dispatch ledger, which has no per-person outcome) — drill from a failed invocation into workflows-logs for the step-by-step trace.",
"category": "Workflows",
"feature": "workflows",
- "summary": "Test-run workflow",
- "title": "Test-run workflow",
- "required_scopes": ["hog_flow:write"],
+ "summary": "List workflow invocations",
+ "title": "List workflow invocations",
+ "required_scopes": ["hog_flow:read", "person:read"],
"annotations": {
- "destructiveHint": true,
- "idempotentHint": false,
+ "destructiveHint": false,
+ "idempotentHint": true,
"openWorldHint": true,
- "readOnlyHint": false
+ "readOnlyHint": true
+ }
+ },
+ "workflows-logs": {
+ "description": "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.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get workflow logs",
+ "title": "Get workflow logs",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
}
},
"workflows-run-batch": {
@@ -6951,8 +6965,36 @@
"readOnlyHint": false
}
},
+ "workflows-stats": {
+ "description": "Execution stats for a single workflow by ID: time-series success/failure counts over a configurable interval (hour, day, or week). Use to inspect one workflow's health — failure spikes and reliability trends. For an at-a-glance view across ALL workflows, call workflows-global-stats first, then drill in here. Supports breakdown by metric kind (success/failure) or name, and time range filtering.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get workflow stats",
+ "title": "Get workflow stats",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "workflows-test-run": {
+ "description": "Test-invoke a saved workflow. Pass test event data via globals (typically {event, person, groups}). Async actions (HTTP/email/SMS) are mocked by default; set mock_async_functions=false to fire real side effects. Optional current_action_id starts from a specific node. Returns the execution trace.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Test-run workflow",
+ "title": "Test-run workflow",
+ "required_scopes": ["hog_flow:write", "group:read"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"workflows-update": {
- "description": "Update a workflow by ID. Draft only — active workflows are read-only via MCP for now (editing risks breaking already-scheduled runs); create a new draft for changes instead. Status changes go through workflows-enable / workflows-disable / workflows-archive. A batch audience is config.filters.properties — person-property conditions and/or cohort references. Prefer person properties or a dynamic (filter-based) cohort, which re-evaluate, over a static frozen-list cohort; behavioral (event-based) cohorts are rejected.",
+ "description": "Update a workflow by ID. Draft only — active workflows are read-only via MCP for now (editing risks breaking already-scheduled runs); create a new draft for changes instead. Status changes go through workflows-enable / workflows-archive. A batch audience is config.filters.properties — person-property conditions and/or cohort references. Prefer person properties or a dynamic (filter-based) cohort, which re-evaluate, over a static frozen-list cohort; behavioral (event-based) cohorts are rejected.",
"category": "Workflows",
"feature": "workflows",
"summary": "Update workflow",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 939659a61644..ac8590315ed4 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19966,6 +19966,49 @@ export namespace Schemas {
readonly execution_order: number | null;
}
+ export interface HogInvocationResult {
+ invocation_id: string;
+ status: string;
+ error_kind: string;
+ error_message: string;
+ distinct_id: string;
+ person_id: string;
+ scheduled_at: string;
+ /** @nullable */
+ started_at: string | null;
+ /** @nullable */
+ finished_at: string | null;
+ /** @nullable */
+ duration_ms: number | null;
+ attempts: number;
+ is_retry: boolean;
+ }
+
+ /**
+ * The triggering payload (event/person/groups) the run executed against, as a JSON object.
+ */
+ export type HogInvocationResultDetailInvocationGlobals = { [key: string]: unknown };
+
+ export interface HogInvocationResultDetail {
+ /** The triggering payload (event/person/groups) the run executed against, as a JSON object. */
+ invocation_globals: HogInvocationResultDetailInvocationGlobals;
+ invocation_id: string;
+ status: string;
+ error_kind: string;
+ error_message: string;
+ distinct_id: string;
+ person_id: string;
+ scheduled_at: string;
+ /** @nullable */
+ started_at: string | null;
+ /** @nullable */
+ finished_at: string | null;
+ /** @nullable */
+ duration_ms: number | null;
+ attempts: number;
+ is_retry: boolean;
+ }
+
export type HogLanguage = typeof HogLanguage[keyof typeof HogLanguage];
@@ -41407,6 +41450,15 @@ export namespace Schemas {
last_failure_at: string | null;
}
+ export interface WorkflowStatsRow {
+ /** The workflow these counts are for. */
+ workflow_id: string;
+ /** Successful invocations in the window. */
+ succeeded: number;
+ /** Failed invocations in the window. */
+ failed: number;
+ }
+
export interface _CompareFilter {
/** When true, also fetch results for a comparison window and return them under `compare`. */
compare?: boolean;
@@ -43619,6 +43671,35 @@ export namespace Schemas {
Draft: 'draft',
} as const;
+ export type EnvironmentsHogFlowsInvocationResultsRetrieveParams = {
+ /**
+ * Start of the time range, matched on scheduled time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d — bounds the ClickHouse partition scan, so widen it explicitly for older runs.
+ * @minLength 1
+ */
+ after?: string;
+ /**
+ * End of the time range, matched on scheduled time. Same format as 'after'. Defaults to now.
+ * @minLength 1
+ */
+ before?: string;
+ /**
+ * Only return invocations triggered for this distinct_id (the person the run executed for).
+ * @minLength 1
+ */
+ distinct_id?: string;
+ /**
+ * Maximum number of invocations to return (1-500, default 50).
+ * @minimum 1
+ * @maximum 500
+ */
+ limit?: number;
+ /**
+ * Comma-separated invocation statuses to include, e.g. 'failed' or 'success,failed'.
+ * @minLength 1
+ */
+ status?: string;
+ };
+
export type EnvironmentsHogFlowsLogsRetrieveParams = {
/**
* Only return entries after this ISO 8601 timestamp.
@@ -43775,6 +43856,19 @@ export namespace Schemas {
Week: 'week',
} as const;
+ export type EnvironmentsHogFlowsMetricsGlobalRetrieveParams = {
+ /**
+ * Start of the window, matched on metric time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d.
+ * @minLength 1
+ */
+ after?: string;
+ /**
+ * End of the window. Same format as 'after'. Defaults to now.
+ * @minLength 1
+ */
+ before?: string;
+ };
+
export type EnvironmentsHogFunctionsListParams = {
created_at?: string;
created_by?: number;
@@ -49302,6 +49396,35 @@ export namespace Schemas {
Draft: 'draft',
} as const;
+ export type HogFlowsInvocationResultsRetrieveParams = {
+ /**
+ * Start of the time range, matched on scheduled time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d — bounds the ClickHouse partition scan, so widen it explicitly for older runs.
+ * @minLength 1
+ */
+ after?: string;
+ /**
+ * End of the time range, matched on scheduled time. Same format as 'after'. Defaults to now.
+ * @minLength 1
+ */
+ before?: string;
+ /**
+ * Only return invocations triggered for this distinct_id (the person the run executed for).
+ * @minLength 1
+ */
+ distinct_id?: string;
+ /**
+ * Maximum number of invocations to return (1-500, default 50).
+ * @minimum 1
+ * @maximum 500
+ */
+ limit?: number;
+ /**
+ * Comma-separated invocation statuses to include, e.g. 'failed' or 'success,failed'.
+ * @minLength 1
+ */
+ status?: string;
+ };
+
export type HogFlowsLogsRetrieveParams = {
/**
* Only return entries after this ISO 8601 timestamp.
@@ -49458,6 +49581,19 @@ export namespace Schemas {
Week: 'week',
} as const;
+ export type HogFlowsMetricsGlobalRetrieveParams = {
+ /**
+ * Start of the window, matched on metric time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d.
+ * @minLength 1
+ */
+ after?: string;
+ /**
+ * End of the window. Same format as 'after'. Defaults to now.
+ * @minLength 1
+ */
+ before?: string;
+ };
+
export type HogFunctionTemplatesListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.ts
index b6f6c3a640f6..a565c10b4443 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 9 enabled ops
+ * PostHog API - MCP 12 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -369,6 +369,61 @@ export const HogFlowsBatchJobsListParams = /* @__PURE__ */ zod.object({
),
})
+export const HogFlowsInvocationResultsRetrieveParams = /* @__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 hogFlowsInvocationResultsRetrieveQueryAfterDefault = `-7d`
+
+export const hogFlowsInvocationResultsRetrieveQueryLimitDefault = 50
+export const hogFlowsInvocationResultsRetrieveQueryLimitMax = 500
+
+export const HogFlowsInvocationResultsRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ after: zod
+ .string()
+ .min(1)
+ .default(hogFlowsInvocationResultsRetrieveQueryAfterDefault)
+ .describe(
+ "Start of the time range, matched on scheduled time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d — bounds the ClickHouse partition scan, so widen it explicitly for older runs."
+ ),
+ before: zod
+ .string()
+ .min(1)
+ .optional()
+ .describe("End of the time range, matched on scheduled time. Same format as 'after'. Defaults to now."),
+ distinct_id: zod
+ .string()
+ .min(1)
+ .optional()
+ .describe('Only return invocations triggered for this distinct_id (the person the run executed for).'),
+ limit: zod
+ .number()
+ .min(1)
+ .max(hogFlowsInvocationResultsRetrieveQueryLimitMax)
+ .default(hogFlowsInvocationResultsRetrieveQueryLimitDefault)
+ .describe('Maximum number of invocations to return (1-500, default 50).'),
+ status: zod
+ .string()
+ .min(1)
+ .optional()
+ .describe("Comma-separated invocation statuses to include, e.g. 'failed' or 'success,failed'."),
+})
+
+export const HogFlowsInvocationResultRetrieveParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this hog flow.'),
+ invocation_id: zod.string(),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
export const HogFlowsInvocationsCreateParams = /* @__PURE__ */ zod.object({
id: zod.string().describe('A UUID string identifying this hog flow.'),
project_id: zod
@@ -497,3 +552,24 @@ export const HogFlowsSchedulesPartialUpdateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('Variable value overrides merged with the workflow defaults on each run.'),
})
+
+export const HogFlowsMetricsGlobalRetrieveParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const hogFlowsMetricsGlobalRetrieveQueryAfterDefault = `-7d`
+
+export const HogFlowsMetricsGlobalRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ after: zod
+ .string()
+ .min(1)
+ .default(hogFlowsMetricsGlobalRetrieveQueryAfterDefault)
+ .describe(
+ "Start of the window, matched on metric time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d."
+ ),
+ before: zod.string().min(1).optional().describe("End of the window. Same format as 'after'. Defaults to now."),
+})
diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.ts
index 950b1f8c59f1..a04ba44a5113 100644
--- a/services/mcp/src/tools/generated/workflows.ts
+++ b/services/mcp/src/tools/generated/workflows.ts
@@ -5,11 +5,15 @@ import type { Schemas } from '@/api/generated'
import {
HogFlowsBatchJobsListParams,
HogFlowsCreateBody,
+ HogFlowsInvocationResultRetrieveParams,
+ HogFlowsInvocationResultsRetrieveParams,
+ HogFlowsInvocationResultsRetrieveQueryParams,
HogFlowsInvocationsCreateBody,
HogFlowsInvocationsCreateParams,
HogFlowsListQueryParams,
HogFlowsLogsRetrieveParams,
HogFlowsLogsRetrieveQueryParams,
+ HogFlowsMetricsGlobalRetrieveQueryParams,
HogFlowsMetricsRetrieveParams,
HogFlowsMetricsRetrieveQueryParams,
HogFlowsPartialUpdateBody,
@@ -22,57 +26,6 @@ import { withUiApp } from '@/resources/ui-apps'
import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
-const HogFlowsLogsRetrieveSchema = HogFlowsLogsRetrieveParams.omit({ project_id: true }).extend(
- HogFlowsLogsRetrieveQueryParams.shape
-)
-
-const hogFlowsLogsRetrieve = (): ToolBase<typeof HogFlowsLogsRetrieveSchema, unknown> => ({
- name: 'hog-flows-logs-retrieve',
- schema: HogFlowsLogsRetrieveSchema,
- handler: async (context: Context, params: z.infer<typeof HogFlowsLogsRetrieveSchema>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<unknown>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/logs/`,
- query: {
- after: params.after,
- before: params.before,
- instance_id: params.instance_id,
- level: params.level,
- limit: params.limit,
- search: params.search,
- },
- })
- return result
- },
-})
-
-const HogFlowsMetricsRetrieveSchema = HogFlowsMetricsRetrieveParams.omit({ project_id: true }).extend(
- HogFlowsMetricsRetrieveQueryParams.shape
-)
-
-const hogFlowsMetricsRetrieve = (): ToolBase<typeof HogFlowsMetricsRetrieveSchema, Schemas.AppMetricsResponse> => ({
- name: 'hog-flows-metrics-retrieve',
- schema: HogFlowsMetricsRetrieveSchema,
- handler: async (context: Context, params: z.infer<typeof HogFlowsMetricsRetrieveSchema>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.AppMetricsResponse>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/metrics/`,
- query: {
- after: params.after,
- before: params.before,
- breakdown_by: params.breakdown_by,
- instance_id: params.instance_id,
- interval: params.interval,
- kind: params.kind,
- name: params.name,
- },
- })
- return result
- },
-})
-
const WorkflowsCreateSchema = HogFlowsCreateBody
const workflowsCreate = (): ToolBase<typeof WorkflowsCreateSchema, WithPostHogUrl<Schemas.HogFlow>> =>
@@ -134,6 +87,46 @@ const workflowsGet = (): ToolBase<typeof WorkflowsGetSchema, WithPostHogUrl<Sche
},
})
+const WorkflowsGetInvocationSchema = HogFlowsInvocationResultRetrieveParams.omit({ project_id: true })
+
+const workflowsGetInvocation = (): ToolBase<
+ typeof WorkflowsGetInvocationSchema,
+ Schemas.HogInvocationResultDetail
+> => ({
+ name: 'workflows-get-invocation',
+ schema: WorkflowsGetInvocationSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsGetInvocationSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.HogInvocationResultDetail>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/invocation_results/${encodeURIComponent(String(params.invocation_id))}/`,
+ })
+ return result
+ },
+})
+
+const WorkflowsGlobalStatsSchema = HogFlowsMetricsGlobalRetrieveQueryParams
+
+const workflowsGlobalStats = (): ToolBase<
+ typeof WorkflowsGlobalStatsSchema,
+ WithPostHogUrl<Schemas.WorkflowStatsRow[]>
+> => ({
+ name: 'workflows-global-stats',
+ schema: WorkflowsGlobalStatsSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsGlobalStatsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.WorkflowStatsRow[]>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/metrics/global/`,
+ query: {
+ after: params.after,
+ before: params.before,
+ },
+ })
+ return await withPostHogUrl(context, result, '/pipeline/destinations')
+ },
+})
+
const WorkflowsListSchema = HogFlowsListQueryParams
const workflowsList = (): ToolBase<typeof WorkflowsListSchema, WithPostHogUrl<Schemas.PaginatedHogFlowMinimalList>> =>
@@ -177,14 +170,92 @@ const workflowsListBatchJobs = (): ToolBase<
},
})
-const WorkflowsRunSchema = HogFlowsInvocationsCreateParams.omit({ project_id: true }).extend(
+const WorkflowsListInvocationsSchema = HogFlowsInvocationResultsRetrieveParams.omit({ project_id: true }).extend(
+ HogFlowsInvocationResultsRetrieveQueryParams.shape
+)
+
+const workflowsListInvocations = (): ToolBase<
+ typeof WorkflowsListInvocationsSchema,
+ WithPostHogUrl<Schemas.HogInvocationResult[]>
+> => ({
+ name: 'workflows-list-invocations',
+ schema: WorkflowsListInvocationsSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsListInvocationsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.HogInvocationResult[]>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/invocation_results/`,
+ query: {
+ after: params.after,
+ before: params.before,
+ distinct_id: params.distinct_id,
+ limit: params.limit,
+ status: params.status,
+ },
+ })
+ return await withPostHogUrl(context, result, '/pipeline/destinations')
+ },
+})
+
+const WorkflowsLogsSchema = HogFlowsLogsRetrieveParams.omit({ project_id: true }).extend(
+ HogFlowsLogsRetrieveQueryParams.shape
+)
+
+const workflowsLogs = (): ToolBase<typeof WorkflowsLogsSchema, unknown> => ({
+ name: 'workflows-logs',
+ schema: WorkflowsLogsSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsLogsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<unknown>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/logs/`,
+ query: {
+ after: params.after,
+ before: params.before,
+ instance_id: params.instance_id,
+ level: params.level,
+ limit: params.limit,
+ search: params.search,
+ },
+ })
+ return result
+ },
+})
+
+const WorkflowsStatsSchema = HogFlowsMetricsRetrieveParams.omit({ project_id: true }).extend(
+ HogFlowsMetricsRetrieveQueryParams.shape
+)
+
+const workflowsStats = (): ToolBase<typeof WorkflowsStatsSchema, Schemas.AppMetricsResponse> => ({
+ name: 'workflows-stats',
+ schema: WorkflowsStatsSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsStatsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AppMetricsResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/metrics/`,
+ query: {
+ after: params.after,
+ before: params.before,
+ breakdown_by: params.breakdown_by,
+ instance_id: params.instance_id,
+ interval: params.interval,
+ kind: params.kind,
+ name: params.name,
+ },
+ })
+ return result
+ },
+})
+
+const WorkflowsTestRunSchema = HogFlowsInvocationsCreateParams.omit({ project_id: true }).extend(
HogFlowsInvocationsCreateBody.shape
)
-const workflowsRun = (): ToolBase<typeof WorkflowsRunSchema, unknown> => ({
- name: 'workflows-run',
- schema: WorkflowsRunSchema,
- handler: async (context: Context, params: z.infer<typeof WorkflowsRunSchema>) => {
+const workflowsTestRun = (): ToolBase<typeof WorkflowsTestRunSchema, unknown> => ({
+ name: 'workflows-test-run',
+ schema: WorkflowsTestRunSchema,
+ handler: async (context: Context, params: z.infer<typeof WorkflowsTestRunSchema>) => {
const projectId = await context.stateManager.getProjectId()
const body: Record<string, unknown> = {}
if (params.globals !== undefined) {
@@ -281,13 +352,16 @@ const workflowsUpdateSchedule = (): ToolBase<typeof WorkflowsUpdateScheduleSchem
})
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
- 'hog-flows-logs-retrieve': hogFlowsLogsRetrieve,
- 'hog-flows-metrics-retrieve': hogFlowsMetricsRetrieve,
'workflows-create': workflowsCreate,
'workflows-get': workflowsGet,
+ 'workflows-get-invocation': workflowsGetInvocation,
+ 'workflows-global-stats': workflowsGlobalStats,
'workflows-list': workflowsList,
'workflows-list-batch-jobs': workflowsListBatchJobs,
- 'workflows-run': workflowsRun,
+ 'workflows-list-invocations': workflowsListInvocations,
+ 'workflows-logs': workflowsLogs,
+ 'workflows-stats': workflowsStats,
+ 'workflows-test-run': workflowsTestRun,
'workflows-update': workflowsUpdate,
'workflows-update-schedule': workflowsUpdateSchedule,
}
diff --git a/services/mcp/src/tools/workflows/batch.ts b/services/mcp/src/tools/workflows/batch.ts
index 1896e2309187..18f164b58eff 100644
--- a/services/mcp/src/tools/workflows/batch.ts
+++ b/services/mcp/src/tools/workflows/batch.ts
@@ -96,7 +96,7 @@ export const workflowsRunBatch = (): ToolBase<typeof RunBatchSchema, unknown> =>
if (trigger.type !== 'batch') {
throw new Error(
`workflows-run-batch only applies to workflows with a 'batch' trigger (this one is ` +
- `'${trigger.type ?? 'unknown'}'). Use workflows-run to test-invoke, or a schedule for recurring runs.`
+ `'${trigger.type ?? 'unknown'}'). Use workflows-test-run to test-invoke, or a schedule for recurring runs.`
)
}
diff --git a/services/mcp/tests/tools/workflows.integration.test.ts b/services/mcp/tests/tools/workflows.integration.test.ts
index 60bf178cb165..84ead009bc02 100644
--- a/services/mcp/tests/tools/workflows.integration.test.ts
+++ b/services/mcp/tests/tools/workflows.integration.test.ts
@@ -22,8 +22,11 @@ describe('Workflows', { concurrent: false }, () => {
const getTool = GENERATED_TOOLS['workflows-get']!()
const createTool = GENERATED_TOOLS['workflows-create']!()
const updateTool = GENERATED_TOOLS['workflows-update']!()
- const logsTool = GENERATED_TOOLS['hog-flows-logs-retrieve']!()
- const metricsTool = GENERATED_TOOLS['hog-flows-metrics-retrieve']!()
+ const logsTool = GENERATED_TOOLS['workflows-logs']!()
+ const statsTool = GENERATED_TOOLS['workflows-stats']!()
+ const globalStatsTool = GENERATED_TOOLS['workflows-global-stats']!()
+ const listInvocationsTool = GENERATED_TOOLS['workflows-list-invocations']!()
+ const getInvocationTool = GENERATED_TOOLS['workflows-get-invocation']!()
const enableTool = workflowsEnable()
const disableTool = workflowsDisable()
const archiveTool = workflowsArchive()
@@ -176,7 +179,7 @@ describe('Workflows', { concurrent: false }, () => {
})
})
- describe('hog-flows-logs-retrieve tool', () => {
+ describe('workflows-logs tool', () => {
it('should return log entries for a workflow', async () => {
const listResult = await listTool.handler(context, {})
const { results: workflows } = parseToolResponse(listResult)
@@ -216,8 +219,8 @@ describe('Workflows', { concurrent: false }, () => {
})
})
- describe('hog-flows-metrics-retrieve tool', () => {
- it('should return metrics for a workflow', async () => {
+ describe('workflows-stats tool', () => {
+ it('should return stats for a workflow', async () => {
const listResult = await listTool.handler(context, {})
const { results: workflows } = parseToolResponse(listResult)
@@ -225,7 +228,7 @@ describe('Workflows', { concurrent: false }, () => {
return
}
- const result = await metricsTool.handler(context, { id: workflows[0].id })
+ const result = await statsTool.handler(context, { id: workflows[0].id })
const data = parseToolResponse(result)
expect(Array.isArray(data.labels)).toBe(true)
@@ -240,7 +243,7 @@ describe('Workflows', { concurrent: false }, () => {
return
}
- const result = await metricsTool.handler(context, {
+ const result = await statsTool.handler(context, {
id: workflows[0].id,
interval: 'day',
})
@@ -252,7 +255,51 @@ describe('Workflows', { concurrent: false }, () => {
it('should throw for a non-existent UUID', async () => {
const absentId = crypto.randomUUID()
- await expect(metricsTool.handler(context, { id: absentId })).rejects.toThrow()
+ await expect(statsTool.handler(context, { id: absentId })).rejects.toThrow()
+ })
+ })
+
+ describe('workflows-global-stats tool', () => {
+ it('should return per-workflow stats for the project', async () => {
+ // Bare-array response enriched via withPostHogUrl — an object with _posthogUrl, not a raw array.
+ const data = parseToolResponse(await globalStatsTool.handler(context, {}))
+ expect(data).toBeTypeOf('object')
+ expect(data).toHaveProperty('_posthogUrl')
+ })
+ })
+
+ describe('workflows-list-invocations tool', () => {
+ it('should return invocations for a workflow', async () => {
+ const listResult = await listTool.handler(context, {})
+ const { results: workflows } = parseToolResponse(listResult)
+
+ if (workflows.length === 0) {
+ return
+ }
+
+ const data = parseToolResponse(await listInvocationsTool.handler(context, { id: workflows[0].id }))
+ expect(data).toBeTypeOf('object')
+ expect(data).toHaveProperty('_posthogUrl')
+ })
+
+ it('should throw for a non-existent UUID', async () => {
+ const absentId = crypto.randomUUID()
+ await expect(listInvocationsTool.handler(context, { id: absentId })).rejects.toThrow()
+ })
+ })
+
+ describe('workflows-get-invocation tool', () => {
+ it('should throw for a non-existent invocation', async () => {
+ const listResult = await listTool.handler(context, {})
+ const { results: workflows } = parseToolResponse(listResult)
+
+ if (workflows.length === 0) {
+ return
+ }
+
+ await expect(
+ getInvocationTool.handler(context, { id: workflows[0].id, invocation_id: crypto.randomUUID() })
+ ).rejects.toThrow()
})
})
@@ -379,7 +426,7 @@ describe('Workflows', { concurrent: false }, () => {
})
})
- // workflows-run hits the invocations endpoint, which forwards to the CDP plugin
+ // workflows-test-run hits the invocations endpoint, which forwards to the CDP plugin
// server (CDP_API_URL). That container isn't started in MCP CI (only the `temporal`
// compose profile is enabled), so the happy-path returns 500 from a DNS failure.
// Coverage for the endpoint lives in posthog/api/test/test_hog_flow.py
@@ -484,7 +531,7 @@ describe('Workflows', { concurrent: false }, () => {
})
// The happy path (matching count → POST batch_jobs) forwards to the CDP plugin server
- // (CDP_API_URL), which isn't running in MCP CI — see the workflows-run note above. Fire-path
+ // (CDP_API_URL), which isn't running in MCP CI — see the workflows-test-run note above. Fire-path
// coverage lives in the backend test and the unit handler test
// (tests/unit/workflows-batch-handlers.test.ts).
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-get-invocation.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-get-invocation.json
new file mode 100644
index 000000000000..d8fdef89a450
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-get-invocation.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this hog flow.",
+ "type": "string"
+ },
+ "invocation_id": {
+ "type": "string"
+ }
+ },
+ "required": ["id", "invocation_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-global-stats.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-global-stats.json
new file mode 100644
index 000000000000..b9b16a56ffe2
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-global-stats.json
@@ -0,0 +1,17 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "after": {
+ "default": "-7d",
+ "description": "Start of the window, matched on metric time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "before": {
+ "description": "End of the window. Same format as 'after'. Defaults to now.",
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-invocations.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-invocations.json
new file mode 100644
index 000000000000..80a052e43489
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list-invocations.json
@@ -0,0 +1,39 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "after": {
+ "default": "-7d",
+ "description": "Start of the time range, matched on scheduled time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d — bounds the ClickHouse partition scan, so widen it explicitly for older runs.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "before": {
+ "description": "End of the time range, matched on scheduled time. Same format as 'after'. Defaults to now.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "distinct_id": {
+ "description": "Only return invocations triggered for this distinct_id (the person the run executed for).",
+ "minLength": 1,
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this hog flow.",
+ "type": "string"
+ },
+ "limit": {
+ "default": 50,
+ "description": "Maximum number of invocations to return (1-500, default 50).",
+ "maximum": 500,
+ "minimum": 1,
+ "type": "number"
+ },
+ "status": {
+ "description": "Comma-separated invocation statuses to include, e.g. 'failed' or 'success,failed'.",
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/hog-flows-logs-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-logs.json
similarity index 100%
rename from services/mcp/tests/unit/__snapshots__/tool-schemas/hog-flows-logs-retrieve.json
rename to services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-logs.json
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/hog-flows-metrics-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-stats.json
similarity index 100%
rename from services/mcp/tests/unit/__snapshots__/tool-schemas/hog-flows-metrics-retrieve.json
rename to services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-stats.json
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-run.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-test-run.json
similarity index 100%
rename from services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-run.json
rename to services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-test-run.json
diff --git a/services/mcp/tests/unit/workflows-run-handler.test.ts b/services/mcp/tests/unit/workflows-run-handler.test.ts
index ce4fbca3c94e..af48df7627be 100644
--- a/services/mcp/tests/unit/workflows-run-handler.test.ts
+++ b/services/mcp/tests/unit/workflows-run-handler.test.ts
@@ -30,9 +30,9 @@ function createMockContext(): { context: Context; request: ReturnType<typeof vi.
return { context, request }
}
-const runTool = GENERATED_TOOLS['workflows-run']!()
+const runTool = GENERATED_TOOLS['workflows-test-run']!()
-describe('workflows-run handler', () => {
+describe('workflows-test-run handler', () => {
it('posts to the invocations endpoint with the workflow id in the path', async () => {
const { context, request } = createMockContext()