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(web-analytics): add API and MCP tool for custom bot rules (#94551)

Lucas Ricoy5cea065adc0e
diff --git a/products/web_analytics/backend/api/custom_bot_rules.py b/products/web_analytics/backend/api/custom_bot_rules.py
new file mode 100644
index 000000000000..37abdff365da
--- /dev/null
+++ b/products/web_analytics/backend/api/custom_bot_rules.py
@@ -0,0 +1,162 @@
+from typing import Any
+from uuid import uuid4
+
+from django.db import transaction
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import serializers, viewsets
+from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.schema import CustomBotDefinition
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models import Team
+from posthog.models.organization import OrganizationMembership
+
+from products.web_analytics.backend.hogql_queries.custom_bot_definitions import (
+ CIDR_MATCHER,
+ CUSTOM_BOT_FIELDS,
+ MAX_CUSTOM_BOT_DEFINITIONS,
+ PATTERN_MATCHERS,
+ assert_patterns_compile,
+ compiled_patterns,
+ validate_definition,
+)
+
+_MATCHERS = (*PATTERN_MATCHERS, CIDR_MATCHER)
+_FIELD_LIST = ", ".join(CUSTOM_BOT_FIELDS)
+
+
+class CustomBotRuleSerializer(serializers.Serializer):
+ id = serializers.CharField(read_only=True, help_text="Stable id for the rule. Pass it to the delete endpoint.")
+ name = serializers.CharField(
+ help_text="Label reported by the `Bot name` property when the rule matches. Also the operator for a rule on a bot PostHog does not know."
+ )
+ key = serializers.CharField(help_text=f"Event property the rule reads. One of: {_FIELD_LIST}.")
+ matcher = serializers.CharField(
+ help_text="How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only valid with the `$ip` property)."
+ )
+ pattern = serializers.CharField(
+ help_text="Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0/24."
+ )
+ category = serializers.CharField(
+ required=False,
+ allow_blank=False,
+ help_text="Reported by the `Traffic category` property. Defaults to 'custom'. A built-in category such as ai_crawler or search_crawler relabels the traffic type too.",
+ )
+
+ def validate_key(self, value: str) -> str:
+ if value not in CUSTOM_BOT_FIELDS:
+ raise serializers.ValidationError(f"Must be one of: {_FIELD_LIST}.")
+ return value
+
+ def validate_matcher(self, value: str) -> str:
+ if value not in _MATCHERS:
+ raise serializers.ValidationError(f"Must be one of: {', '.join(_MATCHERS)}.")
+ return value
+
+
+class CustomBotRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ """A project's own bot rules, stored on the team and read by `Is bot`, `Bot name`, and the
+ traffic-type properties everywhere HogQL runs. A rule extends the built-in bot list rather than
+ replacing it, so a project can flag a scraper PostHog does not know about."""
+
+ scope_object = "web_analytics"
+ serializer_class = CustomBotRuleSerializer
+
+ def _definitions(self) -> list[dict[str, Any]]:
+ return list((self.team.modifiers or {}).get("customBotDefinitions") or [])
+
+ def _require_project_admin(self) -> None:
+ # A rule reshapes bot classification across the whole project, and it is stored on the
+ # admin-only `modifiers` team setting, so mutating it must not be reachable by a plain
+ # editor. This matches the team API's gate on `modifiers` and the path-cleaning endpoint.
+ level = self.user_permissions.team(self.team).effective_membership_level
+ if level is None or level < OrganizationMembership.Level.ADMIN:
+ raise PermissionDenied("Only project admins can change bot rules.")
+
+ @staticmethod
+ def _save(team: Team, definitions: list[dict[str, Any]]) -> None:
+ # Merge so replacing the rules never wipes another modifier the team relies on.
+ modifiers = dict(team.modifiers or {})
+ modifiers["customBotDefinitions"] = definitions
+ team.modifiers = modifiers
+ team.save(update_fields=["modifiers"])
+
+ @extend_schema(
+ operation_id="web_analytics_bot_rules_list",
+ summary="List custom bot rules",
+ description="The project's own bot rules, in the order they are checked at query time.",
+ responses={200: CustomBotRuleSerializer(many=True)},
+ )
+ def list(self, request: Request, **kwargs: Any) -> Response:
+ return Response(self._definitions())
+
+ @extend_schema(
+ operation_id="web_analytics_bot_rules_create",
+ summary="Create a custom bot rule",
+ description="Add one bot rule to the project. The pattern is rejected if it cannot run, because a broken rule would break every query that classifies traffic for the project.",
+ request=CustomBotRuleSerializer,
+ responses={201: CustomBotRuleSerializer},
+ )
+ def create(self, request: Request, **kwargs: Any) -> Response:
+ self._require_project_admin()
+
+ serializer = CustomBotRuleSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+
+ rule = {
+ "id": str(uuid4()),
+ "name": data["name"],
+ "key": data["key"],
+ "matcher": data["matcher"],
+ "pattern": data["pattern"],
+ }
+ if data.get("category"):
+ rule["category"] = data["category"]
+
+ # Validate (and probe ClickHouse) before locking, so the row lock is held only for the
+ # read-check-write and never across the ClickHouse round trip.
+ try:
+ definition = CustomBotDefinition(**rule)
+ validate_definition(definition)
+ assert_patterns_compile(compiled_patterns([definition]))
+ except ValueError as error:
+ raise ValidationError(str(error))
+
+ # Lock and reload the team so a concurrent create can neither drop the other's rule nor
+ # slip past the cap through a stale read of `modifiers`.
+ with transaction.atomic():
+ # Locks the Team row because the read-check-write below mutates team.modifiers itself;
+ # there is no per-product config row for bot definitions to lock instead.
+ team = Team.objects.select_for_update().get(pk=self.team.pk) # nosemgrep: hot-parent-row-select-for-update
+ definitions = list((team.modifiers or {}).get("customBotDefinitions") or [])
+ if len(definitions) >= MAX_CUSTOM_BOT_DEFINITIONS:
+ raise ValidationError(f"You can define at most {MAX_CUSTOM_BOT_DEFINITIONS} bots.")
+ self._save(team, [*definitions, rule])
+
+ return Response(rule, status=201)
+
+ @extend_schema(
+ operation_id="web_analytics_bot_rules_destroy",
+ summary="Delete a custom bot rule",
+ description="Remove one bot rule by its id. The built-in bot list is unaffected.",
+ responses={204: None},
+ )
+ def destroy(self, request: Request, pk: str | None = None, **kwargs: Any) -> Response:
+ self._require_project_admin()
+
+ with transaction.atomic():
+ # Locks the Team row because the read-check-write below mutates team.modifiers itself;
+ # there is no per-product config row for bot definitions to lock instead.
+ team = Team.objects.select_for_update().get(pk=self.team.pk) # nosemgrep: hot-parent-row-select-for-update
+ definitions = list((team.modifiers or {}).get("customBotDefinitions") or [])
+ remaining = [definition for definition in definitions if definition["id"] != pk]
+ if len(remaining) == len(definitions):
+ raise NotFound("No such bot rule.")
+ self._save(team, remaining)
+
+ return Response(status=204)
diff --git a/products/web_analytics/backend/api/test/test_custom_bot_rules.py b/products/web_analytics/backend/api/test/test_custom_bot_rules.py
new file mode 100644
index 000000000000..0eef6fda4812
--- /dev/null
+++ b/products/web_analytics/backend/api/test/test_custom_bot_rules.py
@@ -0,0 +1,83 @@
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models.organization import OrganizationMembership
+
+
+class TestCustomBotRulesAPI(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # A rule is stored on the admin-only `modifiers` setting, so mutating it needs project admin.
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ def _url(self, suffix: str = "") -> str:
+ return f"/api/projects/{self.team.id}/web_analytics_bot_rules/{suffix}"
+
+ def test_non_admin_cannot_mutate_but_can_list(self) -> None:
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ create = self.client.post(
+ self._url(),
+ {"name": "Acme", "key": "$raw_user_agent", "matcher": "contains", "pattern": "AcmeBot"},
+ )
+ assert create.status_code == status.HTTP_403_FORBIDDEN, create.json()
+ assert self.client.delete(self._url("any-id/")).status_code == status.HTTP_403_FORBIDDEN
+ # Reading the rules is not gated.
+ assert self.client.get(self._url()).status_code == status.HTTP_200_OK
+
+ def test_create_list_and_delete_round_trip(self) -> None:
+ create = self.client.post(
+ self._url(),
+ {"name": "Office scraper", "key": "$ip", "matcher": "cidr", "pattern": "192.0.2.0/24"},
+ )
+ assert create.status_code == status.HTTP_201_CREATED, create.json()
+ rule_id = create.json()["id"]
+
+ self.team.refresh_from_db()
+ stored = self.team.modifiers["customBotDefinitions"]
+ assert [rule["name"] for rule in stored] == ["Office scraper"]
+
+ listed = self.client.get(self._url())
+ assert [rule["id"] for rule in listed.json()] == [rule_id]
+
+ deleted = self.client.delete(self._url(f"{rule_id}/"))
+ assert deleted.status_code == status.HTTP_204_NO_CONTENT
+ self.team.refresh_from_db()
+ assert self.team.modifiers["customBotDefinitions"] == []
+
+ def test_create_preserves_other_modifiers(self) -> None:
+ self.team.modifiers = {"bounceRateDurationSeconds": 42}
+ self.team.save()
+
+ create = self.client.post(
+ self._url(),
+ {"name": "Acme", "key": "$raw_user_agent", "matcher": "contains", "pattern": "AcmeBot"},
+ )
+ assert create.status_code == status.HTTP_201_CREATED, create.json()
+
+ self.team.refresh_from_db()
+ assert self.team.modifiers["bounceRateDurationSeconds"] == 42
+ assert len(self.team.modifiers["customBotDefinitions"]) == 1
+
+ @parameterized.expand(
+ [
+ ("unknown property", {"key": "$nope", "matcher": "contains", "pattern": "AcmeBot"}),
+ ("unknown matcher", {"key": "$raw_user_agent", "matcher": "startswith", "pattern": "AcmeBot"}),
+ ("cidr on a non-ip property", {"key": "$raw_user_agent", "matcher": "cidr", "pattern": "192.0.2.0/24"}),
+ ("regex clickhouse cannot run", {"key": "$raw_user_agent", "matcher": "regex", "pattern": "(?=lookahead)"}),
+ ("blank category", {"key": "$raw_user_agent", "matcher": "contains", "pattern": "AcmeBot", "category": ""}),
+ ]
+ )
+ def test_rejects_unusable_rules(self, _name: str, body: dict) -> None:
+ response = self.client.post(self._url(), {"name": "x", **body})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ self.team.refresh_from_db()
+ assert (self.team.modifiers or {}).get("customBotDefinitions", []) == []
+
+ def test_delete_unknown_id_is_not_found(self) -> None:
+ response = self.client.delete(self._url("does-not-exist/"))
+ assert response.status_code == status.HTTP_404_NOT_FOUND
diff --git a/products/web_analytics/backend/routes.py b/products/web_analytics/backend/routes.py
index 9e85afd7d269..acf32e0edbab 100644
--- a/products/web_analytics/backend/routes.py
+++ b/products/web_analytics/backend/routes.py
@@ -1,6 +1,7 @@
from posthog.api.routing import RouterRegistry
from products.web_analytics.backend.api import WebAnalyticsViewSet
+from products.web_analytics.backend.api.custom_bot_rules import CustomBotRuleViewSet
from products.web_analytics.backend.api.heatmaps_api import (
HeatmapScreenshotViewSet,
HeatmapViewSet,
@@ -63,3 +64,9 @@ def register_routes(routers: RouterRegistry) -> None:
"project_web_analytics_path_cleaning_suggestions",
["team_id"],
)
+ routers.projects.register(
+ r"web_analytics_bot_rules",
+ CustomBotRuleViewSet,
+ "project_web_analytics_bot_rules",
+ ["team_id"],
+ )
diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.ts
index 4659a40190f8..5a2a648fefac 100644
--- a/products/web_analytics/frontend/generated/api.schemas.ts
+++ b/products/web_analytics/frontend/generated/api.schemas.ts
@@ -691,6 +691,21 @@ export interface RecordVisitResponseApi {
recorded: boolean
}
+export interface CustomBotRuleApi {
+ /** Stable id for the rule. Pass it to the delete endpoint. */
+ readonly id: string
+ /** Label reported by the `Bot name` property when the rule matches. Also the operator for a rule on a bot PostHog does not know. */
+ name: string
+ /** Event property the rule reads. One of: $raw_user_agent, $ip, $lib, $host, $pathname, $current_url, $browser, $os, $browser_language, $screen_width, $screen_height, $geoip_country_code, $referrer, $referring_domain. */
+ key: string
+ /** How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only valid with the `$ip` property). */
+ matcher: string
+ /** Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0/24. */
+ pattern: string
+ /** Reported by the `Traffic category` property. Defaults to 'custom'. A built-in category such as ai_crawler or search_crawler relabels the traffic type too. */
+ category?: string
+}
+
export interface ContentAutopilotSiteProfileApi {
readonly id: string
/**
diff --git a/products/web_analytics/frontend/generated/api.ts b/products/web_analytics/frontend/generated/api.ts
index d85864cc7ea0..86ee7613f0ef 100644
--- a/products/web_analytics/frontend/generated/api.ts
+++ b/products/web_analytics/frontend/generated/api.ts
@@ -21,6 +21,7 @@ import type {
ContentAutopilotSiteDiscoveryRequestApi,
ContentAutopilotSiteDiscoveryResponseApi,
ContentAutopilotSiteProfileApi,
+ CustomBotRuleApi,
GeneratePathCleaningSuggestionResponseApi,
HeatmapEventsResponseApi,
HeatmapPreflightRequestApi,
@@ -577,6 +578,64 @@ export const webAnalyticsAchievementsRecordVisit = async (
})
}
+export const getWebAnalyticsBotRulesListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/web_analytics_bot_rules/`
+}
+
+/**
+ * The project's own bot rules, in the order they are checked at query time.
+ * @summary List custom bot rules
+ */
+export const webAnalyticsBotRulesList = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<CustomBotRuleApi[]> => {
+ return apiMutator<CustomBotRuleApi[]>(getWebAnalyticsBotRulesListUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getWebAnalyticsBotRulesCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/web_analytics_bot_rules/`
+}
+
+/**
+ * Add one bot rule to the project. The pattern is rejected if it cannot run, because a broken rule would break every query that classifies traffic for the project.
+ * @summary Create a custom bot rule
+ */
+export const webAnalyticsBotRulesCreate = async (
+ projectId: string,
+ customBotRuleApi: NonReadonly<CustomBotRuleApi>,
+ options?: RequestInit
+): Promise<CustomBotRuleApi> => {
+ return apiMutator<CustomBotRuleApi>(getWebAnalyticsBotRulesCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(customBotRuleApi),
+ })
+}
+
+export const getWebAnalyticsBotRulesDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/web_analytics_bot_rules/${id}/`
+}
+
+/**
+ * Remove one bot rule by its id. The built-in bot list is unaffected.
+ * @summary Delete a custom bot rule
+ */
+export const webAnalyticsBotRulesDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getWebAnalyticsBotRulesDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getWebAnalyticsContentAutopilotProfilesListUrl = (
projectId: string,
params?: WebAnalyticsContentAutopilotProfilesListParams
diff --git a/products/web_analytics/frontend/generated/api.zod.ts b/products/web_analytics/frontend/generated/api.zod.ts
index 320f051e2f87..f3c7b1d2989f 100644
--- a/products/web_analytics/frontend/generated/api.zod.ts
+++ b/products/web_analytics/frontend/generated/api.zod.ts
@@ -256,6 +256,39 @@ export const WebAnalyticsAchievementsRecordInteractionBody = /* @__PURE__ */ zod
),
})
+/**
+ * Add one bot rule to the project. The pattern is rejected if it cannot run, because a broken rule would break every query that classifies traffic for the project.
+ * @summary Create a custom bot rule
+ */
+export const WebAnalyticsBotRulesCreateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .describe(
+ 'Label reported by the `Bot name` property when the rule matches. Also the operator for a rule on a bot PostHog does not know.'
+ ),
+ key: zod
+ .string()
+ .describe(
+ 'Event property the rule reads. One of: $raw_user_agent, $ip, $lib, $host, $pathname, $current_url, $browser, $os, $browser_language, $screen_width, $screen_height, $geoip_country_code, $referrer, $referring_domain.'
+ ),
+ matcher: zod
+ .string()
+ .describe(
+ "How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only valid with the `$ip` property)."
+ ),
+ pattern: zod
+ .string()
+ .describe(
+ "Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0\/24."
+ ),
+ category: zod
+ .string()
+ .optional()
+ .describe(
+ "Reported by the `Traffic category` property. Defaults to 'custom'. A built-in category such as ai_crawler or search_crawler relabels the traffic type too."
+ ),
+})
+
export const webAnalyticsContentAutopilotProfilesCreateBodyNameMax = 255
export const webAnalyticsContentAutopilotProfilesCreateBodyDomainMax = 2048
diff --git a/products/web_analytics/mcp/tools.yaml b/products/web_analytics/mcp/tools.yaml
index fa9507d21457..cdb807292cf2 100644
--- a/products/web_analytics/mcp/tools.yaml
+++ b/products/web_analytics/mcp/tools.yaml
@@ -161,6 +161,50 @@ tools:
web-analytics-achievements-update-preferences:
operation: web_analytics_achievements_update_preferences
enabled: false
+ web-analytics-bot-rules-create:
+ operation: web_analytics_bot_rules_create
+ enabled: true
+ scopes:
+ - web_analytics:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Create a custom bot rule
+ description: >
+ Add one bot rule so traffic matching it classifies as a bot. Set `key` to the event property to read (such
+ as $raw_user_agent or $ip), `matcher` to 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr'
+ (an IP network range, only with $ip), `pattern` to the value to match, and `name` to the label to report.
+ Optionally set `category` to a built-in category like ai_crawler to relabel the traffic type. The rule is
+ rejected if its pattern cannot run. Use this when a scraper is hitting the site that the built-in list
+ misses.
+ web-analytics-bot-rules-destroy:
+ operation: web_analytics_bot_rules_destroy
+ enabled: true
+ scopes:
+ - web_analytics:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: false
+ title: Delete a custom bot rule
+ description: |
+ Delete one bot rule by its `id` (from the list tool). The built-in bot list is unaffected.
+ web-analytics-bot-rules-list:
+ operation: web_analytics_bot_rules_list
+ enabled: true
+ scopes:
+ - web_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List custom bot rules
+ description: >
+ List the project's own bot rules. Each rule names an event property, how to match it, a value, and the label
+ reported when it matches. Rules extend PostHog's built-in bot list, so `Is bot` (isLikelyBot), `Bot name`,
+ and `Traffic category` reflect them everywhere — insights, web analytics, session filters, and SQL.
web-analytics-content-autopilot-profiles-create:
operation: web_analytics_content_autopilot_profiles_create
enabled: false
diff --git a/products/web_analytics/skills/filtering-bot-traffic/SKILL.md b/products/web_analytics/skills/filtering-bot-traffic/SKILL.md
index ce295c012910..0903f00c74ff 100644
--- a/products/web_analytics/skills/filtering-bot-traffic/SKILL.md
+++ b/products/web_analytics/skills/filtering-bot-traffic/SKILL.md
@@ -149,6 +149,34 @@ GROUP BY bot, operator
ORDER BY hits DESC
```
+## Adding a bot PostHog doesn't know yet
+
+The built-in list only covers self-declared user agents PostHog already knows. When a
+scraper matters to a project but isn't detected — an internal load test, a partner
+integration, a niche crawler — add a **custom bot rule** instead of waiting for the
+built-in list to catch up. Rules extend the same classification surface, so `Is bot`
+(`isLikelyBot`), `Bot name`, and `Traffic category` reflect them everywhere HogQL runs.
+
+A rule matches one event property — the user agent by default, but also `$ip`, `$lib`,
+`$host`, `$pathname`, `$current_url`, `$browser`, `$os`, `$browser_language`,
+`$screen_width`, `$screen_height`, `$geoip_country_code`, `$referrer`, or
+`$referring_domain` — using `contains` (case-insensitive substring), `regex` (RE2), or
+`cidr` (an IP range, only valid with `$ip`). Set `name` to the label reported by `Bot
+name`, and optionally `category` to a built-in category like `ai_crawler` to relabel the
+traffic type.
+
+Three ways to manage rules:
+
+- **Settings UI** — Settings → Environment → Custom bots.
+- **MCP tools** — `web-analytics-bot-rules-list`, `web-analytics-bot-rules-create`,
+ `web-analytics-bot-rules-destroy`. Prefer these when driving PostHog through an agent.
+- **REST API** — `GET/POST /api/projects/{project_id}/web_analytics_bot_rules/` and
+ `DELETE /api/projects/{project_id}/web_analytics_bot_rules/{id}/`.
+
+Listing is open to project members; creating and deleting require a **project admin**
+(they mutate the admin-only `modifiers` team setting). A rule whose pattern can't run is
+rejected on save, so a bad rule can never take down the project's classification queries.
+
## Seeing bots that don't run JavaScript
Most crawlers and AI agents never execute JS, so `posthog-js` never fires a `$pageview` for
diff --git a/pyproject.toml b/pyproject.toml
index cf0391f6c718..0386ac4e3ab8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -777,6 +777,7 @@ ignore_imports = [
"products.skills.backend.routes -> products.skills.backend.api.skills",
"products.surveys.backend.routes -> products.surveys.backend.api.survey",
"products.web_analytics.backend.routes -> products.web_analytics.backend.api",
+ "products.web_analytics.backend.routes -> products.web_analytics.backend.api.custom_bot_rules",
"products.web_analytics.backend.routes -> products.web_analytics.backend.api.heatmaps_api",
"products.web_analytics.backend.routes -> products.web_analytics.backend.api.web_analytics_achievements",
"products.web_analytics.backend.routes -> products.web_analytics.backend.api.web_analytics_filter_preset",
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 05327851b32c..cf6c182ba27c 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -12256,6 +12256,48 @@
"readOnlyHint": false
}
},
+ "web-analytics-bot-rules-create": {
+ "description": "Add one bot rule so traffic matching it classifies as a bot. Set `key` to the event property to read (such as $raw_user_agent or $ip), `matcher` to 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only with $ip), `pattern` to the value to match, and `name` to the label to report. Optionally set `category` to a built-in category like ai_crawler to relabel the traffic type. The rule is rejected if its pattern cannot run. Use this when a scraper is hitting the site that the built-in list misses.",
+ "category": "Web analytics",
+ "feature": "web_analytics",
+ "summary": "Create a custom bot rule",
+ "title": "Create a custom bot rule",
+ "required_scopes": ["web_analytics:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "web-analytics-bot-rules-destroy": {
+ "description": "Delete one bot rule by its `id` (from the list tool). The built-in bot list is unaffected.",
+ "category": "Web analytics",
+ "feature": "web_analytics",
+ "summary": "Delete a custom bot rule",
+ "title": "Delete a custom bot rule",
+ "required_scopes": ["web_analytics:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "web-analytics-bot-rules-list": {
+ "description": "List the project's own bot rules. Each rule names an event property, how to match it, a value, and the label reported when it matches. Rules extend PostHog's built-in bot list, so `Is bot` (isLikelyBot), `Bot name`, and `Traffic category` reflect them everywhere — insights, web analytics, session filters, and SQL.",
+ "category": "Web analytics",
+ "feature": "web_analytics",
+ "summary": "List custom bot rules",
+ "title": "List custom bot rules",
+ "required_scopes": ["web_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"web-analytics-path-cleaning-suggestions-apply": {
"description": "Apply a suggested set of path-cleaning rules by its health-issue `id`, merging them into the project's path cleaning configuration. Existing rules are never overwritten — only new rules are appended — and the underlying `path_cleaning_suggestions` health issue is resolved. Returns how many rules were added. Requires project admin (the same gate as editing path cleaning rules in team settings). Applying changes historical numbers in every Web analytics and Paths chart that has cleaning enabled, so confirm with the user before calling this.",
"category": "Web analytics",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index eaecc2e17296..56c58347c8ee 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -12901,6 +12901,48 @@
"readOnlyHint": false
}
},
+ "web-analytics-bot-rules-create": {
+ "description": "Add one bot rule so traffic matching it classifies as a bot. Set `key` to the event property to read (such as $raw_user_agent or $ip), `matcher` to 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only with $ip), `pattern` to the value to match, and `name` to the label to report. Optionally set `category` to a built-in category like ai_crawler to relabel the traffic type. The rule is rejected if its pattern cannot run. Use this when a scraper is hitting the site that the built-in list misses.",
+ "category": "Web analytics",
+ "feature": "web_analytics",
+ "summary": "Create a custom bot rule",
+ "title": "Create a custom bot rule",
+ "required_scopes": ["web_analytics:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "web-analytics-bot-rules-destroy": {
+ "description": "Delete one bot rule by its `id` (from the list tool). The built-in bot list is unaffected.",
+ "category": "Web analytics",
+ "feature": "web_analytics",
+ "summary": "Delete a custom bot rule",
+ "title": "Delete a custom bot rule",
+ "required_scopes": ["web_analytics:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "web-analytics-bot-rules-list": {
+ "description": "List the project's own bot rules. Each rule names an event property, how to match it, a value, and the label reported when it matches. Rules extend PostHog's built-in bot list, so `Is bot` (isLikelyBot), `Bot name`, and `Traffic category` reflect them everywhere — insights, web analytics, session filters, and SQL.",
+ "category": "Web analytics",
+ "feature": "web_analytics",
+ "summary": "List custom bot rules",
+ "title": "List custom bot rules",
+ "required_scopes": ["web_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"web-analytics-path-cleaning-suggestions-apply": {
"description": "Apply a suggested set of path-cleaning rules by its health-issue `id`, merging them into the project's path cleaning configuration. Existing rules are never overwritten — only new rules are appended — and the underlying `path_cleaning_suggestions` health issue is resolved. Returns how many rules were added. Requires project admin (the same gate as editing path cleaning rules in team settings). Applying changes historical numbers in every Web analytics and Paths chart that has cleaning enabled, so confirm with the user before calling this.",
"category": "Web analytics",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e5bda54f587e..ac169e94b017 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20433,6 +20433,21 @@ export namespace Schemas {
evaluation_session_cap: number;
}
+ export interface CustomBotRule {
+ /** Stable id for the rule. Pass it to the delete endpoint. */
+ readonly id: string;
+ /** Label reported by the `Bot name` property when the rule matches. Also the operator for a rule on a bot PostHog does not know. */
+ name: string;
+ /** Event property the rule reads. One of: $raw_user_agent, $ip, $lib, $host, $pathname, $current_url, $browser, $os, $browser_language, $screen_width, $screen_height, $geoip_country_code, $referrer, $referring_domain. */
+ key: string;
+ /** How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only valid with the `$ip` property). */
+ matcher: string;
+ /** Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0/24. */
+ pattern: string;
+ /** Reported by the `Traffic category` property. Defaults to 'custom'. A built-in category such as ai_crawler or search_crawler relabels the traffic type too. */
+ category?: string;
+ }
+
/**
* * `text` - text
* * `link` - link
diff --git a/services/mcp/src/generated/web_analytics/api.ts b/services/mcp/src/generated/web_analytics/api.ts
index 274df194c130..9d06b7803b53 100644
--- a/services/mcp/src/generated/web_analytics/api.ts
+++ b/services/mcp/src/generated/web_analytics/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 10 enabled ops
+ * PostHog API - MCP 13 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -433,6 +433,72 @@ export const WebAnalyticsWeeklyDigestQueryParams = () => zod.object({
.describe('Lookback window in days (1–90). Defaults to 7.'),
})
+/**
+ * The project's own bot rules, in the order they are checked at query time.
+ * @summary List custom bot rules
+ */
+export const WebAnalyticsBotRulesListParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+/**
+ * Add one bot rule to the project. The pattern is rejected if it cannot run, because a broken rule would break every query that classifies traffic for the project.
+ * @summary Create a custom bot rule
+ */
+export const WebAnalyticsBotRulesCreateParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const WebAnalyticsBotRulesCreateBody = () => zod.object({
+ name: zod
+ .string()
+ .describe(
+ 'Label reported by the `Bot name` property when the rule matches. Also the operator for a rule on a bot PostHog does not know.'
+ ),
+ key: zod
+ .string()
+ .describe(
+ 'Event property the rule reads. One of: $raw_user_agent, $ip, $lib, $host, $pathname, $current_url, $browser, $os, $browser_language, $screen_width, $screen_height, $geoip_country_code, $referrer, $referring_domain.'
+ ),
+ matcher: zod
+ .string()
+ .describe(
+ "How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only valid with the `$ip` property)."
+ ),
+ pattern: zod
+ .string()
+ .describe(
+ "Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0\/24."
+ ),
+ category: zod
+ .string()
+ .optional()
+ .describe(
+ "Reported by the `Traffic category` property. Defaults to 'custom'. A built-in category such as ai_crawler or search_crawler relabels the traffic type too."
+ ),
+})
+
+/**
+ * Remove one bot rule by its id. The built-in bot list is unaffected.
+ * @summary Delete a custom bot rule
+ */
+export const WebAnalyticsBotRulesDestroyParams = () => zod.object({
+ id: zod.string(),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
/**
* Merges the suggestion's rules into the team's path_cleaning_filters (never overwrites existing rules) and resolves the underlying health issue. Requires project admin, matching the team API's gate on path_cleaning_filters.
* @summary Apply a path-cleaning suggestion
diff --git a/services/mcp/src/tools/generated/web_analytics.ts b/services/mcp/src/tools/generated/web_analytics.ts
index 210b8d67b666..6cd3fb4227cc 100644
--- a/services/mcp/src/tools/generated/web_analytics.ts
+++ b/services/mcp/src/tools/generated/web_analytics.ts
@@ -237,6 +237,80 @@ const heatmapsSavedUpdate = (): ToolBase<
},
})
+const WebAnalyticsBotRulesCreateSchema = () => {
+ const WebAnalyticsBotRulesCreateBody = orvalSchemas.WebAnalyticsBotRulesCreateBody()
+ return WebAnalyticsBotRulesCreateBody
+}
+
+const webAnalyticsBotRulesCreate = (): ToolBase<
+ ReturnType<typeof WebAnalyticsBotRulesCreateSchema>,
+ Schemas.CustomBotRule
+> => ({
+ name: 'web-analytics-bot-rules-create',
+ schema: WebAnalyticsBotRulesCreateSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof WebAnalyticsBotRulesCreateSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.key !== undefined) {
+ body['key'] = params.key
+ }
+ if (params.matcher !== undefined) {
+ body['matcher'] = params.matcher
+ }
+ if (params.pattern !== undefined) {
+ body['pattern'] = params.pattern
+ }
+ if (params.category !== undefined) {
+ body['category'] = params.category
+ }
+ const result = await context.api.request<Schemas.CustomBotRule>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/web_analytics_bot_rules/`,
+ body,
+ })
+ return result
+ },
+})
+
+const WebAnalyticsBotRulesDestroySchema = () => {
+ const WebAnalyticsBotRulesDestroyParams = orvalSchemas.WebAnalyticsBotRulesDestroyParams()
+ return WebAnalyticsBotRulesDestroyParams.omit({ project_id: true })
+}
+
+const webAnalyticsBotRulesDestroy = (): ToolBase<ReturnType<typeof WebAnalyticsBotRulesDestroySchema>, unknown> => ({
+ name: 'web-analytics-bot-rules-destroy',
+ schema: WebAnalyticsBotRulesDestroySchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof WebAnalyticsBotRulesDestroySchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<unknown>({
+ method: 'DELETE',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/web_analytics_bot_rules/${encodeURIComponent(String(params.id))}/`,
+ })
+ return result
+ },
+})
+
+const WebAnalyticsBotRulesListSchema = () => z.object({})
+
+const webAnalyticsBotRulesList = (): ToolBase<
+ ReturnType<typeof WebAnalyticsBotRulesListSchema>,
+ WithPostHogUrl<Schemas.CustomBotRule[]>
+> => ({
+ name: 'web-analytics-bot-rules-list',
+ schema: WebAnalyticsBotRulesListSchema(),
+ handler: async (context: Context, _params: z.infer<ReturnType<typeof WebAnalyticsBotRulesListSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.CustomBotRule[]>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/web_analytics_bot_rules/`,
+ })
+ return await withPostHogUrl(context, result, '/web')
+ },
+})
+
const WebAnalyticsPathCleaningSuggestionsApplySchema = () => {
const WebAnalyticsPathCleaningSuggestionsApplyParams = orvalSchemas.WebAnalyticsPathCleaningSuggestionsApplyParams()
return WebAnalyticsPathCleaningSuggestionsApplyParams.omit({ project_id: true })
@@ -617,6 +691,9 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'heatmaps-saved-list': heatmapsSavedList,
'heatmaps-saved-regenerate': heatmapsSavedRegenerate,
'heatmaps-saved-update': heatmapsSavedUpdate,
+ 'web-analytics-bot-rules-create': webAnalyticsBotRulesCreate,
+ 'web-analytics-bot-rules-destroy': webAnalyticsBotRulesDestroy,
+ 'web-analytics-bot-rules-list': webAnalyticsBotRulesList,
'web-analytics-path-cleaning-suggestions-apply': webAnalyticsPathCleaningSuggestionsApply,
'web-analytics-path-cleaning-suggestions-generate': webAnalyticsPathCleaningSuggestionsGenerate,
'web-analytics-weekly-digest': webAnalyticsWeeklyDigest,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/web-analytics-bot-rules-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/web-analytics-bot-rules-create.json
new file mode 100644
index 000000000000..7d1c48ee33f5
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/web-analytics-bot-rules-create.json
@@ -0,0 +1,27 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "category": {
+ "description": "Reported by the `Traffic category` property. Defaults to 'custom'. A built-in category such as ai_crawler or search_crawler relabels the traffic type too.",
+ "type": "string"
+ },
+ "key": {
+ "description": "Event property the rule reads. One of: $raw_user_agent, $ip, $lib, $host, $pathname, $current_url, $browser, $os, $browser_language, $screen_width, $screen_height, $geoip_country_code, $referrer, $referring_domain.",
+ "type": "string"
+ },
+ "matcher": {
+ "description": "How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only valid with the `$ip` property).",
+ "type": "string"
+ },
+ "name": {
+ "description": "Label reported by the `Bot name` property when the rule matches. Also the operator for a rule on a bot PostHog does not know.",
+ "type": "string"
+ },
+ "pattern": {
+ "description": "Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0/24.",
+ "type": "string"
+ }
+ },
+ "required": ["name", "key", "matcher", "pattern"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/web-analytics-bot-rules-destroy.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/web-analytics-bot-rules-destroy.json
new file mode 100644
index 000000000000..f9bfd8020ef3
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/web-analytics-bot-rules-destroy.json
@@ -0,0 +1,10 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/web-analytics-bot-rules-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/web-analytics-bot-rules-list.json
new file mode 100644
index 000000000000..7b7ea9186078
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/web-analytics-bot-rules-list.json
@@ -0,0 +1,5 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {},
+ "type": "object"
+}