: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): include the insight chart in investigation Slack alerts (#88990)
Andrew Maguire28d86aa32c00
diff --git a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.tsindex 0c25275edfcd..0bdc10972ea0 100644--- a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts+++ b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts@@ -1328,7 +1328,12 @@ export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, Hotype: 'context',elements: [{ type: 'mrkdwn', text: 'Project: <{project.url}|{project.name}>' }],},- { type: 'divider' },+ // 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.+ "{event.properties.insight_chart_url ? {'type': 'image', 'image_url': event.properties.insight_chart_url, 'alt_text': 'Insight chart'} : {'type': 'divider'}}",{type: 'actions',// The alert id in the block_id is what lets the datetimepicker action identifydiff --git a/posthog/cdp/internal_events.py b/posthog/cdp/internal_events.pyindex 8e706e87c0b7..7164ef6c4fd3 100644--- a/posthog/cdp/internal_events.py+++ b/posthog/cdp/internal_events.py@@ -88,7 +88,15 @@ def produce_internal_event(producer = get_producer(topic=kafka_topic)return producer.produce(topic=kafka_topic, data=serialized_data, key=data.event.uuid)except Exception as e:- logger.exception("Failed to produce internal event", data=serialized_data, error=e)+ # Identify the event by ids, not payload: properties can carry credentials+ # (e.g. tokenized delivery URLs) and person data, which must not reach logs.+ logger.exception(+ "Failed to produce internal event",+ team_id=team_id,+ event_name=data.event.event,+ event_uuid=data.event.uuid,+ error=e,+ )raisediff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.pyindex c87a0a0a7fe0..5769e098fc36 100644--- a/posthog/tasks/alerts/utils.py+++ b/posthog/tasks/alerts/utils.py@@ -151,10 +151,14 @@ def trigger_alert_hog_functions(alert: AlertConfiguration, properties: dict) ->"there was nothing to send" apart from "sending failed"."""+ log_properties = dict(properties)+ if "insight_chart_url" in log_properties:+ # The chart URL embeds a bearer token, so logs must not carry a usable credential.+ log_properties["insight_chart_url"] = "[redacted]"logger.info("Triggering internal event for alert destinations/hog functions",alert_id=alert.id,- properties=properties,+ properties=log_properties,)props = {diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.pyindex 5ba55ce6d1c9..6119e2ec1136 100644--- a/posthog/temporal/ai/anomaly_investigation/workflow.py+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py@@ -10,7 +10,7 @@ import reimport jsonimport asynciofrom dataclasses import dataclass-from datetime import timedelta+from datetime import UTC, datetime, timedeltafrom typing import TYPE_CHECKING, Optionalfrom uuid import UUID@@ -22,7 +22,7 @@ from temporalio import activity, workflowfrom temporalio.common import RetryPolicyfrom posthog.models import Team, User-from posthog.tasks.alerts.utils import dispatch_alert_notification, record_alert_delivery+from posthog.tasks.alerts.utils import INSIGHT_ALERT_FIRING_EVENT, dispatch_alert_notification, record_alert_deliveryfrom posthog.temporal.ai.anomaly_investigation.charts import png_to_b64, render_series_chartfrom posthog.temporal.ai.anomaly_investigation.metric_definition import describe_metric_definitionfrom posthog.temporal.ai.anomaly_investigation.notebook import NotebookRenderContext, build_investigation_notebook@@ -34,7 +34,9 @@ from posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.utils import absolute_uri+from products.alerts.backend.destinations import list_active_alert_destinationsfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus+from products.exports.backend.facade import api as exportsfrom products.notebooks.backend.facade import api as notebooksfrom products.signals.backend.facade import api as signals@@ -71,6 +73,15 @@ _MAX_DESCRIPTION_CHARS = 3000# used to clip the summary teaser on a sentence boundary instead of mid-word._SENTENCE_END_RE = re.compile(r"[.!?](?=\s|$)")+# TTL for the tokenized chart URL embedded in Slack. Slack fetches the image at delivery,+# but the URL must stay resolvable while people scroll back to the message; 30 days matches+# the delivery-URL TTL used for task chart artifacts (products/tasks living_artifacts).+_INSIGHT_CHART_URL_TTL = timedelta(days=30)++# The stored PNG outlives its delivery URL by one day so the URL can never point at a+# deleted asset; without an explicit TTL the format default keeps the PNG for six months.+_INSIGHT_CHART_ASSET_TTL = timedelta(days=31)+@dataclassclass AnomalyInvestigationWorkflowInputs:@@ -187,6 +198,17 @@ async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInputcreation_source=notebooks.NotebookCreationSource.TEMPORAL_AGENT,)+ # Rendered before the check is marked DONE: once the status is terminal the safety net's+ # short grace applies (INVESTIGATION_NOTIFY_GRACE_MINUTES), and a slow render sitting+ # between the DONE update and the dispatch would let the sweep force-send its fallback+ # notification mid-render. While the status is RUNNING the sweep waits much longer.+ insight_chart_url = await sync_to_async(_prepare_insight_chart_url, thread_sensitive=False)(+ alert=alert,+ alert_check=alert_check,+ user=user,+ verdict=result.report.verdict,+ )+summary_for_list = _truncate_summary(result.report.summary)await sync_to_async(AlertCheck.objects.filter(id=alert_check.id).update, thread_sensitive=False)(investigation_notebook_id=notebook.id,@@ -210,6 +232,7 @@ async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInputverdict=result.report.verdict,summary=summary_for_list or "",notebook_short_id=notebook.short_id,+ insight_chart_url=insight_chart_url,)# Surface the completed investigation to the Signals inbox, gated on the verdict so@@ -363,6 +386,67 @@ def _build_signal_description(return description+def _should_suppress_notification(verdict: str | None, inconclusive_action: str | None) -> bool:+ """Whether the verdict holds the notification back: false positives always suppress,+ inconclusive follows the alert's configured policy."""+ return verdict == "false_positive" or (+ verdict == "inconclusive" and (inconclusive_action or "notify") == "suppress"+ )+++def _prepare_insight_chart_url(+ *,+ alert: AlertConfiguration,+ alert_check: AlertCheck,+ user: User,+ verdict: str | None,+) -> str | None:+ """Render the alerted insight to a PNG and mint a URL Slack can embed as an image block.++ Skipped when nothing would show it: a suppressed verdict, an already-delivered check+ (the common case for non-gated alerts, whose notification the main task sent+ synchronously), or no active Slack destination (only the Slack template renders the+ chart). Best-effort: on any failure (render error, no viewer access for the+ investigation user, export infrastructure down) return None so the notification still+ goes out, just without the chart.+ """+ if _should_suppress_notification(verdict, alert.investigation_inconclusive_action):+ return None+ pending = AlertCheck.objects.filter(+ id=alert_check.id, notification_sent_at__isnull=True, notification_suppressed_by_agent=False+ ).exists()+ if not pending:+ return None+ try:+ destinations = list_active_alert_destinations(+ team_id=alert.team_id, alert_id=str(alert.id), allowed_event_ids=(INSIGHT_ALERT_FIRING_EVENT,)+ )+ if not any(destination.destination_type == "slack" for destination in destinations):+ return None+ asset, content = exports.render_png_export(+ team=alert.team,+ created_by=user,+ insight_id=alert.insight_id,+ # System render: keep it out of the user's export listings and quota.+ is_system=True,+ expires_after=datetime.now(UTC) + _INSIGHT_CHART_ASSET_TTL,+ )+ if content is None:+ logger.info(+ "anomaly_investigation.insight_chart_render_failed",+ alert_id=str(alert.id),+ asset_id=asset.id,+ exception=asset.exception,+ )+ return None+ return exports.get_delivery_image_url(+ team_id=alert.team_id, asset_id=asset.id, expiry_delta=_INSIGHT_CHART_URL_TTL+ )+ except Exception:+ logger.exception("anomaly_investigation.insight_chart_render_failed", alert_id=str(alert.id))+ return None++def _dispatch_gated_notification(*,alert,@@ -370,6 +454,7 @@ def _dispatch_gated_notification(verdict: str | None,summary: str,notebook_short_id: str | None,+ insight_chart_url: str | None = None,) -> None:"""Decide whether to fire the notification now that we have the verdict.@@ -381,8 +466,7 @@ def _dispatch_gated_notification(Idempotent: if another codepath (retry, safety-net task) already dispatched,this is a no-op."""- inconclusive_action = alert.investigation_inconclusive_action or "notify"- suppress = verdict == "false_positive" or (verdict == "inconclusive" and inconclusive_action == "suppress")+ suppress = _should_suppress_notification(verdict, alert.investigation_inconclusive_action)with transaction.atomic():# Re-fetch under a row lock so concurrent dispatchers can't double-notify.@@ -404,16 +488,17 @@ def _dispatch_gated_notification(breaches = _build_breach_descriptions(alert_check=check, verdict=verdict, summary=summary, notebook_short_id=notebook_short_id)- # Surface the notebook URL as an event property so the Slack destination can render a- # "View Investigation" button. Absent when the investigation produced no notebook, in- # which case the button falls back to "View Alert".- extra_properties = (- {"investigation_notebook_url": absolute_uri(f"/notebooks/{notebook_short_id}")}- if notebook_short_id- else None- )+ # Event properties beyond the breach text, for HogFunction destinations. The notebook+ # URL backs the Slack "View Investigation" button (falls back to "View Alert" when+ # absent), and the chart URL renders as an image block of the alerted insight (the+ # block falls back to a divider when absent).+ extra_properties: dict[str, str] = {}+ if notebook_short_id:+ extra_properties["investigation_notebook_url"] = absolute_uri(f"/notebooks/{notebook_short_id}")+ if insight_chart_url:+ extra_properties["insight_chart_url"] = insight_chart_urltry:- deliveries = dispatch_alert_notification(alert, check, breaches, extra_properties=extra_properties)+ deliveries = dispatch_alert_notification(alert, check, breaches, extra_properties=extra_properties or None)record_alert_delivery(alert, check, deliveries, stamp_on_empty=True)except Exception:logger.exception(diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.pyindex b6f334646921..3766ca59c632 100644--- a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py@@ -21,6 +21,8 @@ from products.alerts.backend.models.alert import (InvestigationStatus,InvestigationVerdict,)+from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.exports.backend.models.exported_asset import ExportedAssetfrom products.product_analytics.backend.facade.models import Insight@@ -29,6 +31,19 @@ class TestInvestigationVerdictPersistence(NonAtomicBaseTest):# force per-test setup so self.team is freshly inserted each time.CLASS_DATA_LEVEL_SETUP = False+ def _create_slack_destination(self) -> HogFunction:+ return HogFunction.objects.create(+ team=self.team,+ name="Slack #alerts",+ type="internal_destination",+ template_id="template-slack",+ enabled=True,+ filters={+ "events": [{"id": "$insight_alert_firing", "type": "events"}],+ "properties": [{"key": "alert_id", "value": str(self.alert.id), "operator": "exact", "type": "event"}],+ },+ )+def setUp(self) -> None:super().setUp()self.insight = Insight.objects.create(team=self.team, name="test insight")@@ -48,10 +63,11 @@ class TestInvestigationVerdictPersistence(NonAtomicBaseTest):)@pytest.mark.asyncio+ @patch("posthog.temporal.ai.anomaly_investigation.workflow._prepare_insight_chart_url", return_value=None)@patch("posthog.temporal.ai.anomaly_investigation.workflow.run_investigation")@patch("temporalio.activity.heartbeat")@patch("temporalio.activity.info")- async def test_true_positive_verdict_is_persisted(self, mock_info, _heartbeat, mock_run) -> None:+ async def test_true_positive_verdict_is_persisted(self, mock_info, _heartbeat, mock_run, _prepare) -> None:mock_info.return_value.heartbeat_timeout = Nonemock_run.return_value = InvestigationRunResult(report=InvestigationReport(@@ -80,10 +96,12 @@ class TestInvestigationVerdictPersistence(NonAtomicBaseTest):assert self.alert_check.investigation_notebook_id is not None@pytest.mark.asyncio+ @patch("posthog.temporal.ai.anomaly_investigation.workflow.exports.render_png_export")@patch("posthog.temporal.ai.anomaly_investigation.workflow.run_investigation")@patch("temporalio.activity.heartbeat")@patch("temporalio.activity.info")- async def test_false_positive_verdict_is_persisted(self, mock_info, _heartbeat, mock_run) -> None:+ async def test_false_positive_verdict_is_persisted(self, mock_info, _heartbeat, mock_run, mock_render) -> None:+ await sync_to_async(self._create_slack_destination)()mock_info.return_value.heartbeat_timeout = Nonemock_run.return_value = InvestigationRunResult(report=InvestigationReport(@@ -107,13 +125,18 @@ class TestInvestigationVerdictPersistence(NonAtomicBaseTest):await sync_to_async(self.alert_check.refresh_from_db)()assert self.alert_check.investigation_verdict == InvestigationVerdict.FALSE_POSITIVE+ # A suppressed notification must not pay for a chart render.+ mock_render.assert_not_called()@pytest.mark.asyncio+ @patch("posthog.temporal.ai.anomaly_investigation.workflow._prepare_insight_chart_url", return_value=None)@patch("posthog.temporal.ai.anomaly_investigation.workflow.signals.emit_signal")@patch("posthog.temporal.ai.anomaly_investigation.workflow.run_investigation")@patch("temporalio.activity.heartbeat")@patch("temporalio.activity.info")- async def test_completed_investigation_emits_signal(self, mock_info, _heartbeat, mock_run, mock_emit) -> None:+ async def test_completed_investigation_emits_signal(+ self, mock_info, _heartbeat, mock_run, mock_emit, _prepare+ ) -> None:mock_info.return_value.heartbeat_timeout = Nonemock_run.return_value = InvestigationRunResult(report=InvestigationReport(@@ -144,3 +167,47 @@ class TestInvestigationVerdictPersistence(NonAtomicBaseTest):assert kwargs["extra"]["verdict"] == "true_positive"assert kwargs["extra"]["insight_id"] == str(self.insight.id)assert not {"summary", "hypotheses", "recommendations", "tool_calls_used"} & kwargs["extra"].keys()++ @pytest.mark.asyncio+ @patch("posthog.temporal.ai.anomaly_investigation.workflow.dispatch_alert_notification", return_value=[])+ @patch("posthog.temporal.ai.anomaly_investigation.workflow.exports.render_png_export")+ @patch("posthog.temporal.ai.anomaly_investigation.workflow.run_investigation")+ @patch("temporalio.activity.heartbeat")+ @patch("temporalio.activity.info")+ async def test_notification_carries_insight_chart_url(+ self, mock_info, _heartbeat, mock_run, mock_render, mock_dispatch+ ) -> None:+ mock_info.return_value.heartbeat_timeout = None+ mock_run.return_value = InvestigationRunResult(+ report=InvestigationReport(+ verdict="true_positive",+ summary="Confirmed spike caused by campaign launch.",+ hypotheses=[],+ recommendations=[],+ ),+ tool_calls_used=0,+ model="test-model",+ )+ await sync_to_async(self._create_slack_destination)()+ asset = await sync_to_async(ExportedAsset.objects.create)(+ team=self.team,+ insight=self.insight,+ export_format=ExportedAsset.ExportFormat.PNG,+ content=b"png-bytes",+ )+ mock_render.return_value = (asset, b"png-bytes")++ await investigate_anomaly_activity(+ AnomalyInvestigationWorkflowInputs(+ team_id=self.team.id,+ alert_id=self.alert.id,+ alert_check_id=self.alert_check.id,+ user_id=self.user.id,+ )+ )++ assert mock_render.call_args.kwargs["insight_id"] == self.insight.id+ assert mock_render.call_args.kwargs["is_system"] is True+ extra_properties = mock_dispatch.call_args.kwargs["extra_properties"]+ assert "/exporter/" in extra_properties["insight_chart_url"]+ assert "token=" in extra_properties["insight_chart_url"]diff --git a/products/cdp/mcp/cdp_functions.yaml b/products/cdp/mcp/cdp_functions.yamlindex 696e6567a341..953fd0138b2a 100644--- a/products/cdp/mcp/cdp_functions.yaml+++ b/products/cdp/mcp/cdp_functions.yaml@@ -62,7 +62,7 @@ tools:{"type": "section", "text": {"type": "plain_text", "text": "{event.properties.breaches}"}},{"type": "context", "elements": [{"type": "mrkdwn","text": "Project: <{project.url}|{project.name}>"}]},- {"type": "divider"},+ "{event.properties.insight_chart_url ? {'type': 'image', 'image_url': event.properties.insight_chart_url, 'alt_text': 'Insight chart'} : {'type': 'divider'}}",{"type": "actions", "block_id": "insight_alert_snooze:{event.properties.alert_id}", "elements": [{"type": "button", "text": {"type": "plain_text", "text": "View Insight"},"url": "{project.url}/insights/{event.properties.insight_id}"},@@ -96,7 +96,10 @@ tools:insight_id (short_id), state (always "Firing" — the event is only emitted on a firing transition,not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g."Series A is below 1000"), and detector metadata: alert_mode (always present), detector_type and- ensemble_operator (null for threshold alerts, set for anomaly detection). Project context is+ ensemble_operator (null for threshold alerts, set for anomaly detection). Dispatches gated on the+ anomaly investigation agent may also carry investigation_notebook_url and insight_chart_url+ (a tokenized image URL the Slack blocks above render as a chart); both are absent otherwise, so+ templates must fall back, as the conditional block above does. Project context isavailable as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Donot reference value, threshold_lower, or insight_url — those are not emitted.diff --git a/products/exports/backend/facade/api.py b/products/exports/backend/facade/api.pyindex b14b6b29bbf3..dbdc22d8cb96 100644--- a/products/exports/backend/facade/api.py+++ b/products/exports/backend/facade/api.py@@ -1,7 +1,7 @@"""Public Python interface for creating and retrieving one-off exports."""from collections.abc import Collection-from datetime import timedelta+from datetime import datetime, timedeltafrom django.conf import settingsfrom django.http.response import HttpResponseBase@@ -184,11 +184,18 @@ def render_png_export(created_by: User,export_context: dict | None = None,insight_id: int | None = None,+ is_system: bool = False,+ expires_after: datetime | None = None,) -> tuple[ExportedAsset, bytes | None]:"""Render a PNG export synchronously and return the asset together with its content bytes.Blocks until the export workflow finishes (typically a few seconds). On failure thereturned bytes are None and ``asset.exception`` carries the error.++ ``is_system`` marks the asset as created by an internal process, which excludes it from+ the user's export listings and the per-team export quota. ``expires_after`` overrides+ the format's default TTL; pass it when the render backs a short-lived delivery URL so+ the stored bytes do not outlive their only consumer by months."""if created_by is None:# Access control below resolves against created_by; a principal-less render would@@ -214,6 +221,9 @@ def render_png_export(export_format=ExportedAsset.ExportFormat.PNG,export_context=export_context,insight_id=insight_id,+ is_system=is_system,+ # None keeps the model's format-default TTL (see ExportedAsset.save).+ expires_after=expires_after,)async def _run() -> None:diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 22dd740c07b8..92516103ec81 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1324,7 +1324,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. 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.",+ "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 \"{event.properties.insight_chart_url ? {'type': 'image', 'image_url': event.properties.insight_chart_url, 'alt_text': 'Insight chart'} : {'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). Dispatches gated on the\n anomaly investigation agent may also carry investigation_notebook_url and insight_chart_url\n (a tokenized image URL the Slack blocks above render as a chart); both are absent otherwise, so\n templates must fall back, as the conditional block above does. 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",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex abc8c6526825..b80b56c88366 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1339,7 +1339,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. 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.",+ "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 \"{event.properties.insight_chart_url ? {'type': 'image', 'image_url': event.properties.insight_chart_url, 'alt_text': 'Insight chart'} : {'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). Dispatches gated on the\n anomaly investigation agent may also carry investigation_notebook_url and insight_chart_url\n (a tokenized image URL the Slack blocks above render as a chart); both are absent otherwise, so\n templates must fall back, as the conditional block above does. 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",