Skip to content

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

feat(error_tracking): add native alert CRUD API behind feature flag (#90534)

Catalin329213721362
diff --git a/products/error_tracking/backend/facade/alerts.py b/products/error_tracking/backend/facade/alerts.py
new file mode 100644
index 000000000000..47a544e53fa3
--- /dev/null
+++ b/products/error_tracking/backend/facade/alerts.py
@@ -0,0 +1,106 @@
+"""Facade for error tracking native alert configurations."""
+
+from typing import Any, Optional
+from uuid import UUID
+
+from posthog.models.user import User
+
+from ..logic import alerts as _alerts
+from ..models import (
+ ErrorTrackingAlert as ErrorTrackingAlertModel,
+ ErrorTrackingAlertDestination as ErrorTrackingAlertDestinationModel,
+)
+from . import contracts
+
+AlertValidationError = _alerts.AlertValidationError
+
+NATIVE_ALERTS_FLAG = _alerts.NATIVE_ALERTS_FLAG
+native_alerts_enabled = _alerts.native_alerts_enabled
+
+# Presentation code reads choice values from here so it never imports Django models.
+ALERT_TRIGGERS: tuple[str, ...] = tuple(ErrorTrackingAlertModel.Trigger.values)
+ALERT_CHANNEL_TYPES: tuple[str, ...] = tuple(ErrorTrackingAlertDestinationModel.ChannelType.values)
+
+
+def _to_alert(alert: ErrorTrackingAlertModel) -> contracts.ErrorTrackingAlert:
+ return contracts.ErrorTrackingAlert(
+ id=alert.id,
+ name=alert.name,
+ enabled=alert.enabled,
+ triggers=list(alert.triggers),
+ filters=dict(alert.filters),
+ throttle_seconds=alert.throttle_seconds,
+ destinations=[
+ contracts.ErrorTrackingAlertDestination(
+ id=destination.id,
+ channel_type=destination.channel_type,
+ integration_id=destination.integration_id,
+ config=dict(destination.config),
+ created_at=destination.created_at,
+ updated_at=destination.updated_at,
+ )
+ for destination in alert.destinations.all()
+ ],
+ created_at=alert.created_at,
+ updated_at=alert.updated_at,
+ )
+
+
+def list_alerts(team_id: int) -> list[contracts.ErrorTrackingAlert]:
+ return [_to_alert(alert) for alert in _alerts.list_alerts(team_id)]
+
+
+def get_alert(team_id: int, alert_id: UUID | str) -> Optional[contracts.ErrorTrackingAlert]:
+ alert = _alerts.get_alert(team_id, alert_id)
+ return _to_alert(alert) if alert is not None else None
+
+
+def create_alert(
+ team_id: int,
+ *,
+ name: str,
+ triggers: list[str],
+ filters: dict[str, Any],
+ throttle_seconds: int,
+ destinations: list[dict[str, Any]],
+ created_by: Optional[User],
+) -> contracts.ErrorTrackingAlert:
+ return _to_alert(
+ _alerts.create_alert(
+ team_id,
+ name=name,
+ triggers=triggers,
+ filters=filters,
+ throttle_seconds=throttle_seconds,
+ destinations=destinations,
+ created_by=created_by,
+ )
+ )
+
+
+def update_alert(
+ team_id: int,
+ alert_id: UUID | str,
+ *,
+ name: Optional[str] = None,
+ enabled: Optional[bool] = None,
+ triggers: Optional[list[str]] = None,
+ filters: Optional[dict[str, Any]] = None,
+ throttle_seconds: Optional[int] = None,
+ destinations: Optional[list[dict[str, Any]]] = None,
+) -> Optional[contracts.ErrorTrackingAlert]:
+ alert = _alerts.update_alert(
+ team_id,
+ alert_id,
+ name=name,
+ enabled=enabled,
+ triggers=triggers,
+ filters=filters,
+ throttle_seconds=throttle_seconds,
+ destinations=destinations,
+ )
+ return _to_alert(alert) if alert is not None else None
+
+
+def delete_alert(team_id: int, alert_id: UUID | str) -> bool:
+ return _alerts.delete_alert(team_id, alert_id)
diff --git a/products/error_tracking/backend/facade/contracts.py b/products/error_tracking/backend/facade/contracts.py
index 5db9cb856c5b..f59560544e87 100644
--- a/products/error_tracking/backend/facade/contracts.py
+++ b/products/error_tracking/backend/facade/contracts.py
@@ -274,3 +274,26 @@ class ErrorTrackingRecommendation:
dismissed_at: datetime | None
created_at: datetime
updated_at: datetime
+
+
+@dataclass(frozen=True)
+class ErrorTrackingAlertDestination:
+ id: UUID
+ channel_type: str
+ integration_id: int | None
+ config: dict
+ created_at: datetime
+ updated_at: datetime
+
+
+@dataclass(frozen=True)
+class ErrorTrackingAlert:
+ id: UUID
+ name: str
+ enabled: bool
+ triggers: list[str]
+ filters: dict
+ throttle_seconds: int
+ destinations: list[ErrorTrackingAlertDestination]
+ created_at: datetime
+ updated_at: datetime
diff --git a/products/error_tracking/backend/logic/alerts.py b/products/error_tracking/backend/logic/alerts.py
new file mode 100644
index 000000000000..51208723b8e3
--- /dev/null
+++ b/products/error_tracking/backend/logic/alerts.py
@@ -0,0 +1,220 @@
+"""CRUD and validation for error tracking alert configurations."""
+
+from typing import Any, Optional
+from uuid import UUID
+
+from django.db import transaction
+from django.db.models import QuerySet
+
+import structlog
+
+from posthog.cdp.filters import compile_filters_bytecode
+from posthog.models.integration import Integration
+from posthog.models.scoping.manager import resolve_effective_team_id
+from posthog.models.team.team import Team
+from posthog.models.user import User
+from posthog.ph_client import feature_enabled_or_false
+
+from products.error_tracking.backend.models import ErrorTrackingAlert, ErrorTrackingAlertDestination
+
+logger = structlog.get_logger(__name__)
+
+NATIVE_ALERTS_FLAG = "error-tracking-native-alerts"
+
+
+def native_alerts_enabled(team_id: int) -> bool:
+ try:
+ # Alert rows are canonical-project-scoped, so the flag must bucket child
+ # environments with their parent or per-environment ids would gate
+ # differently than the rows they read.
+ team_id = resolve_effective_team_id(team_id)
+ return feature_enabled_or_false(
+ NATIVE_ALERTS_FLAG,
+ str(team_id),
+ groups={"project": str(team_id)},
+ group_properties={"project": {"id": str(team_id)}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ except Exception:
+ # An unreleased feature stays off when the flags service is unreachable,
+ # rather than defaulting on or failing the caller.
+ logger.exception("error_tracking_native_alerts_flag_check_failed", team_id=team_id)
+ return False
+
+
+class AlertValidationError(Exception):
+ pass
+
+
+def list_alerts(team_id: int) -> QuerySet[ErrorTrackingAlert]:
+ return ErrorTrackingAlert.objects.for_team(team_id).prefetch_related("destinations").order_by("-created_at")
+
+
+def _parse_alert_id(alert_id: UUID | str) -> Optional[UUID]:
+ if isinstance(alert_id, UUID):
+ return alert_id
+ try:
+ return UUID(str(alert_id))
+ except ValueError:
+ return None
+
+
+def get_alert(team_id: int, alert_id: UUID | str) -> Optional[ErrorTrackingAlert]:
+ parsed_id = _parse_alert_id(alert_id)
+ if parsed_id is None:
+ return None
+ return ErrorTrackingAlert.objects.for_team(team_id).prefetch_related("destinations").filter(id=parsed_id).first()
+
+
+def create_alert(
+ team_id: int,
+ *,
+ name: str,
+ triggers: list[str],
+ filters: dict[str, Any],
+ throttle_seconds: int,
+ destinations: list[dict[str, Any]],
+ created_by: Optional[User],
+) -> ErrorTrackingAlert:
+ # Canonicalize up front so validation, the stored row, and the scoped read
+ # paths (for_team) all agree on the same team id for child environments.
+ team_id = resolve_effective_team_id(team_id)
+ compiled_filters = _compile_filters(team_id, filters)
+ _reject_duplicate_destinations(destinations)
+ for destination in destinations:
+ _validate_destination(team_id, destination)
+
+ with transaction.atomic():
+ alert = ErrorTrackingAlert.objects.for_team(team_id, canonical=True).create(
+ team_id=team_id,
+ name=name,
+ triggers=triggers,
+ filters=compiled_filters,
+ throttle_seconds=throttle_seconds,
+ created_by=created_by,
+ )
+ for destination in destinations:
+ ErrorTrackingAlertDestination.objects.for_team(team_id, canonical=True).create(
+ team_id=team_id,
+ alert=alert,
+ channel_type=destination["channel_type"],
+ integration_id=destination["integration_id"],
+ config=destination["config"],
+ )
+ # Refetch with destinations prefetched so the caller serializes one consistent shape.
+ return ErrorTrackingAlert.objects.for_team(team_id).prefetch_related("destinations").get(id=alert.id)
+
+
+def update_alert(
+ team_id: int,
+ alert_id: UUID | str,
+ *,
+ name: Optional[str] = None,
+ enabled: Optional[bool] = None,
+ triggers: Optional[list[str]] = None,
+ filters: Optional[dict[str, Any]] = None,
+ throttle_seconds: Optional[int] = None,
+ destinations: Optional[list[dict[str, Any]]] = None,
+) -> Optional[ErrorTrackingAlert]:
+ parsed_id = _parse_alert_id(alert_id)
+ if parsed_id is None:
+ return None
+
+ updates = (name, enabled, triggers, filters, throttle_seconds, destinations)
+ if all(value is None for value in updates):
+ # Nothing to change; skip the write so updated_at stays untouched.
+ return get_alert(team_id, parsed_id)
+
+ if destinations is not None:
+ _reject_duplicate_destinations(destinations)
+
+ with transaction.atomic():
+ # Lock the row so concurrent partial updates cannot overwrite each other's fields.
+ alert = ErrorTrackingAlert.objects.for_team(team_id).select_for_update().filter(id=parsed_id).first()
+ if alert is None:
+ return None
+ if name is not None:
+ alert.name = name
+ if enabled is not None:
+ alert.enabled = enabled
+ if triggers is not None:
+ alert.triggers = triggers
+ if filters is not None:
+ # Validate against the stored (canonical) team id, not the raw caller id.
+ alert.filters = _compile_filters(alert.team_id, filters)
+ if throttle_seconds is not None:
+ alert.throttle_seconds = throttle_seconds
+ if destinations is not None:
+ for destination in destinations:
+ _validate_destination(alert.team_id, destination)
+
+ alert.save()
+ if destinations is not None:
+ # Destinations are replaced wholesale: threads cascade with removed rows,
+ # so a repointed channel starts a fresh conversation (per the alerting RFC).
+ alert.destinations.all().delete()
+ for destination in destinations:
+ ErrorTrackingAlertDestination.objects.for_team(alert.team_id, canonical=True).create(
+ team_id=alert.team_id,
+ alert=alert,
+ channel_type=destination["channel_type"],
+ integration_id=destination["integration_id"],
+ config=destination["config"],
+ )
+ return get_alert(team_id, alert.id)
+
+
+def delete_alert(team_id: int, alert_id: UUID | str) -> bool:
+ parsed_id = _parse_alert_id(alert_id)
+ if parsed_id is None:
+ return False
+ deleted, _ = ErrorTrackingAlert.objects.for_team(team_id).filter(id=parsed_id).delete()
+ return deleted > 0
+
+
+def _compile_filters(team_id: int, filters: dict[str, Any]) -> dict[str, Any]:
+ if not isinstance(filters, dict):
+ raise AlertValidationError("Alert filters must be an object.")
+ team = Team.objects.get(id=team_id)
+ compiled = compile_filters_bytecode(dict(filters), team)
+ if compiled.get("bytecode_error"):
+ raise AlertValidationError(f"Invalid filter configuration: {compiled['bytecode_error']}")
+ return compiled
+
+
+def _reject_duplicate_destinations(destinations: list[dict[str, Any]]) -> None:
+ # Delivery fans out one notification per destination row, so two destinations
+ # pointing at the same channel would double-post every notification. The
+ # identity ignores display-only config keys such as channel_name on purpose.
+ seen = set()
+ for destination in destinations:
+ config = destination.get("config")
+ channel = config.get("channel") if isinstance(config, dict) else None
+ key = (destination.get("channel_type"), destination.get("integration_id"), channel)
+ if key in seen:
+ raise AlertValidationError("Duplicate destinations are not allowed.")
+ seen.add(key)
+
+
+def _validate_destination(team_id: int, destination: dict[str, Any]) -> None:
+ channel_type = destination.get("channel_type")
+ integration_id = destination.get("integration_id")
+ config = destination.get("config")
+ if not isinstance(config, dict):
+ raise AlertValidationError("Destination config must be an object.")
+ if channel_type == ErrorTrackingAlertDestination.ChannelType.SLACK:
+ if integration_id is None:
+ raise AlertValidationError("Slack destinations require an integration.")
+ # Integrations are stored on environment teams while alert rows live on the
+ # canonical team, so accept any integration in the same project.
+ project_id = Team.objects.values_list("project_id", flat=True).get(id=team_id)
+ if not Integration.objects.filter(
+ team__project_id=project_id, id=integration_id, kind=Integration.IntegrationKind.SLACK
+ ).exists():
+ raise AlertValidationError("Slack integration not found for this project.")
+ channel = config.get("channel")
+ if not isinstance(channel, str) or not channel:
+ raise AlertValidationError("Slack destinations require a channel id string in the config.")
+ else:
+ raise AlertValidationError(f"Unsupported destination channel type: {channel_type}")
diff --git a/products/error_tracking/backend/presentation/views/__init__.py b/products/error_tracking/backend/presentation/views/__init__.py
index 67979c332808..ed350eec402b 100644
--- a/products/error_tracking/backend/presentation/views/__init__.py
+++ b/products/error_tracking/backend/presentation/views/__init__.py
@@ -1,3 +1,4 @@
+from products.error_tracking.backend.presentation.views.alerts import ErrorTrackingAlertViewSet
from products.error_tracking.backend.presentation.views.assignment_rules import ErrorTrackingAssignmentRuleViewSet
from products.error_tracking.backend.presentation.views.bypass_rules import ErrorTrackingBypassRuleViewSet
from products.error_tracking.backend.presentation.views.external_references import ErrorTrackingExternalReferenceViewSet
@@ -21,6 +22,7 @@ from products.error_tracking.backend.presentation.views.suppression_rules import
from products.error_tracking.backend.presentation.views.symbol_sets import ErrorTrackingSymbolSetViewSet
__all__ = [
+ "ErrorTrackingAlertViewSet",
"ErrorTrackingExternalReferenceViewSet",
"ErrorTrackingIssueViewSet",
"ErrorTrackingQueryViewSet",
diff --git a/products/error_tracking/backend/presentation/views/alerts.py b/products/error_tracking/backend/presentation/views/alerts.py
new file mode 100644
index 000000000000..bbf983f75c05
--- /dev/null
+++ b/products/error_tracking/backend/presentation/views/alerts.py
@@ -0,0 +1,242 @@
+from typing import Any
+
+from drf_spectacular.utils import OpenApiResponse
+from rest_framework import serializers, status, viewsets
+from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models.user import User
+
+from products.error_tracking.backend.facade import alerts as alerts_facade
+
+# PostgreSQL integer column bound; larger values would 500 on save.
+MAX_THROTTLE_SECONDS = 2**31 - 1
+
+
+class _StrictCharField(serializers.CharField):
+ # CharField coerces numbers to strings; delivery identifiers must arrive as strings.
+ def to_internal_value(self, data: Any) -> str:
+ if not isinstance(data, str):
+ self.fail("invalid")
+ return super().to_internal_value(data)
+
+
+class ErrorTrackingAlertSlackConfigSerializer(serializers.Serializer):
+ channel = _StrictCharField(help_text="Slack channel ID notifications are delivered to.")
+ channel_name = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Human-readable Slack channel name, stored for display only.",
+ )
+
+
+class ErrorTrackingAlertFiltersSerializer(serializers.Serializer):
+ # Subset of the hog function filter shape that alert filters support.
+ events = serializers.ListField(
+ child=serializers.DictField(), required=False, help_text="Event filters a transition must match."
+ )
+ actions = serializers.ListField(
+ child=serializers.DictField(), required=False, help_text="Action filters a transition must match."
+ )
+ properties = serializers.ListField(
+ child=serializers.DictField(), required=False, help_text="Property filters a transition must match."
+ )
+ filter_test_accounts = serializers.BooleanField(
+ required=False, help_text="Whether to exclude internal and test accounts."
+ )
+ bytecode = serializers.JSONField(
+ read_only=True, allow_null=True, help_text="Compiled filter bytecode. Generated by the server on save."
+ )
+
+
+class ErrorTrackingAlertDestinationRequestSerializer(serializers.Serializer):
+ # Request-side twin of ErrorTrackingAlertDestinationSerializer without the
+ # server-generated id, so generated clients don't require one on create.
+ channel_type = serializers.ChoiceField(
+ choices=list(alerts_facade.ALERT_CHANNEL_TYPES),
+ help_text="Delivery channel for notifications.",
+ )
+ integration_id = serializers.IntegerField(
+ allow_null=True,
+ required=False,
+ default=None,
+ help_text="ID of the workspace integration used to deliver notifications (required for Slack).",
+ )
+ config = ErrorTrackingAlertSlackConfigSerializer(
+ help_text='Channel-specific delivery settings, e.g. {"channel": "C0123"} for Slack.'
+ )
+
+
+class ErrorTrackingAlertDestinationSerializer(ErrorTrackingAlertDestinationRequestSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique identifier of the destination.")
+
+
+class ErrorTrackingAlertSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique identifier of the alert.")
+ name = serializers.CharField(help_text="Human-readable name of the alert.")
+ enabled = serializers.BooleanField(help_text="Whether the alert currently fires notifications.")
+ triggers = serializers.ListField(
+ child=serializers.ChoiceField(choices=list(alerts_facade.ALERT_TRIGGERS)),
+ help_text="Issue lifecycle events that open a notification thread for an issue.",
+ )
+ filters = ErrorTrackingAlertFiltersSerializer(
+ help_text="Property filters a transition must match to open a notification thread. "
+ "Same shape as hog function filters, including the compiled bytecode."
+ )
+ throttle_seconds = serializers.IntegerField(
+ help_text="Minimum seconds between thread-opening notifications per issue. 0 disables the throttle."
+ )
+ destinations = ErrorTrackingAlertDestinationSerializer(
+ many=True, help_text="Delivery targets notifications fan out to."
+ )
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the alert was created.")
+ updated_at = serializers.DateTimeField(read_only=True, help_text="When the alert was last updated.")
+
+
+class ErrorTrackingAlertCreateRequestSerializer(serializers.Serializer):
+ name = serializers.CharField(max_length=400, help_text="Human-readable name of the alert.")
+ triggers = serializers.ListField(
+ child=serializers.ChoiceField(choices=list(alerts_facade.ALERT_TRIGGERS)),
+ allow_empty=False,
+ help_text="Issue lifecycle events that open a notification thread for an issue.",
+ )
+ filters = ErrorTrackingAlertFiltersSerializer(
+ required=False,
+ default=dict,
+ help_text="Property filters a transition must match to open a notification thread. "
+ "Same shape as hog function filters; the bytecode is compiled on save.",
+ )
+ throttle_seconds = serializers.IntegerField(
+ required=False,
+ default=0,
+ min_value=0,
+ max_value=MAX_THROTTLE_SECONDS,
+ help_text="Minimum seconds between thread-opening notifications per issue. 0 disables the throttle.",
+ )
+ destinations = ErrorTrackingAlertDestinationRequestSerializer(
+ many=True,
+ allow_empty=False,
+ help_text="Delivery targets notifications fan out to.",
+ )
+
+
+class ErrorTrackingAlertUpdateRequestSerializer(serializers.Serializer):
+ name = serializers.CharField(
+ required=False, max_length=400, help_text="Human-readable name of the alert. Omit to keep the current name."
+ )
+ enabled = serializers.BooleanField(
+ required=False, help_text="Whether the alert fires notifications. Omit to keep the current state."
+ )
+ triggers = serializers.ListField(
+ child=serializers.ChoiceField(choices=list(alerts_facade.ALERT_TRIGGERS)),
+ required=False,
+ allow_empty=False,
+ help_text="Issue lifecycle events that open a notification thread. Omit to keep the current triggers.",
+ )
+ filters = ErrorTrackingAlertFiltersSerializer(
+ required=False,
+ help_text="Property filters a transition must match to open a notification thread. "
+ "Omit to keep the current filters.",
+ )
+ throttle_seconds = serializers.IntegerField(
+ required=False,
+ min_value=0,
+ max_value=MAX_THROTTLE_SECONDS,
+ help_text="Minimum seconds between thread-opening notifications per issue. Omit to keep the current value.",
+ )
+ destinations = ErrorTrackingAlertDestinationRequestSerializer(
+ many=True,
+ required=False,
+ allow_empty=False,
+ help_text="Delivery targets notifications fan out to. When provided, replaces all current destinations.",
+ )
+
+
+class ErrorTrackingAlertPutRequestSerializer(ErrorTrackingAlertCreateRequestSerializer):
+ # PUT replaces the whole alert: omitted optional fields reset to their declared
+ # defaults instead of keeping the current values (unlike PATCH).
+ enabled = serializers.BooleanField(
+ required=False, default=True, help_text="Whether the alert fires notifications. Defaults to enabled."
+ )
+
+
+class ErrorTrackingAlertViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "error_tracking"
+ serializer_class = ErrorTrackingAlertSerializer
+
+ def initial(self, request: Request, *args, **kwargs) -> None:
+ super().initial(request, *args, **kwargs)
+ if not alerts_facade.native_alerts_enabled(self.team.id):
+ raise PermissionDenied("This feature is not available.")
+
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ alerts = alerts_facade.list_alerts(self.team.id)
+ page = self.paginate_queryset(alerts)
+ if page is not None:
+ return self.get_paginated_response(self.get_serializer(page, many=True).data)
+ return Response(self.get_serializer(alerts, many=True).data)
+
+ def retrieve(self, request: Request, *args, pk=None, **kwargs) -> Response:
+ alert = alerts_facade.get_alert(self.team.id, pk)
+ if alert is None:
+ raise NotFound()
+ return Response(self.get_serializer(alert).data)
+
+ @validated_request(
+ request_serializer=ErrorTrackingAlertCreateRequestSerializer,
+ responses={201: OpenApiResponse(response=ErrorTrackingAlertSerializer)},
+ )
+ def create(self, request: ValidatedRequest, *args, **kwargs) -> Response:
+ try:
+ alert = alerts_facade.create_alert(
+ self.team.id,
+ name=request.validated_data["name"],
+ triggers=request.validated_data["triggers"],
+ filters=request.validated_data["filters"],
+ throttle_seconds=request.validated_data["throttle_seconds"],
+ destinations=request.validated_data["destinations"],
+ created_by=request.user if isinstance(request.user, User) else None,
+ )
+ except alerts_facade.AlertValidationError as err:
+ raise ValidationError(str(err)) from err
+ return Response(self.get_serializer(alert).data, status=status.HTTP_201_CREATED)
+
+ def _apply_alert_update(self, request: ValidatedRequest, pk: str) -> Response:
+ try:
+ alert = alerts_facade.update_alert(
+ self.team.id,
+ pk,
+ name=request.validated_data.get("name"),
+ enabled=request.validated_data.get("enabled"),
+ triggers=request.validated_data.get("triggers"),
+ filters=request.validated_data.get("filters"),
+ throttle_seconds=request.validated_data.get("throttle_seconds"),
+ destinations=request.validated_data.get("destinations"),
+ )
+ except alerts_facade.AlertValidationError as err:
+ raise ValidationError(str(err)) from err
+ if alert is None:
+ raise NotFound()
+ return Response(self.get_serializer(alert).data)
+
+ @validated_request(
+ request_serializer=ErrorTrackingAlertPutRequestSerializer,
+ responses={200: OpenApiResponse(response=ErrorTrackingAlertSerializer)},
+ )
+ def update(self, request: ValidatedRequest, *args, pk=None, **kwargs) -> Response:
+ return self._apply_alert_update(request, pk)
+
+ @validated_request(
+ request_serializer=ErrorTrackingAlertUpdateRequestSerializer,
+ responses={200: OpenApiResponse(response=ErrorTrackingAlertSerializer)},
+ )
+ def partial_update(self, request: ValidatedRequest, *args, pk=None, **kwargs) -> Response:
+ return self._apply_alert_update(request, pk)
+
+ def destroy(self, request: Request, *args, pk=None, **kwargs) -> Response:
+ if not alerts_facade.delete_alert(self.team.id, pk):
+ raise NotFound()
+ return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/products/error_tracking/backend/routes.py b/products/error_tracking/backend/routes.py
index 4244b3cb1e2c..a1383e6c6b33 100644
--- a/products/error_tracking/backend/routes.py
+++ b/products/error_tracking/backend/routes.py
@@ -1,6 +1,7 @@
from posthog.api.routing import RouterRegistry
from products.error_tracking.backend.presentation.views import (
+ ErrorTrackingAlertViewSet,
ErrorTrackingAssignmentRuleViewSet,
ErrorTrackingBypassRuleViewSet,
ErrorTrackingExternalReferenceViewSet,
@@ -112,3 +113,9 @@ def register_routes(routers: RouterRegistry) -> None:
"project_error_tracking_git_provider_file_links",
["team_id"],
)
+ routers.projects.register(
+ r"error_tracking/alerts",
+ ErrorTrackingAlertViewSet,
+ "project_error_tracking_alerts",
+ ["team_id"],
+ )
diff --git a/products/error_tracking/backend/tests/api/test_alerts_api.py b/products/error_tracking/backend/tests/api/test_alerts_api.py
new file mode 100644
index 000000000000..243fef209379
--- /dev/null
+++ b/products/error_tracking/backend/tests/api/test_alerts_api.py
@@ -0,0 +1,299 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.models.integration import Integration
+from posthog.models.scoping import team_scope
+from posthog.models.team.team import Team
+
+from products.error_tracking.backend.models import ErrorTrackingAlert, ErrorTrackingAlertDestination
+
+# Sentinel swapped for a real integration id inside the test body; parameterized
+# cases are built before setUp so they cannot reference one directly.
+VALID_INTEGRATION = object()
+
+
+class TestErrorTrackingAlerts(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ flag_patcher = patch("products.error_tracking.backend.logic.alerts.feature_enabled_or_false", return_value=True)
+ flag_patcher.start()
+ self.addCleanup(flag_patcher.stop)
+
+ def _create_slack_integration(self, team=None) -> Integration:
+ return Integration.objects.create(
+ team=team or self.team,
+ kind=Integration.IntegrationKind.SLACK.value,
+ config={"team": {"id": "T123"}},
+ sensitive_config={"access_token": "token"},
+ )
+
+ def _valid_payload(self, integration: Integration, **overrides) -> dict:
+ payload = {
+ "name": "Notify #alerts",
+ "triggers": ["issue_created", "issue_spiking"],
+ "destinations": [
+ {
+ "channel_type": "slack",
+ "integration_id": integration.id,
+ "config": {"channel": "C0123"},
+ }
+ ],
+ }
+ payload.update(overrides)
+ return payload
+
+ def _create_alert(self, integration: Integration, **overrides) -> dict:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/error_tracking/alerts/",
+ data=self._valid_payload(integration, **overrides),
+ format="json",
+ )
+ assert response.status_code == 201, response.json()
+ return response.json()
+
+ def test_alert_crud_roundtrip(self):
+ integration = self._create_slack_integration()
+
+ created = self._create_alert(integration)
+ assert created["name"] == "Notify #alerts"
+ assert created["enabled"] is True
+ assert created["triggers"] == ["issue_created", "issue_spiking"]
+ assert created["throttle_seconds"] == 0
+ assert len(created["destinations"]) == 1
+ destination = created["destinations"][0]
+ assert destination["channel_type"] == "slack"
+ assert destination["integration_id"] == integration.id
+ assert destination["config"] == {"channel": "C0123"}
+
+ alert_id = created["id"]
+ update = self.client.patch(
+ f"/api/projects/{self.team.id}/error_tracking/alerts/{alert_id}/",
+ data={"enabled": False, "triggers": ["issue_reopened"], "throttle_seconds": 600},
+ format="json",
+ )
+ assert update.status_code == 200, update.json()
+ assert update.json()["enabled"] is False
+ assert update.json()["triggers"] == ["issue_reopened"]
+ assert update.json()["throttle_seconds"] == 600
+
+ listing = self.client.get(f"/api/projects/{self.team.id}/error_tracking/alerts/")
+ assert listing.status_code == 200
+ assert [alert["id"] for alert in listing.json()["results"]] == [alert_id]
+
+ delete = self.client.delete(f"/api/projects/{self.team.id}/error_tracking/alerts/{alert_id}/")
+ assert delete.status_code == 204
+ assert self.client.get(f"/api/projects/{self.team.id}/error_tracking/alerts/{alert_id}/").status_code == 404
+ assert ErrorTrackingAlertDestination.objects.for_team(self.team.id).count() == 0
+
+ def test_endpoints_require_feature_flag(self):
+ integration = self._create_slack_integration()
+ with patch("products.error_tracking.backend.logic.alerts.feature_enabled_or_false", return_value=False):
+ listing = self.client.get(f"/api/projects/{self.team.id}/error_tracking/alerts/")
+ assert listing.status_code == 403
+ create = self.client.post(
+ f"/api/projects/{self.team.id}/error_tracking/alerts/",
+ data=self._valid_payload(integration),
+ format="json",
+ )
+ assert create.status_code == 403
+ assert ErrorTrackingAlert.objects.for_team(self.team.id).count() == 0
+
+ def test_alert_create_compiles_filter_bytecode(self):
+ integration = self._create_slack_integration()
+
+ created = self._create_alert(
+ integration,
+ filters={"properties": [{"type": "event", "key": "environment", "value": "production"}]},
+ )
+
+ assert created["filters"]["bytecode"] is not None
+ stored = ErrorTrackingAlert.objects.for_team(self.team.id).get(id=created["id"])
+ assert stored.filters["bytecode"] == created["filters"]["bytecode"]
+
+ def test_alert_update_recompiles_filter_bytecode(self):
+ integration = self._create_slack_integration()
+ created = self._create_alert(integration)
+ assert "properties" not in created["filters"]
+
+ update = self.client.patch(
+ f"/api/projects/{self.team.id}/error_tracking/alerts/{created['id']}/",
+ data={"filters": {"properties": [{"type": "event", "key": "environment", "value": "production"}]}},
+ format="json",
+ )
+
+ assert update.status_code == 200, update.json()
+ assert update.json()["filters"]["bytecode"] is not None
+
+ def test_alert_create_rejects_uncompilable_filters(self):
+ integration = self._create_slack_integration()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/error_tracking/alerts/",
+ data=self._valid_payload(integration, filters={"properties": [{"type": "hogql", "key": "(select 1)"}]}),
+ format="json",
+ )
+
+ assert response.status_code == 400, response.json()
+ assert ErrorTrackingAlert.objects.for_team(self.team.id).count() == 0
+
+ def test_alert_update_replaces_destinations(self):
+ integration = self._create_slack_integration()
+ created = self._create_alert(integration)
+ old_destination_id = created["destinations"][0]["id"]
+
+ update = self.client.patch(
+ f"/api/projects/{self.team.id}/error_tracking/alerts/{created['id']}/",
+ data={
+ "destinations": [
+ {"channel_type": "slack", "integration_id": integration.id, "config": {"channel": "C0456"}}
+ ]
+ },
+ format="json",
+ )
+
+ assert update.status_code == 200, update.json()
+ destinations = update.json()["destinations"]
+ assert len(destinations) == 1
+ assert destinations[0]["config"] == {"channel": "C0456"}
+ assert destinations[0]["id"] != old_destination_id
+ assert ErrorTrackingAlertDestination.objects.for_team(self.team.id).count() == 1
+
+ @parameterized.expand(
+ [
+ ("unknown_trigger", {"triggers": ["issue_deleted"]}),
+ ("empty_triggers", {"triggers": []}),
+ ("empty_destinations", {"destinations": []}),
+ ("negative_throttle", {"throttle_seconds": -1}),
+ (
+ "unknown_channel",
+ {"destinations": [{"channel_type": "carrier_pigeon", "integration_id": 1, "config": {}}]},
+ ),
+ ("missing_integration", {"destinations": [{"channel_type": "slack", "config": {"channel": "C1"}}]}),
+ (
+ "missing_channel_in_config",
+ {"destinations": [{"channel_type": "slack", "integration_id": VALID_INTEGRATION, "config": {}}]},
+ ),
+ (
+ "non_string_channel_in_config",
+ {
+ "destinations": [
+ {"channel_type": "slack", "integration_id": VALID_INTEGRATION, "config": {"channel": 12345}}
+ ]
+ },
+ ),
+ ]
+ )
+ def test_alert_create_rejects_invalid_payload(self, _name, overrides):
+ integration = self._create_slack_integration()
+ payload = self._valid_payload(integration, **overrides)
+ # Config cases need a real integration so its validation cannot mask theirs.
+ for destination in payload.get("destinations", []):
+ if destination.get("integration_id") is VALID_INTEGRATION:
+ destination["integration_id"] = integration.id
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/error_tracking/alerts/",
+ data=payload,
+ format="json",
+ )
+
+ assert response.status_code == 400, response.json()
+ assert ErrorTrackingAlert.objects.for_team(self.team.id).count() == 0
+
+ def test_alert_rejects_duplicate_destinations(self):
+ integration = self._create_slack_integration()
+ destination = {"channel_type": "slack", "integration_id": integration.id, "config": {"channel": "C0123"}}
+
+ # A destination differing only in display-only config keys is still the same target.
+ renamed = {**destination, "config": {"channel": "C0123", "channel_name": "#alerts"}}
+ for duplicates in ([destination, destination], [destination, renamed]):
+ create = self.client.post(
+ f"/api/projects/{self.team.id}/error_tracking/alerts/",
+ data=self._valid_payload(integration, destinations=duplicates),
+ format="json",
+ )
+ assert create.status_code == 400, create.json()
+ assert "Duplicate destinations" in str(create.json())
+ assert ErrorTrackingAlert.objects.for_team(self.team.id).count() == 0
+
+ created = self._create_alert(integration)
+ update = self.client.patch(
+ f"/api/projects/{self.team.id}/error_tracking/alerts/{created['id']}/",
+ data={"destinations": [destination, destination]},
+ format="json",
+ )
+ assert update.status_code == 400, update.json()
+ assert ErrorTrackingAlertDestination.objects.for_team(self.team.id).count() == 1
+
+ def test_empty_patch_does_not_touch_updated_at(self):
+ integration = self._create_slack_integration()
+ created = self._create_alert(integration)
+
+ update = self.client.patch(
+ f"/api/projects/{self.team.id}/error_tracking/alerts/{created['id']}/", data={}, format="json"
+ )
+
+ assert update.status_code == 200, update.json()
+ assert update.json()["updated_at"] == created["updated_at"]
+
+ def test_put_replaces_the_whole_alert(self):
+ integration = self._create_slack_integration()
+ created = self._create_alert(integration, throttle_seconds=600)
+ alert_url = f"/api/projects/{self.team.id}/error_tracking/alerts/{created['id']}/"
+ patched = self.client.patch(alert_url, data={"enabled": False}, format="json")
+ assert patched.status_code == 200, patched.json()
+
+ put = self.client.put(alert_url, data=self._valid_payload(integration, name="Renamed"), format="json")
+
+ assert put.status_code == 200, put.json()
+ body = put.json()
+ assert body["name"] == "Renamed"
+ # Fields omitted from a PUT reset to their defaults instead of keeping current values.
+ assert body["enabled"] is True
+ assert body["throttle_seconds"] == 0
+
+ def test_alert_accepts_integration_from_sibling_environment(self):
+ env_team = Team.objects.create(organization=self.organization, project=self.team.project, name="env")
+ integration = self._create_slack_integration(team=env_team)
+
+ created = self._create_alert(integration)
+
+ assert created["destinations"][0]["integration_id"] == integration.id
+
+ def test_alert_create_rejects_other_teams_integration(self):
+ other_team = self.create_team_with_organization(organization=self.organization)
+ foreign_integration = self._create_slack_integration(team=other_team)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/error_tracking/alerts/",
+ data=self._valid_payload(foreign_integration),
+ format="json",
+ )
+
+ assert response.status_code == 400, response.json()
+ assert ErrorTrackingAlert.objects.for_team(self.team.id).count() == 0
+
+ def test_alert_detail_with_malformed_id_returns_404(self):
+ retrieve = self.client.get(f"/api/projects/{self.team.id}/error_tracking/alerts/not-a-uuid/")
+ assert retrieve.status_code == 404
+
+ delete = self.client.delete(f"/api/projects/{self.team.id}/error_tracking/alerts/not-a-uuid/")
+ assert delete.status_code == 404
+
+ def test_alerts_are_isolated_per_team(self):
+ other_team = self.create_team_with_organization(organization=self.organization)
+ with team_scope(other_team.id):
+ foreign_alert = ErrorTrackingAlert.objects.create(
+ team=other_team,
+ name="Other team alert",
+ triggers=["issue_created"],
+ )
+
+ listing = self.client.get(f"/api/projects/{self.team.id}/error_tracking/alerts/")
+ assert listing.status_code == 200
+ assert listing.json()["results"] == []
+
+ retrieve = self.client.get(f"/api/projects/{self.team.id}/error_tracking/alerts/{foreign_alert.id}/")
+ assert retrieve.status_code == 404
diff --git a/products/error_tracking/frontend/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.ts
index 6d42b6b98fed..477bf31a5a69 100644
--- a/products/error_tracking/frontend/generated/api.schemas.ts
+++ b/products/error_tracking/frontend/generated/api.schemas.ts
@@ -7,6 +7,180 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+/**
+ * * `issue_created` - issue_created
+ * * `issue_reopened` - issue_reopened
+ * * `issue_spiking` - issue_spiking
+ * * `issue_assigned` - issue_assigned
+ */
+export type TriggersEnumApi = (typeof TriggersEnumApi)[keyof typeof TriggersEnumApi]
+
+export const TriggersEnumApi = {
+ IssueCreated: 'issue_created',
+ IssueReopened: 'issue_reopened',
+ IssueSpiking: 'issue_spiking',
+ IssueAssigned: 'issue_assigned',
+} as const
+
+export type ErrorTrackingAlertFiltersApiEventsItem = { [key: string]: unknown }
+
+export type ErrorTrackingAlertFiltersApiActionsItem = { [key: string]: unknown }
+
+export type ErrorTrackingAlertFiltersApiPropertiesItem = { [key: string]: unknown }
+
+export interface ErrorTrackingAlertFiltersApi {
+ /** Event filters a transition must match. */
+ events?: ErrorTrackingAlertFiltersApiEventsItem[]
+ /** Action filters a transition must match. */
+ actions?: ErrorTrackingAlertFiltersApiActionsItem[]
+ /** Property filters a transition must match. */
+ properties?: ErrorTrackingAlertFiltersApiPropertiesItem[]
+ /** Whether to exclude internal and test accounts. */
+ filter_test_accounts?: boolean
+ /** Compiled filter bytecode. Generated by the server on save. */
+ readonly bytecode: unknown
+}
+
+/**
+ * * `slack` - slack
+ */
+export type ChannelTypeEnumApi = (typeof ChannelTypeEnumApi)[keyof typeof ChannelTypeEnumApi]
+
+export const ChannelTypeEnumApi = {
+ Slack: 'slack',
+} as const
+
+export interface ErrorTrackingAlertSlackConfigApi {
+ /** Slack channel ID notifications are delivered to. */
+ channel: string
+ /** Human-readable Slack channel name, stored for display only. */
+ channel_name?: string
+}
+
+export interface ErrorTrackingAlertDestinationApi {
+ /** Delivery channel for notifications.
+ *
+ * * `slack` - slack */
+ channel_type: ChannelTypeEnumApi
+ /**
+ * ID of the workspace integration used to deliver notifications (required for Slack).
+ * @nullable
+ */
+ integration_id?: number | null
+ /** Channel-specific delivery settings, e.g. {"channel": "C0123"} for Slack. */
+ config: ErrorTrackingAlertSlackConfigApi
+ /** Unique identifier of the destination. */
+ readonly id: string
+}
+
+export interface ErrorTrackingAlertApi {
+ /** Unique identifier of the alert. */
+ readonly id: string
+ /** Human-readable name of the alert. */
+ name: string
+ /** Whether the alert currently fires notifications. */
+ enabled: boolean
+ /** Issue lifecycle events that open a notification thread for an issue. */
+ triggers: TriggersEnumApi[]
+ /** Property filters a transition must match to open a notification thread. Same shape as hog function filters, including the compiled bytecode. */
+ filters: ErrorTrackingAlertFiltersApi
+ /** Minimum seconds between thread-opening notifications per issue. 0 disables the throttle. */
+ throttle_seconds: number
+ /** Delivery targets notifications fan out to. */
+ destinations: ErrorTrackingAlertDestinationApi[]
+ /** When the alert was created. */
+ readonly created_at: string
+ /** When the alert was last updated. */
+ readonly updated_at: string
+}
+
+export interface PaginatedErrorTrackingAlertListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: ErrorTrackingAlertApi[]
+}
+
+export interface ErrorTrackingAlertDestinationRequestApi {
+ /** Delivery channel for notifications.
+ *
+ * * `slack` - slack */
+ channel_type: ChannelTypeEnumApi
+ /**
+ * ID of the workspace integration used to deliver notifications (required for Slack).
+ * @nullable
+ */
+ integration_id?: number | null
+ /** Channel-specific delivery settings, e.g. {"channel": "C0123"} for Slack. */
+ config: ErrorTrackingAlertSlackConfigApi
+}
+
+export interface ErrorTrackingAlertCreateRequestApi {
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 400
+ */
+ name: string
+ /** Issue lifecycle events that open a notification thread for an issue. */
+ triggers: TriggersEnumApi[]
+ /** Property filters a transition must match to open a notification thread. Same shape as hog function filters; the bytecode is compiled on save. */
+ filters?: ErrorTrackingAlertFiltersApi
+ /**
+ * Minimum seconds between thread-opening notifications per issue. 0 disables the throttle.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ throttle_seconds?: number
+ /** Delivery targets notifications fan out to. */
+ destinations: ErrorTrackingAlertDestinationRequestApi[]
+}
+
+export interface ErrorTrackingAlertPutRequestApi {
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 400
+ */
+ name: string
+ /** Issue lifecycle events that open a notification thread for an issue. */
+ triggers: TriggersEnumApi[]
+ /** Property filters a transition must match to open a notification thread. Same shape as hog function filters; the bytecode is compiled on save. */
+ filters?: ErrorTrackingAlertFiltersApi
+ /**
+ * Minimum seconds between thread-opening notifications per issue. 0 disables the throttle.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ throttle_seconds?: number
+ /** Delivery targets notifications fan out to. */
+ destinations: ErrorTrackingAlertDestinationRequestApi[]
+ /** Whether the alert fires notifications. Defaults to enabled. */
+ enabled?: boolean
+}
+
+export interface PatchedErrorTrackingAlertUpdateRequestApi {
+ /**
+ * Human-readable name of the alert. Omit to keep the current name.
+ * @maxLength 400
+ */
+ name?: string
+ /** Whether the alert fires notifications. Omit to keep the current state. */
+ enabled?: boolean
+ /** Issue lifecycle events that open a notification thread. Omit to keep the current triggers. */
+ triggers?: TriggersEnumApi[]
+ /** Property filters a transition must match to open a notification thread. Omit to keep the current filters. */
+ filters?: ErrorTrackingAlertFiltersApi
+ /**
+ * Minimum seconds between thread-opening notifications per issue. Omit to keep the current value.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ throttle_seconds?: number
+ /** Delivery targets notifications fan out to. When provided, replaces all current destinations. */
+ destinations?: ErrorTrackingAlertDestinationRequestApi[]
+}
+
/**
* @nullable
*/
@@ -2039,6 +2213,17 @@ export interface ErrorTrackingSymbolSetBulkStartUploadResponseApi {
id_map: ErrorTrackingSymbolSetBulkStartUploadResponseApiIdMap
}
+export type ErrorTrackingAlertsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type ErrorTrackingAssignmentRulesListParams = {
/**
* Number of results to return per page.
diff --git a/products/error_tracking/frontend/generated/api.ts b/products/error_tracking/frontend/generated/api.ts
index e29ce1fce9ac..5b3e8fedf5b7 100644
--- a/products/error_tracking/frontend/generated/api.ts
+++ b/products/error_tracking/frontend/generated/api.ts
@@ -9,6 +9,10 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ ErrorTrackingAlertApi,
+ ErrorTrackingAlertCreateRequestApi,
+ ErrorTrackingAlertPutRequestApi,
+ ErrorTrackingAlertsListParams,
ErrorTrackingAssignmentRuleApi,
ErrorTrackingAssignmentRuleCreateRequestApi,
ErrorTrackingAssignmentRuleUpdateRequestApi,
@@ -75,6 +79,7 @@ import type {
ErrorTrackingSymbolSetFinishUploadApi,
ErrorTrackingSymbolSetsListParams,
GitProviderFileLinkResolveResponseApi,
+ PaginatedErrorTrackingAlertListApi,
PaginatedErrorTrackingAssignmentRuleListApi,
PaginatedErrorTrackingBypassRuleListApi,
PaginatedErrorTrackingExternalReferenceResultListApi,
@@ -86,6 +91,7 @@ import type {
PaginatedErrorTrackingStackFrameListApi,
PaginatedErrorTrackingSuppressionRuleListApi,
PaginatedErrorTrackingSymbolSetListApi,
+ PatchedErrorTrackingAlertUpdateRequestApi,
PatchedErrorTrackingAssignmentRuleApi,
PatchedErrorTrackingAssignmentRuleUpdateRequestApi,
PatchedErrorTrackingBypassRuleApi,
@@ -121,6 +127,116 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
+export const getErrorTrackingAlertsListUrl = (projectId: string, params?: ErrorTrackingAlertsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/error_tracking/alerts/?${stringifiedParams}`
+ : `/api/projects/${projectId}/error_tracking/alerts/`
+}
+
+export const errorTrackingAlertsList = async (
+ projectId: string,
+ params?: ErrorTrackingAlertsListParams,
+ options?: RequestInit
+): Promise<PaginatedErrorTrackingAlertListApi> => {
+ return apiMutator<PaginatedErrorTrackingAlertListApi>(getErrorTrackingAlertsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getErrorTrackingAlertsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/error_tracking/alerts/`
+}
+
+export const errorTrackingAlertsCreate = async (
+ projectId: string,
+ errorTrackingAlertCreateRequestApi: NonReadonly<ErrorTrackingAlertCreateRequestApi>,
+ options?: RequestInit
+): Promise<ErrorTrackingAlertApi> => {
+ return apiMutator<ErrorTrackingAlertApi>(getErrorTrackingAlertsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(errorTrackingAlertCreateRequestApi),
+ })
+}
+
+export const getErrorTrackingAlertsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/error_tracking/alerts/${id}/`
+}
+
+export const errorTrackingAlertsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<ErrorTrackingAlertApi> => {
+ return apiMutator<ErrorTrackingAlertApi>(getErrorTrackingAlertsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getErrorTrackingAlertsUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/error_tracking/alerts/${id}/`
+}
+
+export const errorTrackingAlertsUpdate = async (
+ projectId: string,
+ id: string,
+ errorTrackingAlertPutRequestApi: NonReadonly<ErrorTrackingAlertPutRequestApi>,
+ options?: RequestInit
+): Promise<ErrorTrackingAlertApi> => {
+ return apiMutator<ErrorTrackingAlertApi>(getErrorTrackingAlertsUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(errorTrackingAlertPutRequestApi),
+ })
+}
+
+export const getErrorTrackingAlertsPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/error_tracking/alerts/${id}/`
+}
+
+export const errorTrackingAlertsPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedErrorTrackingAlertUpdateRequestApi?: NonReadonly<PatchedErrorTrackingAlertUpdateRequestApi>,
+ options?: RequestInit
+): Promise<ErrorTrackingAlertApi> => {
+ return apiMutator<ErrorTrackingAlertApi>(getErrorTrackingAlertsPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedErrorTrackingAlertUpdateRequestApi),
+ })
+}
+
+export const getErrorTrackingAlertsDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/error_tracking/alerts/${id}/`
+}
+
+export const errorTrackingAlertsDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getErrorTrackingAlertsDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getErrorTrackingAssignmentRulesListUrl = (
projectId: string,
params?: ErrorTrackingAssignmentRulesListParams
diff --git a/products/error_tracking/frontend/generated/api.zod.ts b/products/error_tracking/frontend/generated/api.zod.ts
index 5bbf7447ab5f..5e2777617078 100644
--- a/products/error_tracking/frontend/generated/api.zod.ts
+++ b/products/error_tracking/frontend/generated/api.zod.ts
@@ -9,6 +9,228 @@
*/
import * as zod from 'zod'
+export const errorTrackingAlertsCreateBodyNameMax = 400
+
+export const errorTrackingAlertsCreateBodyThrottleSecondsDefault = 0
+export const errorTrackingAlertsCreateBodyThrottleSecondsMin = 0
+export const errorTrackingAlertsCreateBodyThrottleSecondsMax = 2147483647
+
+export const ErrorTrackingAlertsCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(errorTrackingAlertsCreateBodyNameMax).describe('Human-readable name of the alert.'),
+ triggers: zod
+ .array(
+ zod
+ .enum(['issue_created', 'issue_reopened', 'issue_spiking', 'issue_assigned'])
+ .describe(
+ '\* `issue_created` - issue_created\n\* `issue_reopened` - issue_reopened\n\* `issue_spiking` - issue_spiking\n\* `issue_assigned` - issue_assigned'
+ )
+ )
+ .describe('Issue lifecycle events that open a notification thread for an issue.'),
+ filters: zod
+ .object({
+ events: zod
+ .array(zod.record(zod.string(), zod.unknown()))
+ .optional()
+ .describe('Event filters a transition must match.'),
+ actions: zod
+ .array(zod.record(zod.string(), zod.unknown()))
+ .optional()
+ .describe('Action filters a transition must match.'),
+ properties: zod
+ .array(zod.record(zod.string(), zod.unknown()))
+ .optional()
+ .describe('Property filters a transition must match.'),
+ filter_test_accounts: zod.boolean().optional().describe('Whether to exclude internal and test accounts.'),
+ bytecode: zod.unknown().describe('Compiled filter bytecode. Generated by the server on save.'),
+ })
+ .optional()
+ .describe(
+ 'Property filters a transition must match to open a notification thread. Same shape as hog function filters; the bytecode is compiled on save.'
+ ),
+ throttle_seconds: zod
+ .number()
+ .min(errorTrackingAlertsCreateBodyThrottleSecondsMin)
+ .max(errorTrackingAlertsCreateBodyThrottleSecondsMax)
+ .default(errorTrackingAlertsCreateBodyThrottleSecondsDefault)
+ .describe('Minimum seconds between thread-opening notifications per issue. 0 disables the throttle.'),
+ destinations: zod
+ .array(
+ zod.object({
+ channel_type: zod
+ .enum(['slack'])
+ .describe('\* `slack` - slack')
+ .describe('Delivery channel for notifications.\n\n\* `slack` - slack'),
+ integration_id: zod
+ .number()
+ .nullish()
+ .describe('ID of the workspace integration used to deliver notifications (required for Slack).'),
+ config: zod
+ .object({
+ channel: zod.string().describe('Slack channel ID notifications are delivered to.'),
+ channel_name: zod
+ .string()
+ .optional()
+ .describe('Human-readable Slack channel name, stored for display only.'),
+ })
+ .describe('Channel-specific delivery settings, e.g. {\"channel\": \"C0123\"} for Slack.'),
+ })
+ )
+ .describe('Delivery targets notifications fan out to.'),
+})
+
+export const errorTrackingAlertsUpdateBodyNameMax = 400
+
+export const errorTrackingAlertsUpdateBodyThrottleSecondsDefault = 0
+export const errorTrackingAlertsUpdateBodyThrottleSecondsMin = 0
+export const errorTrackingAlertsUpdateBodyThrottleSecondsMax = 2147483647
+
+export const errorTrackingAlertsUpdateBodyEnabledDefault = true
+
+export const ErrorTrackingAlertsUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(errorTrackingAlertsUpdateBodyNameMax).describe('Human-readable name of the alert.'),
+ triggers: zod
+ .array(
+ zod
+ .enum(['issue_created', 'issue_reopened', 'issue_spiking', 'issue_assigned'])
+ .describe(
+ '\* `issue_created` - issue_created\n\* `issue_reopened` - issue_reopened\n\* `issue_spiking` - issue_spiking\n\* `issue_assigned` - issue_assigned'
+ )
+ )
+ .describe('Issue lifecycle events that open a notification thread for an issue.'),
+ filters: zod
+ .object({
+ events: zod
+ .array(zod.record(zod.string(), zod.unknown()))
+ .optional()
+ .describe('Event filters a transition must match.'),
+ actions: zod
+ .array(zod.record(zod.string(), zod.unknown()))
+ .optional()
+ .describe('Action filters a transition must match.'),
+ properties: zod
+ .array(zod.record(zod.string(), zod.unknown()))
+ .optional()
+ .describe('Property filters a transition must match.'),
+ filter_test_accounts: zod.boolean().optional().describe('Whether to exclude internal and test accounts.'),
+ bytecode: zod.unknown().describe('Compiled filter bytecode. Generated by the server on save.'),
+ })
+ .optional()
+ .describe(
+ 'Property filters a transition must match to open a notification thread. Same shape as hog function filters; the bytecode is compiled on save.'
+ ),
+ throttle_seconds: zod
+ .number()
+ .min(errorTrackingAlertsUpdateBodyThrottleSecondsMin)
+ .max(errorTrackingAlertsUpdateBodyThrottleSecondsMax)
+ .default(errorTrackingAlertsUpdateBodyThrottleSecondsDefault)
+ .describe('Minimum seconds between thread-opening notifications per issue. 0 disables the throttle.'),
+ destinations: zod
+ .array(
+ zod.object({
+ channel_type: zod
+ .enum(['slack'])
+ .describe('\* `slack` - slack')
+ .describe('Delivery channel for notifications.\n\n\* `slack` - slack'),
+ integration_id: zod
+ .number()
+ .nullish()
+ .describe('ID of the workspace integration used to deliver notifications (required for Slack).'),
+ config: zod
+ .object({
+ channel: zod.string().describe('Slack channel ID notifications are delivered to.'),
+ channel_name: zod
+ .string()
+ .optional()
+ .describe('Human-readable Slack channel name, stored for display only.'),
+ })
+ .describe('Channel-specific delivery settings, e.g. {\"channel\": \"C0123\"} for Slack.'),
+ })
+ )
+ .describe('Delivery targets notifications fan out to.'),
+ enabled: zod
+ .boolean()
+ .default(errorTrackingAlertsUpdateBodyEnabledDefault)
+ .describe('Whether the alert fires notifications. Defaults to enabled.'),
+})
+
+export const errorTrackingAlertsPartialUpdateBodyNameMax = 400
+
+export const errorTrackingAlertsPartialUpdateBodyThrottleSecondsMin = 0
+export const errorTrackingAlertsPartialUpdateBodyThrottleSecondsMax = 2147483647
+
+export const ErrorTrackingAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(errorTrackingAlertsPartialUpdateBodyNameMax)
+ .optional()
+ .describe('Human-readable name of the alert. Omit to keep the current name.'),
+ enabled: zod
+ .boolean()
+ .optional()
+ .describe('Whether the alert fires notifications. Omit to keep the current state.'),
+ triggers: zod
+ .array(
+ zod
+ .enum(['issue_created', 'issue_reopened', 'issue_spiking', 'issue_assigned'])
+ .describe(
+ '\* `issue_created` - issue_created\n\* `issue_reopened` - issue_reopened\n\* `issue_spiking` - issue_spiking\n\* `issue_assigned` - issue_assigned'
+ )
+ )
+ .optional()
+ .describe('Issue lifecycle events that open a notification thread. Omit to keep the current triggers.'),
+ filters: zod
+ .object({
+ events: zod
+ .array(zod.record(zod.string(), zod.unknown()))
+ .optional()
+ .describe('Event filters a transition must match.'),
+ actions: zod
+ .array(zod.record(zod.string(), zod.unknown()))
+ .optional()
+ .describe('Action filters a transition must match.'),
+ properties: zod
+ .array(zod.record(zod.string(), zod.unknown()))
+ .optional()
+ .describe('Property filters a transition must match.'),
+ filter_test_accounts: zod.boolean().optional().describe('Whether to exclude internal and test accounts.'),
+ bytecode: zod.unknown().describe('Compiled filter bytecode. Generated by the server on save.'),
+ })
+ .optional()
+ .describe(
+ 'Property filters a transition must match to open a notification thread. Omit to keep the current filters.'
+ ),
+ throttle_seconds: zod
+ .number()
+ .min(errorTrackingAlertsPartialUpdateBodyThrottleSecondsMin)
+ .max(errorTrackingAlertsPartialUpdateBodyThrottleSecondsMax)
+ .optional()
+ .describe('Minimum seconds between thread-opening notifications per issue. Omit to keep the current value.'),
+ destinations: zod
+ .array(
+ zod.object({
+ channel_type: zod
+ .enum(['slack'])
+ .describe('\* `slack` - slack')
+ .describe('Delivery channel for notifications.\n\n\* `slack` - slack'),
+ integration_id: zod
+ .number()
+ .nullish()
+ .describe('ID of the workspace integration used to deliver notifications (required for Slack).'),
+ config: zod
+ .object({
+ channel: zod.string().describe('Slack channel ID notifications are delivered to.'),
+ channel_name: zod
+ .string()
+ .optional()
+ .describe('Human-readable Slack channel name, stored for display only.'),
+ })
+ .describe('Channel-specific delivery settings, e.g. {\"channel\": \"C0123\"} for Slack.'),
+ })
+ )
+ .optional()
+ .describe('Delivery targets notifications fan out to. When provided, replaces all current destinations.'),
+})
+
export const errorTrackingAssignmentRulesCreateBodyOrderKeyDefault = 0
export const ErrorTrackingAssignmentRulesCreateBody = /* @__PURE__ */ zod.object({
diff --git a/products/error_tracking/mcp/tools.yaml b/products/error_tracking/mcp/tools.yaml
index fbc9e942e31d..7c94ea61a91c 100644
--- a/products/error_tracking/mcp/tools.yaml
+++ b/products/error_tracking/mcp/tools.yaml
@@ -20,6 +20,24 @@ ui_apps:
detail_args: '{ issueId: item.id }'
click_prop: onIssueClick
tools:
+ error-tracking-alerts-create:
+ operation: error_tracking_alerts_create
+ enabled: false
+ error-tracking-alerts-destroy:
+ operation: error_tracking_alerts_destroy
+ enabled: false
+ error-tracking-alerts-list:
+ operation: error_tracking_alerts_list
+ enabled: false
+ error-tracking-alerts-partial-update:
+ operation: error_tracking_alerts_partial_update
+ enabled: false
+ error-tracking-alerts-retrieve:
+ operation: error_tracking_alerts_retrieve
+ enabled: false
+ error-tracking-alerts-update:
+ operation: error_tracking_alerts_update
+ enabled: false
error-tracking-assignment-rules-create:
operation: error_tracking_assignment_rules_create
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c7c39e254662..aad416a1932c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -17178,6 +17178,16 @@ 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.
*/
@@ -31018,6 +31028,141 @@ export namespace Schemas {
volume_buckets?: ErrorTrackingVolumeBucket[];
}
+ /**
+ * * `issue_created` - issue_created
+ * * `issue_reopened` - issue_reopened
+ * * `issue_spiking` - issue_spiking
+ * * `issue_assigned` - issue_assigned
+ */
+ export type TriggersEnum = typeof TriggersEnum[keyof typeof TriggersEnum];
+
+
+ export const TriggersEnum = {
+ IssueCreated: 'issue_created',
+ IssueReopened: 'issue_reopened',
+ IssueSpiking: 'issue_spiking',
+ IssueAssigned: 'issue_assigned',
+ } as const;
+
+ export type ErrorTrackingAlertFiltersEventsItem = { [key: string]: unknown };
+
+ export type ErrorTrackingAlertFiltersActionsItem = { [key: string]: unknown };
+
+ export type ErrorTrackingAlertFiltersPropertiesItem = { [key: string]: unknown };
+
+ export interface ErrorTrackingAlertFilters {
+ /** Event filters a transition must match. */
+ events?: ErrorTrackingAlertFiltersEventsItem[];
+ /** Action filters a transition must match. */
+ actions?: ErrorTrackingAlertFiltersActionsItem[];
+ /** Property filters a transition must match. */
+ properties?: ErrorTrackingAlertFiltersPropertiesItem[];
+ /** Whether to exclude internal and test accounts. */
+ filter_test_accounts?: boolean;
+ /** Compiled filter bytecode. Generated by the server on save. */
+ readonly bytecode: unknown;
+ }
+
+ export interface ErrorTrackingAlertSlackConfig {
+ /** Slack channel ID notifications are delivered to. */
+ channel: string;
+ /** Human-readable Slack channel name, stored for display only. */
+ channel_name?: string;
+ }
+
+ export interface ErrorTrackingAlertDestination {
+ /** Delivery channel for notifications.
+ *
+ * * `slack` - slack */
+ channel_type: ChannelTypeEnum;
+ /**
+ * ID of the workspace integration used to deliver notifications (required for Slack).
+ * @nullable
+ */
+ integration_id?: number | null;
+ /** Channel-specific delivery settings, e.g. {"channel": "C0123"} for Slack. */
+ config: ErrorTrackingAlertSlackConfig;
+ /** Unique identifier of the destination. */
+ readonly id: string;
+ }
+
+ export interface ErrorTrackingAlert {
+ /** Unique identifier of the alert. */
+ readonly id: string;
+ /** Human-readable name of the alert. */
+ name: string;
+ /** Whether the alert currently fires notifications. */
+ enabled: boolean;
+ /** Issue lifecycle events that open a notification thread for an issue. */
+ triggers: TriggersEnum[];
+ /** Property filters a transition must match to open a notification thread. Same shape as hog function filters, including the compiled bytecode. */
+ filters: ErrorTrackingAlertFilters;
+ /** Minimum seconds between thread-opening notifications per issue. 0 disables the throttle. */
+ throttle_seconds: number;
+ /** Delivery targets notifications fan out to. */
+ destinations: ErrorTrackingAlertDestination[];
+ /** When the alert was created. */
+ readonly created_at: string;
+ /** When the alert was last updated. */
+ readonly updated_at: string;
+ }
+
+ export interface ErrorTrackingAlertDestinationRequest {
+ /** Delivery channel for notifications.
+ *
+ * * `slack` - slack */
+ channel_type: ChannelTypeEnum;
+ /**
+ * ID of the workspace integration used to deliver notifications (required for Slack).
+ * @nullable
+ */
+ integration_id?: number | null;
+ /** Channel-specific delivery settings, e.g. {"channel": "C0123"} for Slack. */
+ config: ErrorTrackingAlertSlackConfig;
+ }
+
+ export interface ErrorTrackingAlertCreateRequest {
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 400
+ */
+ name: string;
+ /** Issue lifecycle events that open a notification thread for an issue. */
+ triggers: TriggersEnum[];
+ /** Property filters a transition must match to open a notification thread. Same shape as hog function filters; the bytecode is compiled on save. */
+ filters?: ErrorTrackingAlertFilters;
+ /**
+ * Minimum seconds between thread-opening notifications per issue. 0 disables the throttle.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ throttle_seconds?: number;
+ /** Delivery targets notifications fan out to. */
+ destinations: ErrorTrackingAlertDestinationRequest[];
+ }
+
+ export interface ErrorTrackingAlertPutRequest {
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 400
+ */
+ name: string;
+ /** Issue lifecycle events that open a notification thread for an issue. */
+ triggers: TriggersEnum[];
+ /** Property filters a transition must match to open a notification thread. Same shape as hog function filters; the bytecode is compiled on save. */
+ filters?: ErrorTrackingAlertFilters;
+ /**
+ * Minimum seconds between thread-opening notifications per issue. 0 disables the throttle.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ throttle_seconds?: number;
+ /** Delivery targets notifications fan out to. */
+ destinations: ErrorTrackingAlertDestinationRequest[];
+ /** Whether the alert fires notifications. Defaults to enabled. */
+ enabled?: boolean;
+ }
+
export interface ErrorTrackingAssignee {
/** User ID or role UUID to filter by. */
id: string | number;
@@ -54707,6 +54852,15 @@ export namespace Schemas {
results: EnterprisePropertyDefinition[];
}
+ export interface PaginatedErrorTrackingAlertList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: ErrorTrackingAlert[];
+ }
+
export interface PaginatedErrorTrackingAssignmentRuleList {
count: number;
/** @nullable */
@@ -62075,6 +62229,28 @@ export namespace Schemas {
readonly warehouse_origin?: unknown;
}
+ export interface PatchedErrorTrackingAlertUpdateRequest {
+ /**
+ * Human-readable name of the alert. Omit to keep the current name.
+ * @maxLength 400
+ */
+ name?: string;
+ /** Whether the alert fires notifications. Omit to keep the current state. */
+ enabled?: boolean;
+ /** Issue lifecycle events that open a notification thread. Omit to keep the current triggers. */
+ triggers?: TriggersEnum[];
+ /** Property filters a transition must match to open a notification thread. Omit to keep the current filters. */
+ filters?: ErrorTrackingAlertFilters;
+ /**
+ * Minimum seconds between thread-opening notifications per issue. Omit to keep the current value.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ throttle_seconds?: number;
+ /** Delivery targets notifications fan out to. When provided, replaces all current destinations. */
+ destinations?: ErrorTrackingAlertDestinationRequest[];
+ }
+
/**
* @nullable
*/
@@ -94242,6 +94418,17 @@ export namespace Schemas {
context_name: string;
};
+ export type ErrorTrackingAlertsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type ErrorTrackingAssignmentRulesListParams = {
/**
* Number of results to return per page.