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(cdp): stage agent destination edits as reviewable drafts (#74507)

posthog[bot]52311547b53d
diff --git a/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsx b/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsx
index fa96066fb1a1..b373da20260c 100644
--- a/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsx
+++ b/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsx
@@ -18,6 +18,8 @@ import { HogFunctionTypeType } from '~/types'
import { humanizeHogFunctionType } from '../hog-function-utils'
import type { DiffProps } from './Diff'
+const STAGED_CHANGES = 'changed the staged changes'
+
const nameOrLinkToHogFunction = (id?: string | null, name?: string | null): string | JSX.Element => {
const displayName = name?.trim() ? name : 'Untitled hog function'
return id ? <Link to={urls.hogFunction(id)}>{displayName}</Link> : displayName
@@ -103,6 +105,24 @@ export function hogFunctionActivityDescriber(logItem: ActivityLogItem, asNotific
}
}
+ const draftActivities: Record<string, string> = {
+ draft_updated: 'staged changes for review on',
+ published: 'published the staged changes to',
+ draft_discarded: 'discarded the staged changes on',
+ revision_restored: 'staged an earlier version for review on',
+ }
+ if (logItem.activity in draftActivities) {
+ return {
+ description: (
+ <>
+ <strong className="ph-no-capture">{userNameForLogItem(logItem)}</strong>{' '}
+ {draftActivities[logItem.activity]} the {objectNoun}:{' '}
+ {nameOrLinkToHogFunction(logItem?.item_id, logItem?.detail.name)}
+ </>
+ ),
+ }
+ }
+
if (logItem.activity == 'updated') {
const changes: { inline: string | JSX.Element; inlist: string | JSX.Element }[] = []
for (const change of logItem.detail.changes ?? []) {
@@ -114,6 +134,16 @@ export function hogFunctionActivityDescriber(logItem: ActivityLogItem, asNotific
})
break
}
+ // Both are masked server-side, so there is nothing to diff — say the staged config
+ // changed and let the reader open it in the builder. A staged edit usually touches
+ // both fields, so collapse them into one entry.
+ case 'draft':
+ case 'draft_encrypted_inputs': {
+ if (!changes.some((c) => c.inlist === STAGED_CHANGES)) {
+ changes.push({ inline: `${STAGED_CHANGES} on`, inlist: STAGED_CHANGES })
+ }
+ break
+ }
case 'inputs': {
const beforeValues = isObject(change.before)
? (change.before as Record<string, { value?: unknown }>)
diff --git a/posthog/event_usage.py b/posthog/event_usage.py
index 1d7fe158e37d..2101636318fa 100644
--- a/posthog/event_usage.py
+++ b/posthog/event_usage.py
@@ -284,6 +284,15 @@ class EventSource(StrEnum):
SUBSCRIPTION = "subscription"
+# Surfaces where an LLM drives the request through a managed channel (classification is stamped by
+# the harness, not self-reported by the model). Callers use this to hold agent writes to a
+# review-then-apply path; the web app has its own confirm UI, and headless callers (raw API keys,
+# Terraform) apply in one call.
+AGENT_EVENT_SOURCES = frozenset(
+ {EventSource.MCP, EventSource.POSTHOG_CODE, EventSource.WIZARD, EventSource.CLI, EventSource.POSTHOG_AI}
+)
+
+
class McpProps(TypedDict):
mcp_user_agent: str | None
mcp_client_name: str | None
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index e2580997caa6..e61c9931c95a 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -260,7 +260,14 @@ common_field_exclusions = [
field_with_masked_contents: dict[AuditableScope, list[str]] = {
"HogFunction": [
+ # Encrypted secret inputs (Fernet ciphertext) — a diff would be noise at best and
+ # leak-adjacent at worst; record that they changed, never the values.
"encrypted_inputs",
+ "draft_encrypted_inputs",
+ # Full config snapshot including input values (auth headers, API keys on rows written before
+ # secret inputs were encrypted) — record that a draft was staged/published/discarded, never
+ # its contents. The per-version config audit lives in the revisions endpoints instead.
+ "draft",
],
"Integration": [
"config",
@@ -519,6 +526,11 @@ field_exclusions: dict[AuditableScope, list[str]] = {
"HogFunction": [
"bytecode",
"icon_url",
+ # Bookkeeping for the draft/revision cycle: `draft` already records that config was staged,
+ # and the per-version audit lives in the revisions endpoints.
+ "version",
+ "draft_updated_at",
+ "revisions",
],
"Notebook": [
"text_content",
diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.py
index 725dcfadfc3c..d3850146c971 100644
--- a/products/cdp/backend/api/hog_function.py
+++ b/products/cdp/backend/api/hog_function.py
@@ -1,16 +1,19 @@
import json
+from datetime import timedelta
from typing import Any, Optional, cast
+from django.core.signing import BadSignature, SignatureExpired, TimestampSigner
from django.db import transaction
from django.db.models import Q, QuerySet
+from django.utils import timezone
import structlog
import posthoganalytics
from django_filters import BaseInFilter, CharFilter, FilterSet
from django_filters.rest_framework import DjangoFilterBackend
-from drf_spectacular.utils import extend_schema
+from drf_spectacular.utils import OpenApiParameter, extend_schema
from opentelemetry import trace
-from rest_framework import exceptions, serializers, viewsets
+from rest_framework import exceptions, serializers, status, viewsets
from rest_framework.exceptions import PermissionDenied
from rest_framework.request import Request
from rest_framework.response import Response
@@ -33,6 +36,7 @@ from posthog.cdp.validation import (
compile_hog,
generate_template_bytecode,
)
+from posthog.event_usage import AGENT_EVENT_SOURCES, get_event_source
from posthog.exceptions_capture import capture_exception
from posthog.helpers.impersonation import is_impersonated
from posthog.helpers.trigram_search import (
@@ -56,8 +60,10 @@ from products.cdp.backend.models.hog_functions.hog_function import (
HogFunctionState,
HogFunctionType,
)
+from products.cdp.backend.models.hog_functions.hog_function_revision import HogFunctionRevision
from products.cdp.backend.models.hog_functions.utils import humanize_hog_function_type
from products.cdp.backend.models.plugin import TranspilerError
+from products.cdp.backend.services.revisions import use_destinations_revisions
# Maximum size of HOG code as a string in bytes (100KB)
MAX_HOG_CODE_SIZE_BYTES = 100 * 1024
@@ -80,6 +86,160 @@ LOGS_TRANSFORMATIONS_FEATURE_FLAG = "logs-transformations"
logger = structlog.get_logger(__name__)
tracer = trace.get_tracer(__name__)
+# The config of a function: everything the draft cycle stages and publish promotes, and nothing
+# else. Metadata (name, description, icon_url) and lifecycle (enabled, deleted, execution_order)
+# always apply to the live row. The draft blob is a full snapshot of these fields so publish is a
+# plain copy, not a merge.
+DRAFT_CONTENT_FIELDS = ("hog", "inputs_schema", "inputs", "filters", "mappings", "masking")
+
+# Compiled from the config fields above during validation, so they follow whichever row the config
+# lands on and must never be written live by a draft-routed edit.
+_DERIVED_CONTENT_FIELDS = frozenset({"bytecode", "transpiled"})
+
+# `to_internal_value` re-injects these from the instance on every payload, so finding them in
+# validated_data says nothing about what the caller actually asked to change.
+_INJECTED_UPDATE_FIELDS = frozenset({"team", "type", "template_id"})
+
+DRAFTS_DISABLED_MESSAGE = "Drafts aren't enabled for this project yet."
+REVISIONS_DISABLED_MESSAGE = "Revision history isn't enabled for this project yet."
+ENABLE_WITH_OPEN_DRAFT_MESSAGE = (
+ "This function has config staged for review. Publish or discard it before enabling, so you don't "
+ "turn on config nobody looked at."
+)
+CREATE_ENABLED_MESSAGE = (
+ "Create destinations disabled: test with an invocation first, then enable with a separate update "
+ "once the config looks right."
+)
+
+# The confirm token makes the publish preview structurally unskippable: only the preview mints it,
+# and it signs both sides of the publish, so a valid token proves the caller saw what publishing
+# would change. Signing the live timestamp too is what stops a publish from silently discarding a
+# concurrent web edit: the draft is a full snapshot, so it overwrites whatever landed since.
+PUBLISH_CONFIRM_TOKEN_MAX_AGE = timedelta(minutes=15)
+_PUBLISH_CONFIRM_SALT = "hogfunction-publish"
+
+
+def _publish_confirm_value(hog_function: HogFunction) -> str:
+ draft_updated_at = hog_function.draft_updated_at.isoformat() if hog_function.draft_updated_at else ""
+ updated_at = hog_function.updated_at.isoformat() if hog_function.updated_at else ""
+ return f"{hog_function.id}:{draft_updated_at}:{updated_at}"
+
+
+def mint_publish_confirm_token(hog_function: HogFunction) -> str:
+ return TimestampSigner(salt=_PUBLISH_CONFIRM_SALT).sign(_publish_confirm_value(hog_function))
+
+
+def split_content_secrets(content: dict) -> dict:
+ """Move secret input values out of a config snapshot into a separate map, mutating `content`.
+
+ Mirrors `HogFunction.move_secret_inputs` for the draft: a draft's secrets belong in
+ `draft_encrypted_inputs`, never in the plaintext snapshot that feeds the API response and the
+ revision history.
+ """
+ inputs = content.get("inputs")
+ if not isinstance(inputs, dict):
+ return {}
+ secret_keys = {
+ schema["key"]
+ for schema in content.get("inputs_schema") or []
+ if isinstance(schema, dict) and schema.get("secret") and "key" in schema
+ }
+ content["inputs"] = {key: value for key, value in inputs.items() if key not in secret_keys}
+ return {key: value for key, value in inputs.items() if key in secret_keys}
+
+
+def snapshot_hog_function_content(hog_function: HogFunction) -> dict:
+ snapshot = {field: getattr(hog_function, field) for field in DRAFT_CONTENT_FIELDS}
+ # Defensively strip: a row written before secret inputs were encrypted still has plaintext
+ # values in `inputs`, and this snapshot feeds revision content, which must never carry secrets.
+ split_content_secrets(snapshot)
+ return snapshot
+
+
+def _without(value: Any, keys: tuple[str, ...]) -> Any:
+ return {k: v for k, v in value.items() if k not in keys} if isinstance(value, dict) else value
+
+
+def _inputs_without_derived(inputs: Any) -> Any:
+ if not isinstance(inputs, dict):
+ return inputs
+ return {key: _without(value, ("bytecode", "transpiled", "order")) for key, value in inputs.items()}
+
+
+def comparable_content(content: dict) -> dict:
+ """A config snapshot with the values validation derives from it dropped: filter and input
+ bytecode, transpiled JS, input ordering.
+
+ A background re-save can change those on its own without the config changing at all — most often
+ `refresh_affected_hog_functions` recompiling filter bytecode after an action or cohort edit — so
+ comparing them would version a plain rename.
+ """
+ filter_derived = ("bytecode", "bytecode_error", "transpiled")
+ mappings = content.get("mappings")
+ return {
+ **content,
+ "filters": _without(content.get("filters"), filter_derived),
+ "inputs": _inputs_without_derived(content.get("inputs")),
+ "masking": _without(content.get("masking"), ("bytecode",)),
+ "mappings": [
+ {
+ **mapping,
+ "filters": _without(mapping.get("filters"), filter_derived),
+ "inputs": _inputs_without_derived(mapping.get("inputs")),
+ }
+ if isinstance(mapping, dict)
+ else mapping
+ for mapping in mappings
+ ]
+ if isinstance(mappings, list)
+ else mappings,
+ }
+
+
+def explicit_secret_input_keys(raw_inputs: Any) -> set[str]:
+ """Input keys carrying a real value in the request rather than the `{"secret": true}` marker the
+ API hands back for secrets — the same test `InputsSerializer` uses to decide whether to recover
+ the stored value instead."""
+ if not isinstance(raw_inputs, dict):
+ return set()
+ return {
+ key
+ for key, value in raw_inputs.items()
+ if isinstance(value, dict) and "value" in value and not value.get("secret")
+ }
+
+
+def draft_changed_fields(hog_function: HogFunction) -> list[str]:
+ """Which config fields publishing this draft would change. Both sides are compared secret-free
+ and without derived values, with staged secrets reported as an `inputs` change."""
+ live = comparable_content(snapshot_hog_function_content(hog_function))
+ draft = comparable_content(hog_function.draft or {})
+ changed = [field for field in DRAFT_CONTENT_FIELDS if draft.get(field) != live.get(field)]
+
+ staged_secrets = hog_function.draft_encrypted_inputs or {}
+ live_secrets = hog_function.encrypted_inputs or {}
+ if "inputs" not in changed and any(live_secrets.get(key) != value for key, value in staged_secrets.items()):
+ changed.append("inputs")
+ return sorted(changed)
+
+
+class StaleHogFunctionUpdateError(exceptions.APIException):
+ status_code = status.HTTP_409_CONFLICT
+ default_detail = (
+ "This function changed since you previewed the publish, either the draft or the live config. "
+ "Preview again to see where things stand now."
+ )
+ default_code = "stale_update"
+
+
+class DraftExistsError(exceptions.APIException):
+ status_code = status.HTTP_409_CONFLICT
+ default_detail = (
+ "This function has an open draft. Publish or discard it first, or pass overwrite=true to "
+ "replace it with the restored revision."
+ )
+ default_code = "draft_exists"
+
class HogFunctionStatusSerializer(serializers.Serializer):
state = serializers.ChoiceField(choices=[state.value for state in HogFunctionState])
@@ -109,8 +269,14 @@ class HogFunctionMinimalSerializer(SearchMatchTypeSerializerMixin, serializers.M
"status",
"execution_order",
"search_match_type",
+ "draft_updated_at",
]
read_only_fields = fields
+ extra_kwargs = {
+ "draft_updated_at": {
+ "help_text": "When config was last staged for review, or null when nothing is staged.",
+ },
+ }
class HogFunctionMaskingSerializer(serializers.Serializer):
@@ -136,6 +302,15 @@ class HogFunctionMaskingSerializer(serializers.Serializer):
class HogFunctionSerializer(HogFunctionMinimalSerializer):
template = HogFunctionTemplateSerializer(read_only=True)
+ base_updated_at = serializers.DateTimeField(
+ write_only=True,
+ required=False,
+ help_text=(
+ "Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) "
+ "you last read. If the stored side is newer, the write fails with 409 instead of "
+ "overwriting the concurrent edit. Omit to overwrite unconditionally."
+ ),
+ )
masking = HogFunctionMaskingSerializer(
required=False,
allow_null=True,
@@ -192,6 +367,10 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):
"_create_in_folder",
"batch_export_id",
"search_match_type",
+ "version",
+ "draft",
+ "draft_updated_at",
+ "base_updated_at",
]
read_only_fields = [
"id",
@@ -202,6 +381,9 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):
"transpiled",
"template",
"status",
+ "version",
+ "draft",
+ "draft_updated_at",
]
extra_kwargs = {
"hog": {
@@ -223,6 +405,16 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):
"enabled": {"help_text": "Whether the function is active and processing events."},
"icon_url": {"help_text": "URL for the function's icon displayed in the UI."},
"execution_order": {"help_text": "Execution priority for transformations. Lower values run first."},
+ "version": {"help_text": "Incremented every time the live config changes. See the revisions endpoint."},
+ "draft": {
+ "help_text": (
+ "Config staged for review but not live yet: a full snapshot of hog, inputs_schema, inputs, "
+ "filters, mappings and masking. Null when nothing is staged. Publish or discard it to clear."
+ )
+ },
+ "draft_updated_at": {
+ "help_text": "When config was last staged for review, or null when nothing is staged.",
+ },
}
def _validate_template_is_creatable(self, template: HogFunctionTemplate) -> None:
@@ -255,6 +447,10 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):
# NOTE: All pre-validation should be done here such as loading the template info etc.
def to_internal_value(self, data):
+ # Copy before filling in defaults below: `data` is `request.data` itself, and injecting
+ # inputs/inputs_schema/filters into it made every metadata-only PATCH look to the viewset like
+ # a config edit. It also means a form-encoded (immutable QueryDict) payload no longer 500s.
+ data = {**data}
self.initial_data = data
team = self.context["get_team"]()
is_create = self.context.get("is_create") or (
@@ -434,7 +630,9 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):
return attrs
def to_representation(self, data):
- encrypted_inputs = data.encrypted_inputs or {} if isinstance(data, HogFunction) else {}
+ is_instance = isinstance(data, HogFunction)
+ encrypted_inputs = data.encrypted_inputs or {} if is_instance else {}
+ draft_encrypted_inputs = data.draft_encrypted_inputs or {} if is_instance else {}
data = super().to_representation(data)
inputs_schema = data.get("inputs_schema", []) or []
@@ -449,9 +647,29 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):
inputs[schema["key"]] = {"secret": True}
data["inputs"] = inputs
+ data["draft"] = self._mask_draft_secrets(data.get("draft"), draft_encrypted_inputs, encrypted_inputs)
return data
+ @staticmethod
+ def _mask_draft_secrets(
+ draft: Optional[dict], draft_encrypted_inputs: dict, encrypted_inputs: dict
+ ) -> Optional[dict]:
+ # A draft's secret values live in draft_encrypted_inputs (falling back to the live ones on
+ # publish), so the snapshot itself carries no secrets to hide — but the reader still needs to
+ # know a secret is set. Emit the same `{"secret": true}` marker the live inputs use, on a copy
+ # so the instance's stored draft is left alone.
+ if not isinstance(draft, dict):
+ return draft
+ inputs = dict(draft.get("inputs") or {})
+ for schema in draft.get("inputs_schema") or []:
+ key = schema.get("key") if isinstance(schema, dict) else None
+ if not key or not schema.get("secret"):
+ continue
+ if draft_encrypted_inputs.get(key) or encrypted_inputs.get(key) or inputs.get(key):
+ inputs[key] = {"secret": True}
+ return {**draft, "inputs": inputs}
+
def create(self, validated_data: dict, *args, **kwargs) -> HogFunction:
request = self.context["request"]
validated_data["created_by"] = request.user
@@ -512,7 +730,18 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):
class HogFunctionInvocationSerializer(serializers.Serializer):
- configuration = HogFunctionSerializer(write_only=True, help_text="Full function configuration to test.")
+ configuration = HogFunctionSerializer(
+ write_only=True, required=False, help_text="Full function configuration to test. Omit when use_draft is true."
+ )
+ use_draft = serializers.BooleanField(
+ default=False,
+ write_only=True,
+ help_text=(
+ "Test the function's staged draft instead of passing a configuration. Staged secret inputs "
+ "are used; secrets the draft doesn't change fall back to the live values. 400 when nothing "
+ "is staged."
+ ),
+ )
globals = serializers.DictField(
write_only=True, required=False, help_text="Mock global variables available during test invocation."
)
@@ -531,6 +760,76 @@ class HogFunctionInvocationSerializer(serializers.Serializer):
)
+class HogFunctionRevisionBasicSerializer(serializers.ModelSerializer):
+ # allow_null: the first tracked write bootstraps a snapshot of the pre-existing live config,
+ # which has no author.
+ created_by = UserBasicSerializer(read_only=True, allow_null=True)
+
+ class Meta:
+ model = HogFunctionRevision
+ fields = ["version", "created_at", "created_by"]
+ read_only_fields = fields
+
+
+class HogFunctionRevisionSerializer(HogFunctionRevisionBasicSerializer):
+ class Meta(HogFunctionRevisionBasicSerializer.Meta):
+ fields = [*HogFunctionRevisionBasicSerializer.Meta.fields, "content"]
+ read_only_fields = fields
+
+
+class HogFunctionRevisionRestoreRequestSerializer(serializers.Serializer):
+ overwrite = serializers.BooleanField(
+ default=False,
+ help_text=(
+ "Replace the open staged draft with this revision's config. Without it, restoring while a "
+ "draft is open returns 409."
+ ),
+ )
+
+
+class HogFunctionPublishRequestSerializer(serializers.Serializer):
+ confirm = serializers.BooleanField(
+ default=False,
+ help_text=(
+ "False (default) previews the publish: returns which config fields would change without "
+ "changing anything. True applies the staged draft to the live function."
+ ),
+ )
+ confirm_token = serializers.CharField(
+ required=False,
+ help_text=(
+ "From the preview response, and required when confirm=true on an enabled function. Expires "
+ "after 15 minutes, and any edit to the draft or the live config invalidates it (409), so you "
+ "always publish the exact draft you previewed."
+ ),
+ )
+
+
+class HogFunctionPublishResponseSerializer(serializers.Serializer):
+ published = serializers.BooleanField(help_text="Whether the draft was applied to the live function.")
+ draft_updated_at = serializers.DateTimeField(
+ allow_null=True,
+ help_text="The staged draft's timestamp, for reference; publishing is confirmed via confirm_token.",
+ )
+ confirm_token = serializers.CharField(
+ allow_null=True,
+ help_text="Echo this back with confirm=true to publish the previewed draft. Only set on previews.",
+ )
+ changed_fields = serializers.ListField(
+ child=serializers.CharField(),
+ allow_null=True,
+ help_text=(
+ "Config fields publishing would change (hog, inputs_schema, inputs, filters, mappings, masking). "
+ "Only set on previews."
+ ),
+ )
+ function = HogFunctionSerializer(
+ required=False,
+ allow_null=True,
+ help_text="The function after publishing (only set when published=true).",
+ )
+
+
class HogFunctionRearrangeSerializer(serializers.Serializer):
orders = serializers.DictField(
child=serializers.IntegerField(),
@@ -559,8 +858,26 @@ class HogFunctionViewSet(
viewsets.ModelViewSet,
):
scope_object = "hog_function"
- scope_object_read_actions = ["list", "retrieve", "logs", "metrics", "metrics_totals"]
- scope_object_write_actions = ["create", "update", "partial_update", "invocations", "rearrange", "rerun"]
+ scope_object_read_actions = [
+ "list",
+ "retrieve",
+ "logs",
+ "metrics",
+ "metrics_totals",
+ "revisions",
+ "revision_detail",
+ ]
+ scope_object_write_actions = [
+ "create",
+ "update",
+ "partial_update",
+ "invocations",
+ "rearrange",
+ "rerun",
+ "publish",
+ "discard_draft",
+ "restore_revision",
+ ]
queryset = HogFunction.objects.all()
filter_backends = [DjangoFilterBackend]
filterset_class = HogFunctionFilterSet
@@ -684,6 +1001,24 @@ class HogFunctionViewSet(
return icon_service.get_icon_http_response(id, team_id=self.team_id)
+ def _draft_test_configuration(self, hog_function: Optional[HogFunction]) -> dict:
+ """The staged draft as a test-invocable configuration: live config with the draft's content
+ fields on top, staged secrets rehydrated in plaintext so the test exercises what publish
+ would ship. Secrets the draft doesn't stage stay as `{"secret": true}` markers, which
+ validation recovers from the live encrypted inputs."""
+ if not use_destinations_revisions(self.team):
+ raise exceptions.ValidationError(DRAFTS_DISABLED_MESSAGE)
+ if hog_function is None or not hog_function.draft:
+ raise exceptions.ValidationError({"use_draft": "This function has no staged draft to test."})
+
+ serialized = self.get_serializer(hog_function).data
+ draft = serialized.get("draft") or {}
+ configuration = {**serialized, **{field: draft[field] for field in DRAFT_CONTENT_FIELDS if field in draft}}
+ inputs = dict(configuration.get("inputs") or {})
+ inputs.update(hog_function.draft_encrypted_inputs or {})
+ configuration["inputs"] = inputs
+ return configuration
+
@extend_schema(
request=HogFunctionInvocationSerializer,
responses={200: HogFunctionInvocationSerializer},
@@ -695,8 +1030,14 @@ class HogFunctionViewSet(
except Exception:
hog_function = None
+ data = request.data
+ if data.get("use_draft"):
+ data = {**data, "configuration": self._draft_test_configuration(hog_function)}
+ elif "configuration" not in data:
+ raise exceptions.ValidationError({"configuration": "Required unless use_draft is true."})
+
serializer = HogFunctionInvocationSerializer(
- data=request.data, context={**self.get_serializer_context(), "instance": hog_function}
+ data=data, context={**self.get_serializer_context(), "instance": hog_function}
)
if not serializer.is_valid():
return Response(serializer.errors, status=400)
@@ -778,6 +1119,19 @@ class HogFunctionViewSet(
return Response(res.json())
def perform_create(self, serializer):
+ # base_updated_at is an update-only concurrency guard; there is nothing to race on a create.
+ serializer.validated_data.pop("base_updated_at", None)
+ # An agent-created destination starts disabled: create, test, then enable in a separate call
+ # once the config looks right. Scoped like the draft cycle — other types (e.g. the alert
+ # recipe's internal_destination) create as sent, and a null type behaves as a destination
+ # everywhere else in this file.
+ if (
+ serializer.validated_data.get("enabled")
+ and (serializer.validated_data.get("type") or HogFunctionType.DESTINATION) == HogFunctionType.DESTINATION
+ and self._is_agent_request(self.request)
+ and use_destinations_revisions(self.team)
+ ):
+ raise exceptions.ValidationError({"enabled": CREATE_ENABLED_MESSAGE})
serializer.save()
log_activity_from_viewset(
self,
@@ -786,25 +1140,411 @@ class HogFunctionViewSet(
detail_type=humanize_hog_function_type(serializer.instance.type),
)
+ @staticmethod
+ def _is_agent_request(request: Request) -> bool:
+ return get_event_source(request) in AGENT_EVENT_SOURCES
+
+ def _sent_content_fields(self) -> set[str]:
+ # The config fields the caller actually asked to change. `to_internal_value` re-injects
+ # inputs/inputs_schema/filters from the instance on every payload, so validated_data can't
+ # tell us this — and trusting it would let a hog-only edit overwrite already-staged inputs
+ # with the live ones.
+ return set(self.request.data.keys()) & set(DRAFT_CONTENT_FIELDS)
+
+ def _should_route_to_draft(self, serializer: BaseSerializer, revisions_enabled: bool) -> bool:
+ # Guardrail for agent callers (MCP and the surfaces that wrap it; the web builder and raw API
+ # keys are unaffected). An agent editing a destination that is running right now stages a
+ # draft for a human to publish instead of changing what workers execute on the spot.
+ # Destinations only for now: transformations add execution-order semantics, site_* types add
+ # transpiled-JS concerns, and internal_destination rows are written by other products' code
+ # rather than by agents.
+ if not revisions_enabled or not self._is_agent_request(self.request):
+ return False
+ instance = serializer.instance
+ if not isinstance(instance, HogFunction) or not instance.enabled:
+ return False
+ if instance.type != HogFunctionType.DESTINATION:
+ return False
+ return bool(self._sent_content_fields())
+
+ def _write_draft(
+ self, instance: HogFunction, locked: HogFunction, serializer: BaseSerializer, validated_content: dict
+ ) -> None:
+ # The draft is always a full config snapshot (live config as the base, staged draft on top,
+ # this edit's validated fields last) so publish is a plain copy with no merge logic.
+ # validated_content is passed in because the caller's metadata save clears validated_data.
+ sent = self._sent_content_fields()
+ draft = {**snapshot_hog_function_content(locked), **(locked.draft or {})}
+ for field in sent:
+ if field in validated_content:
+ draft[field] = validated_content[field]
+
+ recovered = split_content_secrets(draft)
+ staged = locked.draft_encrypted_inputs or {}
+ if "inputs" in sent:
+ # Validation recovers a resent `{"secret": true}` marker from the *live* encrypted inputs,
+ # so a secret already staged in the draft has to win over that recovery — otherwise this
+ # edit would silently revert it to the live value. Keys the draft no longer declares
+ # secret drop out entirely.
+ supplied = explicit_secret_input_keys(getattr(serializer, "initial_data", {}).get("inputs"))
+ draft_secrets = {
+ key: value if key in supplied or key not in staged else staged[key] for key, value in recovered.items()
+ }
+ else:
+ # This edit didn't touch inputs, so whatever is already staged still applies — and with
+ # nothing staged, publish recovers the live secrets.
+ draft_secrets = staged
+
+ instance.draft = draft
+ instance.draft_updated_at = timezone.now()
+ instance.draft_encrypted_inputs = draft_secrets or None
+ instance.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])
+
+ def _record_revision(self, instance: HogFunction, before: HogFunction, before_content: dict) -> None:
+ """Version and snapshot a live config change. Runs right after the write it describes, in the
+ same transaction. Comparing two *persisted* snapshots, rather than validated_data against the
+ stored row, keeps a partial payload from reading as a config change; comparing them without
+ derived values keeps a background bytecode recompile from reading as one either."""
+ after_content = snapshot_hog_function_content(instance)
+ if comparable_content(after_content) == comparable_content(before_content):
+ return
+
+ instance.version = (before.version or 0) + 1
+ # queryset.update() rather than instance.save(): the bump must not fire a second worker
+ # reload for a config push that already happened, and workers never read `version`.
+ # nosemgrep: idor-lookup-without-team (ID from already team-scoped instance)
+ HogFunction.objects.filter(pk=instance.pk).update(version=instance.version)
+
+ # On the first tracked write, also snapshot the outgoing config so the state before any
+ # tracked change is always available to roll back to (there's no backfill).
+ if not HogFunctionRevision.objects.filter(hog_function=instance).exists():
+ HogFunctionRevision.objects.create(
+ team_id=self.team_id,
+ hog_function=instance,
+ version=before.version or 0,
+ content=before_content,
+ created_by=None,
+ )
+ HogFunctionRevision.objects.create(
+ team_id=self.team_id,
+ hog_function=instance,
+ version=instance.version,
+ content=after_content,
+ created_by=self.request.user if self.request.user.is_authenticated else None,
+ )
+
def perform_update(self, serializer):
instance_id = serializer.instance.id
+ # Resolved before the write transaction: the flag check can hit the network and must not
+ # extend the row lock.
+ revisions_enabled = use_destinations_revisions(self.team)
+ route_to_draft = self._should_route_to_draft(serializer, revisions_enabled)
+
+ # Enabling with a draft open would turn on the live config while the reviewed one sits
+ # unpublished. Make the caller resolve the draft first rather than picking for them.
+ # Checked on the validated value: BooleanField coerces "true"/"True", and the raw payload
+ # wouldn't catch those.
+ if (
+ revisions_enabled
+ and serializer.validated_data.get("enabled") is True
+ and isinstance(serializer.instance, HogFunction)
+ and serializer.instance.draft
+ and not serializer.instance.enabled
+ ):
+ raise exceptions.ValidationError({"enabled": ENABLE_WITH_OPEN_DRAFT_MESSAGE})
- try:
- # nosemgrep: idor-lookup-without-team (ID from already team-scoped instance)
- before_update = HogFunction.objects.get(pk=instance_id)
- except HogFunction.DoesNotExist:
- before_update = None
+ # Optimistic concurrency, same contract as workflows: a client may send the updated_at (or
+ # draft_updated_at) it last loaded as `base_updated_at`. If the stored side is strictly newer,
+ # another channel wrote in between: 409 rather than silently clobbering. Omitting it keeps
+ # last-writer-wins. Popped so it never reaches the model save.
+ base_updated_at = serializer.validated_data.pop("base_updated_at", None)
- serializer.save()
+ with transaction.atomic():
+ try:
+ # nosemgrep: idor-lookup-without-team (ID from already team-scoped instance; locked for the save)
+ locked = HogFunction.objects.select_for_update().get(pk=instance_id)
+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)
+ before_update = HogFunction.objects.get(pk=instance_id)
+ except HogFunction.DoesNotExist:
+ locked = None
+ before_update = None
+
+ route_to_draft = route_to_draft and locked is not None
+
+ # Draft edits race against other draft edits, not against the live row (which they don't
+ # touch), so the staleness baseline is the draft's own timestamp once a draft exists.
+ guard_timestamp = locked.updated_at if locked else None
+ if route_to_draft and locked and locked.draft_updated_at:
+ guard_timestamp = locked.draft_updated_at
+ if base_updated_at and guard_timestamp and guard_timestamp > base_updated_at:
+ raise StaleHogFunctionUpdateError()
+ if route_to_draft:
+ assert locked is not None
+ # Preserved before the metadata save clears validated_data below.
+ validated_content = {
+ field: serializer.validated_data[field]
+ for field in DRAFT_CONTENT_FIELDS
+ if field in serializer.validated_data
+ }
+ # Metadata in the same payload still applies live. Config (and the bytecode compiled
+ # from it) must not leak onto the live row — it belongs to the draft now.
+ remaining = {
+ key: value
+ for key, value in serializer.validated_data.items()
+ if key not in DRAFT_CONTENT_FIELDS
+ and key not in _DERIVED_CONTENT_FIELDS
+ and key not in _INJECTED_UPDATE_FIELDS
+ }
+ # The save target is the locked row, never the request-start instance: a
+ # ModelSerializer save writes every column, so saving the object fetched before
+ # validation would write its stale config back over anything a concurrent live edit
+ # committed in between. Metadata saves first — the full save would otherwise clobber
+ # the draft columns _write_draft is about to fill with the locked row's pre-draft
+ # values.
+ serializer.instance = locked
+ if remaining:
+ serializer.validated_data.clear()
+ serializer.validated_data.update({**remaining, "team": self.team})
+ serializer.save()
+ self._write_draft(locked, locked, serializer, validated_content)
+ else:
+ before_content = snapshot_hog_function_content(locked) if locked else None
+ serializer.save()
+ if locked is not None and before_content is not None and revisions_enabled:
+ self._record_revision(serializer.instance, locked, before_content)
log_activity_from_viewset(
self,
serializer.instance,
+ activity="draft_updated" if route_to_draft else None,
name=serializer.instance.name,
previous=before_update,
detail_type=humanize_hog_function_type(serializer.instance.type),
)
+ @extend_schema(request=HogFunctionPublishRequestSerializer, responses={200: HogFunctionPublishResponseSerializer})
+ @action(detail=True, methods=["POST"])
+ def publish(self, request: Request, *args, **kwargs):
+ # Promote the staged draft to the live config. Two-step by design: a call without confirm only
+ # echoes what would change, so callers — especially agents — never publish blind.
+ if not use_destinations_revisions(self.team):
+ raise exceptions.ValidationError(DRAFTS_DISABLED_MESSAGE)
+
+ param_serializer = HogFunctionPublishRequestSerializer(data=request.data)
+ param_serializer.is_valid(raise_exception=True)
+
+ instance = self.get_object()
+ if not instance.draft:
+ raise exceptions.ValidationError("This function has no staged draft to publish.")
+
+ if not param_serializer.validated_data["confirm"]:
+ return Response(
+ {
+ "published": False,
+ "draft_updated_at": instance.draft_updated_at,
+ "confirm_token": mint_publish_confirm_token(instance),
+ "changed_fields": draft_changed_fields(instance),
+ "function": None,
+ }
+ )
+
+ with transaction.atomic():
+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)
+ locked = HogFunction.objects.select_for_update().get(pk=instance.pk)
+ if not locked.draft:
+ raise exceptions.ValidationError("This function has no staged draft to publish.")
+ # A disabled function processes nothing, so publishing into it can't misroute traffic and
+ # doesn't need the preview receipt. The preview is still offered either way.
+ if locked.enabled:
+ previewed_value = self._unsign_publish_confirm_token(
+ param_serializer.validated_data.get("confirm_token")
+ )
+ if previewed_value != _publish_confirm_value(locked):
+ raise StaleHogFunctionUpdateError()
+
+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)
+ before_update = HogFunction.objects.get(pk=instance.pk)
+ before_content = snapshot_hog_function_content(before_update)
+
+ # The draft's own staged secrets outrank the live ones while the draft is revalidated: the
+ # serializer recovers secret inputs from `instance.encrypted_inputs`, and save() re-splits
+ # whatever it recovered back into that column.
+ locked.encrypted_inputs = {
+ **(locked.encrypted_inputs or {}),
+ **(locked.draft_encrypted_inputs or {}),
+ }
+ # The draft goes back through the normal serializer so publish revalidates strictly and
+ # recompiles bytecode — a stored blob is never trusted to be execution-ready.
+ serializer = self.get_serializer(locked, data=dict(locked.draft), partial=True)
+ serializer.is_valid(raise_exception=True)
+ serializer.save()
+ self._record_revision(locked, before_update, before_content)
+
+ locked.draft = None
+ locked.draft_updated_at = None
+ locked.draft_encrypted_inputs = None
+ locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])
+
+ log_activity_from_viewset(
+ self,
+ locked,
+ activity="published",
+ name=locked.name,
+ previous=before_update,
+ detail_type=humanize_hog_function_type(locked.type),
+ )
+
+ return Response(
+ {
+ "published": True,
+ "draft_updated_at": None,
+ "confirm_token": None,
+ "changed_fields": None,
+ "function": self.get_serializer(locked).data,
+ }
+ )
+
+ @staticmethod
+ def _unsign_publish_confirm_token(confirm_token: Optional[str]) -> str:
+ if not confirm_token:
+ raise exceptions.ValidationError(
+ {
+ "confirm_token": (
+ "Required when confirming a publish. Call publish without confirm first to see "
+ "what would change and get a token."
+ )
+ }
+ )
+ try:
+ return TimestampSigner(salt=_PUBLISH_CONFIRM_SALT).unsign(
+ confirm_token, max_age=PUBLISH_CONFIRM_TOKEN_MAX_AGE
+ )
+ except SignatureExpired:
+ raise exceptions.ValidationError(
+ {"confirm_token": "Expired. Preview the publish again to get a fresh token."}
+ )
+ except BadSignature:
+ raise exceptions.ValidationError(
+ {
+ "confirm_token": (
+ "Invalid. Call publish without confirm first to see what would change and get a token."
+ )
+ }
+ )
+
+ @extend_schema(request=None, responses={200: HogFunctionSerializer})
+ @action(detail=True, methods=["POST"])
+ def discard_draft(self, request: Request, *args, **kwargs):
+ # Throw away the staged draft. Idempotent: discarding when nothing is staged is a no-op.
+ if not use_destinations_revisions(self.team):
+ raise exceptions.ValidationError(DRAFTS_DISABLED_MESSAGE)
+
+ instance = self.get_object()
+ with transaction.atomic():
+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)
+ locked = HogFunction.objects.select_for_update().get(pk=instance.pk)
+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)
+ before_update = HogFunction.objects.get(pk=instance.pk)
+ had_draft = locked.draft is not None
+ locked.draft = None
+ locked.draft_updated_at = None
+ locked.draft_encrypted_inputs = None
+ locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])
+
+ # The no-op case stays out of the audit trail: nothing was discarded.
+ if had_draft:
+ log_activity_from_viewset(
+ self,
+ locked,
+ activity="draft_discarded",
+ name=locked.name,
+ previous=before_update,
+ detail_type=humanize_hog_function_type(locked.type),
+ )
+
+ return Response(self.get_serializer(locked).data)
+
+ @extend_schema(responses={200: HogFunctionRevisionBasicSerializer(many=True)})
+ # filter_backends=[]: don't inherit the viewset's HogFunction filterset — its fields would be
+ # advertised as query params in the generated contract but silently ignored here.
+ @action(detail=True, methods=["GET"], filter_backends=[])
+ def revisions(self, request: Request, *args, **kwargs):
+ # Version history: one snapshot per live-config change, newest first. Config is fetched
+ # per-version via the detail endpoint — the list stays light.
+ if not use_destinations_revisions(self.team):
+ raise exceptions.ValidationError(REVISIONS_DISABLED_MESSAGE)
+ instance = self.get_object()
+ queryset = (
+ HogFunctionRevision.objects.filter(hog_function=instance).order_by("-version").select_related("created_by")
+ )
+ page = self.paginate_queryset(queryset)
+ return self.get_paginated_response(HogFunctionRevisionBasicSerializer(page, many=True).data)
+
+ @extend_schema(
+ parameters=[OpenApiParameter("version", int, OpenApiParameter.PATH, description="Function version to fetch.")],
+ responses={200: HogFunctionRevisionSerializer},
+ filters=False,
+ )
+ @action(detail=True, methods=["GET"], url_path=r"revisions/(?P<version>\d+)", filter_backends=[])
+ def revision_detail(self, request: Request, version: Optional[str] = None, *args, **kwargs):
+ if not use_destinations_revisions(self.team):
+ raise exceptions.ValidationError(REVISIONS_DISABLED_MESSAGE)
+ instance = self.get_object()
+ try:
+ revision = HogFunctionRevision.objects.get(hog_function=instance, version=int(version or 0))
+ except HogFunctionRevision.DoesNotExist:
+ raise exceptions.NotFound("No such revision for this function.")
+ return Response(HogFunctionRevisionSerializer(revision).data)
+
+ @extend_schema(
+ parameters=[
+ OpenApiParameter("version", int, OpenApiParameter.PATH, description="Function version to restore.")
+ ],
+ request=HogFunctionRevisionRestoreRequestSerializer,
+ responses={200: HogFunctionSerializer},
+ filters=False,
+ )
+ @action(detail=True, methods=["POST"], url_path=r"revisions/(?P<version>\d+)/restore", filter_backends=[])
+ def restore_revision(self, request: Request, version: Optional[str] = None, *args, **kwargs):
+ # Rollback (or roll-forward) = copy the revision's config into the draft, then go through the
+ # normal publish preview + confirm. Nothing here touches the live config, so a rollback is
+ # reviewed like any other change.
+ if not use_destinations_revisions(self.team):
+ raise exceptions.ValidationError(REVISIONS_DISABLED_MESSAGE)
+ param_serializer = HogFunctionRevisionRestoreRequestSerializer(data=request.data)
+ param_serializer.is_valid(raise_exception=True)
+
+ instance = self.get_object()
+ with transaction.atomic():
+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)
+ locked = HogFunction.objects.select_for_update().get(pk=instance.pk)
+ try:
+ revision = HogFunctionRevision.objects.get(hog_function_id=locked.pk, version=int(version or 0))
+ except HogFunctionRevision.DoesNotExist:
+ raise exceptions.NotFound("No such revision for this function.")
+ if locked.draft and not param_serializer.validated_data["overwrite"]:
+ raise DraftExistsError()
+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)
+ before_update = HogFunction.objects.get(pk=instance.pk)
+ locked.draft = dict(revision.content)
+ locked.draft_updated_at = timezone.now()
+ # Revision snapshots carry no secrets, so the restored draft re-attaches from the live
+ # encrypted inputs on the follow-up publish. Clearing also stops a prior draft's staged
+ # secrets from bleeding into this one.
+ locked.draft_encrypted_inputs = None
+ locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])
+
+ log_activity_from_viewset(
+ self,
+ locked,
+ activity="revision_restored",
+ name=locked.name,
+ previous=before_update,
+ detail_type=humanize_hog_function_type(locked.type),
+ )
+
+ return Response(self.get_serializer(locked).data)
+
@extend_schema(
request=HogFunctionRearrangeSerializer,
responses={200: HogFunctionSerializer(many=True)},
diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.py
index 85f4c3e1917d..3dc3faf09604 100644
--- a/products/cdp/backend/api/test/test_hog_function.py
+++ b/products/cdp/backend/api/test/test_hog_function.py
@@ -387,6 +387,9 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
"status": {"state": 0, "tokens": 0},
"execution_order": None,
"batch_export_id": None,
+ "version": 1,
+ "draft": None,
+ "draft_updated_at": None,
}
id = response.json()["id"]
diff --git a/products/cdp/backend/api/test/test_hog_function_drafts.py b/products/cdp/backend/api/test/test_hog_function_drafts.py
new file mode 100644
index 000000000000..c69f6e557554
--- /dev/null
+++ b/products/cdp/backend/api/test/test_hog_function_drafts.py
@@ -0,0 +1,526 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models.activity_logging.activity_log import ActivityLog
+
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cdp.backend.models.hog_functions.hog_function_revision import HogFunctionRevision
+
+FLAG_PATH = "products.cdp.backend.api.hog_function.use_destinations_revisions"
+RELOAD_PATH = "products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers"
+
+LIVE_HOG = "fetch(inputs.url);"
+EDITED_HOG = "fetch(inputs.url, {'method': 'PUT'});"
+
+BASE_FUNCTION = {
+ "name": "Webhook",
+ "type": "destination",
+ "hog": LIVE_HOG,
+ "enabled": True,
+ "inputs_schema": [
+ {"key": "url", "type": "string", "label": "Webhook URL", "required": True},
+ {"key": "token", "type": "string", "label": "Token", "secret": True, "required": False},
+ ],
+ "inputs": {"url": {"value": "https://example.com/live"}, "token": {"value": "live-token"}},
+}
+
+
+class DraftTestCase(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ flag = patch(FLAG_PATH, return_value=True)
+ flag.start()
+ self.addCleanup(flag.stop)
+
+ def _url(self, function_id: str = "", suffix: str = "") -> str:
+ base = f"/api/projects/{self.team.id}/hog_functions/"
+ return f"{base}{function_id}{suffix}" if function_id else base
+
+ def _create(self, **overrides) -> str:
+ response = self.client.post(self._url(), data={**BASE_FUNCTION, **overrides})
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ return response.json()["id"]
+
+ def _agent_patch(self, function_id: str, payload: dict):
+ return self.client.patch(self._url(function_id), payload, headers={"x-posthog-client": "mcp"})
+
+ def _stage(self, function_id: str, payload: dict) -> dict:
+ response = self._agent_patch(function_id, payload)
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ return response.json()
+
+ def _live_edit(self, function_id: str, payload: dict):
+ response = self.client.patch(self._url(function_id), payload)
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ return response.json()
+
+ def _revisions(self, function_id: str):
+ return HogFunctionRevision.objects.for_team(self.team.id).filter(hog_function_id=function_id)
+
+
+class TestHogFunctionDrafts(DraftTestCase):
+ def _preview_publish(self, function_id: str) -> dict:
+ response = self.client.post(self._url(function_id, "/publish"), {})
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ return response.json()
+
+ def _publish(self, function_id: str):
+ preview = self._preview_publish(function_id)
+ return self.client.post(
+ self._url(function_id, "/publish"),
+ {"confirm": True, "confirm_token": preview["confirm_token"]},
+ )
+
+ def test_agent_config_edit_to_enabled_function_stages_a_draft(self):
+ function_id = self._create()
+
+ with patch(RELOAD_PATH) as mock_reload:
+ response = self._stage(function_id, {"hog": EDITED_HOG})
+
+ assert response["draft"]["hog"] == EDITED_HOG
+ assert response["draft_updated_at"] is not None
+ # The whole point: workers keep running the config a human last approved.
+ mock_reload.assert_not_called()
+ assert HogFunction.objects.get(id=function_id).hog == LIVE_HOG
+
+ @parameterized.expand(
+ [
+ # An agent can't stage a draft on a function that isn't running, and the web builder
+ # saves what the person just reviewed, so neither routes to a draft.
+ ("disabled_function", True, {"enabled": False}, True),
+ ("web_caller", False, {}, True),
+ # Only destinations are in the cycle for now. A transformation edit still applies live.
+ ("transformation", True, {"type": "transformation", "hog": "return event"}, True),
+ # The flag is the kill switch: off means the pre-draft behavior, edits apply live.
+ ("flag_off", True, {}, False),
+ ]
+ )
+ def test_config_edit_applies_live(self, _name: str, from_agent: bool, overrides: dict, flag_on: bool):
+ function_id = self._create(**overrides)
+
+ with patch(FLAG_PATH, return_value=flag_on):
+ response = (
+ self._agent_patch(function_id, {"hog": EDITED_HOG})
+ if from_agent
+ else self.client.patch(self._url(function_id), {"hog": EDITED_HOG})
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["draft"] is None
+ assert HogFunction.objects.get(id=function_id).hog == EDITED_HOG
+
+ def test_agent_metadata_in_a_config_edit_still_applies_live(self):
+ function_id = self._create()
+
+ self._stage(function_id, {"name": "Renamed", "enabled": False, "filters": {"source": "events"}})
+
+ function = HogFunction.objects.get(id=function_id)
+ assert function.name == "Renamed"
+ assert function.enabled is False
+ assert function.draft is not None
+ assert function.draft["filters"]["source"] == "events"
+
+ def test_metadata_in_a_draft_edit_does_not_revert_a_concurrent_live_edit(self):
+ function_id = self._create()
+ concurrent_hog = "fetch(inputs.url, {'method': 'DELETE'});"
+
+ def live_edit_lands_after_initial_fetch(_team):
+ # Stand in for a builder edit committing between the request's initial unlocked fetch
+ # and its write: the flag check runs after get_object() and before the transaction.
+ HogFunction.objects.filter(id=function_id).update(hog=concurrent_hog)
+ return True
+
+ with patch(FLAG_PATH, side_effect=live_edit_lands_after_initial_fetch):
+ response = self._agent_patch(function_id, {"name": "Renamed", "hog": EDITED_HOG})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ function = HogFunction.objects.get(id=function_id)
+ assert function.name == "Renamed"
+ # The metadata save must not write the request-start config back over the concurrent edit.
+ assert function.hog == concurrent_hog
+ assert function.draft is not None
+ assert function.draft["hog"] == EDITED_HOG
+
+ def test_metadata_only_agent_edit_stages_nothing(self):
+ function_id = self._create()
+
+ # The serializer fills inputs/inputs_schema/filters defaults in; that must not read as a
+ # config edit and strand a no-op draft on the function.
+ self._stage(function_id, {"description": "Now documented"})
+
+ function = HogFunction.objects.get(id=function_id)
+ assert function.draft is None
+ assert function.description == "Now documented"
+
+ def test_a_later_draft_edit_keeps_earlier_staged_config(self):
+ function_id = self._create()
+ self._stage(function_id, {"inputs": {"url": {"value": "https://example.com/staged"}}})
+
+ draft = self._stage(function_id, {"hog": EDITED_HOG})["draft"]
+
+ assert draft["inputs"]["url"]["value"] == "https://example.com/staged"
+ assert draft["hog"] == EDITED_HOG
+
+ def test_publish_preview_reports_changed_fields_without_applying(self):
+ function_id = self._create()
+ self._stage(function_id, {"hog": EDITED_HOG})
+
+ preview = self._preview_publish(function_id)
+
+ assert preview["published"] is False
+ assert preview["changed_fields"] == ["hog"]
+ assert preview["confirm_token"]
+ assert HogFunction.objects.get(id=function_id).hog == LIVE_HOG
+
+ def test_publish_applies_the_draft_and_bumps_the_version(self):
+ function_id = self._create()
+ self._stage(function_id, {"hog": EDITED_HOG})
+
+ response = self._publish(function_id)
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["published"] is True
+ function = HogFunction.objects.get(id=function_id)
+ assert function.hog == EDITED_HOG
+ assert function.draft is None
+ assert function.draft_updated_at is None
+ assert function.version == 2
+ # Publish revalidates rather than trusting the stored blob, so bytecode is recompiled.
+ assert function.bytecode is not None
+ assert self._revisions(function_id).count() == 2
+
+ @parameterized.expand(
+ [
+ ("no_token", {"confirm": True}, status.HTTP_400_BAD_REQUEST),
+ ("nothing_staged", {}, status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ def test_publish_is_rejected(self, name: str, payload: dict, expected: int):
+ function_id = self._create()
+ if name != "nothing_staged":
+ self._stage(function_id, {"hog": EDITED_HOG})
+
+ response = self.client.post(self._url(function_id, "/publish"), payload)
+
+ assert response.status_code == expected, response.json()
+ assert HogFunction.objects.get(id=function_id).hog == LIVE_HOG
+
+ @parameterized.expand(
+ [
+ # The draft is a full snapshot, so a token minted before either side moved would publish
+ # over whatever landed since. Both cases have to force a fresh preview.
+ ("draft_moved", True),
+ ("live_moved", False),
+ ]
+ )
+ def test_publish_with_a_token_from_before_the_latest_edit_conflicts(self, _name: str, edit_draft: bool):
+ function_id = self._create()
+ self._stage(function_id, {"hog": EDITED_HOG})
+ stale_token = self._preview_publish(function_id)["confirm_token"]
+ if edit_draft:
+ self._stage(function_id, {"hog": "fetch(inputs.url, {'method': 'PATCH'});"})
+ else:
+ self._live_edit(function_id, {"name": "Renamed in the builder"})
+
+ response = self.client.post(self._url(function_id, "/publish"), {"confirm": True, "confirm_token": stale_token})
+
+ assert response.status_code == status.HTTP_409_CONFLICT, response.json()
+ assert HogFunction.objects.get(id=function_id).hog == LIVE_HOG
+
+ def test_publishing_a_disabled_function_skips_the_confirm_token(self):
+ function_id = self._create()
+ self._stage(function_id, {"hog": EDITED_HOG})
+ self._live_edit(function_id, {"enabled": False})
+
+ # Nothing is running, so there is no traffic to misroute and no receipt to insist on.
+ response = self.client.post(self._url(function_id, "/publish"), {"confirm": True})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert HogFunction.objects.get(id=function_id).hog == EDITED_HOG
+
+ def test_enabling_with_a_draft_open_is_refused(self):
+ function_id = self._create()
+ self._stage(function_id, {"hog": EDITED_HOG})
+ self._live_edit(function_id, {"enabled": False})
+
+ response = self.client.patch(self._url(function_id), {"enabled": True})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert HogFunction.objects.get(id=function_id).enabled is False
+
+ def test_discard_draft_clears_the_draft_and_is_idempotent(self):
+ function_id = self._create()
+ self._stage(function_id, {"hog": EDITED_HOG})
+
+ first = self.client.post(self._url(function_id, "/discard_draft"))
+ second = self.client.post(self._url(function_id, "/discard_draft"))
+
+ assert first.status_code == status.HTTP_200_OK, first.json()
+ assert second.status_code == status.HTTP_200_OK, second.json()
+ function = HogFunction.objects.get(id=function_id)
+ assert function.draft is None
+ assert function.draft_encrypted_inputs is None
+ assert function.hog == LIVE_HOG
+ # The no-op second discard must not add audit noise.
+ assert (
+ ActivityLog.objects.filter(scope="HogFunction", item_id=function_id, activity="draft_discarded").count()
+ == 1
+ )
+
+ def test_staged_secret_survives_a_later_edit_that_resends_the_marker(self):
+ function_id = self._create()
+ self._stage(function_id, {"inputs": {"url": {"value": "https://example.com/live"}, "token": {"value": "new"}}})
+
+ # The API hands secrets back as `{"secret": true}`; resending that must not revert the staged
+ # value to the live one.
+ self._stage(
+ function_id,
+ {"inputs": {"url": {"value": "https://example.com/staged"}, "token": {"secret": True}}},
+ )
+
+ function = HogFunction.objects.get(id=function_id)
+ assert function.draft_encrypted_inputs["token"]["value"] == "new"
+ assert function.encrypted_inputs["token"]["value"] == "live-token"
+
+ def test_publishing_promotes_the_staged_secret(self):
+ function_id = self._create()
+ self._stage(function_id, {"inputs": {"url": {"value": "https://example.com/live"}, "token": {"value": "new"}}})
+
+ response = self._publish(function_id)
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ function = HogFunction.objects.get(id=function_id)
+ assert function.encrypted_inputs["token"]["value"] == "new"
+ assert function.draft_encrypted_inputs is None
+
+ def test_draft_never_carries_secret_values(self):
+ function_id = self._create()
+
+ draft = self._stage(
+ function_id, {"inputs": {"url": {"value": "https://example.com/live"}, "token": {"value": "new"}}}
+ )["draft"]
+
+ assert draft["inputs"]["token"] == {"secret": True}
+ stored_draft = HogFunction.objects.get(id=function_id).draft
+ assert stored_draft is not None
+ assert "token" not in stored_draft["inputs"]
+
+ def test_enabling_with_a_draft_open_is_refused_for_coercible_booleans(self):
+ function_id = self._create()
+ self._stage(function_id, {"hog": EDITED_HOG})
+ self._live_edit(function_id, {"enabled": False})
+
+ # BooleanField coerces "true" to True, so the refusal must fire on the validated value, not
+ # the raw payload.
+ response = self.client.patch(self._url(function_id), {"enabled": "true"})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert HogFunction.objects.get(id=function_id).enabled is False
+
+ @parameterized.expand(
+ [
+ # A draft edit races other draft edits, a live edit races the live row; either way a
+ # base_updated_at older than the stored side means someone wrote in between.
+ ("draft_edit", True),
+ ("live_edit", False),
+ ]
+ )
+ def test_stale_base_updated_at_is_a_conflict(self, _name: str, agent_edit: bool):
+ function_id = self._create()
+ self._stage(function_id, {"hog": EDITED_HOG})
+
+ payload = {"hog": "fetch(inputs.url, {'method': 'PATCH'});", "base_updated_at": "2020-01-01T00:00:00Z"}
+ response = (
+ self._agent_patch(function_id, payload)
+ if agent_edit
+ else self.client.patch(self._url(function_id), payload)
+ )
+
+ assert response.status_code == status.HTTP_409_CONFLICT, response.json()
+
+ def test_current_base_updated_at_is_accepted(self):
+ function_id = self._create()
+ staged = self._stage(function_id, {"hog": EDITED_HOG})
+
+ response = self._agent_patch(
+ function_id,
+ {"hog": "fetch(inputs.url, {'method': 'PATCH'});", "base_updated_at": staged["draft_updated_at"]},
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ def _test_invoke(self, function_id: str, payload: dict):
+ with patch("products.cdp.backend.api.hog_function.create_hog_invocation_test") as mock_invoke:
+ mock_invoke.return_value.status_code = 200
+ mock_invoke.return_value.json.return_value = {"status": "success", "logs": []}
+ response = self.client.post(self._url(function_id, "/invocations"), payload)
+ return response, mock_invoke
+
+ def test_invocations_use_draft_tests_staged_config_and_secrets(self):
+ function_id = self._create()
+ self._stage(
+ function_id,
+ {"hog": EDITED_HOG, "inputs": {"url": {"value": "https://example.com/live"}, "token": {"value": "new"}}},
+ )
+
+ response, mock_invoke = self._test_invoke(function_id, {"use_draft": True})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ configuration = mock_invoke.call_args.kwargs["payload"]["configuration"]
+ assert configuration["hog"] == EDITED_HOG
+ # The staged secret is what gets exercised, not the live one it will replace.
+ assert configuration["inputs"]["token"]["value"] == "new"
+
+ def test_invocations_use_draft_recovers_unstaged_secrets_from_live(self):
+ function_id = self._create()
+ self._stage(function_id, {"hog": EDITED_HOG})
+
+ response, mock_invoke = self._test_invoke(function_id, {"use_draft": True})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ configuration = mock_invoke.call_args.kwargs["payload"]["configuration"]
+ assert configuration["inputs"]["token"]["value"] == "live-token"
+
+ def test_invocations_use_draft_without_a_draft_is_rejected(self):
+ function_id = self._create()
+
+ response = self.client.post(self._url(function_id, "/invocations"), {"use_draft": True})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+
+ @parameterized.expand(
+ [
+ # Only the destination type is held to the create-disabled-then-enable path: the alert
+ # recipe legitimately creates internal_destination functions enabled in one call, and the
+ # web builder is a human clicking through a confirm UI.
+ ("agent_destination", True, "destination", status.HTTP_400_BAD_REQUEST),
+ ("agent_internal_destination", True, "internal_destination", status.HTTP_201_CREATED),
+ ("web_destination", False, "destination", status.HTTP_201_CREATED),
+ ]
+ )
+ def test_create_as_enabled(self, _name: str, from_agent: bool, function_type: str, expected: int):
+ payload = {**BASE_FUNCTION, "type": function_type}
+ headers = {"x-posthog-client": "mcp"} if from_agent else {}
+
+ response = self.client.post(self._url(), data=payload, headers=headers)
+
+ assert response.status_code == expected, response.json()
+
+
+class TestHogFunctionRevisions(DraftTestCase):
+ def test_first_live_config_change_also_snapshots_the_outgoing_config(self):
+ function_id = self._create()
+
+ self._live_edit(function_id, {"hog": EDITED_HOG})
+
+ revisions = list(self._revisions(function_id).order_by("version"))
+ assert [revision.version for revision in revisions] == [1, 2]
+ # Rollback to the state before the revision system saw this function must be possible.
+ assert revisions[0].content["hog"] == LIVE_HOG
+ assert revisions[0].created_by is None
+ assert revisions[1].content["hog"] == EDITED_HOG
+ assert revisions[1].created_by == self.user
+
+ @parameterized.expand(
+ [
+ # `to_internal_value` re-injects inputs/filters and the serializer recompiles bytecode on
+ # every save, so an unchanged config must still compare equal and stay unversioned.
+ ("metadata_only", {"name": "Renamed"}, True),
+ ("config_resent_unchanged", {"hog": LIVE_HOG, "name": "Renamed"}, True),
+ ("flag_off", {"hog": EDITED_HOG}, False),
+ ]
+ )
+ def test_no_revision_is_written(self, _name: str, payload: dict, flag_on: bool):
+ function_id = self._create()
+
+ with patch(FLAG_PATH, return_value=flag_on):
+ self._live_edit(function_id, payload)
+
+ assert not self._revisions(function_id).exists()
+ assert HogFunction.objects.get(id=function_id).version == 1
+
+ def test_recompiled_filter_bytecode_does_not_create_a_revision(self):
+ function_id = self._create()
+ # Stand in for a background re-save that recompiled filter bytecode without the config
+ # changing, which is what refresh_affected_hog_functions does after an action or cohort edit.
+ # queryset.update() so no signal or serializer runs.
+ HogFunction.objects.filter(id=function_id).update(filters={"source": "events", "bytecode": ["_H", 1, 999]})
+
+ self._live_edit(function_id, {"name": "Renamed"})
+
+ assert not self._revisions(function_id).exists()
+ assert HogFunction.objects.get(id=function_id).version == 1
+
+ def test_revisions_list_is_newest_first_and_omits_config(self):
+ function_id = self._create()
+ self._live_edit(function_id, {"hog": EDITED_HOG})
+
+ response = self.client.get(self._url(function_id, "/revisions"))
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ results = response.json()["results"]
+ assert [result["version"] for result in results] == [2, 1]
+ assert "content" not in results[0]
+
+ def test_revision_detail_returns_config_without_secret_values(self):
+ function_id = self._create()
+ self._live_edit(function_id, {"hog": EDITED_HOG})
+
+ response = self.client.get(self._url(function_id, "/revisions/1"))
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["content"]["hog"] == LIVE_HOG
+ assert "token" not in response.json()["content"]["inputs"]
+
+ def test_unknown_revision_is_a_404(self):
+ function_id = self._create()
+
+ response = self.client.get(self._url(function_id, "/revisions/99"))
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND, response.json()
+
+ def test_restore_stages_the_old_config_without_touching_the_live_one(self):
+ function_id = self._create()
+ self._live_edit(function_id, {"hog": EDITED_HOG})
+
+ response = self.client.post(self._url(function_id, "/revisions/1/restore"))
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ function = HogFunction.objects.get(id=function_id)
+ assert function.draft is not None
+ assert function.draft["hog"] == LIVE_HOG
+ assert function.hog == EDITED_HOG
+
+ def test_restore_over_an_open_draft_needs_overwrite(self):
+ function_id = self._create()
+ self._live_edit(function_id, {"hog": EDITED_HOG})
+ self._stage(function_id, {"hog": "fetch(inputs.url, {'method': 'PATCH'});"})
+
+ conflict = self.client.post(self._url(function_id, "/revisions/1/restore"))
+ forced = self.client.post(self._url(function_id, "/revisions/1/restore"), {"overwrite": True})
+
+ assert conflict.status_code == status.HTTP_409_CONFLICT, conflict.json()
+ assert forced.status_code == status.HTTP_200_OK, forced.json()
+ restored_draft = HogFunction.objects.get(id=function_id).draft
+ assert restored_draft is not None
+ assert restored_draft["hog"] == LIVE_HOG
+
+ @parameterized.expand(
+ [
+ ("publish", "post", "/publish"),
+ ("discard_draft", "post", "/discard_draft"),
+ ("revisions", "get", "/revisions"),
+ ("revision_detail", "get", "/revisions/1"),
+ ("restore_revision", "post", "/revisions/1/restore"),
+ ]
+ )
+ def test_endpoints_are_rejected_when_the_flag_is_off(self, _name: str, method: str, suffix: str):
+ function_id = self._create()
+
+ with patch(FLAG_PATH, return_value=False):
+ response = getattr(self.client, method)(self._url(function_id, suffix))
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
diff --git a/products/cdp/backend/services/revisions.py b/products/cdp/backend/services/revisions.py
new file mode 100644
index 000000000000..5c91b25b0189
--- /dev/null
+++ b/products/cdp/backend/services/revisions.py
@@ -0,0 +1,37 @@
+import structlog
+import posthoganalytics
+
+from posthog.models.team.team import Team
+
+logger = structlog.get_logger(__name__)
+
+DESTINATIONS_REVISIONS_FLAG = "destinations-revisions"
+
+
+def use_destinations_revisions(team: Team) -> bool:
+ """Gates the draft → review → publish cycle on enabled functions; off means today's behavior
+ (every edit lands straight on the live config that workers execute).
+
+ A raised exception (Redis/HyperCache blip, network glitch, SDK bug) is treated as "flag off" so
+ the flag is a kill switch: edits keep applying live, exactly as they did before this shipped.
+ """
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ DESTINATIONS_REVISIONS_FLAG,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ "project": {"id": str(team.id)},
+ },
+ )
+ )
+ except Exception:
+ logger.warning(
+ "cdp.revisions.feature_flag_check_failed_defaulting_off",
+ team_id=team.id,
+ flag=DESTINATIONS_REVISIONS_FLAG,
+ exc_info=True,
+ )
+ return False
diff --git a/products/cdp/frontend/generated/api.schemas.ts b/products/cdp/frontend/generated/api.schemas.ts
index 3ab5a6246d98..e3dcd00f814a 100644
--- a/products/cdp/frontend/generated/api.schemas.ts
+++ b/products/cdp/frontend/generated/api.schemas.ts
@@ -199,6 +199,11 @@ export interface HogFunctionMinimalApi {
readonly execution_order: number | null
/** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`. */
readonly search_match_type: SearchMatchTypeEnumApi | null
+ /**
+ * When config was last staged for review, or null when nothing is staged.
+ * @nullable
+ */
+ readonly draft_updated_at: string | null
}
export interface PaginatedHogFunctionMinimalListApi {
@@ -452,6 +457,17 @@ export interface HogFunctionApi {
readonly batch_export_id: string | null
/** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`. */
readonly search_match_type: SearchMatchTypeEnumApi | null
+ /** Incremented every time the live config changes. See the revisions endpoint. */
+ readonly version: number
+ /** Config staged for review but not live yet: a full snapshot of hog, inputs_schema, inputs, filters, mappings and masking. Null when nothing is staged. Publish or discard it to clear. */
+ readonly draft: unknown
+ /**
+ * When config was last staged for review, or null when nothing is staged.
+ * @nullable
+ */
+ readonly draft_updated_at: string | null
+ /** Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) you last read. If the stored side is newer, the write fails with 409 instead of overwriting the concurrent edit. Omit to overwrite unconditionally. */
+ base_updated_at?: string
}
/**
@@ -530,6 +546,17 @@ export interface PatchedHogFunctionApi {
readonly batch_export_id?: string | null
/** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`. */
readonly search_match_type?: SearchMatchTypeEnumApi | null
+ /** Incremented every time the live config changes. See the revisions endpoint. */
+ readonly version?: number
+ /** Config staged for review but not live yet: a full snapshot of hog, inputs_schema, inputs, filters, mappings and masking. Null when nothing is staged. Publish or discard it to clear. */
+ readonly draft?: unknown
+ /**
+ * When config was last staged for review, or null when nothing is staged.
+ * @nullable
+ */
+ readonly draft_updated_at?: string | null
+ /** Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) you last read. If the stored side is newer, the write fails with 409 instead of overwriting the concurrent edit. Omit to overwrite unconditionally. */
+ base_updated_at?: string
}
/**
@@ -543,8 +570,10 @@ export type HogFunctionInvocationApiGlobals = { [key: string]: unknown }
export type HogFunctionInvocationApiClickhouseEvent = { [key: string]: unknown }
export interface HogFunctionInvocationApi {
- /** Full function configuration to test. */
- configuration: HogFunctionApi
+ /** Full function configuration to test. Omit when use_draft is true. */
+ configuration?: HogFunctionApi
+ /** Test the function's staged draft instead of passing a configuration. Staged secret inputs are used; secrets the draft doesn't change fall back to the live values. 400 when nothing is staged. */
+ use_draft?: boolean
/** Mock global variables available during test invocation. */
globals?: HogFunctionInvocationApiGlobals
/** Mock ClickHouse event data to test the function with. */
@@ -578,6 +607,35 @@ export interface AppMetricsTotalsResponseApi {
totals: AppMetricsTotalsResponseApiTotals
}
+export interface HogFunctionPublishRequestApi {
+ /** False (default) previews the publish: returns which config fields would change without changing anything. True applies the staged draft to the live function. */
+ confirm?: boolean
+ /** From the preview response, and required when confirm=true on an enabled function. Expires after 15 minutes, and any edit to the draft or the live config invalidates it (409), so you always publish the exact draft you previewed. */
+ confirm_token?: string
+}
+
+export interface HogFunctionPublishResponseApi {
+ /** Whether the draft was applied to the live function. */
+ published: boolean
+ /**
+ * The staged draft's timestamp, for reference; publishing is confirmed via confirm_token.
+ * @nullable
+ */
+ draft_updated_at: string | null
+ /**
+ * Echo this back with confirm=true to publish the previewed draft. Only set on previews.
+ * @nullable
+ */
+ confirm_token: string | null
+ /**
+ * Config fields publishing would change (hog, inputs_schema, inputs, filters, mappings, masking). Only set on previews.
+ * @nullable
+ */
+ changed_fields: string[] | null
+ /** The function after publishing (only set when published=true). */
+ function?: HogFunctionApi | null
+}
+
/**
* * `running` - running
* * `succeeded` - succeeded
@@ -646,6 +704,36 @@ export interface HogInvocationRerunResponseApi {
skipped_count: number
}
+export interface HogFunctionRevisionBasicApi {
+ /** Function version this snapshot was published as. */
+ readonly version: number
+ readonly created_at: string
+ readonly created_by: UserBasicApi | null
+}
+
+export interface PaginatedHogFunctionRevisionBasicListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: HogFunctionRevisionBasicApi[]
+}
+
+export interface HogFunctionRevisionApi {
+ /** Function version this snapshot was published as. */
+ readonly version: number
+ readonly created_at: string
+ readonly created_by: UserBasicApi | null
+ /** Full snapshot of the function's config fields (hog, inputs_schema, inputs, filters, mappings, masking) at this version. */
+ readonly content: unknown
+}
+
+export interface HogFunctionRevisionRestoreRequestApi {
+ /** Replace the open staged draft with this revision's config. Without it, restoring while a draft is open returns 409. */
+ overwrite?: boolean
+}
+
/**
* Map of hog function UUIDs to their new execution_order values.
*/
@@ -906,6 +994,17 @@ export const HogFunctionsMetricsTotalsRetrieveInterval = {
Week: 'week',
} as const
+export type HogFunctionsRevisionsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type PluginConfigsLogsListParams = {
/**
* Number of results to return per page.
diff --git a/products/cdp/frontend/generated/api.ts b/products/cdp/frontend/generated/api.ts
index 48e947518f6e..7a2a0dec05fc 100644
--- a/products/cdp/frontend/generated/api.ts
+++ b/products/cdp/frontend/generated/api.ts
@@ -13,15 +13,21 @@ import type {
AppMetricsTotalsResponseApi,
HogFunctionApi,
HogFunctionInvocationApi,
+ HogFunctionPublishRequestApi,
+ HogFunctionPublishResponseApi,
+ HogFunctionRevisionApi,
+ HogFunctionRevisionRestoreRequestApi,
HogFunctionTemplateApi,
HogFunctionTemplatesListParams,
HogFunctionsListParams,
HogFunctionsLogsRetrieveParams,
HogFunctionsMetricsRetrieveParams,
HogFunctionsMetricsTotalsRetrieveParams,
+ HogFunctionsRevisionsListParams,
HogInvocationRerunRequestApi,
HogInvocationRerunResponseApi,
PaginatedHogFunctionMinimalListApi,
+ PaginatedHogFunctionRevisionBasicListApi,
PaginatedHogFunctionTemplateListApi,
PaginatedPluginLogEntryListApi,
PatchedHogFunctionApi,
@@ -198,6 +204,21 @@ export const hogFunctionsDestroy = async (projectId: string, id: string, options
})
}
+export const getHogFunctionsDiscardDraftCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/hog_functions/${id}/discard_draft/`
+}
+
+export const hogFunctionsDiscardDraftCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<HogFunctionApi> => {
+ return apiMutator<HogFunctionApi>(getHogFunctionsDiscardDraftCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getHogFunctionsEnableBackfillsCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/hog_functions/${id}/enable_backfills/`
}
@@ -223,7 +244,7 @@ export const getHogFunctionsInvocationsCreateUrl = (projectId: string, id: strin
export const hogFunctionsInvocationsCreate = async (
projectId: string,
id: string,
- hogFunctionInvocationApi: NonReadonly<HogFunctionInvocationApi>,
+ hogFunctionInvocationApi?: NonReadonly<HogFunctionInvocationApi>,
options?: RequestInit
): Promise<HogFunctionInvocationApi> => {
return apiMutator<HogFunctionInvocationApi>(getHogFunctionsInvocationsCreateUrl(projectId, id), {
@@ -330,6 +351,24 @@ export const hogFunctionsMetricsTotalsRetrieve = async (
})
}
+export const getHogFunctionsPublishCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/hog_functions/${id}/publish/`
+}
+
+export const hogFunctionsPublishCreate = async (
+ projectId: string,
+ id: string,
+ hogFunctionPublishRequestApi?: HogFunctionPublishRequestApi,
+ options?: RequestInit
+): Promise<HogFunctionPublishResponseApi> => {
+ return apiMutator<HogFunctionPublishResponseApi>(getHogFunctionsPublishCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(hogFunctionPublishRequestApi),
+ })
+}
+
export const getHogFunctionsRerunCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/hog_functions/${id}/rerun/`
}
@@ -368,6 +407,76 @@ export const hogFunctionsRerunCreate = async (
})
}
+export const getHogFunctionsRevisionsListUrl = (
+ projectId: string,
+ id: string,
+ params?: HogFunctionsRevisionsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/hog_functions/${id}/revisions/?${stringifiedParams}`
+ : `/api/projects/${projectId}/hog_functions/${id}/revisions/`
+}
+
+export const hogFunctionsRevisionsList = async (
+ projectId: string,
+ id: string,
+ params?: HogFunctionsRevisionsListParams,
+ options?: RequestInit
+): Promise<PaginatedHogFunctionRevisionBasicListApi> => {
+ return apiMutator<PaginatedHogFunctionRevisionBasicListApi>(
+ getHogFunctionsRevisionsListUrl(projectId, id, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getHogFunctionsRevisionsRetrieveUrl = (projectId: string, id: string, version: number) => {
+ return `/api/projects/${projectId}/hog_functions/${id}/revisions/${version}/`
+}
+
+export const hogFunctionsRevisionsRetrieve = async (
+ projectId: string,
+ id: string,
+ version: number,
+ options?: RequestInit
+): Promise<HogFunctionRevisionApi> => {
+ return apiMutator<HogFunctionRevisionApi>(getHogFunctionsRevisionsRetrieveUrl(projectId, id, version), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getHogFunctionsRevisionsRestoreCreateUrl = (projectId: string, id: string, version: number) => {
+ return `/api/projects/${projectId}/hog_functions/${id}/revisions/${version}/restore/`
+}
+
+export const hogFunctionsRevisionsRestoreCreate = async (
+ projectId: string,
+ id: string,
+ version: number,
+ hogFunctionRevisionRestoreRequestApi?: HogFunctionRevisionRestoreRequestApi,
+ options?: RequestInit
+): Promise<HogFunctionApi> => {
+ return apiMutator<HogFunctionApi>(getHogFunctionsRevisionsRestoreCreateUrl(projectId, id, version), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(hogFunctionRevisionRestoreRequestApi),
+ })
+}
+
export const getHogFunctionsIconRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/hog_functions/icon/`
}
diff --git a/products/cdp/frontend/generated/api.zod.ts b/products/cdp/frontend/generated/api.zod.ts
index b401fcbde8a8..c0343e7aea6d 100644
--- a/products/cdp/frontend/generated/api.zod.ts
+++ b/products/cdp/frontend/generated/api.zod.ts
@@ -258,6 +258,12 @@ export const HogFunctionsCreateBody = /* @__PURE__ */ zod.object({
.nullish()
.describe('Execution priority for transformations. Lower values run first.'),
_create_in_folder: zod.string().optional(),
+ base_updated_at: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) you last read. If the stored side is newer, the write fails with 409 instead of overwriting the concurrent edit. Omit to overwrite unconditionally.'
+ ),
})
export const hogFunctionsUpdateBodyNameMax = 400
@@ -509,6 +515,12 @@ export const HogFunctionsUpdateBody = /* @__PURE__ */ zod.object({
.nullish()
.describe('Execution priority for transformations. Lower values run first.'),
_create_in_folder: zod.string().optional(),
+ base_updated_at: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) you last read. If the stored side is newer, the write fails with 409 instead of overwriting the concurrent edit. Omit to overwrite unconditionally.'
+ ),
})
export const hogFunctionsPartialUpdateBodyNameMax = 400
@@ -760,6 +772,12 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({
.nullish()
.describe('Execution priority for transformations. Lower values run first.'),
_create_in_folder: zod.string().optional(),
+ base_updated_at: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) you last read. If the stored side is newer, the write fails with 409 instead of overwriting the concurrent edit. Omit to overwrite unconditionally.'
+ ),
})
export const hogFunctionsEnableBackfillsCreateBodyNameMax = 400
@@ -1021,6 +1039,12 @@ export const HogFunctionsEnableBackfillsCreateBody = /* @__PURE__ */ zod.object(
.nullish()
.describe('Execution priority for transformations. Lower values run first.'),
_create_in_folder: zod.string().optional(),
+ base_updated_at: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) you last read. If the stored side is newer, the write fails with 409 instead of overwriting the concurrent edit. Omit to overwrite unconditionally.'
+ ),
})
export const hogFunctionsInvocationsCreateBodyConfigurationOneNameMax = 400
@@ -1057,6 +1081,7 @@ export const hogFunctionsInvocationsCreateBodyConfigurationOneTemplateIdMax = 40
export const hogFunctionsInvocationsCreateBodyConfigurationOneExecutionOrderMin = 0
export const hogFunctionsInvocationsCreateBodyConfigurationOneExecutionOrderMax = 32767
+export const hogFunctionsInvocationsCreateBodyUseDraftDefault = false
export const hogFunctionsInvocationsCreateBodyMockAsyncFunctionsDefault = true
export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({
@@ -1435,8 +1460,33 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({
.describe(
'How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`.'
),
+ version: zod
+ .number()
+ .describe('Incremented every time the live config changes. See the revisions endpoint.'),
+ draft: zod
+ .unknown()
+ .describe(
+ 'Config staged for review but not live yet: a full snapshot of hog, inputs_schema, inputs, filters, mappings and masking. Null when nothing is staged. Publish or discard it to clear.'
+ ),
+ draft_updated_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When config was last staged for review, or null when nothing is staged.'),
+ base_updated_at: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) you last read. If the stored side is newer, the write fails with 409 instead of overwriting the concurrent edit. Omit to overwrite unconditionally.'
+ ),
})
- .describe('Full function configuration to test.'),
+ .optional()
+ .describe('Full function configuration to test. Omit when use_draft is true.'),
+ use_draft: zod
+ .boolean()
+ .default(hogFunctionsInvocationsCreateBodyUseDraftDefault)
+ .describe(
+ "Test the function's staged draft instead of passing a configuration. Staged secret inputs are used; secrets the draft doesn't change fall back to the live values. 400 when nothing is staged."
+ ),
globals: zod
.record(zod.string(), zod.unknown())
.optional()
@@ -1452,6 +1502,23 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({
invocation_id: zod.string().nullish().describe('Optional invocation ID for correlation.'),
})
+export const hogFunctionsPublishCreateBodyConfirmDefault = false
+
+export const HogFunctionsPublishCreateBody = /* @__PURE__ */ zod.object({
+ confirm: zod
+ .boolean()
+ .default(hogFunctionsPublishCreateBodyConfirmDefault)
+ .describe(
+ 'False (default) previews the publish: returns which config fields would change without changing anything. True applies the staged draft to the live function.'
+ ),
+ confirm_token: zod
+ .string()
+ .optional()
+ .describe(
+ 'From the preview response, and required when confirm=true on an enabled function. Expires after 15 minutes, and any edit to the draft or the live config invalidates it (409), so you always publish the exact draft you previewed.'
+ ),
+})
+
/**
* Rerun past invocations of this hog function from their stored payloads.
*
@@ -1529,6 +1596,17 @@ export const HogFunctionsRerunCreateBody = /* @__PURE__ */ zod
})
.describe('Rerun invocations of a hog function or hog flow from their stored payloads.')
+export const hogFunctionsRevisionsRestoreCreateBodyOverwriteDefault = false
+
+export const HogFunctionsRevisionsRestoreCreateBody = /* @__PURE__ */ zod.object({
+ overwrite: zod
+ .boolean()
+ .default(hogFunctionsRevisionsRestoreCreateBodyOverwriteDefault)
+ .describe(
+ "Replace the open staged draft with this revision's config. Without it, restoring while a draft is open returns 409."
+ ),
+})
+
/**
* Update the execution order of multiple HogFunctions.
*/
diff --git a/products/cdp/mcp/cdp_functions.yaml b/products/cdp/mcp/cdp_functions.yaml
index 604eaaf358c9..696e6567a341 100644
--- a/products/cdp/mcp/cdp_functions.yaml
+++ b/products/cdp/mcp/cdp_functions.yaml
@@ -24,7 +24,9 @@ tools:
warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to
derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with
their values. Use 'filters' to control which events trigger the function. Transformations run during
- ingestion and have an 'execution_order' field.
+ ingestion and have an 'execution_order' field. Create destinations disabled: test with
+ cdp-functions-invocations-create, then enable with cdp-functions-partial-update once the config looks right.
+ (Other types, like internal_destination below, create as sent.)
Recipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create /
alert-update point here):
@@ -103,6 +105,7 @@ tools:
created function's id. Never share a URL read from the function's inputs — those are destination endpoints
(e.g. incoming webhook URLs) and may grant access to the destination.
exclude_params:
+ - base_updated_at
- _create_in_folder
- batch_export_id
- bytecode
@@ -171,9 +174,36 @@ tools:
Delete a function by ID (soft delete). The function will no longer appear in lists or process events, but
historical data is preserved.
soft_delete: true
+ cdp-functions-discard-draft:
+ operation: hog_functions_discard_draft_create
+ enabled: true
+ scopes:
+ - hog_function:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Discard staged changes
+ description: >
+ Throw away the config staged on a function, leaving the live config untouched. Idempotent — discarding when
+ nothing is staged is a no-op. Returns 400 when drafts aren't enabled for the project.
cdp-functions-enable-backfills-create:
operation: hog_functions_enable_backfills_create
enabled: false
+ cdp-functions-get-revision:
+ operation: hog_functions_revisions_retrieve
+ enabled: true
+ scopes:
+ - hog_function:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get function revision
+ description: >
+ Get one version of a function's config by version number, including the full snapshot (hog, inputs_schema,
+ inputs, filters, mappings, masking) as it was at that version. Secret input values are never included. Use
+ cdp-functions-list-revisions first to find the version you want.
cdp-functions-icon-retrieve:
operation: hog_functions_icon_retrieve
enabled: false
@@ -193,7 +223,9 @@ tools:
description: >
Test-invoke a function with a mock event payload. Sends the function configuration and test data to the
plugin server for execution and returns logs and status. Use 'mock_async_functions: true' (default) to
- simulate external calls like fetch() without making real HTTP requests.
+ simulate external calls like fetch() without making real HTTP requests. To test config that is staged for
+ review, pass 'use_draft: true' instead of a 'configuration' — staged secret inputs are used, so the test
+ exercises exactly what publishing would ship.
cdp-functions-list:
operation: hog_functions_list
enabled: true
@@ -227,6 +259,22 @@ tools:
- updated_at
- created_by
- filters
+ cdp-functions-list-revisions:
+ operation: hog_functions_revisions_list
+ enabled: true
+ scopes:
+ - hog_function:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List function revisions
+ description: >
+ List a function's config versions, newest first — one per change to its live config, with who made it and
+ when. The config itself is not included; fetch a single version with cdp-functions-get-revision, then stage
+ it for review with cdp-functions-restore-revision. Returns 400 when revision history isn't enabled for the
+ project.
cdp-functions-logs-retrieve:
operation: hog_functions_logs_retrieve
enabled: true
@@ -274,6 +322,15 @@ tools:
Partially update a function. Can enable/disable the function, change its name, description, source code,
inputs, filters, mappings, or masking config. The 'type' field cannot be changed after creation. To delete a
function, use the cdp-functions-delete tool instead.
+
+ On a destination that is currently enabled, config edits (hog, inputs_schema, inputs, filters, mappings,
+ masking) are staged for review rather than applied — they show up as 'draft' on the function and do not
+ change what is running. Name, description and enable/disable still apply immediately, except that enabling a
+ function with staged config is refused until it is published or discarded. Tell the user what you staged and
+ that they need to publish it; publish it yourself only when they ask, with cdp-functions-publish. Discard it
+ with cdp-functions-discard-draft. To test a staged config before publishing, call
+ cdp-functions-invocations-create with 'use_draft: true'. Optionally pass 'base_updated_at' (the
+ draft_updated_at or updated_at you last read) to fail with 409 instead of overwriting a concurrent edit.
exclude_params:
- _create_in_folder
- batch_export_id
@@ -313,6 +370,24 @@ tools:
exclude:
- inputs.*.value
- mappings.*.inputs.*.value
+ cdp-functions-publish:
+ operation: hog_functions_publish_create
+ enabled: true
+ scopes:
+ - hog_function:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: false
+ title: Publish staged changes
+ description: >
+ Apply the config staged on a function to what is actually running. Two steps, and the first is mandatory on
+ an enabled function: call it without 'confirm' to see which config fields would change and get a
+ 'confirm_token', then call it again with confirm=true and that token. The token expires after 15 minutes,
+ and any further edit to either the staged config or the live config invalidates it (409) — so you always
+ publish exactly what you previewed, and never silently overwrite someone else's edit. A disabled function
+ processes nothing, so publishing into one skips the token. Returns 400 when nothing is staged, when the
+ token is missing or expired, or when drafts aren't enabled for the project.
cdp-functions-rearrange-partial-update:
operation: hog_functions_rearrange_partial_update
enabled: true
@@ -327,6 +402,20 @@ tools:
Update the execution order of transformation functions. Send an 'orders' object mapping function UUIDs to
their new execution_order integer values. Only applies to functions with type=transformation. Returns the
updated list of transformations.
+ cdp-functions-restore-revision:
+ operation: hog_functions_revisions_restore_create
+ enabled: true
+ scopes:
+ - hog_function:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Restore function revision
+ description: >
+ Roll a function back to an earlier version by staging that version's config for review. Nothing goes live
+ here — finish with cdp-functions-publish so the rollback is previewed and confirmed like any other change.
+ Returns 409 when config is already staged; pass overwrite=true to replace it.
cdp-functions-retrieve:
operation: hog_functions_retrieve
enabled: true
diff --git a/products/error_tracking/mcp/error_tracking_alerts.yaml b/products/error_tracking/mcp/error_tracking_alerts.yaml
index 22f0a3f74a08..65012afdfb74 100644
--- a/products/error_tracking/mcp/error_tracking_alerts.yaml
+++ b/products/error_tracking/mcp/error_tracking_alerts.yaml
@@ -130,6 +130,7 @@ tools:
properties. Project context is available as `{project.url}` (already includes `/project/<team_id>`),
`{project.name}`, and the alert's own metadata as `{source.url}` and `{source.name}`.
exclude_params:
+ - base_updated_at
- _create_in_folder
- batch_export_id
- bytecode
diff --git a/products/posthog_ai/frontend/policy/toolPolicy.ts b/products/posthog_ai/frontend/policy/toolPolicy.ts
index 20f0d5243e86..5e61fbf6ecb7 100644
--- a/products/posthog_ai/frontend/policy/toolPolicy.ts
+++ b/products/posthog_ai/frontend/policy/toolPolicy.ts
@@ -37,6 +37,9 @@ const POSTHOG_DESTRUCTIVE_SUB_TOOLS = new Set([
// never a runtime tool, so the destructive `-execute` variant is what must be gated.
'change-requests-approve-execute',
'change-requests-reject-execute',
+ 'cdp-functions-discard-draft',
+ 'cdp-functions-publish',
+ 'cdp-functions-restore-revision',
'error-tracking-bypass-rules-create',
'error-tracking-issues-merge-create',
'error-tracking-issues-split-create',
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index 70c4aa061b43..ea4fb8a85c4a 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -142,6 +142,9 @@ POSTHOG_EXEC_DESTRUCTIVE_SUB_TOOLS: tuple[str, ...] = (
# never a runtime tool, so the destructive `-execute` variant is what must be gated.
"change-requests-approve-execute",
"change-requests-reject-execute",
+ "cdp-functions-discard-draft",
+ "cdp-functions-publish",
+ "cdp-functions-restore-revision",
"error-tracking-bypass-rules-create",
"error-tracking-issues-merge-create",
"error-tracking-issues-split-create",
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 7f64a908230a..ef6cd5347ef4 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -54,7 +54,7 @@ from posthog.cdp.validation import (
generate_template_bytecode,
)
from posthog.clickhouse.query_tagging import Feature, tag_queries
-from posthog.event_usage import EventSource, get_event_source, report_user_action
+from posthog.event_usage import AGENT_EVENT_SOURCES, EventSource, get_event_source, report_user_action
from posthog.models import Team
from posthog.models.filters import Filter
from posthog.plugins.plugin_server_api import (
@@ -2413,13 +2413,6 @@ def mint_publish_confirm_token(hog_flow: HogFlow) -> str:
AUDIENCE_CONFIRM_TOKEN_MAX_AGE = timedelta(minutes=15)
_AUDIENCE_CONFIRM_SALT = "hogflow-batch-audience"
-# Surfaces where an LLM drives the request through a managed channel (classification is stamped by
-# the harness, not self-reported by the model). These get the audience-confirm gate; the web builder
-# has its own confirm UI, and headless callers (raw API keys, Terraform) dispatch in one call.
-AGENT_EVENT_SOURCES = frozenset(
- {EventSource.MCP, EventSource.POSTHOG_CODE, EventSource.WIZARD, EventSource.CLI, EventSource.POSTHOG_AI}
-)
-
def _audience_confirm_value(
team_id: int, filters: dict, group_type_index: Optional[int] = None, dedupe_key: Optional[str] = None
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 6d8c47065630..f9db42cbe071 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1123,7 +1123,7 @@
}
},
"cdp-functions-create": {
- "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field.\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n {\"type\": \"divider\"},\n {\"type\": \"actions\", \"block_id\": \"insight_alert_snooze:{event.properties.alert_id}\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"},\n {\"type\": \"static_select\", \"action_id\": \"insight_alert_snooze\",\n \"placeholder\": {\"type\": \"plain_text\", \"text\": \"Snooze…\"},\n \"options\": [\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 hour\"}, \"value\": \"{event.properties.alert_id}|1h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 6 hours\"}, \"value\": \"{event.properties.alert_id}|6h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 day\"}, \"value\": \"{event.properties.alert_id}|1d\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 week\"}, \"value\": \"{event.properties.alert_id}|1w\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"Pick a date & time…\"}, \"value\": \"{event.properties.alert_id}|custom\"}\n ]}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.\n\nAfter a successful create, do not stop at a silent success: in chat, tell the user the function was created and offer a link to it. Build the link with the generate-app-url tool, path template /functions/{id} and the created function's id. Never share a URL read from the function's inputs — those are destination endpoints (e.g. incoming webhook URLs) and may grant access to the destination.",
+ "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field. Create destinations disabled: test with cdp-functions-invocations-create, then enable with cdp-functions-partial-update once the config looks right. (Other types, like internal_destination below, create as sent.)\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n {\"type\": \"divider\"},\n {\"type\": \"actions\", \"block_id\": \"insight_alert_snooze:{event.properties.alert_id}\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"},\n {\"type\": \"static_select\", \"action_id\": \"insight_alert_snooze\",\n \"placeholder\": {\"type\": \"plain_text\", \"text\": \"Snooze…\"},\n \"options\": [\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 hour\"}, \"value\": \"{event.properties.alert_id}|1h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 6 hours\"}, \"value\": \"{event.properties.alert_id}|6h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 day\"}, \"value\": \"{event.properties.alert_id}|1d\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 week\"}, \"value\": \"{event.properties.alert_id}|1w\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"Pick a date & time…\"}, \"value\": \"{event.properties.alert_id}|custom\"}\n ]}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.\n\nAfter a successful create, do not stop at a silent success: in chat, tell the user the function was created and offer a link to it. Build the link with the generate-app-url tool, path template /functions/{id} and the created function's id. Never share a URL read from the function's inputs — those are destination endpoints (e.g. incoming webhook URLs) and may grant access to the destination.",
"category": "Functions",
"feature": "hog_functions",
"summary": "Create function",
@@ -1150,8 +1150,36 @@
"readOnlyHint": false
}
},
+ "cdp-functions-discard-draft": {
+ "description": "Throw away the config staged on a function, leaving the live config untouched. Idempotent — discarding when nothing is staged is a no-op. Returns 400 when drafts aren't enabled for the project.",
+ "category": "Functions",
+ "feature": "hog_functions",
+ "summary": "Discard staged changes",
+ "title": "Discard staged changes",
+ "required_scopes": ["hog_function:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "cdp-functions-get-revision": {
+ "description": "Get one version of a function's config by version number, including the full snapshot (hog, inputs_schema, inputs, filters, mappings, masking) as it was at that version. Secret input values are never included. Use cdp-functions-list-revisions first to find the version you want.",
+ "category": "Functions",
+ "feature": "hog_functions",
+ "summary": "Get function revision",
+ "title": "Get function revision",
+ "required_scopes": ["hog_function:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"cdp-functions-invocations-create": {
- "description": "Test-invoke a function with a mock event payload. Sends the function configuration and test data to the plugin server for execution and returns logs and status. Use 'mock_async_functions: true' (default) to simulate external calls like fetch() without making real HTTP requests.",
+ "description": "Test-invoke a function with a mock event payload. Sends the function configuration and test data to the plugin server for execution and returns logs and status. Use 'mock_async_functions: true' (default) to simulate external calls like fetch() without making real HTTP requests. To test config that is staged for review, pass 'use_draft: true' instead of a 'configuration' — staged secret inputs are used, so the test exercises exactly what publishing would ship.",
"category": "Functions",
"feature": "hog_functions",
"summary": "Test-invoke function",
@@ -1178,6 +1206,20 @@
"readOnlyHint": true
}
},
+ "cdp-functions-list-revisions": {
+ "description": "List a function's config versions, newest first — one per change to its live config, with who made it and when. The config itself is not included; fetch a single version with cdp-functions-get-revision, then stage it for review with cdp-functions-restore-revision. Returns 400 when revision history isn't enabled for the project.",
+ "category": "Functions",
+ "feature": "hog_functions",
+ "summary": "List function revisions",
+ "title": "List function revisions",
+ "required_scopes": ["hog_function:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"cdp-functions-logs-retrieve": {
"description": "Retrieve execution logs for a specific CDP function by ID. Returns log entries with timestamp, level (DEBUG, LOG, INFO, WARN, ERROR), and message. Use to debug why a destination or transformation is failing or not producing expected results. Supports filtering by log level, text search, time range (after/before), and pagination via limit.",
"category": "Functions",
@@ -1207,7 +1249,7 @@
}
},
"cdp-functions-partial-update": {
- "description": "Partially update a function. Can enable/disable the function, change its name, description, source code, inputs, filters, mappings, or masking config. The 'type' field cannot be changed after creation. To delete a function, use the cdp-functions-delete tool instead.",
+ "description": "Partially update a function. Can enable/disable the function, change its name, description, source code, inputs, filters, mappings, or masking config. The 'type' field cannot be changed after creation. To delete a function, use the cdp-functions-delete tool instead.\nOn a destination that is currently enabled, config edits (hog, inputs_schema, inputs, filters, mappings, masking) are staged for review rather than applied — they show up as 'draft' on the function and do not change what is running. Name, description and enable/disable still apply immediately, except that enabling a function with staged config is refused until it is published or discarded. Tell the user what you staged and that they need to publish it; publish it yourself only when they ask, with cdp-functions-publish. Discard it with cdp-functions-discard-draft. To test a staged config before publishing, call cdp-functions-invocations-create with 'use_draft: true'. Optionally pass 'base_updated_at' (the draft_updated_at or updated_at you last read) to fail with 409 instead of overwriting a concurrent edit.",
"category": "Functions",
"feature": "hog_functions",
"summary": "Update function",
@@ -1220,6 +1262,20 @@
"readOnlyHint": false
}
},
+ "cdp-functions-publish": {
+ "description": "Apply the config staged on a function to what is actually running. Two steps, and the first is mandatory on an enabled function: call it without 'confirm' to see which config fields would change and get a 'confirm_token', then call it again with confirm=true and that token. The token expires after 15 minutes, and any further edit to either the staged config or the live config invalidates it (409) — so you always publish exactly what you previewed, and never silently overwrite someone else's edit. A disabled function processes nothing, so publishing into one skips the token. Returns 400 when nothing is staged, when the token is missing or expired, or when drafts aren't enabled for the project.",
+ "category": "Functions",
+ "feature": "hog_functions",
+ "summary": "Publish staged changes",
+ "title": "Publish staged changes",
+ "required_scopes": ["hog_function:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"cdp-functions-rearrange-partial-update": {
"description": "Update the execution order of transformation functions. Send an 'orders' object mapping function UUIDs to their new execution_order integer values. Only applies to functions with type=transformation. Returns the updated list of transformations.",
"category": "Functions",
@@ -1234,6 +1290,20 @@
"readOnlyHint": false
}
},
+ "cdp-functions-restore-revision": {
+ "description": "Roll a function back to an earlier version by staging that version's config for review. Nothing goes live here — finish with cdp-functions-publish so the rollback is previewed and confirmed like any other change. Returns 409 when config is already staged; pass overwrite=true to replace it.",
+ "category": "Functions",
+ "feature": "hog_functions",
+ "summary": "Restore function revision",
+ "title": "Restore function revision",
+ "required_scopes": ["hog_function:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"cdp-functions-retrieve": {
"description": "Get a specific function by ID. Returns the full configuration including source code, inputs schema, input values (secrets are masked), filters, mappings, masking config, and runtime status.",
"category": "Functions",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index b07511564acf..2de332181406 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1138,7 +1138,7 @@
}
},
"cdp-functions-create": {
- "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field.\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n {\"type\": \"divider\"},\n {\"type\": \"actions\", \"block_id\": \"insight_alert_snooze:{event.properties.alert_id}\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"},\n {\"type\": \"static_select\", \"action_id\": \"insight_alert_snooze\",\n \"placeholder\": {\"type\": \"plain_text\", \"text\": \"Snooze…\"},\n \"options\": [\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 hour\"}, \"value\": \"{event.properties.alert_id}|1h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 6 hours\"}, \"value\": \"{event.properties.alert_id}|6h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 day\"}, \"value\": \"{event.properties.alert_id}|1d\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 week\"}, \"value\": \"{event.properties.alert_id}|1w\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"Pick a date & time…\"}, \"value\": \"{event.properties.alert_id}|custom\"}\n ]}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.\n\nAfter a successful create, do not stop at a silent success: in chat, tell the user the function was created and offer a link to it. Build the link with the generate-app-url tool, path template /functions/{id} and the created function's id. Never share a URL read from the function's inputs — those are destination endpoints (e.g. incoming webhook URLs) and may grant access to the destination.",
+ "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field. Create destinations disabled: test with cdp-functions-invocations-create, then enable with cdp-functions-partial-update once the config looks right. (Other types, like internal_destination below, create as sent.)\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n {\"type\": \"divider\"},\n {\"type\": \"actions\", \"block_id\": \"insight_alert_snooze:{event.properties.alert_id}\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"},\n {\"type\": \"static_select\", \"action_id\": \"insight_alert_snooze\",\n \"placeholder\": {\"type\": \"plain_text\", \"text\": \"Snooze…\"},\n \"options\": [\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 hour\"}, \"value\": \"{event.properties.alert_id}|1h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 6 hours\"}, \"value\": \"{event.properties.alert_id}|6h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 day\"}, \"value\": \"{event.properties.alert_id}|1d\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 week\"}, \"value\": \"{event.properties.alert_id}|1w\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"Pick a date & time…\"}, \"value\": \"{event.properties.alert_id}|custom\"}\n ]}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.\n\nAfter a successful create, do not stop at a silent success: in chat, tell the user the function was created and offer a link to it. Build the link with the generate-app-url tool, path template /functions/{id} and the created function's id. Never share a URL read from the function's inputs — those are destination endpoints (e.g. incoming webhook URLs) and may grant access to the destination.",
"category": "Functions",
"feature": "hog_functions",
"summary": "Create function",
@@ -1165,8 +1165,36 @@
"readOnlyHint": false
}
},
+ "cdp-functions-discard-draft": {
+ "description": "Throw away the config staged on a function, leaving the live config untouched. Idempotent — discarding when nothing is staged is a no-op. Returns 400 when drafts aren't enabled for the project.",
+ "category": "Functions",
+ "feature": "hog_functions",
+ "summary": "Discard staged changes",
+ "title": "Discard staged changes",
+ "required_scopes": ["hog_function:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "cdp-functions-get-revision": {
+ "description": "Get one version of a function's config by version number, including the full snapshot (hog, inputs_schema, inputs, filters, mappings, masking) as it was at that version. Secret input values are never included. Use cdp-functions-list-revisions first to find the version you want.",
+ "category": "Functions",
+ "feature": "hog_functions",
+ "summary": "Get function revision",
+ "title": "Get function revision",
+ "required_scopes": ["hog_function:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"cdp-functions-invocations-create": {
- "description": "Test-invoke a function with a mock event payload. Sends the function configuration and test data to the plugin server for execution and returns logs and status. Use 'mock_async_functions: true' (default) to simulate external calls like fetch() without making real HTTP requests.",
+ "description": "Test-invoke a function with a mock event payload. Sends the function configuration and test data to the plugin server for execution and returns logs and status. Use 'mock_async_functions: true' (default) to simulate external calls like fetch() without making real HTTP requests. To test config that is staged for review, pass 'use_draft: true' instead of a 'configuration' — staged secret inputs are used, so the test exercises exactly what publishing would ship.",
"category": "Functions",
"feature": "hog_functions",
"summary": "Test-invoke function",
@@ -1193,6 +1221,20 @@
"readOnlyHint": true
}
},
+ "cdp-functions-list-revisions": {
+ "description": "List a function's config versions, newest first — one per change to its live config, with who made it and when. The config itself is not included; fetch a single version with cdp-functions-get-revision, then stage it for review with cdp-functions-restore-revision. Returns 400 when revision history isn't enabled for the project.",
+ "category": "Functions",
+ "feature": "hog_functions",
+ "summary": "List function revisions",
+ "title": "List function revisions",
+ "required_scopes": ["hog_function:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"cdp-functions-logs-retrieve": {
"description": "Retrieve execution logs for a specific CDP function by ID. Returns log entries with timestamp, level (DEBUG, LOG, INFO, WARN, ERROR), and message. Use to debug why a destination or transformation is failing or not producing expected results. Supports filtering by log level, text search, time range (after/before), and pagination via limit.",
"category": "Functions",
@@ -1222,7 +1264,7 @@
}
},
"cdp-functions-partial-update": {
- "description": "Partially update a function. Can enable/disable the function, change its name, description, source code, inputs, filters, mappings, or masking config. The 'type' field cannot be changed after creation. To delete a function, use the cdp-functions-delete tool instead.",
+ "description": "Partially update a function. Can enable/disable the function, change its name, description, source code, inputs, filters, mappings, or masking config. The 'type' field cannot be changed after creation. To delete a function, use the cdp-functions-delete tool instead.\nOn a destination that is currently enabled, config edits (hog, inputs_schema, inputs, filters, mappings, masking) are staged for review rather than applied — they show up as 'draft' on the function and do not change what is running. Name, description and enable/disable still apply immediately, except that enabling a function with staged config is refused until it is published or discarded. Tell the user what you staged and that they need to publish it; publish it yourself only when they ask, with cdp-functions-publish. Discard it with cdp-functions-discard-draft. To test a staged config before publishing, call cdp-functions-invocations-create with 'use_draft: true'. Optionally pass 'base_updated_at' (the draft_updated_at or updated_at you last read) to fail with 409 instead of overwriting a concurrent edit.",
"category": "Functions",
"feature": "hog_functions",
"summary": "Update function",
@@ -1235,6 +1277,20 @@
"readOnlyHint": false
}
},
+ "cdp-functions-publish": {
+ "description": "Apply the config staged on a function to what is actually running. Two steps, and the first is mandatory on an enabled function: call it without 'confirm' to see which config fields would change and get a 'confirm_token', then call it again with confirm=true and that token. The token expires after 15 minutes, and any further edit to either the staged config or the live config invalidates it (409) — so you always publish exactly what you previewed, and never silently overwrite someone else's edit. A disabled function processes nothing, so publishing into one skips the token. Returns 400 when nothing is staged, when the token is missing or expired, or when drafts aren't enabled for the project.",
+ "category": "Functions",
+ "feature": "hog_functions",
+ "summary": "Publish staged changes",
+ "title": "Publish staged changes",
+ "required_scopes": ["hog_function:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"cdp-functions-rearrange-partial-update": {
"description": "Update the execution order of transformation functions. Send an 'orders' object mapping function UUIDs to their new execution_order integer values. Only applies to functions with type=transformation. Returns the updated list of transformations.",
"category": "Functions",
@@ -1249,6 +1305,20 @@
"readOnlyHint": false
}
},
+ "cdp-functions-restore-revision": {
+ "description": "Roll a function back to an earlier version by staging that version's config for review. Nothing goes live here — finish with cdp-functions-publish so the rollback is previewed and confirmed like any other change. Returns 409 when config is already staged; pass overwrite=true to replace it.",
+ "category": "Functions",
+ "feature": "hog_functions",
+ "summary": "Restore function revision",
+ "title": "Restore function revision",
+ "required_scopes": ["hog_function:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"cdp-functions-retrieve": {
"description": "Get a specific function by ID. Returns the full configuration including source code, inputs schema, input values (secrets are masked), filters, mappings, masking config, and runtime status.",
"category": "Functions",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d7bd39995e37..1076739991cf 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -35796,6 +35796,17 @@ export namespace Schemas {
readonly batch_export_id: string | null;
/** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`. */
readonly search_match_type: SearchMatchTypeEnum | null;
+ /** Incremented every time the live config changes. See the revisions endpoint. */
+ readonly version: number;
+ /** Config staged for review but not live yet: a full snapshot of hog, inputs_schema, inputs, filters, mappings and masking. Null when nothing is staged. Publish or discard it to clear. */
+ readonly draft: unknown;
+ /**
+ * When config was last staged for review, or null when nothing is staged.
+ * @nullable
+ */
+ readonly draft_updated_at: string | null;
+ /** Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) you last read. If the stored side is newer, the write fails with 409 instead of overwriting the concurrent edit. Omit to overwrite unconditionally. */
+ base_updated_at?: string;
}
/**
@@ -35809,8 +35820,10 @@ export namespace Schemas {
export type HogFunctionInvocationClickhouseEvent = { [key: string]: unknown };
export interface HogFunctionInvocation {
- /** Full function configuration to test. */
- configuration: HogFunction;
+ /** Full function configuration to test. Omit when use_draft is true. */
+ configuration?: HogFunction;
+ /** Test the function's staged draft instead of passing a configuration. Staged secret inputs are used; secrets the draft doesn't change fall back to the live values. 400 when nothing is staged. */
+ use_draft?: boolean;
/** Mock global variables available during test invocation. */
globals?: HogFunctionInvocationGlobals;
/** Mock ClickHouse event data to test the function with. */
@@ -35849,6 +35862,61 @@ export namespace Schemas {
readonly execution_order: number | null;
/** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`. */
readonly search_match_type: SearchMatchTypeEnum | null;
+ /**
+ * When config was last staged for review, or null when nothing is staged.
+ * @nullable
+ */
+ readonly draft_updated_at: string | null;
+ }
+
+ export interface HogFunctionPublishRequest {
+ /** False (default) previews the publish: returns which config fields would change without changing anything. True applies the staged draft to the live function. */
+ confirm?: boolean;
+ /** From the preview response, and required when confirm=true on an enabled function. Expires after 15 minutes, and any edit to the draft or the live config invalidates it (409), so you always publish the exact draft you previewed. */
+ confirm_token?: string;
+ }
+
+ export interface HogFunctionPublishResponse {
+ /** Whether the draft was applied to the live function. */
+ published: boolean;
+ /**
+ * The staged draft's timestamp, for reference; publishing is confirmed via confirm_token.
+ * @nullable
+ */
+ draft_updated_at: string | null;
+ /**
+ * Echo this back with confirm=true to publish the previewed draft. Only set on previews.
+ * @nullable
+ */
+ confirm_token: string | null;
+ /**
+ * Config fields publishing would change (hog, inputs_schema, inputs, filters, mappings, masking). Only set on previews.
+ * @nullable
+ */
+ changed_fields: string[] | null;
+ /** The function after publishing (only set when published=true). */
+ function?: HogFunction | null;
+ }
+
+ export interface HogFunctionRevision {
+ /** Function version this snapshot was published as. */
+ readonly version: number;
+ readonly created_at: string;
+ readonly created_by: UserBasic | null;
+ /** Full snapshot of the function's config fields (hog, inputs_schema, inputs, filters, mappings, masking) at this version. */
+ readonly content: unknown;
+ }
+
+ export interface HogFunctionRevisionBasic {
+ /** Function version this snapshot was published as. */
+ readonly version: number;
+ readonly created_at: string;
+ readonly created_by: UserBasic | null;
+ }
+
+ export interface HogFunctionRevisionRestoreRequest {
+ /** Replace the open staged draft with this revision's config. Without it, restoring while a draft is open returns 409. */
+ overwrite?: boolean;
}
/**
@@ -45085,6 +45153,15 @@ export namespace Schemas {
results: HogFunctionMinimal[];
}
+ export interface PaginatedHogFunctionRevisionBasicList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: HogFunctionRevisionBasic[];
+ }
+
export interface PaginatedHogFunctionTemplateList {
count: number;
/** @nullable */
@@ -52955,6 +53032,17 @@ export namespace Schemas {
readonly batch_export_id?: string | null;
/** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`. */
readonly search_match_type?: SearchMatchTypeEnum | null;
+ /** Incremented every time the live config changes. See the revisions endpoint. */
+ readonly version?: number;
+ /** Config staged for review but not live yet: a full snapshot of hog, inputs_schema, inputs, filters, mappings and masking. Null when nothing is staged. Publish or discard it to clear. */
+ readonly draft?: unknown;
+ /**
+ * When config was last staged for review, or null when nothing is staged.
+ * @nullable
+ */
+ readonly draft_updated_at?: string | null;
+ /** Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) you last read. If the stored side is newer, the write fails with 409 instead of overwriting the concurrent edit. Omit to overwrite unconditionally. */
+ base_updated_at?: string;
}
/**
@@ -81261,6 +81349,17 @@ export namespace Schemas {
Week: 'week',
} as const;
+ export type HogFunctionsRevisionsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type IdentityMatchingLinksListParams = {
/**
* Identity matching run to read. Defaults to the team's most recent run.
diff --git a/services/mcp/src/generated/cdp_functions/api.ts b/services/mcp/src/generated/cdp_functions/api.ts
index 9d1c7c04517e..f8f8fc5cd070 100644
--- a/services/mcp/src/generated/cdp_functions/api.ts
+++ b/services/mcp/src/generated/cdp_functions/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 14 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -523,6 +523,12 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({
.max(hogFunctionsPartialUpdateBodyExecutionOrderMax)
.nullish()
.describe('Execution priority for transformations. Lower values run first.'),
+ base_updated_at: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) you last read. If the stored side is newer, the write fails with 409 instead of overwriting the concurrent edit. Omit to overwrite unconditionally.'
+ ),
})
/**
@@ -537,6 +543,15 @@ export const HogFunctionsDestroyParams = /* @__PURE__ */ zod.object({
),
})
+export const HogFunctionsDiscardDraftCreateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this hog function.'),
+ 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 HogFunctionsInvocationsCreateParams = /* @__PURE__ */ zod.object({
id: zod.string().describe('A UUID string identifying this hog function.'),
project_id: zod
@@ -580,6 +595,7 @@ export const hogFunctionsInvocationsCreateBodyConfigurationOneTemplateIdMax = 40
export const hogFunctionsInvocationsCreateBodyConfigurationOneExecutionOrderMin = 0
export const hogFunctionsInvocationsCreateBodyConfigurationOneExecutionOrderMax = 32767
+export const hogFunctionsInvocationsCreateBodyUseDraftDefault = false
export const hogFunctionsInvocationsCreateBodyMockAsyncFunctionsDefault = true
export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({
@@ -965,8 +981,35 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({
.describe(
'How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`.'
),
+ version: zod
+ .number()
+ .optional()
+ .describe('Incremented every time the live config changes. See the revisions endpoint.'),
+ draft: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Config staged for review but not live yet: a full snapshot of hog, inputs_schema, inputs, filters, mappings and masking. Null when nothing is staged. Publish or discard it to clear.'
+ ),
+ draft_updated_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('When config was last staged for review, or null when nothing is staged.'),
+ base_updated_at: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) you last read. If the stored side is newer, the write fails with 409 instead of overwriting the concurrent edit. Omit to overwrite unconditionally.'
+ ),
})
- .describe('Full function configuration to test.'),
+ .optional()
+ .describe('Full function configuration to test. Omit when use_draft is true.'),
+ use_draft: zod
+ .boolean()
+ .default(hogFunctionsInvocationsCreateBodyUseDraftDefault)
+ .describe(
+ "Test the function's staged draft instead of passing a configuration. Staged secret inputs are used; secrets the draft doesn't change fall back to the live values. 400 when nothing is staged."
+ ),
globals: zod
.record(zod.string(), zod.unknown())
.optional()
@@ -1057,6 +1100,77 @@ export const HogFunctionsMetricsRetrieveQueryParams = /* @__PURE__ */ zod.object
name: zod.string().min(1).optional().describe('Comma-separated metric names to filter by.'),
})
+export const HogFunctionsPublishCreateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this hog function.'),
+ 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 hogFunctionsPublishCreateBodyConfirmDefault = false
+
+export const HogFunctionsPublishCreateBody = /* @__PURE__ */ zod.object({
+ confirm: zod
+ .boolean()
+ .default(hogFunctionsPublishCreateBodyConfirmDefault)
+ .describe(
+ 'False (default) previews the publish: returns which config fields would change without changing anything. True applies the staged draft to the live function.'
+ ),
+ confirm_token: zod
+ .string()
+ .optional()
+ .describe(
+ 'From the preview response, and required when confirm=true on an enabled function. Expires after 15 minutes, and any edit to the draft or the live config invalidates it (409), so you always publish the exact draft you previewed.'
+ ),
+})
+
+export const HogFunctionsRevisionsListParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this hog function.'),
+ 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 HogFunctionsRevisionsListQueryParams = /* @__PURE__ */ zod.object({
+ limit: zod.number().optional().describe('Number of results to return per page.'),
+ offset: zod.number().optional().describe('The initial index from which to return the results.'),
+})
+
+export const HogFunctionsRevisionsRetrieveParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this hog function.'),
+ 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\/."
+ ),
+ version: zod.number().describe('Function version to fetch.'),
+})
+
+export const HogFunctionsRevisionsRestoreCreateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this hog function.'),
+ 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\/."
+ ),
+ version: zod.number().describe('Function version to restore.'),
+})
+
+export const hogFunctionsRevisionsRestoreCreateBodyOverwriteDefault = false
+
+export const HogFunctionsRevisionsRestoreCreateBody = /* @__PURE__ */ zod.object({
+ overwrite: zod
+ .boolean()
+ .default(hogFunctionsRevisionsRestoreCreateBodyOverwriteDefault)
+ .describe(
+ "Replace the open staged draft with this revision's config. Without it, restoring while a draft is open returns 409."
+ ),
+})
+
/**
* Update the execution order of multiple HogFunctions.
*/
diff --git a/services/mcp/src/generated/error_tracking_alerts/api.ts b/services/mcp/src/generated/error_tracking_alerts/api.ts
index 7e89df8416bf..20b8778d03a8 100644
--- a/services/mcp/src/generated/error_tracking_alerts/api.ts
+++ b/services/mcp/src/generated/error_tracking_alerts/api.ts
@@ -514,6 +514,12 @@ export const HogFunctionsPartialUpdateBody = /* @__PURE__ */ zod.object({
.max(hogFunctionsPartialUpdateBodyExecutionOrderMax)
.nullish()
.describe('Execution priority for transformations. Lower values run first.'),
+ base_updated_at: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe(
+ 'Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) you last read. If the stored side is newer, the write fails with 409 instead of overwriting the concurrent edit. Omit to overwrite unconditionally.'
+ ),
})
/**
diff --git a/services/mcp/src/tools/generated/cdp_functions.ts b/services/mcp/src/tools/generated/cdp_functions.ts
index 56788dd29a21..ad641047b419 100644
--- a/services/mcp/src/tools/generated/cdp_functions.ts
+++ b/services/mcp/src/tools/generated/cdp_functions.ts
@@ -5,6 +5,7 @@ import type { Schemas } from '@/api/generated'
import {
HogFunctionsCreateBody,
HogFunctionsDestroyParams,
+ HogFunctionsDiscardDraftCreateParams,
HogFunctionsInvocationsCreateBody,
HogFunctionsInvocationsCreateParams,
HogFunctionsListQueryParams,
@@ -14,8 +15,15 @@ import {
HogFunctionsMetricsRetrieveQueryParams,
HogFunctionsPartialUpdateBody,
HogFunctionsPartialUpdateParams,
+ HogFunctionsPublishCreateBody,
+ HogFunctionsPublishCreateParams,
HogFunctionsRearrangePartialUpdateBody,
HogFunctionsRetrieveParams,
+ HogFunctionsRevisionsListParams,
+ HogFunctionsRevisionsListQueryParams,
+ HogFunctionsRevisionsRestoreCreateBody,
+ HogFunctionsRevisionsRestoreCreateParams,
+ HogFunctionsRevisionsRetrieveParams,
} from '@/generated/cdp_functions/api'
import { withPostHogUrl, omitResponseFields, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
@@ -107,6 +115,36 @@ const cdpFunctionsDelete = (): ToolBase<typeof CdpFunctionsDeleteSchema, Schemas
},
})
+const CdpFunctionsDiscardDraftSchema = HogFunctionsDiscardDraftCreateParams.omit({ project_id: true })
+
+const cdpFunctionsDiscardDraft = (): ToolBase<typeof CdpFunctionsDiscardDraftSchema, Schemas.HogFunction> => ({
+ name: 'cdp-functions-discard-draft',
+ schema: CdpFunctionsDiscardDraftSchema,
+ handler: async (context: Context, params: z.infer<typeof CdpFunctionsDiscardDraftSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.HogFunction>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_functions/${encodeURIComponent(String(params.id))}/discard_draft/`,
+ })
+ return result
+ },
+})
+
+const CdpFunctionsGetRevisionSchema = HogFunctionsRevisionsRetrieveParams.omit({ project_id: true })
+
+const cdpFunctionsGetRevision = (): ToolBase<typeof CdpFunctionsGetRevisionSchema, Schemas.HogFunctionRevision> => ({
+ name: 'cdp-functions-get-revision',
+ schema: CdpFunctionsGetRevisionSchema,
+ handler: async (context: Context, params: z.infer<typeof CdpFunctionsGetRevisionSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.HogFunctionRevision>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_functions/${encodeURIComponent(String(params.id))}/revisions/${encodeURIComponent(String(params.version))}/`,
+ })
+ return result
+ },
+})
+
const CdpFunctionsInvocationsCreateSchema = HogFunctionsInvocationsCreateParams.omit({ project_id: true }).extend(
HogFunctionsInvocationsCreateBody.shape
)
@@ -123,6 +161,9 @@ const cdpFunctionsInvocationsCreate = (): ToolBase<
if (params.configuration !== undefined) {
body['configuration'] = params.configuration
}
+ if (params.use_draft !== undefined) {
+ body['use_draft'] = params.use_draft
+ }
if (params.globals !== undefined) {
body['globals'] = params.globals
}
@@ -192,6 +233,30 @@ const cdpFunctionsList = (): ToolBase<
},
})
+const CdpFunctionsListRevisionsSchema = HogFunctionsRevisionsListParams.omit({ project_id: true }).extend(
+ HogFunctionsRevisionsListQueryParams.shape
+)
+
+const cdpFunctionsListRevisions = (): ToolBase<
+ typeof CdpFunctionsListRevisionsSchema,
+ WithPostHogUrl<Schemas.PaginatedHogFunctionRevisionBasicList>
+> => ({
+ name: 'cdp-functions-list-revisions',
+ schema: CdpFunctionsListRevisionsSchema,
+ handler: async (context: Context, params: z.infer<typeof CdpFunctionsListRevisionsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedHogFunctionRevisionBasicList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_functions/${encodeURIComponent(String(params.id))}/revisions/`,
+ query: {
+ limit: params.limit,
+ offset: params.offset,
+ },
+ })
+ return await withPostHogUrl(context, result, '/pipeline')
+ },
+})
+
const CdpFunctionsLogsRetrieveSchema = HogFunctionsLogsRetrieveParams.omit({ project_id: true }).extend(
HogFunctionsLogsRetrieveQueryParams.shape
)
@@ -299,6 +364,9 @@ const cdpFunctionsPartialUpdate = (): ToolBase<typeof CdpFunctionsPartialUpdateS
if (params.execution_order !== undefined) {
body['execution_order'] = params.execution_order
}
+ if (params.base_updated_at !== undefined) {
+ body['base_updated_at'] = params.base_updated_at
+ }
const result = await context.api.request<Schemas.HogFunction>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_functions/${encodeURIComponent(String(params.id))}/`,
@@ -309,6 +377,31 @@ const cdpFunctionsPartialUpdate = (): ToolBase<typeof CdpFunctionsPartialUpdateS
},
})
+const CdpFunctionsPublishSchema = HogFunctionsPublishCreateParams.omit({ project_id: true }).extend(
+ HogFunctionsPublishCreateBody.shape
+)
+
+const cdpFunctionsPublish = (): ToolBase<typeof CdpFunctionsPublishSchema, Schemas.HogFunctionPublishResponse> => ({
+ name: 'cdp-functions-publish',
+ schema: CdpFunctionsPublishSchema,
+ handler: async (context: Context, params: z.infer<typeof CdpFunctionsPublishSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.confirm !== undefined) {
+ body['confirm'] = params.confirm
+ }
+ if (params.confirm_token !== undefined) {
+ body['confirm_token'] = params.confirm_token
+ }
+ const result = await context.api.request<Schemas.HogFunctionPublishResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_functions/${encodeURIComponent(String(params.id))}/publish/`,
+ body,
+ })
+ return result
+ },
+})
+
const CdpFunctionsRearrangePartialUpdateSchema = HogFunctionsRearrangePartialUpdateBody
const cdpFunctionsRearrangePartialUpdate = (): ToolBase<
@@ -332,6 +425,28 @@ const cdpFunctionsRearrangePartialUpdate = (): ToolBase<
},
})
+const CdpFunctionsRestoreRevisionSchema = HogFunctionsRevisionsRestoreCreateParams.omit({ project_id: true }).extend(
+ HogFunctionsRevisionsRestoreCreateBody.shape
+)
+
+const cdpFunctionsRestoreRevision = (): ToolBase<typeof CdpFunctionsRestoreRevisionSchema, Schemas.HogFunction> => ({
+ name: 'cdp-functions-restore-revision',
+ schema: CdpFunctionsRestoreRevisionSchema,
+ handler: async (context: Context, params: z.infer<typeof CdpFunctionsRestoreRevisionSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.overwrite !== undefined) {
+ body['overwrite'] = params.overwrite
+ }
+ const result = await context.api.request<Schemas.HogFunction>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_functions/${encodeURIComponent(String(params.id))}/revisions/${encodeURIComponent(String(params.version))}/restore/`,
+ body,
+ })
+ return result
+ },
+})
+
const CdpFunctionsRetrieveSchema = HogFunctionsRetrieveParams.omit({ project_id: true })
const cdpFunctionsRetrieve = (): ToolBase<typeof CdpFunctionsRetrieveSchema, Schemas.HogFunction> => ({
@@ -350,11 +465,16 @@ const cdpFunctionsRetrieve = (): ToolBase<typeof CdpFunctionsRetrieveSchema, Sch
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'cdp-functions-create': cdpFunctionsCreate,
'cdp-functions-delete': cdpFunctionsDelete,
+ 'cdp-functions-discard-draft': cdpFunctionsDiscardDraft,
+ 'cdp-functions-get-revision': cdpFunctionsGetRevision,
'cdp-functions-invocations-create': cdpFunctionsInvocationsCreate,
'cdp-functions-list': cdpFunctionsList,
+ 'cdp-functions-list-revisions': cdpFunctionsListRevisions,
'cdp-functions-logs-retrieve': cdpFunctionsLogsRetrieve,
'cdp-functions-metrics-retrieve': cdpFunctionsMetricsRetrieve,
'cdp-functions-partial-update': cdpFunctionsPartialUpdate,
+ 'cdp-functions-publish': cdpFunctionsPublish,
'cdp-functions-rearrange-partial-update': cdpFunctionsRearrangePartialUpdate,
+ 'cdp-functions-restore-revision': cdpFunctionsRestoreRevision,
'cdp-functions-retrieve': cdpFunctionsRetrieve,
}
diff --git a/services/mcp/src/tools/generated/error_tracking_alerts.ts b/services/mcp/src/tools/generated/error_tracking_alerts.ts
index 11f204ebd4af..e4455603e1e7 100644
--- a/services/mcp/src/tools/generated/error_tracking_alerts.ts
+++ b/services/mcp/src/tools/generated/error_tracking_alerts.ts
@@ -195,6 +195,9 @@ const errorTrackingAlertsPartialUpdate = (): ToolBase<
if (params.execution_order !== undefined) {
body['execution_order'] = params.execution_order
}
+ if (params.base_updated_at !== undefined) {
+ body['base_updated_at'] = params.base_updated_at
+ }
const result = await context.api.request<Schemas.HogFunction>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_functions/${encodeURIComponent(String(params.id))}/`,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-discard-draft.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-discard-draft.json
new file mode 100644
index 000000000000..b79faf66d487
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-discard-draft.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this hog function.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-get-revision.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-get-revision.json
new file mode 100644
index 000000000000..bbdf58f16bed
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-get-revision.json
@@ -0,0 +1,15 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this hog function.",
+ "type": "string"
+ },
+ "version": {
+ "description": "Function version to fetch.",
+ "type": "number"
+ }
+ },
+ "required": ["id", "version"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-invocations-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-invocations-create.json
index 8c2da2947db3..c51ed64ad6ba 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-invocations-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-invocations-create.json
@@ -10,11 +10,17 @@
"type": "object"
},
"configuration": {
- "description": "Full function configuration to test.",
+ "description": "Full function configuration to test. Omit when use_draft is true.",
"properties": {
"_create_in_folder": {
"type": "string"
},
+ "base_updated_at": {
+ "description": "Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) you last read. If the stored side is newer, the write fails with 409 instead of overwriting the concurrent edit. Omit to overwrite unconditionally.",
+ "format": "date-time",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
"batch_export_id": {
"anyOf": [
{
@@ -126,6 +132,22 @@
"description": "Human-readable description of what this function does.",
"type": "string"
},
+ "draft": {
+ "description": "Config staged for review but not live yet: a full snapshot of hog, inputs_schema, inputs, filters, mappings and masking. Null when nothing is staged. Publish or discard it to clear."
+ },
+ "draft_updated_at": {
+ "anyOf": [
+ {
+ "format": "date-time",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "When config was last staged for review, or null when nothing is staged."
+ },
"enabled": {
"description": "Whether the function is active and processing events.",
"type": "boolean"
@@ -816,6 +838,10 @@
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
"type": "string"
+ },
+ "version": {
+ "description": "Incremented every time the live config changes. See the revisions endpoint.",
+ "type": "number"
}
},
"type": "object"
@@ -847,8 +873,13 @@
"default": true,
"description": "When true (default), async functions like fetch() are simulated.",
"type": "boolean"
+ },
+ "use_draft": {
+ "default": false,
+ "description": "Test the function's staged draft instead of passing a configuration. Staged secret inputs are used; secrets the draft doesn't change fall back to the live values. 400 when nothing is staged.",
+ "type": "boolean"
}
},
- "required": ["id", "configuration"],
+ "required": ["id"],
"type": "object"
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-list-revisions.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-list-revisions.json
new file mode 100644
index 000000000000..8caf2da6621f
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-list-revisions.json
@@ -0,0 +1,19 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this hog function.",
+ "type": "string"
+ },
+ "limit": {
+ "description": "Number of results to return per page.",
+ "type": "number"
+ },
+ "offset": {
+ "description": "The initial index from which to return the results.",
+ "type": "number"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-partial-update.json
index 04bb42fff703..681b6419f4ef 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-partial-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-partial-update.json
@@ -1,6 +1,12 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
+ "base_updated_at": {
+ "description": "Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) you last read. If the stored side is newer, the write fails with 409 instead of overwriting the concurrent edit. Omit to overwrite unconditionally.",
+ "format": "date-time",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
"description": {
"description": "Human-readable description of what this function does.",
"type": "string"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-publish.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-publish.json
new file mode 100644
index 000000000000..63de519cb791
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-publish.json
@@ -0,0 +1,20 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "confirm": {
+ "default": false,
+ "description": "False (default) previews the publish: returns which config fields would change without changing anything. True applies the staged draft to the live function.",
+ "type": "boolean"
+ },
+ "confirm_token": {
+ "description": "From the preview response, and required when confirm=true on an enabled function. Expires after 15 minutes, and any edit to the draft or the live config invalidates it (409), so you always publish the exact draft you previewed.",
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this hog function.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-restore-revision.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-restore-revision.json
new file mode 100644
index 000000000000..c2c95881c3f0
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-restore-revision.json
@@ -0,0 +1,20 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this hog function.",
+ "type": "string"
+ },
+ "overwrite": {
+ "default": false,
+ "description": "Replace the open staged draft with this revision's config. Without it, restoring while a draft is open returns 409.",
+ "type": "boolean"
+ },
+ "version": {
+ "description": "Function version to restore.",
+ "type": "number"
+ }
+ },
+ "required": ["id", "version"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-alerts-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-alerts-partial-update.json
index dd7693008a6d..752638b8377d 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-alerts-partial-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-alerts-partial-update.json
@@ -1,6 +1,12 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
+ "base_updated_at": {
+ "description": "Optimistic concurrency: the updated_at (or draft_updated_at when editing a staged draft) you last read. If the stored side is newer, the write fails with 409 instead of overwriting the concurrent edit. Omit to overwrite unconditionally.",
+ "format": "date-time",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
"description": {
"description": "Human-readable description of what this function does.",
"type": "string"