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(alerts): add name search and created-by filters on alerts list (#60720)

Matt Pua00f05358bd97
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 41485f72a9b2..92c9a0d9cd76 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -6216,7 +6216,7 @@ const api = {
},
async list(
insightId?: InsightModel['id'],
- params: { limit?: number; offset?: number } = {}
+ params: { limit?: number; offset?: number; search?: string; created_by?: string } = {}
): Promise<CountedPaginatedResponse<AlertType>> {
const queryParams: Record<string, any> = { ...params }
if (insightId !== undefined) {
diff --git a/frontend/src/lib/components/Alerts/AlertsFiltersBar.tsx b/frontend/src/lib/components/Alerts/AlertsFiltersBar.tsx
new file mode 100644
index 000000000000..545c8cfcee2c
--- /dev/null
+++ b/frontend/src/lib/components/Alerts/AlertsFiltersBar.tsx
@@ -0,0 +1,30 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonInput } from '@posthog/lemon-ui'
+
+import { MemberSelect } from 'lib/components/MemberSelect'
+
+import { alertsLogic } from './alertsLogic'
+
+export function AlertsFiltersBar(): JSX.Element {
+ const { filters } = useValues(alertsLogic)
+ const { setFilters } = useActions(alertsLogic)
+
+ return (
+ <div className="flex justify-between gap-2 flex-wrap mb-4">
+ <LemonInput
+ type="search"
+ placeholder="Search for alerts"
+ onChange={(value) => setFilters({ search: value })}
+ value={filters.search}
+ />
+ <div className="flex items-center gap-2">
+ <span>Created by:</span>
+ <MemberSelect
+ value={filters.createdBy === 'All users' ? null : filters.createdBy}
+ onChange={(user) => setFilters({ createdBy: user?.uuid || 'All users' })}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/lib/components/Alerts/alertsLogic.ts b/frontend/src/lib/components/Alerts/alertsLogic.ts
index 38aeb4313f35..ca2b0f28c712 100644
--- a/frontend/src/lib/components/Alerts/alertsLogic.ts
+++ b/frontend/src/lib/components/Alerts/alertsLogic.ts
@@ -4,6 +4,7 @@ import { loaders } from 'kea-loaders'
import { PaginationManual } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { objectClean } from 'lib/utils'
import { AlertState } from '~/queries/schema/schema-general'
@@ -15,11 +16,22 @@ export interface AlertsLogicProps extends AlertLogicProps {}
export const ALERTS_PER_PAGE = 30
+export interface AlertsFilters {
+ search: string
+ createdBy: string
+}
+
+export const DEFAULT_ALERTS_FILTERS: AlertsFilters = {
+ search: '',
+ createdBy: 'All users',
+}
+
export const alertsLogic = kea<alertsLogicType>([
path(['lib', 'components', 'Alerts', 'alertsLogic']),
actions({
setPage: (page: number) => ({ page }),
+ setFilters: (filters: Partial<AlertsFilters>) => ({ filters }),
}),
reducers({
@@ -29,6 +41,16 @@ export const alertsLogic = kea<alertsLogicType>([
setPage: (_, { page }) => page,
},
],
+ filters: [
+ DEFAULT_ALERTS_FILTERS,
+ {
+ setFilters: (state, { filters }) =>
+ objectClean({
+ ...state,
+ ...filters,
+ }),
+ },
+ ],
}),
loaders(({ values }) => ({
@@ -36,9 +58,13 @@ export const alertsLogic = kea<alertsLogicType>([
{ results: [], count: 0 } as { results: AlertType[]; count: number },
{
loadAlerts: async () => {
+ const search = values.filters.search.trim()
+
const response = await api.alerts.list(undefined, {
limit: ALERTS_PER_PAGE,
offset: (values.page - 1) * ALERTS_PER_PAGE,
+ ...(search ? { search } : {}),
+ ...(values.filters.createdBy !== 'All users' ? { created_by: values.filters.createdBy } : {}),
})
return { results: response.results, count: response.count ?? response.results.length }
},
@@ -49,6 +75,12 @@ export const alertsLogic = kea<alertsLogicType>([
selectors(({ actions }) => ({
alerts: [(s) => [s.alertsResponse], (response): AlertType[] => response.results],
alertsCount: [(s) => [s.alertsResponse], (response): number => response.count],
+ isFiltering: [
+ (s) => [s.filters],
+ (filters): boolean =>
+ filters.search !== DEFAULT_ALERTS_FILTERS.search ||
+ filters.createdBy !== DEFAULT_ALERTS_FILTERS.createdBy,
+ ],
alertsSortedByState: [
(s) => [s.alerts],
(alerts: AlertType[]): AlertType[] =>
@@ -67,10 +99,20 @@ export const alertsLogic = kea<alertsLogicType>([
],
})),
- listeners(({ actions }) => ({
+ listeners(({ actions, values }) => ({
setPage: () => {
actions.loadAlerts()
},
+ setFilters: async ({ filters }, breakpoint) => {
+ if ('search' in filters && filters.search?.trim()) {
+ await breakpoint(300)
+ }
+ if (values.page !== 1) {
+ actions.setPage(1)
+ } else {
+ actions.loadAlerts()
+ }
+ },
})),
afterMount(({ actions }) => actions.loadAlerts()),
diff --git a/frontend/src/lib/components/Alerts/views/Alerts.tsx b/frontend/src/lib/components/Alerts/views/Alerts.tsx
index ec97a014a271..81410e207a29 100644
--- a/frontend/src/lib/components/Alerts/views/Alerts.tsx
+++ b/frontend/src/lib/components/Alerts/views/Alerts.tsx
@@ -15,6 +15,7 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { AlertState } from '../../../../queries/schema/schema-general'
import { alertLogic } from '../alertLogic'
+import { AlertsFiltersBar } from '../AlertsFiltersBar'
import { alertsLogic } from '../alertsLogic'
import { AlertType } from '../types'
import { EditAlertModal } from './EditAlertModal'
@@ -28,7 +29,7 @@ export function Alerts({ alertId }: AlertsProps): JSX.Element {
const { push } = useActions(router)
const logic = alertsLogic()
const { loadAlerts } = useActions(logic)
- const { alertsSortedByState, alertsResponseLoading, pagination, alertsCount } = useValues(logic)
+ const { alertsSortedByState, alertsResponseLoading, pagination, alertsCount, isFiltering } = useValues(logic)
const { alert } = useValues(alertLogic({ alertId }))
@@ -125,7 +126,7 @@ export function Alerts({ alertId }: AlertsProps): JSX.Element {
},
]
- const isEmpty = alertsCount === 0 && !alertsResponseLoading
+ const isEmpty = alertsCount === 0 && !alertsResponseLoading && !isFiltering
// TODO: add info here to sign up for alerts early access
return (
<>
@@ -163,17 +164,25 @@ export function Alerts({ alertId }: AlertsProps): JSX.Element {
)}
{isEmpty ? null : (
- <LemonTable
- loading={alertsResponseLoading}
- columns={columns}
- dataSource={alertsSortedByState}
- noSortingCancellation
- rowKey="id"
- loadingSkeletonRows={5}
- nouns={['alert', 'alerts']}
- pagination={pagination}
- rowClassName={(alert) => (alert.state === AlertState.NOT_FIRING ? null : 'highlighted')}
- />
+ <>
+ <AlertsFiltersBar />
+ <LemonTable
+ loading={alertsResponseLoading}
+ columns={columns}
+ dataSource={alertsSortedByState}
+ noSortingCancellation
+ rowKey="id"
+ loadingSkeletonRows={5}
+ nouns={['alert', 'alerts']}
+ pagination={pagination}
+ rowClassName={(alert) => (alert.state === AlertState.NOT_FIRING ? null : 'highlighted')}
+ emptyState={
+ isFiltering ? (
+ <div className="py-8 text-center text-secondary">No alerts match your filters</div>
+ ) : undefined
+ }
+ />
+ </>
)}
</>
)
diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.py
index fa669e6517db..48e67dfe2a20 100644
--- a/products/alerts/backend/api/alert.py
+++ b/products/alerts/backend/api/alert.py
@@ -1,12 +1,15 @@
+import uuid
import dataclasses
from typing import Optional
from zoneinfo import ZoneInfo
-from django.db.models import OuterRef, QuerySet, Subquery
+from django.contrib.postgres.search import TrigramSimilarity, TrigramWordSimilarity
+from django.db.models import F, OuterRef, Q, QuerySet, Subquery, Value
+from django.db.models.functions import Coalesce
from django.db.models.signals import pre_delete
from django.dispatch import receiver
-from drf_spectacular.utils import OpenApiParameter, extend_schema
+from drf_spectacular.utils import OpenApiParameter, OpenApiTypes, extend_schema, extend_schema_view
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
@@ -26,6 +29,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.shared import UserBasicSerializer
from posthog.event_usage import get_request_analytics_properties
+from posthog.helpers.trigram_search import MAX_SEARCH_LENGTH, MIN_NAME_TRIGRAM_SIMILARITY, normalize_search_term
from posthog.models import User
from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activity
from posthog.models.signals import model_activity_signal, mutable_receiver
@@ -689,6 +693,34 @@ class AlertSimulateResponseSerializer(serializers.Serializer):
)
+@extend_schema_view(
+ list=extend_schema(
+ parameters=[
+ OpenApiParameter(
+ "search",
+ OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ description=(
+ "Optional. Fuzzy match against alert `name` using Postgres trigram word similarity "
+ "(handles typos, transpositions, and prefix-as-you-type). Results are ordered by relevance, "
+ "then creation time. Capped at 200 characters; longer queries return a 400 error."
+ ),
+ ),
+ OpenApiParameter(
+ "created_by",
+ OpenApiTypes.UUID,
+ location=OpenApiParameter.QUERY,
+ description="Optional. Restrict results to alerts created by the user with this UUID.",
+ ),
+ OpenApiParameter(
+ "insight_id",
+ OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ description="Optional. Restrict results to alerts on this insight ID.",
+ ),
+ ],
+ ),
+)
class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "alert"
queryset = (
@@ -703,11 +735,51 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if "insight" in filters:
queryset = queryset.filter(insight_id=filters["insight"])
+ insight_id = filters.get("insight_id")
+ if insight_id is not None:
+ queryset = queryset.filter(insight_id=insight_id)
+
+ created_by = filters.get("created_by")
+ if created_by:
+ try:
+ uuid.UUID(created_by)
+ except ValueError:
+ raise ValidationError({"created_by": ["Not a valid UUID."]}) from None
+ queryset = queryset.filter(created_by__uuid=created_by)
+
+ search = filters.get("search")
+ if search:
+ if len(search) > MAX_SEARCH_LENGTH:
+ raise serializers.ValidationError(
+ {"search": f"Search query must be {MAX_SEARCH_LENGTH} characters or fewer."}
+ )
+ queryset = self._apply_search(queryset, search)
+
latest_check = AlertCheck.objects.filter(alert_configuration=OuterRef("pk")).order_by("-created_at")
queryset = queryset.annotate(last_value=Subquery(latest_check.values("calculated_value")[:1]))
return queryset
+ @staticmethod
+ def _apply_search(queryset: QuerySet, search: str) -> QuerySet:
+ search = normalize_search_term(search)
+ if not search:
+ return queryset
+
+ zero = Value(0.0)
+ name_word_score = Coalesce(TrigramWordSimilarity(search, "name"), zero)
+ name_full_score = Coalesce(TrigramSimilarity("name", search), zero)
+
+ return (
+ queryset.annotate(
+ _name_word=name_word_score,
+ _name_full=name_full_score,
+ )
+ .filter(Q(_name_word__gt=MIN_NAME_TRIGRAM_SIMILARITY) | Q(_name_full__gt=MIN_NAME_TRIGRAM_SIMILARITY))
+ .annotate(_search_score=F("_name_word") + F("_name_full"))
+ .order_by("-_search_score", "-created_at")
+ )
+
CHECKS_DEFAULT_LIMIT = 5
CHECKS_MAX_LIMIT = 500
@@ -783,10 +855,6 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
- insight_id = request.GET.get("insight_id")
- if insight_id is not None:
- queryset = queryset.filter(insight=insight_id)
-
# Paginate first, then prefetch checks only for the page
page = self.paginate_queryset(queryset)
alerts = list(page) if page is not None else list(queryset)
diff --git a/products/alerts/backend/api/test/test_alert.py b/products/alerts/backend/api/test/test_alert.py
index 22d7dae7a512..3d4a15df4327 100644
--- a/products/alerts/backend/api/test/test_alert.py
+++ b/products/alerts/backend/api/test/test_alert.py
@@ -11,6 +11,7 @@ from rest_framework import status
from posthog.schema import AlertCalculationInterval, AlertConditionType, AlertState, InsightThresholdType
+from posthog.models import User
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team import Team
from posthog.models.utils import generate_random_token_personal, hash_key_value
@@ -1231,6 +1232,81 @@ class TestTriggerAlertHogFunctions(APIBaseTest):
assert event.properties["breaches"] == "test breach"
+class TestAlertListFilters(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.default_insight_data: dict[str, Any] = {
+ "query": {
+ "kind": "TrendsQuery",
+ "series": [
+ {
+ "kind": "EventsNode",
+ "event": "$pageview",
+ }
+ ],
+ "trendsFilter": {"display": "BoldNumber"},
+ },
+ }
+ self.insight = self.client.post(f"/api/projects/{self.team.id}/insights", data=self.default_insight_data).json()
+
+ def _create_alert(self, name: str, user=None) -> AlertConfiguration:
+ return AlertConfiguration.objects.create(
+ team=self.team,
+ insight_id=self.insight["id"],
+ name=name,
+ created_by=user or self.user,
+ )
+
+ def test_list_filter_by_search(self) -> None:
+ self._create_alert("Revenue spike")
+ self._create_alert("Unrelated alert")
+
+ response = self.client.get(f"/api/projects/{self.team.id}/alerts", {"search": "Reven"})
+ result_names = [alert["name"] for alert in response.json()["results"]]
+
+ assert result_names == ["Revenue spike"]
+
+ def test_list_filter_by_created_by_uuid(self) -> None:
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)
+
+ self._create_alert("Mine", user=self.user)
+ self._create_alert("Theirs", user=other_user)
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/alerts",
+ {"created_by": str(other_user.uuid)},
+ )
+ result_names = [alert["name"] for alert in response.json()["results"]]
+
+ assert result_names == ["Theirs"]
+
+ def test_list_filter_by_search_and_created_by(self) -> None:
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)
+
+ self._create_alert("Revenue spike", user=self.user)
+ self._create_alert("Revenue other", user=other_user)
+ self._create_alert("Unrelated", user=other_user)
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/alerts",
+ {"search": "Revenue", "created_by": str(other_user.uuid)},
+ )
+ result_names = [alert["name"] for alert in response.json()["results"]]
+
+ assert result_names == ["Revenue other"]
+
+ @parameterized.expand(
+ [
+ ("search_length_cap", {"search": "a" * 201}, "search"),
+ ("invalid_created_by_uuid", {"created_by": "not-a-uuid"}, "created_by"),
+ ]
+ )
+ def test_list_filter_validation_errors(self, _name: str, query_params: dict[str, str], expected_attr: str) -> None:
+ response = self.client.get(f"/api/projects/{self.team.id}/alerts", query_params)
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == expected_attr
+
+
class TestAlertAPIKeyAccess(APIBaseTest):
"""Test that the alert scope is properly enforced for API key access."""
diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.ts
index 0698e30da7ed..9d6cea9167f2 100644
--- a/products/alerts/frontend/generated/api.schemas.ts
+++ b/products/alerts/frontend/generated/api.schemas.ts
@@ -655,6 +655,14 @@ export interface PaginatedThresholdWithAlertListApi {
}
export type AlertsListParams = {
+ /**
+ * Optional. Restrict results to alerts created by the user with this UUID.
+ */
+ created_by?: string
+ /**
+ * Optional. Restrict results to alerts on this insight ID.
+ */
+ insight_id?: number
/**
* Number of results to return per page.
*/
@@ -663,6 +671,10 @@ export type AlertsListParams = {
* The initial index from which to return the results.
*/
offset?: number
+ /**
+ * Optional. Fuzzy match against alert `name` using Postgres trigram word similarity (handles typos, transpositions, and prefix-as-you-type). Results are ordered by relevance, then creation time. Capped at 200 characters; longer queries return a 400 error.
+ */
+ search?: string
}
export type AlertsRetrieveParams = {
diff --git a/products/alerts/mcp/tools.yaml b/products/alerts/mcp/tools.yaml
index 034bcadc4c9f..064c6bb145fa 100644
--- a/products/alerts/mcp/tools.yaml
+++ b/products/alerts/mcp/tools.yaml
@@ -122,9 +122,10 @@ tools:
title: List alerts
description: >
List all insight alerts in the project. Returns alerts with their current state, threshold or detector
- configuration, timing information, and firing check history. Supports filtering by insight ID via query
- parameter. Alerts can use either threshold-based conditions (absolute_value, relative_increase,
- relative_decrease) or anomaly detection via detector_config (zscore, mad, iqr, isolation_forest, knn, etc.).
+ configuration, timing information, and firing check history. Supports filtering by insight ID
+ (`insight_id`), fuzzy name search (`search`), and creator (`created_by` user UUID). Alerts can use either
+ threshold-based conditions (absolute_value, relative_increase, relative_decrease) or anomaly detection via
+ detector_config (zscore, mad, iqr, isolation_forest, knn, etc.).
alerts-simulate-create:
operation: alerts_simulate_create
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 5026efea69e9..a815d6c9e3df 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -317,7 +317,7 @@
}
},
"alerts-list": {
- "description": "List all insight alerts in the project. Returns alerts with their current state, threshold or detector configuration, timing information, and firing check history. Supports filtering by insight ID via query parameter. Alerts can use either threshold-based conditions (absolute_value, relative_increase, relative_decrease) or anomaly detection via detector_config (zscore, mad, iqr, isolation_forest, knn, etc.).",
+ "description": "List all insight alerts in the project. Returns alerts with their current state, threshold or detector configuration, timing information, and firing check history. Supports filtering by insight ID (`insight_id`), fuzzy name search (`search`), and creator (`created_by` user UUID). Alerts can use either threshold-based conditions (absolute_value, relative_increase, relative_decrease) or anomaly detection via detector_config (zscore, mad, iqr, isolation_forest, knn, etc.).",
"category": "Alerts",
"feature": "alerts",
"summary": "List alerts",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 3473779149e8..7e6ba0f2f8bc 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -333,7 +333,7 @@
}
},
"alerts-list": {
- "description": "List all insight alerts in the project. Returns alerts with their current state, threshold or detector configuration, timing information, and firing check history. Supports filtering by insight ID via query parameter. Alerts can use either threshold-based conditions (absolute_value, relative_increase, relative_decrease) or anomaly detection via detector_config (zscore, mad, iqr, isolation_forest, knn, etc.).",
+ "description": "List all insight alerts in the project. Returns alerts with their current state, threshold or detector configuration, timing information, and firing check history. Supports filtering by insight ID (`insight_id`), fuzzy name search (`search`), and creator (`created_by` user UUID). Alerts can use either threshold-based conditions (absolute_value, relative_increase, relative_decrease) or anomaly detection via detector_config (zscore, mad, iqr, isolation_forest, knn, etc.).",
"category": "Alerts",
"feature": "alerts",
"summary": "List alerts",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 289a9804600e..d85056ad122b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -41288,6 +41288,14 @@ export namespace Schemas {
};
export type EnvironmentsAlertsListParams = {
+ /**
+ * Optional. Restrict results to alerts created by the user with this UUID.
+ */
+ created_by?: string;
+ /**
+ * Optional. Restrict results to alerts on this insight ID.
+ */
+ insight_id?: number;
/**
* Number of results to return per page.
*/
@@ -41296,6 +41304,10 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
+ /**
+ * Optional. Fuzzy match against alert `name` using Postgres trigram word similarity (handles typos, transpositions, and prefix-as-you-type). Results are ordered by relevance, then creation time. Capped at 200 characters; longer queries return a 400 error.
+ */
+ search?: string;
};
export type EnvironmentsAlertsRetrieveParams = {
@@ -46250,6 +46262,14 @@ export namespace Schemas {
};
export type AlertsListParams = {
+ /**
+ * Optional. Restrict results to alerts created by the user with this UUID.
+ */
+ created_by?: string;
+ /**
+ * Optional. Restrict results to alerts on this insight ID.
+ */
+ insight_id?: number;
/**
* Number of results to return per page.
*/
@@ -46258,6 +46278,10 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
+ /**
+ * Optional. Fuzzy match against alert `name` using Postgres trigram word similarity (handles typos, transpositions, and prefix-as-you-type). Results are ordered by relevance, then creation time. Capped at 200 characters; longer queries return a 400 error.
+ */
+ search?: string;
};
export type AlertsRetrieveParams = {
diff --git a/services/mcp/src/generated/alerts/api.ts b/services/mcp/src/generated/alerts/api.ts
index 5b4ad2034d2b..7c89ed63530e 100644
--- a/services/mcp/src/generated/alerts/api.ts
+++ b/services/mcp/src/generated/alerts/api.ts
@@ -17,8 +17,19 @@ export const AlertsListParams = /* @__PURE__ */ zod.object({
})
export const AlertsListQueryParams = /* @__PURE__ */ zod.object({
+ created_by: zod
+ .string()
+ .optional()
+ .describe('Optional. Restrict results to alerts created by the user with this UUID.'),
+ insight_id: zod.number().optional().describe('Optional. Restrict results to alerts on this insight ID.'),
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
+ search: zod
+ .string()
+ .optional()
+ .describe(
+ 'Optional. Fuzzy match against alert `name` using Postgres trigram word similarity (handles typos, transpositions, and prefix-as-you-type). Results are ordered by relevance, then creation time. Capped at 200 characters; longer queries return a 400 error.'
+ ),
})
export const AlertsCreateParams = /* @__PURE__ */ zod.object({
diff --git a/services/mcp/src/tools/generated/alerts.ts b/services/mcp/src/tools/generated/alerts.ts
index f1e75f1086e8..8808e002985c 100644
--- a/services/mcp/src/tools/generated/alerts.ts
+++ b/services/mcp/src/tools/generated/alerts.ts
@@ -215,8 +215,11 @@ const alertsList = (): ToolBase<typeof AlertsListSchema, WithPostHogUrl<Schemas.
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/alerts/`,
query: {
+ created_by: params.created_by,
+ insight_id: params.insight_id,
limit: params.limit,
offset: params.offset,
+ search: params.search,
},
})
return await withPostHogUrl(context, result, '/insights?tab=alerts')
diff --git a/services/mcp/tests/tools/alerts.integration.test.ts b/services/mcp/tests/tools/alerts.integration.test.ts
index 585e650c7d82..88dd9255a29b 100644
--- a/services/mcp/tests/tools/alerts.integration.test.ts
+++ b/services/mcp/tests/tools/alerts.integration.test.ts
@@ -18,6 +18,7 @@ describe('Alerts', { concurrent: false }, () => {
let context: Context
let insightId: number
let currentUserId: number
+ let currentUserUuid: string
const createdAlertIds: string[] = []
const listTool = GENERATED_TOOLS['alerts-list']!()
@@ -44,11 +45,12 @@ describe('Alerts', { concurrent: false }, () => {
insightId = insight.id
// Fetch the current user ID — required for subscribed_users
- const user = await context.api.request<{ id: number }>({
+ const user = await context.api.request<{ id: number; uuid: string }>({
method: 'GET',
path: '/api/users/@me/',
})
currentUserId = user.id
+ currentUserUuid = user.uuid
})
afterEach(async () => {
@@ -103,6 +105,34 @@ describe('Alerts', { concurrent: false }, () => {
expect(Array.isArray(data.results)).toBe(true)
expect(data.results.length).toBeLessThanOrEqual(1)
})
+
+ it('should filter by search', async () => {
+ const name = `mcp-search-alert-${generateUniqueKey('search')}`
+ const created = await createTool.handler(context, makeAlertParams({ name }))
+ const alert = parseToolResponse(created)
+ createdAlertIds.push(alert.id)
+
+ const result = await listTool.handler(context, { search: 'mcp-search-alert' })
+ const data = parseToolResponse(result)
+
+ const found = data.results.find((a: { id: string }) => a.id === alert.id)
+ expect(found).toBeTruthy()
+ expect(found.name).toBe(name)
+ })
+
+ it('should filter by created_by uuid', async () => {
+ const name = `mcp-created-by-alert-${generateUniqueKey('creator')}`
+ const created = await createTool.handler(context, makeAlertParams({ name }))
+ const alert = parseToolResponse(created)
+ createdAlertIds.push(alert.id)
+
+ const result = await listTool.handler(context, { created_by: currentUserUuid })
+ const data = parseToolResponse(result)
+
+ const found = data.results.find((a: { id: string }) => a.id === alert.id)
+ expect(found).toBeTruthy()
+ expect(found.created_by?.uuid).toBe(currentUserUuid)
+ })
})
describe('alert-create tool', () => {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alerts-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alerts-list.json
index 8331b796ac73..b891ba8c2a3f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alerts-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alerts-list.json
@@ -1,6 +1,14 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
+ "created_by": {
+ "description": "Optional. Restrict results to alerts created by the user with this UUID.",
+ "type": "string"
+ },
+ "insight_id": {
+ "description": "Optional. Restrict results to alerts on this insight ID.",
+ "type": "number"
+ },
"limit": {
"description": "Number of results to return per page.",
"type": "number"
@@ -8,6 +16,10 @@
"offset": {
"description": "The initial index from which to return the results.",
"type": "number"
+ },
+ "search": {
+ "description": "Optional. Fuzzy match against alert `name` using Postgres trigram word similarity (handles typos, transpositions, and prefix-as-you-type). Results are ordered by relevance, then creation time. Capped at 200 characters; longer queries return a 400 error.",
+ "type": "string"
}
},
"type": "object"