:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(alerts): let an alert:write caller attach a Slack destination (#96910)
posthog[bot]a819fa9e2626
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex da93176acabc..d3278c540a7a 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7721,25 +7721,25 @@ snapshots:scenes-app-inbox-scoutwriteaccesstag--granted--light:hash: v1.k794b7964.f43a37d7ad168d1f8b879e6361bf0cf88f1c492e176567a24f8919f7281cff27.WDlRZQnnmsRUqVgEm4VItfi-i3Dq86esxOUoRJ35jdsscenes-app-inbox-scoutwritescopespicker--cannot-edit--dark:- hash: v1.k794b7964.4820a938c147b5e5b8a19a4ef5579c075adad2a78cb54ae28757ebf819be362c.QHnBAPxl99LesInpWgpAcYmkTKjf9_pY4t0ApRetyH8+ hash: v1.k794b7964.2e5e62b6c1fdf168a96f485f4a16d5a77cd6df619a039653cac462426091d664.W2HqpF2v9JoF2Hyvpda7_Ye5GaOy38Sf_fTe7_LeymEscenes-app-inbox-scoutwritescopespicker--cannot-edit--light:- hash: v1.k794b7964.a2256c6af5a8d09856bae2658cded030e971d5e52cf74c30a3d8bea8b4a11f57.kQhpT-V43IHPjyLNcXmrBj0L5lCC7WBjQSMCERNUQ1U+ hash: v1.k794b7964.a0c60cbf9d4d7f7126b4a76eb3cee11d6154afb44cba256456bbd77bce12c20e.P-WzCPC_FbG9VFPRK6nDdC765gYG5mB9oJY6HZuFVJ8scenes-app-inbox-scoutwritescopespicker--maintainer-scout--dark:- hash: v1.k794b7964.72f538bf380993bc7fc246ed67d7caace58fda08c92c4ad6b265e5c10c39733a.y7pgcsDFEuOxedxq2eCYW5eHi0ngIePGHVg_4V6NcrI+ hash: v1.k794b7964.14e1d0b64fc8695419b8da6b34c47b85571733c98d6c62191432ede885b1e92a.4QaDRwPSPVUXB5K2_oPmuCtM-3I07p3EaGD-sdgzjswscenes-app-inbox-scoutwritescopespicker--maintainer-scout--light:- hash: v1.k794b7964.3c7aef60ecfe3a384ffa1c51ee04e50bcebcfd056b42cfba33f0bcea7303a97b.RLYS2W9Y7IhMFOOQyzdAMagO4im-ix06mfo93UtaLWw+ hash: v1.k794b7964.6e0c5cfb04cf7d467844745ad4878608f801566c1aa7b66b830004e13261ad3c.TlUph_SWaV1Fml49c_KStA-JhGr5g9utnNnWE1RUSnkscenes-app-inbox-scoutwritescopespicker--read-only-scout--dark:- hash: v1.k794b7964.9fb7e116e13b1896e38b10f634c340066fbe7d2aefddc47323c41fd4ee4f371e.zgjQu0gsAfZGt0JxW55R-8JenDmXG5W8Jtkf3Unm7Jg+ hash: v1.k794b7964.c3fc252bd71aeae229912e6f978b0432ef191e11f833f36c41ee3e035e01be72.MsG2dpcGSBFgpP8BgOpHZssTiw0SblAeXK-xjESbfNUscenes-app-inbox-scoutwritescopespicker--read-only-scout--light:- hash: v1.k794b7964.dc5c6d8070163b07938bdf61434da1a7b65838a9fe48a9329833c71db7a51fa1.J6ygWvr0aUItivRfy71hBmlVNF33RBltyfWAEe_4RAI+ hash: v1.k794b7964.03f31489eec0d8c526fc9d59f2b93da01c27834d1f2503cf1f4f4e4af7b2710e.OVSlH81mB1rn-fUXHn4E5ViDvUUO2YwFQZVj-LcjrYMscenes-app-inbox-scoutwritescopespicker--scout-settings-variant--dark:- hash: v1.k794b7964.c294e4ebf438fca43a28d4d65cc5b116bf6527b1f7d0a22bd1e65654915eea70.v8YsHf5-L75BZvz8rW06LLYCOGN8rGJ5C8tAYgovlmQ+ hash: v1.k794b7964.f17cd7eb2b59801be1addc9170ab301cf708d47e0b14fe94e78cc3be91de7f3c.9hdUIxhBvCTk_ySZFlxlvb3HUtER2eEZ-rgLXhaNAbcscenes-app-inbox-scoutwritescopespicker--scout-settings-variant--light:- hash: v1.k794b7964.f727cbeee1f3615531893760978f7090ff4ecfec6772fbe5fb2cb536593c8471.xfqBRXJCi2tH3GwqtGuHr5S7NS6qoJ_4VF3JR1QeR2I+ hash: v1.k794b7964.19c8347585199682f9c210ffb27dbaf00dc06714783403b70afb9d18ba2a05b4.VcU_UczfJF_HhHLrEJpW9WtQwkg4ea8_2swinAUYoWIscenes-app-inbox-scoutwritescopespicker--with-granted-scopes--dark:- hash: v1.k794b7964.a9cd49fa37279245a18f8feec8a3613efb004af7bc63c58475c9c791606b81c2.2CVV35AjWF6Kx6lzLfWPevKs1XGsNsBCwCxP-HjOyHk+ hash: v1.k794b7964.aee73ee47ec430b3705c7f80fcaa4b724365b1c1113a5a8e0420d2656dafad29.7KXrZ7JGnt5I63V0s2KaeQrIP9SJ83bIKzbtK98vJIsscenes-app-inbox-scoutwritescopespicker--with-granted-scopes--light:- hash: v1.k794b7964.3b8813917f25fb61d1e93b4eded220de12e80e1acf190602e5e035e97c224e2a.vwHsiCcNA8QX3i-TBhTjwI_UEJlJRGKNbMHd0MH1O_4+ hash: v1.k794b7964.b3f53357dbbbc84b6580fa82faf34538e4f6e4e3c15691c14848541cae742227.I9ecpLcQZZ47Wrm82d-qMSDOzcmvbXUSlgD_VSYMUrgscenes-app-inbox-selfdrivingsection--daily-limit-reached--dark:hash: v1.k794b7964.6bb86cc044462ca9b5d59151d279fb763b8ffc1918c913a4ba5786e9714a9675.F8GMUyNcVBI5ASlEgXgZaNW4sL-8zvLioKKu0JVua34scenes-app-inbox-selfdrivingsection--daily-limit-reached--light:diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.pyindex 1a7609102d8d..38b5d349048f 100644--- a/posthog/temporal/oauth.py+++ b/posthog/temporal/oauth.py@@ -206,7 +206,9 @@ SCOUT_USER_WRITE_SCOPES: list[str] = [# An update can also move an organization annotation to the scout's team.# alert:write Every insight alert in the scout's project. Delete is PERMANENT: the# viewset has no soft-delete, so it removes the alert and its check-# history for good.+# history for good. It also attaches and removes the alert's Slack+# destinations, bounded to workspaces the project already connected, so a+# scout still reaches no URL of its own choosing.# llm_skill:write Every shared skill on the scout's project: body, description, and# bundled files. Custom scouts are skills in that same store, so this# reaches a sibling scout's prompt and the scout's own. Archive marksdiff --git a/products/alerts/backend/destination_backfill.py b/products/alerts/backend/destination_backfill.pyindex ef39e65e3ecb..22d9ec9d7e95 100644--- a/products/alerts/backend/destination_backfill.py+++ b/products/alerts/backend/destination_backfill.py@@ -24,20 +24,13 @@ from posthog.dataclasses import frozenfrom posthog.plugins.plugin_server_api import reload_hog_functions_on_workersfrom posthog.tasks.alerts.utils import INSIGHT_ALERT_FIRING_EVENT-from products.alerts.backend.destination_configs import DESTINATION_SPECS, DestinationType+from products.alerts.backend.insight_alert_destinations import INSIGHT_CHART_BLOCK, SLACK_TEMPLATE_IDfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionlogger = structlog.get_logger(__name__)-SLACK_TEMPLATE_ID = DESTINATION_SPECS[DestinationType.SLACK].template_id-DIVIDER_BLOCK = {"type": "divider"}-# Byte-for-byte the block the sub-template now writes, so a repaired destination and a freshly-# created one are indistinguishable. Keep it in step with the insight-alert-firing Slack entry in-# frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.-INSIGHT_CHART_BLOCK = "{event.properties.insight_chart_url ? {'type': 'image', 'image_url': event.properties.insight_chart_url, 'alt_text': 'Insight chart'} : {'type': 'divider'}}"-@frozenclass ChartBlockBackfill:diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.pyindex 0a75f1c6c12f..0b9b0e76d271 100644--- a/products/alerts/backend/facade/api.py+++ b/products/alerts/backend/facade/api.py@@ -25,6 +25,7 @@ from products.alerts.backend.destination_configs import (validate_destination_data,)from products.alerts.backend.destinations import (+ count_active_alert_destinations,create_alert_destination_hog_functions,list_alert_destination_groups,owned_alert_destinations_qs,@@ -34,6 +35,13 @@ from products.alerts.backend.destinations import (soft_delete_all_alert_destinations,)from products.alerts.backend.email_notifications import send_alert_email+from products.alerts.backend.insight_alert_destinations import (+ INSIGHT_ALERT_DESTINATION_TYPES,+ INSIGHT_ALERT_EVENT_IDS,+ MAX_DESTINATION_IDS_PER_DELETE_REQUEST,+ MAX_DESTINATIONS_PER_ALERT,+ build_insight_alert_slack_config,+)from products.alerts.backend.insight_alert_state_machine import apply_snoozefrom products.alerts.backend.models.alert import AlertCheck, AlertConfigurationfrom products.alerts.backend.presentation.views.alert_schedule_restriction import AlertScheduleRestriction@@ -206,6 +214,10 @@ def snooze_alert_from_slack(__all__ = ["DESTINATION_SPECS",+ "INSIGHT_ALERT_DESTINATION_TYPES",+ "INSIGHT_ALERT_EVENT_IDS",+ "MAX_DESTINATIONS_PER_ALERT",+ "MAX_DESTINATION_IDS_PER_DELETE_REQUEST","AlertDestinationData","AlertDestinationValidationError","AlertScheduleRestriction",@@ -213,6 +225,8 @@ __all__ = ["SLACK_SNOOZE_MAX_DAYS","SlackSnoozeOutcome","build_alert_destination_config",+ "build_insight_alert_slack_config",+ "count_active_alert_destinations","create_alert_destination_hog_functions","delete_insight_alerts","get_alert_team_id",diff --git a/products/alerts/backend/insight_alert_destinations.py b/products/alerts/backend/insight_alert_destinations.pynew file mode 100644index 000000000000..ba16141c197b--- /dev/null+++ b/products/alerts/backend/insight_alert_destinations.py@@ -0,0 +1,140 @@+"""Slack destinations for insight alerts.++The alert UI builds these from the `insight-alert-firing` Slack sub-template in+frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts. The blocks here mirror that+entry, so a destination attached through the API posts the same message as one attached in the+UI — same chart, same buttons, same snooze menu. Keep the two in step.+"""++from __future__ import annotations++from typing import Any, Final++from posthog.cdp.internal_events import LEGACY_INSIGHT_ALERT_EVENT++from products.alerts.backend.destination_configs import (+ DESTINATION_SPECS,+ AlertDestinationConfig,+ AlertDestinationData,+ DestinationType,+ clip_hog_function_name,+ destination_filter,+)++# The event an insight alert check emits, named legacy where it is defined because it predates the+# managed-alert event boundary. Do not take it from `posthog.tasks.alerts.utils` instead, because+# that module imports this product's facade, which imports this one.+INSIGHT_ALERT_EVENT_IDS: Final[tuple[str, ...]] = (LEGACY_INSIGHT_ALERT_EVENT,)++# Slack only, because `alert:write` is grantable to a sandboxed agent. A connected workspace is a+# destination an admin chose, while every other transport takes a URL the caller supplies.+INSIGHT_ALERT_DESTINATION_TYPES: Final[tuple[DestinationType, ...]] = (DestinationType.SLACK,)++# Each destination is another message every time the alert fires, so a caller in a loop is capped.+MAX_DESTINATIONS_PER_ALERT: Final = 5++# One destination is one HogFunction, so this only stops a malformed request becoming a huge query.+MAX_DESTINATION_IDS_PER_DELETE_REQUEST: Final = 100++SLACK_TEMPLATE_ID: Final = DESTINATION_SPECS[DestinationType.SLACK].template_id++# A hog template that is a single {…} expression resolves to the expression's raw value, so this+# string becomes a whole block: a chart of the alerted insight when the anomaly investigation+# rendered one (`insight_chart_url` set by investigate_anomaly_activity), otherwise the plain+# divider — Slack has no way to omit a block conditionally, and an image block with an empty URL+# fails the send.+INSIGHT_CHART_BLOCK: Final = "{event.properties.insight_chart_url ? {'type': 'image', 'image_url': event.properties.insight_chart_url, 'alt_text': 'Insight chart'} : {'type': 'divider'}}"++# Points to the anomaly investigation notebook when present, otherwise falls back to the alert+# page (Slack can't conditionally hide a button, so the one button does double duty).+_PRIMARY_BUTTON_URL: Final = (+ "{event.properties.investigation_notebook_url ? event.properties.investigation_notebook_url : "+ "concat(project.url, '/insights/', event.properties.insight_id, '/alerts?alert_id=', "+ "event.properties.alert_id, '&utm_source=alert&utm_campaign=alert_check_firing&utm_medium=slack')}"+)++_SNOOZE_OPTIONS: Final = (+ ("For 1 hour", "1h"),+ ("For 6 hours", "6h"),+ ("For 1 day", "1d"),+ ("For 1 week", "1w"),+ ("Pick a date & time…", "custom"),+)+++def _slack_blocks() -> list[Any]:+ return [+ {+ "type": "header",+ "text": {+ "type": "plain_text",+ "text": "Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'",+ },+ },+ {+ # plain_text (not mrkdwn) so user-controlled names in the breach text can't inject+ # Slack markup/links/mentions. Newlines still render as line breaks.+ "type": "section",+ "text": {"type": "plain_text", "text": "{event.properties.breaches}"},+ },+ {+ "type": "context",+ "elements": [{"type": "mrkdwn", "text": "Project: <{project.url}|{project.name}>"}],+ },+ INSIGHT_CHART_BLOCK,+ {+ "type": "actions",+ # A datetimepicker element carries no value, unlike a select option, so the alert id+ # in the block_id is the only way the snooze action can identify its alert.+ "block_id": "insight_alert_snooze:{event.properties.alert_id}",+ "elements": [+ {+ "url": _PRIMARY_BUTTON_URL,+ "text": {+ "text": "{event.properties.investigation_notebook_url ? 'View Investigation' : 'View Alert'}",+ "type": "plain_text",+ },+ "type": "button",+ },+ {+ "url": "{project.url}/insights/{event.properties.insight_id}?utm_source=alert&utm_campaign=alert_check_firing&utm_medium=slack",+ "text": {"text": "View Insight", "type": "plain_text"},+ "type": "button",+ },+ {+ "action_id": "insight_alert_snooze",+ "placeholder": {"text": "Snooze…", "type": "plain_text"},+ "options": [+ {+ "text": {"text": label, "type": "plain_text"},+ "value": "{event.properties.alert_id}|" + duration,+ }+ for label, duration in _SNOOZE_OPTIONS+ ],+ "type": "static_select",+ },+ ],+ },+ ]+++def build_insight_alert_slack_config(+ *, team: Any, alert_id: str, alert_name: str | None, data: AlertDestinationData+) -> AlertDestinationConfig:+ channel_name = data.get("slack_channel_name") or "channel"+ return AlertDestinationConfig(+ team=team,+ payload={+ "type": "internal_destination",+ "enabled": True,+ "filters": destination_filter(alert_id, LEGACY_INSIGHT_ALERT_EVENT),+ "name": clip_hog_function_name(f"{alert_name or 'Alert'}: Slack #{channel_name}"),+ "template_id": SLACK_TEMPLATE_ID,+ "inputs": {+ "blocks": {"value": _slack_blocks()},+ "text": {"value": "Alert triggered: {event.properties.insight_name}"},+ "slack_workspace": {"value": data["slack_workspace_id"]},+ "channel": {"value": data["slack_channel_id"]},+ },+ },+ )diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.pyindex aed643e13d91..7ff2f90cab5c 100644--- a/products/alerts/backend/presentation/views/alert.py+++ b/products/alerts/backend/presentation/views/alert.py@@ -43,6 +43,7 @@ from posthog.helpers.trigram_search import (drop_similar_when_exact_exists,)from posthog.models import User+from posthog.models.integration import Integrationfrom posthog.models.tag import tagifyfrom posthog.models.tagged_item import TaggedItemfrom posthog.permissions import get_authenticator_scopes@@ -58,8 +59,6 @@ from posthog.tasks.alerts.utils import ()from posthog.utils import relative_date_parse-from products.alerts.backend.destination_configs import DestinationType-from products.alerts.backend.destinations import count_active_alert_destinationsfrom products.alerts.backend.evaluation.contract import AlertExtractionErrorfrom products.alerts.backend.evaluation.detector import simulate_detector_on_insightfrom products.alerts.backend.evaluation.validation import (@@ -67,6 +66,20 @@ from products.alerts.backend.evaluation.validation import (should_default_check_ongoing_interval,validate_alert_config,)+from products.alerts.backend.facade.api import (+ INSIGHT_ALERT_DESTINATION_TYPES,+ INSIGHT_ALERT_EVENT_IDS,+ MAX_DESTINATION_IDS_PER_DELETE_REQUEST,+ MAX_DESTINATIONS_PER_ALERT,+ AlertDestinationData,+ AlertDestinationValidationError,+ DestinationType,+ build_insight_alert_slack_config,+ count_active_alert_destinations,+ create_alert_destination_hog_functions,+ soft_delete_alert_destinations,+ validate_destination_data,+)from products.alerts.backend.insight_alert_state_machine import (apply_disable,apply_enable,@@ -78,8 +91,6 @@ from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration,from products.alerts.backend.presentation.views.alert_schedule_restriction import AlertScheduleRestrictionfrom products.product_analytics.backend.facade.models import Insight, resolve_insight_by_id_or_short_id-INSIGHT_ALERT_FIRING_EVENT = "$insight_alert_firing"-def _validate_interval_entitlement(*,@@ -1026,6 +1037,56 @@ class AlertTestDeliveryResponseSerializer(serializers.Serializer):)+class AlertCreateDestinationSerializer(serializers.Serializer):+ type = serializers.ChoiceField(+ choices=INSIGHT_ALERT_DESTINATION_TYPES,+ default=DestinationType.SLACK,+ help_text="Destination type. Slack is the only type this endpoint creates.",+ )+ slack_workspace_id = serializers.IntegerField(+ help_text="Integration ID of the Slack workspace to post in. List them with the integrations endpoint."+ )+ slack_channel_id = serializers.CharField(help_text="Slack channel ID to post in, for example C0123456789.")+ slack_channel_name = serializers.CharField(+ required=False,+ allow_blank=True,+ help_text="Channel name shown on the destination, for example product-alerts.",+ )++ def validate(self, attrs: dict) -> dict:+ data = cast(AlertDestinationData, attrs)+ data["type"] = DestinationType(attrs["type"])+ try:+ validate_destination_data(data, allowed_destination_types=INSIGHT_ALERT_DESTINATION_TYPES)+ except AlertDestinationValidationError as error:+ if error.field:+ raise ValidationError({error.field: error.message})+ raise ValidationError(error.message)++ # The runtime refuses another team's integration anyway, so without this the destination+ # is created and then silently never posts.+ team = self.context["get_team"]()+ if not Integration.objects.filter(team=team, id=attrs["slack_workspace_id"], kind="slack").exists():+ raise ValidationError({"slack_workspace_id": "Connect this Slack workspace to PostHog first."})+ return attrs+++class AlertDestinationResponseSerializer(serializers.Serializer):+ hog_function_ids = serializers.ListField(+ child=serializers.UUIDField(),+ help_text="IDs of the created destination. Pass them to destinations/delete to remove it.",+ )+++class AlertDeleteDestinationSerializer(serializers.Serializer):+ hog_function_ids = serializers.ListField(+ child=serializers.UUIDField(),+ min_length=1,+ max_length=MAX_DESTINATION_IDS_PER_DELETE_REQUEST,+ help_text="Destination IDs to delete, as returned when the destination was created.",+ )++class AlertListFiltersSerializer(serializers.Serializer):insight_tag = serializers.CharField(required=False, max_length=255)has_detector = OptionalBooleanField(required=False)@@ -1285,7 +1346,7 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):destination_count = count_active_alert_destinations(team_id=alert.team_id,alert_id=str(alert.id),- allowed_event_ids=(INSIGHT_ALERT_FIRING_EVENT,),+ allowed_event_ids=INSIGHT_ALERT_EVENT_IDS,)email_targets = alert.get_subscribed_users_emails()if destination_count == 0 and not email_targets:@@ -1351,6 +1412,84 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):status=status.HTTP_202_ACCEPTED,)+ @extend_schema(+ request=AlertCreateDestinationSerializer,+ responses={201: AlertDestinationResponseSerializer},+ description=(+ "Send this alert to a Slack channel as well as by email. The workspace must already be "+ "connected to the project. The returned IDs identify the destination."+ ),+ )+ @action(detail=True, methods=["POST"], url_path="destinations", required_scopes=["alert:write"])+ def create_destination(self, request, *args, **kwargs):+ alert = self.get_object()+ serializer = AlertCreateDestinationSerializer(data=request.data, context=self.get_serializer_context())+ serializer.is_valid(raise_exception=True)+ data = cast(AlertDestinationData, serializer.validated_data)++ existing = count_active_alert_destinations(+ team_id=self.team_id, alert_id=str(alert.id), allowed_event_ids=INSIGHT_ALERT_EVENT_IDS+ )+ if existing >= MAX_DESTINATIONS_PER_ALERT:+ raise ValidationError(+ f"This alert already has {MAX_DESTINATIONS_PER_ALERT} destinations. Remove one to add another."+ )++ hog_functions = create_alert_destination_hog_functions(+ [+ build_insight_alert_slack_config(+ team=alert.team, alert_id=str(alert.id), alert_name=alert.name, data=data+ )+ ],+ request=self.request,+ alert_id=str(alert.id),+ allowed_event_ids=INSIGHT_ALERT_EVENT_IDS,+ )++ posthoganalytics.capture(+ distinct_id=str(request.user.distinct_id),+ event="insight alert destination created",+ properties={+ **get_request_analytics_properties(request),+ "alert_id": str(alert.id),+ "team_id": alert.team_id,+ "type": data["type"],+ },+ )+ response = AlertDestinationResponseSerializer({"hog_function_ids": [hf.id for hf in hog_functions]})+ return Response(response.data, status=status.HTTP_201_CREATED)++ @extend_schema(+ request=AlertDeleteDestinationSerializer,+ responses={204: None},+ description="Stop sending this alert to a destination. The alert keeps its email recipients.",+ )+ @action(detail=True, methods=["POST"], url_path="destinations/delete", required_scopes=["alert:write"])+ def delete_destination(self, request, *args, **kwargs):+ alert = self.get_object()+ serializer = AlertDeleteDestinationSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ hog_function_ids = serializer.validated_data["hog_function_ids"]++ soft_delete_alert_destinations(+ team_id=self.team_id,+ alert_id=str(alert.id),+ allowed_event_ids=INSIGHT_ALERT_EVENT_IDS,+ hog_function_ids=hog_function_ids,+ )++ posthoganalytics.capture(+ distinct_id=str(request.user.distinct_id),+ event="insight alert destination deleted",+ properties={+ **get_request_analytics_properties(request),+ "alert_id": str(alert.id),+ "count": len(hog_function_ids),+ "team_id": alert.team_id,+ },+ )+ return Response(status=status.HTTP_204_NO_CONTENT)+@extend_schema(request=AlertSimulateSerializer,responses={200: AlertSimulateResponseSerializer},diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.pyindex 0c91459f0ac6..64f55a216dd4 100644--- a/products/alerts/backend/tests/api/test_alert.py+++ b/products/alerts/backend/tests/api/test_alert.py@@ -14,13 +14,21 @@ from rest_framework import statusfrom posthog.schema import AlertCalculationInterval, AlertConditionType, AlertState, InsightThresholdTypefrom posthog.api.tagged_item import set_tags_on_object+from posthog.cdp.templates.fixtures import template_slack+from posthog.cdp.templates.hog_function_template import sync_template_to_dbfrom posthog.constants import AvailableFeaturefrom posthog.models import User+from posthog.models.integration import Integrationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_value-from products.alerts.backend.destinations import AlertDelivery+from products.alerts.backend.destinations import AlertDelivery, count_active_alert_destinations+from products.alerts.backend.insight_alert_destinations import (+ INSIGHT_ALERT_EVENT_IDS,+ MAX_DESTINATIONS_PER_ALERT,+ SLACK_TEMPLATE_ID,+)from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Thresholdfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.product_analytics.backend.facade.models import Insight@@ -2242,6 +2250,13 @@ class TestAlertAPIKeyAccess(APIBaseTest):status.HTTP_403_FORBIDDEN,"alert:write",),+ (+ ["alert:read"],+ "post",+ "/{alert_id}/destinations/",+ status.HTTP_403_FORBIDDEN,+ "alert:write",+ ),])def test_alert_api_key_access(self, scopes, http_method, endpoint_suffix, expected_status, error_scope):@@ -2484,3 +2499,125 @@ class TestAlertRealTimeInterval(APIBaseTest):)assert response.status_code == status.HTTP_400_BAD_REQUESTassert "limit of 1 real-time alerts" in str(response.json())+++class TestAlertDestinations(APIBaseTest):+ def setUp(self):+ super().setUp()+ # Destination creation looks the template up by id through the HogFunction serializer.+ sync_template_to_db(template_slack)+ # No query on the insight, so this module does not drive another product's query runner.+ self.insight = Insight.objects.create(team=self.team, name="Signups", created_by=self.user)+ self.alert = AlertConfiguration.objects.create(+ team=self.team,+ insight_id=self.insight.id,+ name="Signups dropped",+ created_by=self.user,+ )+ self.integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T123",+ config={"authed_user": {"id": "u"}},+ sensitive_config={"access_token": "xoxb-test"},+ )+ self.url = f"/api/projects/{self.team.id}/alerts/{self.alert.id}/destinations/"++ def _slack_payload(self, **overrides: Any) -> dict[str, Any]:+ return {+ "type": "slack",+ "slack_workspace_id": self.integration.id,+ "slack_channel_id": "C123",+ "slack_channel_name": "product-alerts",+ **overrides,+ }++ def _active_destination_count(self) -> int:+ return count_active_alert_destinations(+ team_id=self.team.id, alert_id=str(self.alert.id), allowed_event_ids=INSIGHT_ALERT_EVENT_IDS+ )++ def test_alert_write_key_alone_attaches_a_slack_destination(self) -> None:+ key_value = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="Scout key",+ user=self.user,+ secure_value=hash_key_value(key_value),+ scopes=["alert:write"],+ )+ self.client.logout()++ response = self.client.post(+ self.url, self._slack_payload(), format="json", HTTP_AUTHORIZATION=f"Bearer {key_value}"+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ hog_function_ids = response.json()["hog_function_ids"]+ assert len(hog_function_ids) == 1+ assert self._active_destination_count() == 1++ hog_function = HogFunction.objects.get(id=hog_function_ids[0])+ assert hog_function.template_id == SLACK_TEMPLATE_ID+ assert hog_function.name == "Signups dropped: Slack #product-alerts"+ assert (hog_function.inputs or {})["channel"]["value"] == "C123"+ assert (hog_function.inputs or {})["slack_workspace"]["value"] == self.integration.id+ assert (hog_function.filters or {})["events"] == [{"id": "$insight_alert_firing", "type": "events"}]+ assert (hog_function.filters or {})["properties"] == [+ {"key": "alert_id", "value": str(self.alert.id), "operator": "exact", "type": "event"}+ ]+ # The Slack snooze handler finds its alert through these two ids.+ actions = next(block for block in (hog_function.inputs or {})["blocks"]["value"] if _is_actions_block(block))+ assert actions["block_id"] == "insight_alert_snooze:{event.properties.alert_id}"+ assert any(element.get("action_id") == "insight_alert_snooze" for element in actions["elements"])++ @parameterized.expand(+ [+ ("webhook_url_instead_of_slack", {"type": "webhook", "webhook_url": "https://example.com/hook"}, "type"),+ ("channel_missing", {"slack_channel_id": ""}, "slack_channel_id"),+ ("workspace_not_connected", {"slack_workspace_id": 987654}, "slack_workspace_id"),+ ]+ )+ def test_destination_request_is_refused(self, _name: str, overrides: dict, field: str) -> None:+ response = self.client.post(self.url, self._slack_payload(**overrides), format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == field+ assert self._active_destination_count() == 0++ def test_another_teams_slack_workspace_is_refused(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="Other")+ other_integration = Integration.objects.create(+ team=other_team, kind="slack", integration_id="T999", config={}, sensitive_config={}+ )++ response = self.client.post(+ self.url, self._slack_payload(slack_workspace_id=other_integration.id), format="json"+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert self._active_destination_count() == 0++ def test_destination_is_removed_again(self) -> None:+ created = self.client.post(self.url, self._slack_payload(), format="json")+ assert created.status_code == status.HTTP_201_CREATED, created.json()++ response = self.client.post(+ f"{self.url}delete/", {"hog_function_ids": created.json()["hog_function_ids"]}, format="json"+ )++ assert response.status_code == status.HTTP_204_NO_CONTENT, response.content+ assert self._active_destination_count() == 0++ def test_an_alert_stops_taking_destinations_at_the_cap(self) -> None:+ for index in range(MAX_DESTINATIONS_PER_ALERT):+ response = self.client.post(self.url, self._slack_payload(slack_channel_id=f"C{index}"), format="json")+ assert response.status_code == status.HTTP_201_CREATED, response.json()++ response = self.client.post(self.url, self._slack_payload(slack_channel_id="C-one-too-many"), format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert self._active_destination_count() == MAX_DESTINATIONS_PER_ALERT+++def _is_actions_block(block: Any) -> bool:+ return isinstance(block, dict) and block.get("type") == "actions"diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.tsindex c996321ad1af..f598ed89842d 100644--- a/products/alerts/frontend/generated/api.schemas.ts+++ b/products/alerts/frontend/generated/api.schemas.ts@@ -797,6 +797,42 @@ export interface PatchedAlertApi {readonly search_match_type?: SearchMatchTypeEnumApi | null}+/**+ * * `slack` - slack+ */+export type ChannelTypeEnumApi = (typeof ChannelTypeEnumApi)[keyof typeof ChannelTypeEnumApi]++export const ChannelTypeEnumApi = {+ Slack: 'slack',+} as const++export interface AlertCreateDestinationApi {+ /** Destination type. Slack is the only type this endpoint creates.+ *+ * * `slack` - slack */+ type?: ChannelTypeEnumApi+ /** Integration ID of the Slack workspace to post in. List them with the integrations endpoint. */+ slack_workspace_id: number+ /** Slack channel ID to post in, for example C0123456789. */+ slack_channel_id: string+ /** Channel name shown on the destination, for example product-alerts. */+ slack_channel_name?: string+}++export interface AlertDestinationResponseApi {+ /** IDs of the created destination. Pass them to destinations/delete to remove it. */+ hog_function_ids: string[]+}++export interface AlertDeleteDestinationApi {+ /**+ * Destination IDs to delete, as returned when the destination was created.+ * @minItems 1+ * @maxItems 100+ */+ hog_function_ids: string[]+}+/*** * `email` - email* * `destination` - destinationdiff --git a/products/alerts/frontend/generated/api.ts b/products/alerts/frontend/generated/api.tsindex 05452550b5f5..7dafccdeccd1 100644--- a/products/alerts/frontend/generated/api.ts+++ b/products/alerts/frontend/generated/api.ts@@ -10,6 +10,9 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'*/import type {AlertApi,+ AlertCreateDestinationApi,+ AlertDeleteDestinationApi,+ AlertDestinationResponseApi,AlertSimulateApi,AlertSimulateResponseApi,AlertTestDeliveryResponseApi,@@ -158,6 +161,48 @@ export const alertsDestroy = async (projectId: string, id: string, options?: Req})}+export const getAlertsDestinationsCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/alerts/${id}/destinations/`+}++/**+ * Send this alert to a Slack channel as well as by email. The workspace must already be connected to the project. The returned IDs identify the destination.+ */+export const alertsDestinationsCreate = async (+ projectId: string,+ id: string,+ alertCreateDestinationApi: AlertCreateDestinationApi,+ options?: RequestInit+): Promise<AlertDestinationResponseApi> => {+ return apiMutator<AlertDestinationResponseApi>(getAlertsDestinationsCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(alertCreateDestinationApi),+ })+}++export const getAlertsDestinationsDeleteCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/alerts/${id}/destinations/delete/`+}++/**+ * Stop sending this alert to a destination. The alert keeps its email recipients.+ */+export const alertsDestinationsDeleteCreate = async (+ projectId: string,+ id: string,+ alertDeleteDestinationApi: AlertDeleteDestinationApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getAlertsDestinationsDeleteCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(alertDeleteDestinationApi),+ })+}+export const getAlertsTestDeliveryCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/alerts/${id}/test-delivery/`}diff --git a/products/alerts/frontend/generated/api.zod.ts b/products/alerts/frontend/generated/api.zod.tsindex 0677a931c6b3..7017ca52cb88 100644--- a/products/alerts/frontend/generated/api.zod.ts+++ b/products/alerts/frontend/generated/api.zod.ts@@ -21,6 +21,40 @@ export const AlertsPartialUpdateBody = /* @__PURE__ */ zod.record(zod.string(), zod.unknown()).describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')+/**+ * Send this alert to a Slack channel as well as by email. The workspace must already be connected to the project. The returned IDs identify the destination.+ */+export const alertsDestinationsCreateBodyTypeDefault = `slack`++export const AlertsDestinationsCreateBody = /* @__PURE__ */ zod.object({+ type: zod+ .enum(['slack'])+ .describe('\* `slack` - slack')+ .default(alertsDestinationsCreateBodyTypeDefault)+ .describe('Destination type. Slack is the only type this endpoint creates.\n\n\* `slack` - slack'),+ slack_workspace_id: zod+ .number()+ .describe('Integration ID of the Slack workspace to post in. List them with the integrations endpoint.'),+ slack_channel_id: zod.string().describe('Slack channel ID to post in, for example C0123456789.'),+ slack_channel_name: zod+ .string()+ .optional()+ .describe('Channel name shown on the destination, for example product-alerts.'),+})++/**+ * Stop sending this alert to a destination. The alert keeps its email recipients.+ */+export const alertsDestinationsDeleteCreateBodyHogFunctionIdsMax = 100++export const AlertsDestinationsDeleteCreateBody = /* @__PURE__ */ zod.object({+ hog_function_ids: zod+ .array(zod.uuid())+ .min(1)+ .max(alertsDestinationsDeleteCreateBodyHogFunctionIdsMax)+ .describe('Destination IDs to delete, as returned when the destination was created.'),+})+/*** Simulate a detector on an insight's historical data. Read-only — no AlertCheck records are created.*/diff --git a/products/alerts/mcp/tools.yaml b/products/alerts/mcp/tools.yamlindex bf73f99a41fc..803d93486fcc 100644--- a/products/alerts/mcp/tools.yaml+++ b/products/alerts/mcp/tools.yaml@@ -49,7 +49,8 @@ tools:add-on. The field is optional and defaults to daily. If the user does not specify a cadence, ask beforecreating the alert.- Note: subscribed_users only controls email recipients. For Slack, HTTPS webhook, or Discord delivery, see+ Note: subscribed_users only controls email recipients. To also post the alert to Slack, create it and then+ call alert-destinations-create with the workspace and channel. For HTTPS webhook or Discord delivery, seethe recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe(cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.exclude_params:@@ -71,6 +72,46 @@ tools:description: >Delete an alert by ID. This permanently removes the alert and all its check history. Subscribed users willno longer receive notifications.+ alert-destinations-create:+ operation: alerts_destinations_create+ enabled: true+ scopes:+ - alert:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Send an alert to Slack+ description: >+ Post this insight alert to a Slack channel as well as emailing its subscribed users. The Slack workspace+ must already be connected to the project — list the workspaces and their channels with+ integrations-channels-retrieve. An alert can have up to 5 destinations. The returned hog_function_ids+ identify the destination; pass them to alert-destinations-delete to remove it.+ param_overrides:+ type:+ description: Destination type. Slack is the only type this tool creates.+ slack_workspace_id:+ description: Integration ID of the connected Slack workspace.+ slack_channel_id:+ description: Slack channel ID to post in, for example C0123456789.+ slack_channel_name:+ description: Optional channel name shown on the destination.+ response:+ include:+ - hog_function_ids+ alert-destinations-delete:+ operation: alerts_destinations_delete_create+ enabled: true+ scopes:+ - alert:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Stop sending an alert to Slack+ description: >+ Remove a destination from an insight alert by passing the hog_function_ids that alert-destinations-create+ returned. The alert keeps its email recipients.alert-get:operation: alerts_retrieveenabled: true@@ -130,10 +171,11 @@ tools:To snooze an alert, set snoozed_until to a relative date string (e.g. '2h', '1d'). To unsnooze, setsnoozed_until to null.- Note: Slack/webhook/Discord delivery for this alert lives as a HogFunction. See the recipe on- cdp-functions-create for the dedupe-and-create flow; to change or remove an existing destination, find it- via cdp-functions-list (type=internal_destination, limit=1000) by matching filters.properties value against- this alert's id, then use cdp-functions-partial-update or cdp-functions-delete.+ Note: Slack/webhook/Discord delivery for this alert lives as a HogFunction. Add or remove a Slack channel+ with alert-destinations-create and alert-destinations-delete. For webhook and Discord, see the recipe on+ cdp-functions-create; to change or remove one of those, find it via cdp-functions-list+ (type=internal_destination, limit=1000) by matching filters.properties value against this alert's id, then+ use cdp-functions-partial-update or cdp-functions-delete.exclude_params:- state- last_notified_atdiff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.pyindex 9fdb7adb264c..f386ba348249 100644--- a/products/signals/backend/scout_harness/prompt.py+++ b/products/signals/backend/scout_harness/prompt.py@@ -720,7 +720,7 @@ _WRITE_ACCESS_OBJECTS: dict[str, str] = {"dashboard:write": "dashboards and their tiles","insight:write": "saved insights","annotation:write": "annotations",- "alert:write": "insight alerts",+ "alert:write": "insight alerts, including the Slack channels they post to","llm_skill:write": "shared skills","warehouse_view:write": "data warehouse views","warehouse_table:write": "data warehouse tables",diff --git a/products/signals/frontend/inbox/components/config/scouts/scoutWriteScopes.ts b/products/signals/frontend/inbox/components/config/scouts/scoutWriteScopes.tsindex 707a1bc614b0..ebfe26f6deb4 100644--- a/products/signals/frontend/inbox/components/config/scouts/scoutWriteScopes.ts+++ b/products/signals/frontend/inbox/components/config/scouts/scoutWriteScopes.ts@@ -38,7 +38,8 @@ export const SCOUT_WRITE_SCOPE_ROWS: ScoutWriteScopeRow[] = [scope: 'alert:write',group: 'Monitoring',label: 'Alerts',- description: 'Create, update, and delete insight alerts',+ description:+ 'Create, update, and delete insight alerts, and post them to a Slack channel your project has connected',},{scope: 'llm_skill:write',diff --git a/pyproject.toml b/pyproject.tomlindex 0386ac4e3ab8..96c4346a5014 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -561,8 +561,6 @@ ignore_imports = ["products.**.backend.presentation.** -> products.**.backend.facade.**","products.**.backend.presentation.** -> products.**.backend.presentation.**",# TODO: existing violations — fix by routing through facade- "products.alerts.backend.presentation.views.alert -> products.alerts.backend.destination_configs",- "products.alerts.backend.presentation.views.alert -> products.alerts.backend.destinations","products.alerts.backend.presentation.views.alert -> products.alerts.backend.evaluation.contract","products.alerts.backend.presentation.views.alert -> products.alerts.backend.evaluation.detector","products.alerts.backend.presentation.views.alert -> products.alerts.backend.evaluation.validation",diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 203ee2c6a938..1d492507b26a 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -415,7 +415,7 @@"feature_entitlement": "audit_logs"},"alert-create": {- "description": "Create a new alert on an insight. Alerts can use either threshold-based conditions or anomaly detection. For threshold alerts: set condition (absolute_value, relative_increase, relative_decrease) and threshold configuration with bounds — at least one of lower or upper is required (omit detector_config). For anomaly detection: set detector_config with a detector type (zscore, mad, iqr, threshold, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca) and parameters like threshold (sensitivity 0-1, default 0.9) and window size. Ensemble detectors combine 2+ sub-detectors with AND/OR logic. Requires an insight ID and at least one subscribed user.\nThe config type must match the insight kind. Trends insights: TrendsAlertConfig (series_index, check_ongoing_interval). SQL/HogQL insights: HogQLAlertConfig — column picks which result column to evaluate (defaults to the single numeric column), evaluation is required and selects how rows are read: 'last_row' (query ordered oldest->newest, the last row is the current value), 'first_row' (query ordered newest->oldest, the first row is the current value — pair with a LIMIT, and it is unaffected by result truncation), or 'any_row' (every row is checked and the alert fires if any value breaches; absolute_value condition only). label_column names the evaluated row(s) in breach messages in every evaluation mode (defaults to the first non-evaluated column). Label values appear in delivered notifications — avoid label columns containing PII. Funnel insights: FunnelsAlertConfig — funnel_step picks the step to monitor (null for the overall last step), metric is 'conversion_from_start' or 'conversion_from_previous', and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease. Anomaly detection (detector_config) is supported for trends and SQL insights (not funnels).\ncalculation_interval sets how often the alert runs: real_time, every_15_minutes, hourly, daily, weekly, or monthly. real_time needs a Scale or Enterprise plan. every_15_minutes needs a Boost, Scale, or Enterprise add-on. The field is optional and defaults to daily. If the user does not specify a cadence, ask before creating the alert.\nNote: subscribed_users only controls email recipients. For Slack, HTTPS webhook, or Discord delivery, see the recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe (cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.",+ "description": "Create a new alert on an insight. Alerts can use either threshold-based conditions or anomaly detection. For threshold alerts: set condition (absolute_value, relative_increase, relative_decrease) and threshold configuration with bounds — at least one of lower or upper is required (omit detector_config). For anomaly detection: set detector_config with a detector type (zscore, mad, iqr, threshold, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca) and parameters like threshold (sensitivity 0-1, default 0.9) and window size. Ensemble detectors combine 2+ sub-detectors with AND/OR logic. Requires an insight ID and at least one subscribed user.\nThe config type must match the insight kind. Trends insights: TrendsAlertConfig (series_index, check_ongoing_interval). SQL/HogQL insights: HogQLAlertConfig — column picks which result column to evaluate (defaults to the single numeric column), evaluation is required and selects how rows are read: 'last_row' (query ordered oldest->newest, the last row is the current value), 'first_row' (query ordered newest->oldest, the first row is the current value — pair with a LIMIT, and it is unaffected by result truncation), or 'any_row' (every row is checked and the alert fires if any value breaches; absolute_value condition only). label_column names the evaluated row(s) in breach messages in every evaluation mode (defaults to the first non-evaluated column). Label values appear in delivered notifications — avoid label columns containing PII. Funnel insights: FunnelsAlertConfig — funnel_step picks the step to monitor (null for the overall last step), metric is 'conversion_from_start' or 'conversion_from_previous', and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease. Anomaly detection (detector_config) is supported for trends and SQL insights (not funnels).\ncalculation_interval sets how often the alert runs: real_time, every_15_minutes, hourly, daily, weekly, or monthly. real_time needs a Scale or Enterprise plan. every_15_minutes needs a Boost, Scale, or Enterprise add-on. The field is optional and defaults to daily. If the user does not specify a cadence, ask before creating the alert.\nNote: subscribed_users only controls email recipients. To also post the alert to Slack, create it and then call alert-destinations-create with the workspace and channel. For HTTPS webhook or Discord delivery, see the recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe (cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.","category": "Alerts","feature": "alerts","summary": "Create alert",@@ -442,6 +442,34 @@"readOnlyHint": false}},+ "alert-destinations-create": {+ "description": "Post this insight alert to a Slack channel as well as emailing its subscribed users. The Slack workspace must already be connected to the project — list the workspaces and their channels with integrations-channels-retrieve. An alert can have up to 5 destinations. The returned hog_function_ids identify the destination; pass them to alert-destinations-delete to remove it.",+ "category": "Alerts",+ "feature": "alerts",+ "summary": "Send an alert to Slack",+ "title": "Send an alert to Slack",+ "required_scopes": ["alert:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "alert-destinations-delete": {+ "description": "Remove a destination from an insight alert by passing the hog_function_ids that alert-destinations-create returned. The alert keeps its email recipients.",+ "category": "Alerts",+ "feature": "alerts",+ "summary": "Stop sending an alert to Slack",+ "title": "Stop sending an alert to Slack",+ "required_scopes": ["alert:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"alert-get": {"description": "Get a specific alert by ID. Returns the full alert configuration including check results, threshold settings, detector_config (for anomaly detection alerts), and subscribed users. Check results include anomaly_scores, triggered_points, and triggered_dates for detector-based alerts. By default returns the last 5 checks. Use checks_date_from and checks_date_to (e.g. '-24h', '-7d') to get checks within a time window, and checks_limit to control the maximum returned (default 5, max 500). When date filters are provided without checks_limit, up to 500 checks are returned. Check history is retained for 14 days.","category": "Alerts",@@ -471,7 +499,7 @@}},"alert-update": {- "description": "Update an existing alert by ID. Can update name, threshold, condition, config, detector_config, subscribed users, enabled state, calculation_interval, and weekend skipping. calculation_interval sets how often the alert runs: real_time, every_15_minutes, hourly, daily, weekly, or monthly. real_time needs a Scale or Enterprise plan. every_15_minutes needs a Boost, Scale, or Enterprise add-on. Set detector_config to switch to anomaly detection (trends and SQL insights), or set it to null to switch back to threshold mode (threshold mode requires at least one of lower or upper in threshold.configuration.bounds). For SQL-insight alerts the config is HogQLAlertConfig (column, evaluation 'last_row'/'first_row'/'any_row', label_column). To snooze an alert, set snoozed_until to a relative date string (e.g. '2h', '1d'). To unsnooze, set snoozed_until to null.\nNote: Slack/webhook/Discord delivery for this alert lives as a HogFunction. See the recipe on cdp-functions-create for the dedupe-and-create flow; to change or remove an existing destination, find it via cdp-functions-list (type=internal_destination, limit=1000) by matching filters.properties value against this alert's id, then use cdp-functions-partial-update or cdp-functions-delete.",+ "description": "Update an existing alert by ID. Can update name, threshold, condition, config, detector_config, subscribed users, enabled state, calculation_interval, and weekend skipping. calculation_interval sets how often the alert runs: real_time, every_15_minutes, hourly, daily, weekly, or monthly. real_time needs a Scale or Enterprise plan. every_15_minutes needs a Boost, Scale, or Enterprise add-on. Set detector_config to switch to anomaly detection (trends and SQL insights), or set it to null to switch back to threshold mode (threshold mode requires at least one of lower or upper in threshold.configuration.bounds). For SQL-insight alerts the config is HogQLAlertConfig (column, evaluation 'last_row'/'first_row'/'any_row', label_column). To snooze an alert, set snoozed_until to a relative date string (e.g. '2h', '1d'). To unsnooze, set snoozed_until to null.\nNote: Slack/webhook/Discord delivery for this alert lives as a HogFunction. Add or remove a Slack channel with alert-destinations-create and alert-destinations-delete. For webhook and Discord, see the recipe on cdp-functions-create; to change or remove one of those, find it via cdp-functions-list (type=internal_destination, limit=1000) by matching filters.properties value against this alert's id, then use cdp-functions-partial-update or cdp-functions-delete.","category": "Alerts","feature": "alerts","summary": "Update alert",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex bb73d8ddeec6..71309ac98c64 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -430,7 +430,7 @@}},"alert-create": {- "description": "Create a new alert on an insight. Alerts can use either threshold-based conditions or anomaly detection. For threshold alerts: set condition (absolute_value, relative_increase, relative_decrease) and threshold configuration with bounds — at least one of lower or upper is required (omit detector_config). For anomaly detection: set detector_config with a detector type (zscore, mad, iqr, threshold, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca) and parameters like threshold (sensitivity 0-1, default 0.9) and window size. Ensemble detectors combine 2+ sub-detectors with AND/OR logic. Requires an insight ID and at least one subscribed user.\nThe config type must match the insight kind. Trends insights: TrendsAlertConfig (series_index, check_ongoing_interval). SQL/HogQL insights: HogQLAlertConfig — column picks which result column to evaluate (defaults to the single numeric column), evaluation is required and selects how rows are read: 'last_row' (query ordered oldest->newest, the last row is the current value), 'first_row' (query ordered newest->oldest, the first row is the current value — pair with a LIMIT, and it is unaffected by result truncation), or 'any_row' (every row is checked and the alert fires if any value breaches; absolute_value condition only). label_column names the evaluated row(s) in breach messages in every evaluation mode (defaults to the first non-evaluated column). Label values appear in delivered notifications — avoid label columns containing PII. Funnel insights: FunnelsAlertConfig — funnel_step picks the step to monitor (null for the overall last step), metric is 'conversion_from_start' or 'conversion_from_previous', and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease. Anomaly detection (detector_config) is supported for trends and SQL insights (not funnels).\ncalculation_interval sets how often the alert runs: real_time, every_15_minutes, hourly, daily, weekly, or monthly. real_time needs a Scale or Enterprise plan. every_15_minutes needs a Boost, Scale, or Enterprise add-on. The field is optional and defaults to daily. If the user does not specify a cadence, ask before creating the alert.\nNote: subscribed_users only controls email recipients. For Slack, HTTPS webhook, or Discord delivery, see the recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe (cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.",+ "description": "Create a new alert on an insight. Alerts can use either threshold-based conditions or anomaly detection. For threshold alerts: set condition (absolute_value, relative_increase, relative_decrease) and threshold configuration with bounds — at least one of lower or upper is required (omit detector_config). For anomaly detection: set detector_config with a detector type (zscore, mad, iqr, threshold, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca) and parameters like threshold (sensitivity 0-1, default 0.9) and window size. Ensemble detectors combine 2+ sub-detectors with AND/OR logic. Requires an insight ID and at least one subscribed user.\nThe config type must match the insight kind. Trends insights: TrendsAlertConfig (series_index, check_ongoing_interval). SQL/HogQL insights: HogQLAlertConfig — column picks which result column to evaluate (defaults to the single numeric column), evaluation is required and selects how rows are read: 'last_row' (query ordered oldest->newest, the last row is the current value), 'first_row' (query ordered newest->oldest, the first row is the current value — pair with a LIMIT, and it is unaffected by result truncation), or 'any_row' (every row is checked and the alert fires if any value breaches; absolute_value condition only). label_column names the evaluated row(s) in breach messages in every evaluation mode (defaults to the first non-evaluated column). Label values appear in delivered notifications — avoid label columns containing PII. Funnel insights: FunnelsAlertConfig — funnel_step picks the step to monitor (null for the overall last step), metric is 'conversion_from_start' or 'conversion_from_previous', and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease. Anomaly detection (detector_config) is supported for trends and SQL insights (not funnels).\ncalculation_interval sets how often the alert runs: real_time, every_15_minutes, hourly, daily, weekly, or monthly. real_time needs a Scale or Enterprise plan. every_15_minutes needs a Boost, Scale, or Enterprise add-on. The field is optional and defaults to daily. If the user does not specify a cadence, ask before creating the alert.\nNote: subscribed_users only controls email recipients. To also post the alert to Slack, create it and then call alert-destinations-create with the workspace and channel. For HTTPS webhook or Discord delivery, see the recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe (cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.","category": "Alerts","feature": "alerts","summary": "Create alert",@@ -457,6 +457,34 @@"readOnlyHint": false}},+ "alert-destinations-create": {+ "description": "Post this insight alert to a Slack channel as well as emailing its subscribed users. The Slack workspace must already be connected to the project — list the workspaces and their channels with integrations-channels-retrieve. An alert can have up to 5 destinations. The returned hog_function_ids identify the destination; pass them to alert-destinations-delete to remove it.",+ "category": "Alerts",+ "feature": "alerts",+ "summary": "Send an alert to Slack",+ "title": "Send an alert to Slack",+ "required_scopes": ["alert:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "alert-destinations-delete": {+ "description": "Remove a destination from an insight alert by passing the hog_function_ids that alert-destinations-create returned. The alert keeps its email recipients.",+ "category": "Alerts",+ "feature": "alerts",+ "summary": "Stop sending an alert to Slack",+ "title": "Stop sending an alert to Slack",+ "required_scopes": ["alert:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"alert-get": {"description": "Get a specific alert by ID. Returns the full alert configuration including check results, threshold settings, detector_config (for anomaly detection alerts), and subscribed users. Check results include anomaly_scores, triggered_points, and triggered_dates for detector-based alerts. By default returns the last 5 checks. Use checks_date_from and checks_date_to (e.g. '-24h', '-7d') to get checks within a time window, and checks_limit to control the maximum returned (default 5, max 500). When date filters are provided without checks_limit, up to 500 checks are returned. Check history is retained for 14 days.","category": "Alerts",@@ -486,7 +514,7 @@}},"alert-update": {- "description": "Update an existing alert by ID. Can update name, threshold, condition, config, detector_config, subscribed users, enabled state, calculation_interval, and weekend skipping. calculation_interval sets how often the alert runs: real_time, every_15_minutes, hourly, daily, weekly, or monthly. real_time needs a Scale or Enterprise plan. every_15_minutes needs a Boost, Scale, or Enterprise add-on. Set detector_config to switch to anomaly detection (trends and SQL insights), or set it to null to switch back to threshold mode (threshold mode requires at least one of lower or upper in threshold.configuration.bounds). For SQL-insight alerts the config is HogQLAlertConfig (column, evaluation 'last_row'/'first_row'/'any_row', label_column). To snooze an alert, set snoozed_until to a relative date string (e.g. '2h', '1d'). To unsnooze, set snoozed_until to null.\nNote: Slack/webhook/Discord delivery for this alert lives as a HogFunction. See the recipe on cdp-functions-create for the dedupe-and-create flow; to change or remove an existing destination, find it via cdp-functions-list (type=internal_destination, limit=1000) by matching filters.properties value against this alert's id, then use cdp-functions-partial-update or cdp-functions-delete.",+ "description": "Update an existing alert by ID. Can update name, threshold, condition, config, detector_config, subscribed users, enabled state, calculation_interval, and weekend skipping. calculation_interval sets how often the alert runs: real_time, every_15_minutes, hourly, daily, weekly, or monthly. real_time needs a Scale or Enterprise plan. every_15_minutes needs a Boost, Scale, or Enterprise add-on. Set detector_config to switch to anomaly detection (trends and SQL insights), or set it to null to switch back to threshold mode (threshold mode requires at least one of lower or upper in threshold.configuration.bounds). For SQL-insight alerts the config is HogQLAlertConfig (column, evaluation 'last_row'/'first_row'/'any_row', label_column). To snooze an alert, set snoozed_until to a relative date string (e.g. '2h', '1d'). To unsnooze, set snoozed_until to null.\nNote: Slack/webhook/Discord delivery for this alert lives as a HogFunction. Add or remove a Slack channel with alert-destinations-create and alert-destinations-delete. For webhook and Discord, see the recipe on cdp-functions-create; to change or remove one of those, find it via cdp-functions-list (type=internal_destination, limit=1000) by matching filters.properties value against this alert's id, then use cdp-functions-partial-update or cdp-functions-delete.","category": "Alerts","feature": "alerts","summary": "Update alert",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 84f796fd8ba6..f7030215658c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -9987,6 +9987,43 @@ export namespace Schemas {readonly search_match_type: SearchMatchTypeEnum | null;}+ /**+ * * `slack` - slack+ */+ export type ChannelTypeEnum = typeof ChannelTypeEnum[keyof typeof ChannelTypeEnum];+++ export const ChannelTypeEnum = {+ Slack: 'slack',+ } as const;++ export interface AlertCreateDestination {+ /** Destination type. Slack is the only type this endpoint creates.+ *+ * * `slack` - slack */+ type?: ChannelTypeEnum;+ /** Integration ID of the Slack workspace to post in. List them with the integrations endpoint. */+ slack_workspace_id: number;+ /** Slack channel ID to post in, for example C0123456789. */+ slack_channel_id: string;+ /** Channel name shown on the destination, for example product-alerts. */+ slack_channel_name?: string;+ }++ export interface AlertDeleteDestination {+ /**+ * Destination IDs to delete, as returned when the destination was created.+ * @minItems 1+ * @maxItems 100+ */+ hog_function_ids: string[];+ }++ export interface AlertDestinationResponse {+ /** IDs of the created destination. Pass them to destinations/delete to remove it. */+ hog_function_ids: string[];+ }+export interface AlertSimulate {/** Numeric insight ID or saved insight short ID to simulate the detector on. */insight: number | string;@@ -17107,16 +17144,6 @@ export namespace Schemas {starred: boolean;}- /**- * * `slack` - slack- */- export type ChannelTypeEnum = typeof ChannelTypeEnum[keyof typeof ChannelTypeEnum];--- export const ChannelTypeEnum = {- Slack: 'slack',- } as const;-/*** Response shape for a channel's page identity in the wiki.*/diff --git a/services/mcp/src/generated/alerts/api.ts b/services/mcp/src/generated/alerts/api.tsindex 7e0e9c6ebaff..d36d5b1b4640 100644--- a/services/mcp/src/generated/alerts/api.ts+++ b/services/mcp/src/generated/alerts/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 6 enabled ops+ * PostHog API - MCP 8 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -2646,6 +2646,58 @@ export const AlertsDestroyParams = () => zod.object({),})+/**+ * Send this alert to a Slack channel as well as by email. The workspace must already be connected to the project. The returned IDs identify the destination.+ */+export const AlertsDestinationsCreateParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this alert configuration.'),+ 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 alertsDestinationsCreateBodyTypeDefault = `slack`++export const AlertsDestinationsCreateBody = () => zod.object({+ type: zod+ .enum(['slack'])+ .describe('\* `slack` - slack')+ .default(alertsDestinationsCreateBodyTypeDefault)+ .describe('Destination type. Slack is the only type this endpoint creates.\n\n\* `slack` - slack'),+ slack_workspace_id: zod+ .number()+ .describe('Integration ID of the Slack workspace to post in. List them with the integrations endpoint.'),+ slack_channel_id: zod.string().describe('Slack channel ID to post in, for example C0123456789.'),+ slack_channel_name: zod+ .string()+ .optional()+ .describe('Channel name shown on the destination, for example product-alerts.'),+})++/**+ * Stop sending this alert to a destination. The alert keeps its email recipients.+ */+export const AlertsDestinationsDeleteCreateParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this alert configuration.'),+ 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 alertsDestinationsDeleteCreateBodyHogFunctionIdsMax = 100++export const AlertsDestinationsDeleteCreateBody = () => zod.object({+ hog_function_ids: zod+ .array(zod.string())+ .min(1)+ .max(alertsDestinationsDeleteCreateBodyHogFunctionIdsMax)+ .describe('Destination IDs to delete, as returned when the destination was created.'),+})+/*** Simulate a detector on an insight's historical data. Read-only — no AlertCheck records are created.*/diff --git a/services/mcp/src/tools/generated/alerts.ts b/services/mcp/src/tools/generated/alerts.tsindex bb5b67812288..e213696bfc26 100644--- a/services/mcp/src/tools/generated/alerts.ts+++ b/services/mcp/src/tools/generated/alerts.ts@@ -3,7 +3,7 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import * as orvalSchemas from '@/generated/alerts/api'-import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'+import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'const AlertCreateSchema = () => {@@ -89,6 +89,84 @@ const alertDelete = (): ToolBase<ReturnType<typeof AlertDeleteSchema>, unknown>},})+const AlertDestinationsCreateSchema = () => {+ const AlertsDestinationsCreateBody = orvalSchemas.AlertsDestinationsCreateBody()+ const AlertsDestinationsCreateParams = orvalSchemas.AlertsDestinationsCreateParams()+ return AlertsDestinationsCreateParams.omit({ project_id: true })+ .extend(AlertsDestinationsCreateBody.shape)+ .extend({+ type: AlertsDestinationsCreateBody.shape['type'].describe(+ 'Destination type. Slack is the only type this tool creates.'+ ),+ slack_workspace_id: AlertsDestinationsCreateBody.shape['slack_workspace_id'].describe(+ 'Integration ID of the connected Slack workspace.'+ ),+ slack_channel_id: AlertsDestinationsCreateBody.shape['slack_channel_id'].describe(+ 'Slack channel ID to post in, for example C0123456789.'+ ),+ slack_channel_name: AlertsDestinationsCreateBody.shape['slack_channel_name'].describe(+ 'Optional channel name shown on the destination.'+ ),+ })+}++const alertDestinationsCreate = (): ToolBase<+ ReturnType<typeof AlertDestinationsCreateSchema>,+ Schemas.AlertDestinationResponse+> => ({+ name: 'alert-destinations-create',+ schema: AlertDestinationsCreateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AlertDestinationsCreateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.type !== undefined) {+ body['type'] = params.type+ }+ if (params.slack_workspace_id !== undefined) {+ body['slack_workspace_id'] = params.slack_workspace_id+ }+ if (params.slack_channel_id !== undefined) {+ body['slack_channel_id'] = params.slack_channel_id+ }+ if (params.slack_channel_name !== undefined) {+ body['slack_channel_name'] = params.slack_channel_name+ }+ const result = await context.api.request<Schemas.AlertDestinationResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/alerts/${encodeURIComponent(String(params.id))}/destinations/`,+ body,+ })+ const filtered = pickResponseFields(result, ['hog_function_ids']) as typeof result+ return filtered+ },+})++const AlertDestinationsDeleteSchema = () => {+ const AlertsDestinationsDeleteCreateBody = orvalSchemas.AlertsDestinationsDeleteCreateBody()+ const AlertsDestinationsDeleteCreateParams = orvalSchemas.AlertsDestinationsDeleteCreateParams()+ return AlertsDestinationsDeleteCreateParams.omit({ project_id: true }).extend(+ AlertsDestinationsDeleteCreateBody.shape+ )+}++const alertDestinationsDelete = (): ToolBase<ReturnType<typeof AlertDestinationsDeleteSchema>, unknown> => ({+ name: 'alert-destinations-delete',+ schema: AlertDestinationsDeleteSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AlertDestinationsDeleteSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.hog_function_ids !== undefined) {+ body['hog_function_ids'] = params.hog_function_ids+ }+ const result = await context.api.request<unknown>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/alerts/${encodeURIComponent(String(params.id))}/destinations/delete/`,+ body,+ })+ return result+ },+})+const AlertGetSchema = () => {const AlertsRetrieveParams = orvalSchemas.AlertsRetrieveParams()const AlertsRetrieveQueryParams = orvalSchemas.AlertsRetrieveQueryParams()@@ -256,6 +334,8 @@ const alertsList = (): ToolBase<ReturnType<typeof AlertsListSchema>, WithPostHogexport const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'alert-create': alertCreate,'alert-delete': alertDelete,+ 'alert-destinations-create': alertDestinationsCreate,+ 'alert-destinations-delete': alertDestinationsDelete,'alert-get': alertGet,'alert-simulate': alertSimulate,'alert-update': alertUpdate,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-destinations-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-destinations-create.jsonnew file mode 100644index 000000000000..8750d94c4984--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-destinations-create.json@@ -0,0 +1,29 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this alert configuration.",+ "type": "string"+ },+ "slack_channel_id": {+ "description": "Slack channel ID to post in, for example C0123456789.",+ "type": "string"+ },+ "slack_channel_name": {+ "description": "Optional channel name shown on the destination.",+ "type": "string"+ },+ "slack_workspace_id": {+ "description": "Integration ID of the connected Slack workspace.",+ "type": "number"+ },+ "type": {+ "default": "slack",+ "description": "Destination type. Slack is the only type this tool creates.",+ "enum": ["slack"],+ "type": "string"+ }+ },+ "required": ["id", "slack_workspace_id", "slack_channel_id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-destinations-delete.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-destinations-delete.jsonnew file mode 100644index 000000000000..05f623df9b55--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-destinations-delete.json@@ -0,0 +1,20 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "hog_function_ids": {+ "description": "Destination IDs to delete, as returned when the destination was created.",+ "items": {+ "type": "string"+ },+ "maxItems": 100,+ "minItems": 1,+ "type": "array"+ },+ "id": {+ "description": "A UUID string identifying this alert configuration.",+ "type": "string"+ }+ },+ "required": ["id", "hog_function_ids"],+ "type": "object"+}