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(llma): enable tagger MCP tools (#58070)

Radu Raicead6758c10ce3f
diff --git a/products/llm_analytics/backend/api/taggers.py b/products/llm_analytics/backend/api/taggers.py
index 8848dc92fd28..ea2ecd262bd7 100644
--- a/products/llm_analytics/backend/api/taggers.py
+++ b/products/llm_analytics/backend/api/taggers.py
@@ -1,3 +1,4 @@
+import json
from typing import Any, cast
from django.db import transaction
@@ -6,21 +7,34 @@ from django.db.models import Q, QuerySet
import structlog
import django_filters
from django_filters.rest_framework import DjangoFilterBackend
+from drf_spectacular.utils import OpenApiResponse, PolymorphicProxySerializer, extend_schema, extend_schema_field
from pydantic import ValidationError
-from rest_framework import serializers, viewsets
+from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.serializers import BaseSerializer
+from posthog.hogql import ast
+from posthog.hogql.query import execute_hogql_query
+
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.monitoring import Feature, monitor
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
+from posthog.cdp.validation import compile_hog
+from posthog.clickhouse.query_tagging import (
+ Feature as QueryFeature,
+ Product,
+ tag_queries,
+)
from posthog.event_usage import report_user_action
from posthog.permissions import AccessControlPermission
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
+from posthog.temporal.llm_analytics.message_utils import extract_text_from_messages
+from posthog.temporal.llm_analytics.run_evaluation import extract_event_io
+from posthog.temporal.llm_analytics.run_tagger import run_hog_tagger
from ..models.model_configuration import LLMModelConfiguration
from ..models.provider_keys import LLMProvider, LLMProviderKey
@@ -49,7 +63,7 @@ class TaggerConditionSerializer(serializers.Serializer):
)
-class TaggerConfigSerializer(serializers.Serializer):
+class LLMTaggerConfigSerializer(serializers.Serializer):
prompt = serializers.CharField(min_length=1, help_text="Prompt instructing the LLM how to tag generations")
tags = TagDefinitionSerializer(many=True, help_text="Available tags the LLM can assign")
min_tags = serializers.IntegerField(default=0, min_value=0, help_text="Minimum number of tags to apply")
@@ -76,12 +90,52 @@ class TaggerConfigSerializer(serializers.Serializer):
return data
-class TaggerModelConfigurationSerializer(serializers.Serializer):
+class HogTaggerConfigSerializer(serializers.Serializer):
+ source = serializers.CharField( # type: ignore[assignment]
+ min_length=1,
+ help_text="Hog source code to classify a generation into tags.",
+ )
+ tags = TagDefinitionSerializer(
+ many=True,
+ required=False,
+ default=list,
+ help_text="Optional tag whitelist. Leave empty to allow any tag returned by the Hog code.",
+ )
+
+
+TAGGER_CONFIG_SCHEMA = PolymorphicProxySerializer(
+ component_name="TaggerConfig",
+ serializers=[LLMTaggerConfigSerializer, HogTaggerConfigSerializer],
+ resource_type_field_name=None,
+)
+
+
+@extend_schema_field(TAGGER_CONFIG_SCHEMA)
+class TaggerConfigField(serializers.JSONField):
+ pass
+
+
+class TaggerModelConfigurationWriteSerializer(serializers.Serializer):
+ provider = serializers.ChoiceField(choices=LLMProvider.choices, help_text="LLM provider to use for this tagger.")
+ model = serializers.CharField(max_length=100, help_text="Provider model identifier to use for this tagger.")
+ provider_key_id = serializers.UUIDField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Existing LLM provider key UUID for the current project. Do not invent this value; use a real provider key "
+ "ID returned by PostHog, or omit/null when no provider key should be pinned."
+ ),
+ )
+
+ def to_internal_value(self, data: Any) -> dict[str, Any]:
+ if isinstance(data, dict) and "provider_key_name" in data:
+ raise serializers.ValidationError({"provider_key_name": "This field is read-only."})
+ return super().to_internal_value(data)
+
+
+class TaggerModelConfigurationSerializer(TaggerModelConfigurationWriteSerializer):
"""Nested serializer for model configuration."""
- provider = serializers.ChoiceField(choices=LLMProvider.choices)
- model = serializers.CharField(max_length=100)
- provider_key_id = serializers.UUIDField(required=False, allow_null=True)
provider_key_name = serializers.SerializerMethodField(read_only=True)
def get_provider_key_name(self, obj: LLMModelConfiguration) -> str | None:
@@ -98,10 +152,14 @@ class TaggerModelConfigurationSerializer(serializers.Serializer):
}
-class TaggerSerializer(serializers.ModelSerializer):
- created_by = UserBasicSerializer(read_only=True)
- model_configuration = TaggerModelConfigurationSerializer(required=False, allow_null=True)
- tagger_config = serializers.JSONField(help_text="Tagger configuration (varies by tagger_type)")
+class TaggerBaseWriteSerializer(serializers.ModelSerializer):
+ model_configuration = TaggerModelConfigurationWriteSerializer(required=False, allow_null=True)
+ tagger_config = TaggerConfigField(
+ help_text=(
+ "Tagger configuration. For tagger_type 'llm': {prompt, tags, min_tags?, max_tags?}. "
+ "For tagger_type 'hog': {source, tags?}."
+ )
+ )
tagger_type = serializers.ChoiceField(choices=TaggerType.choices, default=TaggerType.LLM)
conditions = TaggerConditionSerializer(
many=True, required=False, default=list, help_text="Conditions that scope when the tagger runs"
@@ -110,7 +168,6 @@ class TaggerSerializer(serializers.ModelSerializer):
class Meta:
model = Tagger
fields = [
- "id",
"name",
"description",
"enabled",
@@ -118,14 +175,9 @@ class TaggerSerializer(serializers.ModelSerializer):
"tagger_config",
"conditions",
"model_configuration",
- "created_at",
- "updated_at",
- "created_by",
- "deleted",
]
- read_only_fields = ["id", "created_at", "updated_at", "created_by"]
- def validate(self, data: dict) -> dict:
+ def validate(self, data: dict[str, Any]) -> dict[str, Any]:
tagger_type = data.get("tagger_type", self.instance.tagger_type if self.instance else TaggerType.LLM)
tagger_config = data.get("tagger_config")
@@ -193,7 +245,7 @@ class TaggerSerializer(serializers.ModelSerializer):
model_config.save()
return model_config
- def create(self, validated_data: dict) -> Tagger:
+ def create(self, validated_data: dict[str, Any]) -> Tagger:
request = self.context["request"]
team = self.context["get_team"]()
validated_data["team"] = team
@@ -211,7 +263,7 @@ class TaggerSerializer(serializers.ModelSerializer):
)
return super().create(validated_data)
- def update(self, instance: Tagger, validated_data: dict) -> Tagger:
+ def update(self, instance: Tagger, validated_data: dict[str, Any]) -> Tagger:
model_config_data = validated_data.pop("model_configuration", None)
# Transaction wraps the model_configuration update and the tagger save so a failed
@@ -225,6 +277,34 @@ class TaggerSerializer(serializers.ModelSerializer):
return super().update(instance, validated_data)
+class TaggerCreateSerializer(TaggerBaseWriteSerializer):
+ def to_internal_value(self, data: Any) -> dict[str, Any]:
+ if isinstance(data, dict) and "deleted" in data:
+ raise serializers.ValidationError({"deleted": "This field cannot be set when creating a tagger."})
+ return super().to_internal_value(data)
+
+
+class TaggerUpdateSerializer(TaggerBaseWriteSerializer):
+ class Meta(TaggerBaseWriteSerializer.Meta):
+ fields = [*TaggerBaseWriteSerializer.Meta.fields, "deleted"]
+
+
+class TaggerSerializer(TaggerBaseWriteSerializer):
+ created_by = UserBasicSerializer(read_only=True)
+ model_configuration = TaggerModelConfigurationSerializer(required=False, allow_null=True)
+
+ class Meta(TaggerBaseWriteSerializer.Meta):
+ fields = [
+ "id",
+ *TaggerBaseWriteSerializer.Meta.fields,
+ "created_at",
+ "updated_at",
+ "created_by",
+ "deleted",
+ ]
+ read_only_fields = ["id", "created_at", "updated_at", "created_by"]
+
+
class TaggerFilter(django_filters.FilterSet):
search = django_filters.CharFilter(method="filter_search", help_text="Search in name or description")
enabled = django_filters.BooleanFilter(help_text="Filter by enabled status")
@@ -254,6 +334,57 @@ class TaggerFilter(django_filters.FilterSet):
return queryset
+class TestHogTaggerTagSerializer(serializers.Serializer):
+ # Enforce the same {name, description?} shape as TagDefinitionSerializer so a payload
+ # like {"tags": [{}]} is rejected with a 400 instead of blowing up on KeyError downstream.
+ name = serializers.CharField(max_length=100, help_text="Tag identifier to allow in Hog test results.")
+ description = serializers.CharField(
+ max_length=500,
+ required=False,
+ default="",
+ allow_blank=True,
+ help_text="Optional description for the tag.",
+ )
+
+
+class TestHogTaggerRequestSerializer(serializers.Serializer):
+ source = serializers.CharField(
+ required=True,
+ min_length=1,
+ help_text="Hog source code to test. Return a tag name string, a list of tag name strings, or null.",
+ ) # type: ignore[assignment]
+ sample_count = serializers.IntegerField(
+ required=False,
+ default=5,
+ min_value=1,
+ max_value=10,
+ help_text="Number of recent $ai_generation events to test against (1-10, default 5).",
+ )
+ tags = TestHogTaggerTagSerializer(
+ many=True,
+ required=False,
+ default=list,
+ help_text="Optional tag whitelist. Returned tags outside this list are filtered out.",
+ )
+
+
+class TestHogTaggerResultItemSerializer(serializers.Serializer):
+ event_uuid = serializers.CharField(help_text="UUID of the sampled $ai_generation event.")
+ trace_id = serializers.CharField(allow_null=True, required=False, help_text="Trace ID if available.")
+ input_preview = serializers.CharField(help_text="First 200 characters of the generation input.")
+ output_preview = serializers.CharField(help_text="First 200 characters of the generation output.")
+ tags = serializers.ListField(child=serializers.CharField(), help_text="Tag names returned by the Hog code.")
+ reasoning = serializers.CharField(allow_blank=True, help_text="Text written to stdout by the Hog code.")
+ error = serializers.CharField(allow_null=True, required=False, help_text="Error message if the Hog code failed.")
+
+
+class TestHogTaggerResponseSerializer(serializers.Serializer):
+ results = TestHogTaggerResultItemSerializer(many=True, help_text="Per-event Hog tagger test results.")
+ message = serializers.CharField(
+ required=False, help_text="Optional message, for example when no recent AI events were found."
+ )
+
+
class TaggerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDestroyModel, viewsets.ModelViewSet):
scope_object = "tagger"
permission_classes = [IsAuthenticated, AccessControlPermission]
@@ -262,6 +393,13 @@ class TaggerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDes
filter_backends = [DjangoFilterBackend]
filterset_class = TaggerFilter
+ def get_serializer_class(self) -> type[BaseSerializer[Any]]:
+ if self.action == "create":
+ return TaggerCreateSerializer
+ if self.action in ("update", "partial_update"):
+ return TaggerUpdateSerializer
+ return super().get_serializer_class()
+
def safely_get_queryset(self, queryset: QuerySet[Tagger]) -> QuerySet[Tagger]:
queryset = (
queryset.filter(team_id=self.team_id)
@@ -273,7 +411,7 @@ class TaggerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDes
return queryset
- def perform_create(self, serializer: BaseSerializer) -> None:
+ def perform_create(self, serializer: BaseSerializer[Any]) -> None:
instance = serializer.save()
conditions = instance.conditions or []
@@ -297,7 +435,7 @@ class TaggerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDes
request=self.request,
)
- def perform_update(self, serializer: BaseSerializer) -> None:
+ def perform_update(self, serializer: BaseSerializer[Any]) -> None:
instance_before = cast(Tagger, serializer.instance)
is_deletion = serializer.validated_data.get("deleted") is True and not instance_before.deleted
old_enabled_value = instance_before.enabled
@@ -336,56 +474,66 @@ class TaggerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDes
request=self.request,
)
+ def _serialize_saved_tagger(self, tagger: Tagger) -> dict[str, Any]:
+ hydrated_tagger = self.get_queryset().get(pk=tagger.pk)
+ return TaggerSerializer(hydrated_tagger, context=self.get_serializer_context()).data
+
@llma_track_latency("llma_taggers_list")
@monitor(feature=Feature.LLM_ANALYTICS, endpoint="llma_taggers_list", method="GET")
- def list(self, request: Request, *args, **kwargs) -> Response:
+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
return super().list(request, *args, **kwargs)
@llma_track_latency("llma_taggers_retrieve")
@monitor(feature=Feature.LLM_ANALYTICS, endpoint="llma_taggers_retrieve", method="GET")
- def retrieve(self, request: Request, *args, **kwargs) -> Response:
+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
return super().retrieve(request, *args, **kwargs)
+ @extend_schema(request=TaggerCreateSerializer, responses={201: OpenApiResponse(response=TaggerSerializer)})
@llma_track_latency("llma_taggers_create")
@monitor(feature=Feature.LLM_ANALYTICS, endpoint="llma_taggers_create", method="POST")
- def create(self, request: Request, *args, **kwargs) -> Response:
- return super().create(request, *args, **kwargs)
-
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ serializer = self.get_serializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ self.perform_create(serializer)
+ instance = cast(Tagger, serializer.instance)
+ response_data = self._serialize_saved_tagger(instance)
+ headers = self.get_success_headers(response_data)
+ return Response(response_data, status=status.HTTP_201_CREATED, headers=headers)
+
+ @extend_schema(request=TaggerUpdateSerializer, responses={200: OpenApiResponse(response=TaggerSerializer)})
@llma_track_latency("llma_taggers_update")
@monitor(feature=Feature.LLM_ANALYTICS, endpoint="llma_taggers_update", method="PUT")
- def update(self, request: Request, *args, **kwargs) -> Response:
- return super().update(request, *args, **kwargs)
+ def update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ return self._update_tagger(request=request, partial=False)
+ @extend_schema(request=TaggerUpdateSerializer, responses={200: OpenApiResponse(response=TaggerSerializer)})
@llma_track_latency("llma_taggers_partial_update")
@monitor(feature=Feature.LLM_ANALYTICS, endpoint="llma_taggers_partial_update", method="PATCH")
- def partial_update(self, request: Request, *args, **kwargs) -> Response:
- return super().partial_update(request, *args, **kwargs)
+ def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ return self._update_tagger(request=request, partial=True)
+
+ def _update_tagger(self, request: Request, partial: bool) -> Response:
+ instance = self.get_object()
+ serializer = self.get_serializer(
+ instance,
+ data=request.data,
+ partial=partial,
+ )
+ serializer.is_valid(raise_exception=True)
+ self.perform_update(serializer)
+
+ if getattr(instance, "_prefetched_objects_cache", None):
+ instance._prefetched_objects_cache = {}
- @action(detail=False, methods=["post"], url_path="test_hog")
+ updated_instance = cast(Tagger, serializer.instance)
+ return Response(self._serialize_saved_tagger(updated_instance), status=status.HTTP_200_OK)
+
+ @extend_schema(request=TestHogTaggerRequestSerializer, responses=TestHogTaggerResponseSerializer)
+ @action(detail=False, methods=["post"], url_path="test_hog", required_scopes=["tagger:read"])
@llma_track_latency("llma_taggers_test_hog")
@monitor(feature=Feature.LLM_ANALYTICS, endpoint="llma_taggers_test_hog", method="POST")
def test_hog(self, request: Request, **kwargs) -> Response:
"""Test Hog tagger code against sample events without saving."""
- import json
-
- from posthog.hogql import ast
- from posthog.hogql.query import execute_hogql_query
-
- from posthog.cdp.validation import compile_hog
- from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
- from posthog.temporal.llm_analytics.message_utils import extract_text_from_messages
- from posthog.temporal.llm_analytics.run_evaluation import extract_event_io
-
- # The Hog tagger workflow ships in the next PR of the stack. Surface a clean 503
- # if /test_hog is hit before that PR is deployed, instead of a 500 from ImportError.
- try:
- from posthog.temporal.llm_analytics.run_tagger import run_hog_tagger
- except ImportError:
- return Response(
- {"error": "Hog tagger runtime is not yet deployed in this environment."},
- status=503,
- )
-
test_serializer = TestHogTaggerRequestSerializer(data=request.data)
if not test_serializer.is_valid():
return Response({"error": test_serializer.errors}, status=400)
@@ -438,7 +586,7 @@ class TaggerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDes
limit=ast.Constant(value=sample_count),
)
- tag_queries(product=Product.LLM_ANALYTICS, feature=Feature.QUERY)
+ tag_queries(product=Product.LLM_ANALYTICS, feature=QueryFeature.QUERY)
response = execute_hogql_query(query=query, team=team, limit_context=None)
if not response.results:
@@ -480,16 +628,3 @@ class TaggerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDes
)
return Response({"results": results})
-
-
-class TestHogTaggerTagSerializer(serializers.Serializer):
- # Enforce the same {name, description?} shape as TagDefinitionSerializer so a payload
- # like {"tags": [{}]} is rejected with a 400 instead of blowing up on KeyError downstream.
- name = serializers.CharField(max_length=100)
- description = serializers.CharField(max_length=500, required=False, default="", allow_blank=True)
-
-
-class TestHogTaggerRequestSerializer(serializers.Serializer):
- source = serializers.CharField(required=True, min_length=1) # type: ignore[assignment]
- sample_count = serializers.IntegerField(required=False, default=5, min_value=1, max_value=10)
- tags = TestHogTaggerTagSerializer(many=True, required=False, default=list)
diff --git a/products/llm_analytics/backend/api/test/test_taggers.py b/products/llm_analytics/backend/api/test/test_taggers.py
index 9c95f8fa2144..40623c4be891 100644
--- a/products/llm_analytics/backend/api/test/test_taggers.py
+++ b/products/llm_analytics/backend/api/test/test_taggers.py
@@ -7,6 +7,7 @@ from rest_framework import status
from posthog.models import Organization, Project, Team, User
+from products.llm_analytics.backend.models.provider_keys import LLMProvider
from products.llm_analytics.backend.models.taggers import Tagger, TaggerType
@@ -79,6 +80,46 @@ class TestTaggersApi(APIBaseTest):
assert tagger.created_by == self.user
assert tagger.deleted is False
+ def test_create_cannot_soft_delete_tagger(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/taggers/",
+ {
+ "name": "Feature Tagger",
+ "tagger_config": _make_tagger_config(),
+ "deleted": True,
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.data == self.validation_error_response(
+ "This field cannot be set when creating a tagger.",
+ attr="deleted",
+ )
+ assert Tagger.objects.count() == 0
+
+ def test_create_rejects_read_only_provider_key_name(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/taggers/",
+ {
+ "name": "Feature Tagger",
+ "tagger_config": _make_tagger_config(),
+ "model_configuration": {
+ "provider": LLMProvider.OPENAI,
+ "model": "gpt-4o",
+ "provider_key_name": "Main key",
+ },
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.data == self.validation_error_response(
+ "This field is read-only.",
+ attr="model_configuration__provider_key_name",
+ )
+ assert Tagger.objects.count() == 0
+
def test_can_retrieve_list_of_taggers(self):
Tagger.objects.create(
name="Tagger 1",
diff --git a/products/llm_analytics/frontend/generated/api.schemas.ts b/products/llm_analytics/frontend/generated/api.schemas.ts
index 63fa97281a99..38c4f228163d 100644
--- a/products/llm_analytics/frontend/generated/api.schemas.ts
+++ b/products/llm_analytics/frontend/generated/api.schemas.ts
@@ -2026,6 +2026,52 @@ export const TaggerTypeEnumApi = {
Hog: 'hog',
} as const
+export interface TagDefinitionApi {
+ /**
+ * Tag identifier
+ * @maxLength 100
+ */
+ name: string
+ /**
+ * Description to help the LLM classify
+ * @maxLength 500
+ */
+ description?: string
+}
+
+export interface LLMTaggerConfigApi {
+ /**
+ * Prompt instructing the LLM how to tag generations
+ * @minLength 1
+ */
+ prompt: string
+ /** Available tags the LLM can assign */
+ tags: TagDefinitionApi[]
+ /**
+ * Minimum number of tags to apply
+ * @minimum 0
+ */
+ min_tags?: number
+ /**
+ * Maximum number of tags to apply (null = no limit)
+ * @minimum 1
+ * @nullable
+ */
+ max_tags?: number | null
+}
+
+export interface HogTaggerConfigApi {
+ /**
+ * Hog source code to classify a generation into tags.
+ * @minLength 1
+ */
+ source: string
+ /** Optional tag whitelist. Leave empty to allow any tag returned by the Hog code. */
+ tags?: TagDefinitionApi[]
+}
+
+export type TaggerConfigApi = LLMTaggerConfigApi | HogTaggerConfigApi
+
export type TaggerConditionApiPropertiesItem = { [key: string]: unknown }
export interface TaggerConditionApi {
@@ -2048,10 +2094,25 @@ export interface TaggerConditionApi {
* Nested serializer for model configuration.
*/
export interface TaggerModelConfigurationApi {
+ /** LLM provider to use for this tagger.
+
+ * `openai` - Openai
+ * `anthropic` - Anthropic
+ * `gemini` - Gemini
+ * `openrouter` - Openrouter
+ * `fireworks` - Fireworks
+ * `azure_openai` - Azure OpenAI
+ * `together_ai` - Together AI */
provider: LLMProviderEnumApi
- /** @maxLength 100 */
+ /**
+ * Provider model identifier to use for this tagger.
+ * @maxLength 100
+ */
model: string
- /** @nullable */
+ /**
+ * Existing LLM provider key UUID for the current project. Do not invent this value; use a real provider key ID returned by PostHog, or omit/null when no provider key should be pinned.
+ * @nullable
+ */
provider_key_id?: string | null
/** @nullable */
readonly provider_key_name: string | null
@@ -2064,8 +2125,8 @@ export interface TaggerApi {
description?: string
enabled?: boolean
tagger_type?: TaggerTypeEnumApi
- /** Tagger configuration (varies by tagger_type) */
- tagger_config: unknown
+ /** Tagger configuration. For tagger_type 'llm': {prompt, tags, min_tags?, max_tags?}. For tagger_type 'hog': {source, tags?}. */
+ tagger_config: TaggerConfigApi
/** Conditions that scope when the tagger runs */
conditions?: TaggerConditionApi[]
model_configuration?: TaggerModelConfigurationApi | null
@@ -2084,6 +2145,101 @@ export interface PaginatedTaggerListApi {
results: TaggerApi[]
}
+export interface TaggerModelConfigurationWriteApi {
+ /** LLM provider to use for this tagger.
+
+ * `openai` - Openai
+ * `anthropic` - Anthropic
+ * `gemini` - Gemini
+ * `openrouter` - Openrouter
+ * `fireworks` - Fireworks
+ * `azure_openai` - Azure OpenAI
+ * `together_ai` - Together AI */
+ provider: LLMProviderEnumApi
+ /**
+ * Provider model identifier to use for this tagger.
+ * @maxLength 100
+ */
+ model: string
+ /**
+ * Existing LLM provider key UUID for the current project. Do not invent this value; use a real provider key ID returned by PostHog, or omit/null when no provider key should be pinned.
+ * @nullable
+ */
+ provider_key_id?: string | null
+}
+
+export interface TaggerCreateApi {
+ /** @maxLength 400 */
+ name: string
+ description?: string
+ enabled?: boolean
+ tagger_type?: TaggerTypeEnumApi
+ /** Tagger configuration. For tagger_type 'llm': {prompt, tags, min_tags?, max_tags?}. For tagger_type 'hog': {source, tags?}. */
+ tagger_config: TaggerConfigApi
+ /** Conditions that scope when the tagger runs */
+ conditions?: TaggerConditionApi[]
+ model_configuration?: TaggerModelConfigurationWriteApi | null
+}
+
+export interface TestHogTaggerTagApi {
+ /**
+ * Tag identifier to allow in Hog test results.
+ * @maxLength 100
+ */
+ name: string
+ /**
+ * Optional description for the tag.
+ * @maxLength 500
+ */
+ description?: string
+}
+
+export interface TestHogTaggerRequestApi {
+ /**
+ * Hog source code to test. Return a tag name string, a list of tag name strings, or null.
+ * @minLength 1
+ */
+ source: string
+ /**
+ * Number of recent $ai_generation events to test against (1-10, default 5).
+ * @minimum 1
+ * @maximum 10
+ */
+ sample_count?: number
+ /** Optional tag whitelist. Returned tags outside this list are filtered out. */
+ tags?: TestHogTaggerTagApi[]
+}
+
+export interface TestHogTaggerResultItemApi {
+ /** UUID of the sampled $ai_generation event. */
+ event_uuid: string
+ /**
+ * Trace ID if available.
+ * @nullable
+ */
+ trace_id?: string | null
+ /** First 200 characters of the generation input. */
+ input_preview: string
+ /** First 200 characters of the generation output. */
+ output_preview: string
+ /** Tag names returned by the Hog code. */
+ tags: string[]
+ /** Text written to stdout by the Hog code. */
+ reasoning: string
+ /**
+ * Error message if the Hog code failed.
+ * @nullable
+ */
+ error?: string | null
+}
+
+export interface TestHogTaggerResponseApi {
+ /** Per-event Hog tagger test results. */
+ results: TestHogTaggerResultItemApi[]
+ /** Optional message, for example when no recent AI events were found. */
+ message?: string
+}
+
export interface DatasetItemApi {
readonly id: string
dataset: string
diff --git a/products/llm_analytics/frontend/generated/api.ts b/products/llm_analytics/frontend/generated/api.ts
index 3ffe5a90f715..ee08032cbc15 100644
--- a/products/llm_analytics/frontend/generated/api.ts
+++ b/products/llm_analytics/frontend/generated/api.ts
@@ -102,9 +102,12 @@ import type {
SummarizeRequestApi,
SummarizeResponseApi,
TaggerApi,
+ TaggerCreateApi,
TaggersListParams,
TestHogRequestApi,
TestHogResponseApi,
+ TestHogTaggerRequestApi,
+ TestHogTaggerResponseApi,
TextReprRequestApi,
TextReprResponseApi,
TraceReviewApi,
@@ -1997,14 +2000,14 @@ export const getTaggersCreateUrl = (projectId: string) => {
export const taggersCreate = async (
projectId: string,
- taggerApi: NonReadonly<TaggerApi>,
+ taggerCreateApi: TaggerCreateApi,
options?: RequestInit
): Promise<TaggerApi> => {
return apiMutator<TaggerApi>(getTaggersCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(taggerApi),
+ body: JSON.stringify(taggerCreateApi),
})
}
@@ -2017,14 +2020,14 @@ export const getTaggersTestHogCreateUrl = (projectId: string) => {
*/
export const taggersTestHogCreate = async (
projectId: string,
- taggerApi: NonReadonly<TaggerApi>,
+ testHogTaggerRequestApi: TestHogTaggerRequestApi,
options?: RequestInit
-): Promise<TaggerApi> => {
- return apiMutator<TaggerApi>(getTaggersTestHogCreateUrl(projectId), {
+): Promise<TestHogTaggerResponseApi> => {
+ return apiMutator<TestHogTaggerResponseApi>(getTaggersTestHogCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(taggerApi),
+ body: JSON.stringify(testHogTaggerRequestApi),
})
}
diff --git a/products/llm_analytics/frontend/generated/api.zod.ts b/products/llm_analytics/frontend/generated/api.zod.ts
index 069d4fd98892..768f8aea9fc4 100644
--- a/products/llm_analytics/frontend/generated/api.zod.ts
+++ b/products/llm_analytics/frontend/generated/api.zod.ts
@@ -1716,6 +1716,19 @@ export const LlmSkillsNameFilesRenameCreateBody = /* @__PURE__ */ zod.object({
export const taggersCreateBodyNameMax = 400
export const taggersCreateBodyTaggerTypeDefault = `llm`
+export const taggersCreateBodyTaggerConfigOneOneTagsItemNameMax = 100
+
+export const taggersCreateBodyTaggerConfigOneOneTagsItemDescriptionDefault = ``
+export const taggersCreateBodyTaggerConfigOneOneTagsItemDescriptionMax = 500
+
+export const taggersCreateBodyTaggerConfigOneOneMinTagsDefault = 0
+export const taggersCreateBodyTaggerConfigOneOneMinTagsMin = 0
+
+export const taggersCreateBodyTaggerConfigOneTwoTagsItemNameMax = 100
+
+export const taggersCreateBodyTaggerConfigOneTwoTagsItemDescriptionDefault = ``
+export const taggersCreateBodyTaggerConfigOneTwoTagsItemDescriptionMax = 500
+
export const taggersCreateBodyConditionsItemIdMax = 100
export const taggersCreateBodyConditionsItemRolloutPercentageDefault = 100
@@ -1732,7 +1745,55 @@ export const TaggersCreateBody = /* @__PURE__ */ zod.object({
.enum(['llm', 'hog'])
.describe('\* `llm` - LLM\n\* `hog` - Hog')
.default(taggersCreateBodyTaggerTypeDefault),
- tagger_config: zod.unknown().describe('Tagger configuration (varies by tagger_type)'),
+ tagger_config: zod
+ .union([
+ zod.object({
+ prompt: zod.string().min(1).describe('Prompt instructing the LLM how to tag generations'),
+ tags: zod
+ .array(
+ zod.object({
+ name: zod
+ .string()
+ .max(taggersCreateBodyTaggerConfigOneOneTagsItemNameMax)
+ .describe('Tag identifier'),
+ description: zod
+ .string()
+ .max(taggersCreateBodyTaggerConfigOneOneTagsItemDescriptionMax)
+ .default(taggersCreateBodyTaggerConfigOneOneTagsItemDescriptionDefault)
+ .describe('Description to help the LLM classify'),
+ })
+ )
+ .describe('Available tags the LLM can assign'),
+ min_tags: zod
+ .number()
+ .min(taggersCreateBodyTaggerConfigOneOneMinTagsMin)
+ .default(taggersCreateBodyTaggerConfigOneOneMinTagsDefault)
+ .describe('Minimum number of tags to apply'),
+ max_tags: zod.number().min(1).nullish().describe('Maximum number of tags to apply (null = no limit)'),
+ }),
+ zod.object({
+ source: zod.string().min(1).describe('Hog source code to classify a generation into tags.'),
+ tags: zod
+ .array(
+ zod.object({
+ name: zod
+ .string()
+ .max(taggersCreateBodyTaggerConfigOneTwoTagsItemNameMax)
+ .describe('Tag identifier'),
+ description: zod
+ .string()
+ .max(taggersCreateBodyTaggerConfigOneTwoTagsItemDescriptionMax)
+ .default(taggersCreateBodyTaggerConfigOneTwoTagsItemDescriptionDefault)
+ .describe('Description to help the LLM classify'),
+ })
+ )
+ .optional()
+ .describe('Optional tag whitelist. Leave empty to allow any tag returned by the Hog code.'),
+ }),
+ ])
+ .describe(
+ "Tagger configuration. For tagger_type 'llm': {prompt, tags, min_tags?, max_tags?}. For tagger_type 'hog': {source, tags?}."
+ ),
conditions: zod
.array(
zod.object({
@@ -1756,102 +1817,70 @@ export const TaggersCreateBody = /* @__PURE__ */ zod.object({
.describe('Conditions that scope when the tagger runs'),
model_configuration: zod
.union([
- zod
- .object({
- provider: zod
- .enum([
- 'openai',
- 'anthropic',
- 'gemini',
- 'openrouter',
- 'fireworks',
- 'azure_openai',
- 'together_ai',
- ])
- .describe(
- '\* `openai` - Openai\n\* `anthropic` - Anthropic\n\* `gemini` - Gemini\n\* `openrouter` - Openrouter\n\* `fireworks` - Fireworks\n\* `azure_openai` - Azure OpenAI\n\* `together_ai` - Together AI'
- ),
- model: zod.string().max(taggersCreateBodyModelConfigurationOneModelMax),
- provider_key_id: zod.uuid().nullish(),
- provider_key_name: zod.string().nullable(),
- })
- .describe('Nested serializer for model configuration.'),
+ zod.object({
+ provider: zod
+ .enum(['openai', 'anthropic', 'gemini', 'openrouter', 'fireworks', 'azure_openai', 'together_ai'])
+ .describe(
+ '\* `openai` - Openai\n\* `anthropic` - Anthropic\n\* `gemini` - Gemini\n\* `openrouter` - Openrouter\n\* `fireworks` - Fireworks\n\* `azure_openai` - Azure OpenAI\n\* `together_ai` - Together AI'
+ )
+ .describe(
+ 'LLM provider to use for this tagger.\n\n\* `openai` - Openai\n\* `anthropic` - Anthropic\n\* `gemini` - Gemini\n\* `openrouter` - Openrouter\n\* `fireworks` - Fireworks\n\* `azure_openai` - Azure OpenAI\n\* `together_ai` - Together AI'
+ ),
+ model: zod
+ .string()
+ .max(taggersCreateBodyModelConfigurationOneModelMax)
+ .describe('Provider model identifier to use for this tagger.'),
+ provider_key_id: zod
+ .uuid()
+ .nullish()
+ .describe(
+ 'Existing LLM provider key UUID for the current project. Do not invent this value; use a real provider key ID returned by PostHog, or omit\/null when no provider key should be pinned.'
+ ),
+ }),
zod.null(),
])
.optional(),
- deleted: zod.boolean().optional(),
})
/**
* Test Hog tagger code against sample events without saving.
*/
-export const taggersTestHogCreateBodyNameMax = 400
-export const taggersTestHogCreateBodyTaggerTypeDefault = `llm`
-export const taggersTestHogCreateBodyConditionsItemIdMax = 100
+export const taggersTestHogCreateBodySampleCountDefault = 5
+export const taggersTestHogCreateBodySampleCountMax = 10
-export const taggersTestHogCreateBodyConditionsItemRolloutPercentageDefault = 100
-export const taggersTestHogCreateBodyConditionsItemRolloutPercentageMin = 0
-export const taggersTestHogCreateBodyConditionsItemRolloutPercentageMax = 100
+export const taggersTestHogCreateBodyTagsItemNameMax = 100
-export const taggersTestHogCreateBodyModelConfigurationOneModelMax = 100
+export const taggersTestHogCreateBodyTagsItemDescriptionDefault = ``
+export const taggersTestHogCreateBodyTagsItemDescriptionMax = 500
export const TaggersTestHogCreateBody = /* @__PURE__ */ zod.object({
- name: zod.string().max(taggersTestHogCreateBodyNameMax),
- description: zod.string().optional(),
- enabled: zod.boolean().optional(),
- tagger_type: zod
- .enum(['llm', 'hog'])
- .describe('\* `llm` - LLM\n\* `hog` - Hog')
- .default(taggersTestHogCreateBodyTaggerTypeDefault),
- tagger_config: zod.unknown().describe('Tagger configuration (varies by tagger_type)'),
- conditions: zod
+ source: zod
+ .string()
+ .min(1)
+ .describe('Hog source code to test. Return a tag name string, a list of tag name strings, or null.'),
+ sample_count: zod
+ .number()
+ .min(1)
+ .max(taggersTestHogCreateBodySampleCountMax)
+ .default(taggersTestHogCreateBodySampleCountDefault)
+ .describe('Number of recent $ai_generation events to test against (1-10, default 5).'),
+ tags: zod
.array(
zod.object({
- id: zod
+ name: zod
.string()
- .max(taggersTestHogCreateBodyConditionsItemIdMax)
- .describe('Stable identifier for this condition'),
- rollout_percentage: zod
- .number()
- .min(taggersTestHogCreateBodyConditionsItemRolloutPercentageMin)
- .max(taggersTestHogCreateBodyConditionsItemRolloutPercentageMax)
- .default(taggersTestHogCreateBodyConditionsItemRolloutPercentageDefault)
- .describe('Percentage of matching events to apply this condition to'),
- properties: zod
- .array(zod.record(zod.string(), zod.unknown()))
- .optional()
- .describe('Property filters that scope when this condition fires'),
+ .max(taggersTestHogCreateBodyTagsItemNameMax)
+ .describe('Tag identifier to allow in Hog test results.'),
+ description: zod
+ .string()
+ .max(taggersTestHogCreateBodyTagsItemDescriptionMax)
+ .default(taggersTestHogCreateBodyTagsItemDescriptionDefault)
+ .describe('Optional description for the tag.'),
})
)
.optional()
- .describe('Conditions that scope when the tagger runs'),
- model_configuration: zod
- .union([
- zod
- .object({
- provider: zod
- .enum([
- 'openai',
- 'anthropic',
- 'gemini',
- 'openrouter',
- 'fireworks',
- 'azure_openai',
- 'together_ai',
- ])
- .describe(
- '\* `openai` - Openai\n\* `anthropic` - Anthropic\n\* `gemini` - Gemini\n\* `openrouter` - Openrouter\n\* `fireworks` - Fireworks\n\* `azure_openai` - Azure OpenAI\n\* `together_ai` - Together AI'
- ),
- model: zod.string().max(taggersTestHogCreateBodyModelConfigurationOneModelMax),
- provider_key_id: zod.uuid().nullish(),
- provider_key_name: zod.string().nullable(),
- })
- .describe('Nested serializer for model configuration.'),
- zod.null(),
- ])
- .optional(),
- deleted: zod.boolean().optional(),
+ .describe('Optional tag whitelist. Returned tags outside this list are filtered out.'),
})
export const datasetItemsCreateBodyRefTraceIdMax = 255
diff --git a/products/llm_analytics/mcp/tools.yaml b/products/llm_analytics/mcp/tools.yaml
index 687a776ba472..8025e9631498 100644
--- a/products/llm_analytics/mcp/tools.yaml
+++ b/products/llm_analytics/mcp/tools.yaml
@@ -971,13 +971,52 @@ tools:
requires_ai_consent: true
llma-tagger-create:
operation: taggers_create
- enabled: false
+ enabled: true
+ scopes:
+ - tagger:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ enrich_url: tags/{id}
+ title: Create tagger
+ description: >
+ Create an LLM analytics tagger that automatically adds custom tags to $ai_generation events. For tagger_type
+ "llm", provide tagger_config.prompt plus tagger_config.tags (each with name and optional description);
+ optionally set min_tags and max_tags. For tagger_type "hog", provide tagger_config.source Hog code that
+ returns a tag name string, a list of tag name strings, or null; optionally provide tagger_config.tags as a
+ whitelist. Use enabled=false while drafting, then update the tagger from the UI.
llma-tagger-list:
operation: taggers_list
- enabled: false
+ enabled: true
+ scopes:
+ - tagger:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ enrich_url: tags/{id}
+ list: true
+ title: List taggers
+ description: >
+ List LLM analytics taggers for the current project. Supports filtering by enabled status, id__in, search,
+ and ordering. Returns each tagger's name, description, enabled state, type, configuration, conditions, model
+ configuration, creator, and timestamps.
llma-tagger-test-hog:
operation: taggers_test_hog_create
- enabled: false
+ enabled: true
+ scopes:
+ - tagger:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: false
+ title: Test Hog tagger code
+ description: >
+ Test Hog tagger source code against recent $ai_generation events without saving a tagger. The source should
+ return a tag name string, a list of tag name strings, or null. Optionally pass tags as a whitelist; returned
+ tags outside the whitelist are filtered out. Results include input/output previews, selected tags, stdout
+ reasoning, and any execution error for each sampled event.
llma-text-repr-create:
operation: llm_analytics_text_repr_create
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 18427c3f86cf..108d86e7ff77 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -3125,6 +3125,51 @@
},
"requires_ai_consent": true
},
+ "llma-tagger-create": {
+ "description": "Create an LLM analytics tagger that automatically adds custom tags to $ai_generation events. For tagger_type \"llm\", provide tagger_config.prompt plus tagger_config.tags (each with name and optional description); optionally set min_tags and max_tags. For tagger_type \"hog\", provide tagger_config.source Hog code that returns a tag name string, a list of tag name strings, or null; optionally provide tagger_config.tags as a whitelist. Use enabled=false while drafting, then update the tagger from the UI.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "Create tagger",
+ "title": "Create tagger",
+ "required_scopes": ["tagger:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "llma-tagger-list": {
+ "description": "List LLM analytics taggers for the current project. Supports filtering by enabled status, id__in, search, and ordering. Returns each tagger's name, description, enabled state, type, configuration, conditions, model configuration, creator, and timestamps.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "List taggers",
+ "title": "List taggers",
+ "required_scopes": ["tagger:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "llma-tagger-test-hog": {
+ "description": "Test Hog tagger source code against recent $ai_generation events without saving a tagger. The source should return a tag name string, a list of tag name strings, or null. Optionally pass tags as a whitelist; returned tags outside the whitelist are filtered out. Results include input/output previews, selected tags, stdout reasoning, and any execution error for each sampled event.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "Test Hog tagger code",
+ "title": "Test Hog tagger code",
+ "required_scopes": ["tagger:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"llma-trace-review-create": {
"description": "Save a trace review. Supports an optional comment, an optional scores array, and an optional queue_id to clear a matching pending review-queue item after the review is saved.",
"category": "LLM analytics",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 6e0425b1c396..a58f8cd28243 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3438,6 +3438,51 @@
},
"requires_ai_consent": true
},
+ "llma-tagger-create": {
+ "description": "Create an LLM analytics tagger that automatically adds custom tags to $ai_generation events. For tagger_type \"llm\", provide tagger_config.prompt plus tagger_config.tags (each with name and optional description); optionally set min_tags and max_tags. For tagger_type \"hog\", provide tagger_config.source Hog code that returns a tag name string, a list of tag name strings, or null; optionally provide tagger_config.tags as a whitelist. Use enabled=false while drafting, then update the tagger from the UI.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "Create tagger",
+ "title": "Create tagger",
+ "required_scopes": ["tagger:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "llma-tagger-list": {
+ "description": "List LLM analytics taggers for the current project. Supports filtering by enabled status, id__in, search, and ordering. Returns each tagger's name, description, enabled state, type, configuration, conditions, model configuration, creator, and timestamps.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "List taggers",
+ "title": "List taggers",
+ "required_scopes": ["tagger:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "llma-tagger-test-hog": {
+ "description": "Test Hog tagger source code against recent $ai_generation events without saving a tagger. The source should return a tag name string, a list of tag name strings, or null. Optionally pass tags as a whitelist; returned tags outside the whitelist are filtered out. Results include input/output previews, selected tags, stdout reasoning, and any execution error for each sampled event.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "Test Hog tagger code",
+ "title": "Test Hog tagger code",
+ "required_scopes": ["tagger:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"llma-trace-review-create": {
"description": "Save a trace review. Supports an optional comment, an optional scores array, and an optional queue_id to clear a matching pending review-queue item after the review is saved.",
"category": "LLM analytics",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 292fb6a90837..ebd0af323ef0 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -18048,6 +18048,29 @@ export namespace Schemas {
version?: number | null;
}
+ export interface TagDefinition {
+ /**
+ * Tag identifier
+ * @maxLength 100
+ */
+ name: string;
+ /**
+ * Description to help the LLM classify
+ * @maxLength 500
+ */
+ description?: string;
+ }
+
+ export interface HogTaggerConfig {
+ /**
+ * Hog source code to classify a generation into tags.
+ * @minLength 1
+ */
+ source: string;
+ /** Optional tag whitelist. Leave empty to allow any tag returned by the Hog code. */
+ tags?: TagDefinition[];
+ }
+
/**
* @nullable
*/
@@ -18807,6 +18830,27 @@ export namespace Schemas {
has_more: boolean;
}
+ export interface LLMTaggerConfig {
+ /**
+ * Prompt instructing the LLM how to tag generations
+ * @minLength 1
+ */
+ prompt: string;
+ /** Available tags the LLM can assign */
+ tags: TagDefinition[];
+ /**
+ * Minimum number of tags to apply
+ * @minimum 0
+ */
+ min_tags?: number;
+ /**
+ * Maximum number of tags to apply (null = no limit)
+ * @minimum 1
+ * @nullable
+ */
+ max_tags?: number | null;
+ }
+
/**
* * `today` - today
* `this_week` - this_week
@@ -22890,6 +22934,8 @@ export namespace Schemas {
Hog: 'hog',
} as const;
+ export type TaggerConfig = LLMTaggerConfig | HogTaggerConfig;
+
export type TaggerConditionPropertiesItem = { [key: string]: unknown };
export interface TaggerCondition {
@@ -22912,10 +22958,25 @@ export namespace Schemas {
* Nested serializer for model configuration.
*/
export interface TaggerModelConfiguration {
+ /** LLM provider to use for this tagger.
+
+ * `openai` - Openai
+ * `anthropic` - Anthropic
+ * `gemini` - Gemini
+ * `openrouter` - Openrouter
+ * `fireworks` - Fireworks
+ * `azure_openai` - Azure OpenAI
+ * `together_ai` - Together AI */
provider: LLMProviderEnum;
- /** @maxLength 100 */
+ /**
+ * Provider model identifier to use for this tagger.
+ * @maxLength 100
+ */
model: string;
- /** @nullable */
+ /**
+ * Existing LLM provider key UUID for the current project. Do not invent this value; use a real provider key ID returned by PostHog, or omit/null when no provider key should be pinned.
+ * @nullable
+ */
provider_key_id?: string | null;
/** @nullable */
readonly provider_key_name: string | null;
@@ -22928,8 +22989,8 @@ export namespace Schemas {
description?: string;
enabled?: boolean;
tagger_type?: TaggerTypeEnum;
- /** Tagger configuration (varies by tagger_type) */
- tagger_config: unknown;
+ /** Tagger configuration. For tagger_type 'llm': {prompt, tags, min_tags?, max_tags?}. For tagger_type 'hog': {source, tags?}. */
+ tagger_config: TaggerConfig;
/** Conditions that scope when the tagger runs */
conditions?: TaggerCondition[];
model_configuration?: TaggerModelConfiguration | null;
@@ -28615,21 +28676,40 @@ export namespace Schemas {
readonly user_access_level?: string | null;
}
- export interface PatchedTagger {
- readonly id?: string;
+ export interface TaggerModelConfigurationWrite {
+ /** LLM provider to use for this tagger.
+
+ * `openai` - Openai
+ * `anthropic` - Anthropic
+ * `gemini` - Gemini
+ * `openrouter` - Openrouter
+ * `fireworks` - Fireworks
+ * `azure_openai` - Azure OpenAI
+ * `together_ai` - Together AI */
+ provider: LLMProviderEnum;
+ /**
+ * Provider model identifier to use for this tagger.
+ * @maxLength 100
+ */
+ model: string;
+ /**
+ * Existing LLM provider key UUID for the current project. Do not invent this value; use a real provider key ID returned by PostHog, or omit/null when no provider key should be pinned.
+ * @nullable
+ */
+ provider_key_id?: string | null;
+ }
+
+ export interface PatchedTaggerUpdate {
/** @maxLength 400 */
name?: string;
description?: string;
enabled?: boolean;
tagger_type?: TaggerTypeEnum;
- /** Tagger configuration (varies by tagger_type) */
- tagger_config?: unknown;
+ /** Tagger configuration. For tagger_type 'llm': {prompt, tags, min_tags?, max_tags?}. For tagger_type 'hog': {source, tags?}. */
+ tagger_config?: TaggerConfig;
/** Conditions that scope when the tagger runs */
conditions?: TaggerCondition[];
- model_configuration?: TaggerModelConfiguration | null;
- readonly created_at?: string;
- readonly updated_at?: string;
- readonly created_by?: UserBasic;
+ model_configuration?: TaggerModelConfigurationWrite | null;
deleted?: boolean;
}
@@ -33228,6 +33308,33 @@ export namespace Schemas {
rates: SurveyStatsResponseRates;
}
+ export interface TaggerCreate {
+ /** @maxLength 400 */
+ name: string;
+ description?: string;
+ enabled?: boolean;
+ tagger_type?: TaggerTypeEnum;
+ /** Tagger configuration. For tagger_type 'llm': {prompt, tags, min_tags?, max_tags?}. For tagger_type 'hog': {source, tags?}. */
+ tagger_config: TaggerConfig;
+ /** Conditions that scope when the tagger runs */
+ conditions?: TaggerCondition[];
+ model_configuration?: TaggerModelConfigurationWrite | null;
+ }
+
+ export interface TaggerUpdate {
+ /** @maxLength 400 */
+ name: string;
+ description?: string;
+ enabled?: boolean;
+ tagger_type?: TaggerTypeEnum;
+ /** Tagger configuration. For tagger_type 'llm': {prompt, tags, min_tags?, max_tags?}. For tagger_type 'hog': {source, tags?}. */
+ tagger_config: TaggerConfig;
+ /** Conditions that scope when the tagger runs */
+ conditions?: TaggerCondition[];
+ model_configuration?: TaggerModelConfigurationWrite | null;
+ deleted?: boolean;
+ }
+
export interface TaskRepositoriesResponse {
/** Distinct repositories in use by non-deleted, non-internal tasks for the current team. */
repositories: string[];
@@ -33991,6 +34098,65 @@ export namespace Schemas {
message?: string;
}
+ export interface TestHogTaggerTag {
+ /**
+ * Tag identifier to allow in Hog test results.
+ * @maxLength 100
+ */
+ name: string;
+ /**
+ * Optional description for the tag.
+ * @maxLength 500
+ */
+ description?: string;
+ }
+
+ export interface TestHogTaggerRequest {
+ /**
+ * Hog source code to test. Return a tag name string, a list of tag name strings, or null.
+ * @minLength 1
+ */
+ source: string;
+ /**
+ * Number of recent $ai_generation events to test against (1-10, default 5).
+ * @minimum 1
+ * @maximum 10
+ */
+ sample_count?: number;
+ /** Optional tag whitelist. Returned tags outside this list are filtered out. */
+ tags?: TestHogTaggerTag[];
+ }
+
+ export interface TestHogTaggerResultItem {
+ /** UUID of the sampled $ai_generation event. */
+ event_uuid: string;
+ /**
+ * Trace ID if available.
+ * @nullable
+ */
+ trace_id?: string | null;
+ /** First 200 characters of the generation input. */
+ input_preview: string;
+ /** First 200 characters of the generation output. */
+ output_preview: string;
+ /** Tag names returned by the Hog code. */
+ tags: string[];
+ /** Text written to stdout by the Hog code. */
+ reasoning: string;
+ /**
+ * Error message if the Hog code failed.
+ * @nullable
+ */
+ error?: string | null;
+ }
+
+ export interface TestHogTaggerResponse {
+ /** Per-event Hog tagger test results. */
+ results: TestHogTaggerResultItem[];
+ /** Optional message, for example when no recent AI events were found. */
+ message?: string;
+ }
+
export interface TextReprMetadata {
event_type?: string;
event_id?: string;
diff --git a/services/mcp/src/generated/llm_analytics/api.ts b/services/mcp/src/generated/llm_analytics/api.ts
index 5690ae0b8e35..c6320cd47278 100644
--- a/services/mcp/src/generated/llm_analytics/api.ts
+++ b/services/mcp/src/generated/llm_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 57 enabled ops
+ * PostHog API - MCP 60 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -1777,3 +1777,210 @@ export const LlmSkillsNameFilesDestroyQueryParams = /* @__PURE__ */ zod.object({
'Latest version you are editing from. If provided, the request fails with 409 when another write has landed in the meantime.'
),
})
+
+export const TaggersListParams = /* @__PURE__ */ 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 TaggersListQueryParams = /* @__PURE__ */ zod.object({
+ enabled: zod.boolean().optional().describe('Filter by enabled status'),
+ id__in: zod.array(zod.string()).optional().describe('Multiple values may be separated by commas.'),
+ 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.'),
+ order_by: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Ordering\n\n* `created_at` - Created At\n* `-created_at` - Created At (descending)\n* `updated_at` - Updated At\n* `-updated_at` - Updated At (descending)\n* `name` - Name\n* `-name` - Name (descending)'
+ ),
+ search: zod.string().optional().describe('Search in name or description'),
+})
+
+export const TaggersCreateParams = /* @__PURE__ */ 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 taggersCreateBodyNameMax = 400
+
+export const taggersCreateBodyTaggerTypeDefault = `llm`
+export const taggersCreateBodyTaggerConfigOneOneTagsItemNameMax = 100
+
+export const taggersCreateBodyTaggerConfigOneOneTagsItemDescriptionDefault = ``
+export const taggersCreateBodyTaggerConfigOneOneTagsItemDescriptionMax = 500
+
+export const taggersCreateBodyTaggerConfigOneOneMinTagsDefault = 0
+export const taggersCreateBodyTaggerConfigOneOneMinTagsMin = 0
+
+export const taggersCreateBodyTaggerConfigOneTwoTagsItemNameMax = 100
+
+export const taggersCreateBodyTaggerConfigOneTwoTagsItemDescriptionDefault = ``
+export const taggersCreateBodyTaggerConfigOneTwoTagsItemDescriptionMax = 500
+
+export const taggersCreateBodyConditionsItemIdMax = 100
+
+export const taggersCreateBodyConditionsItemRolloutPercentageDefault = 100
+export const taggersCreateBodyConditionsItemRolloutPercentageMin = 0
+export const taggersCreateBodyConditionsItemRolloutPercentageMax = 100
+
+export const taggersCreateBodyModelConfigurationOneModelMax = 100
+
+export const TaggersCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(taggersCreateBodyNameMax),
+ description: zod.string().optional(),
+ enabled: zod.boolean().optional(),
+ tagger_type: zod
+ .enum(['llm', 'hog'])
+ .describe('* `llm` - LLM\n* `hog` - Hog')
+ .default(taggersCreateBodyTaggerTypeDefault),
+ tagger_config: zod
+ .union([
+ zod.object({
+ prompt: zod.string().min(1).describe('Prompt instructing the LLM how to tag generations'),
+ tags: zod
+ .array(
+ zod.object({
+ name: zod
+ .string()
+ .max(taggersCreateBodyTaggerConfigOneOneTagsItemNameMax)
+ .describe('Tag identifier'),
+ description: zod
+ .string()
+ .max(taggersCreateBodyTaggerConfigOneOneTagsItemDescriptionMax)
+ .default(taggersCreateBodyTaggerConfigOneOneTagsItemDescriptionDefault)
+ .describe('Description to help the LLM classify'),
+ })
+ )
+ .describe('Available tags the LLM can assign'),
+ min_tags: zod
+ .number()
+ .min(taggersCreateBodyTaggerConfigOneOneMinTagsMin)
+ .default(taggersCreateBodyTaggerConfigOneOneMinTagsDefault)
+ .describe('Minimum number of tags to apply'),
+ max_tags: zod.number().min(1).nullish().describe('Maximum number of tags to apply (null = no limit)'),
+ }),
+ zod.object({
+ source: zod.string().min(1).describe('Hog source code to classify a generation into tags.'),
+ tags: zod
+ .array(
+ zod.object({
+ name: zod
+ .string()
+ .max(taggersCreateBodyTaggerConfigOneTwoTagsItemNameMax)
+ .describe('Tag identifier'),
+ description: zod
+ .string()
+ .max(taggersCreateBodyTaggerConfigOneTwoTagsItemDescriptionMax)
+ .default(taggersCreateBodyTaggerConfigOneTwoTagsItemDescriptionDefault)
+ .describe('Description to help the LLM classify'),
+ })
+ )
+ .optional()
+ .describe('Optional tag whitelist. Leave empty to allow any tag returned by the Hog code.'),
+ }),
+ ])
+ .describe(
+ "Tagger configuration. For tagger_type 'llm': {prompt, tags, min_tags?, max_tags?}. For tagger_type 'hog': {source, tags?}."
+ ),
+ conditions: zod
+ .array(
+ zod.object({
+ id: zod
+ .string()
+ .max(taggersCreateBodyConditionsItemIdMax)
+ .describe('Stable identifier for this condition'),
+ rollout_percentage: zod
+ .number()
+ .min(taggersCreateBodyConditionsItemRolloutPercentageMin)
+ .max(taggersCreateBodyConditionsItemRolloutPercentageMax)
+ .default(taggersCreateBodyConditionsItemRolloutPercentageDefault)
+ .describe('Percentage of matching events to apply this condition to'),
+ properties: zod
+ .array(zod.record(zod.string(), zod.unknown()))
+ .optional()
+ .describe('Property filters that scope when this condition fires'),
+ })
+ )
+ .optional()
+ .describe('Conditions that scope when the tagger runs'),
+ model_configuration: zod
+ .union([
+ zod.object({
+ provider: zod
+ .enum(['openai', 'anthropic', 'gemini', 'openrouter', 'fireworks', 'azure_openai', 'together_ai'])
+ .describe(
+ '* `openai` - Openai\n* `anthropic` - Anthropic\n* `gemini` - Gemini\n* `openrouter` - Openrouter\n* `fireworks` - Fireworks\n* `azure_openai` - Azure OpenAI\n* `together_ai` - Together AI'
+ )
+ .describe(
+ 'LLM provider to use for this tagger.\n\n* `openai` - Openai\n* `anthropic` - Anthropic\n* `gemini` - Gemini\n* `openrouter` - Openrouter\n* `fireworks` - Fireworks\n* `azure_openai` - Azure OpenAI\n* `together_ai` - Together AI'
+ ),
+ model: zod
+ .string()
+ .max(taggersCreateBodyModelConfigurationOneModelMax)
+ .describe('Provider model identifier to use for this tagger.'),
+ provider_key_id: zod
+ .uuid()
+ .nullish()
+ .describe(
+ 'Existing LLM provider key UUID for the current project. Do not invent this value; use a real provider key ID returned by PostHog, or omit/null when no provider key should be pinned.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+})
+
+/**
+ * Test Hog tagger code against sample events without saving.
+ */
+export const TaggersTestHogCreateParams = /* @__PURE__ */ 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 taggersTestHogCreateBodySampleCountDefault = 5
+export const taggersTestHogCreateBodySampleCountMax = 10
+
+export const taggersTestHogCreateBodyTagsItemNameMax = 100
+
+export const taggersTestHogCreateBodyTagsItemDescriptionDefault = ``
+export const taggersTestHogCreateBodyTagsItemDescriptionMax = 500
+
+export const TaggersTestHogCreateBody = /* @__PURE__ */ zod.object({
+ source: zod
+ .string()
+ .min(1)
+ .describe('Hog source code to test. Return a tag name string, a list of tag name strings, or null.'),
+ sample_count: zod
+ .number()
+ .min(1)
+ .max(taggersTestHogCreateBodySampleCountMax)
+ .default(taggersTestHogCreateBodySampleCountDefault)
+ .describe('Number of recent $ai_generation events to test against (1-10, default 5).'),
+ tags: zod
+ .array(
+ zod.object({
+ name: zod
+ .string()
+ .max(taggersTestHogCreateBodyTagsItemNameMax)
+ .describe('Tag identifier to allow in Hog test results.'),
+ description: zod
+ .string()
+ .max(taggersTestHogCreateBodyTagsItemDescriptionMax)
+ .default(taggersTestHogCreateBodyTagsItemDescriptionDefault)
+ .describe('Optional description for the tag.'),
+ })
+ )
+ .optional()
+ .describe('Optional tag whitelist. Returned tags outside this list are filtered out.'),
+})
diff --git a/services/mcp/src/tools/generated/llm_analytics.ts b/services/mcp/src/tools/generated/llm_analytics.ts
index df42ae4b102b..9ae30b191dd7 100644
--- a/services/mcp/src/tools/generated/llm_analytics.ts
+++ b/services/mcp/src/tools/generated/llm_analytics.ts
@@ -76,6 +76,9 @@ import {
LlmSkillsNamePartialUpdateParams,
LlmSkillsNameRetrieveParams,
LlmSkillsNameRetrieveQueryParams,
+ TaggersCreateBody,
+ TaggersListQueryParams,
+ TaggersTestHogCreateBody,
} from '@/generated/llm_analytics/api'
import { PromptListInputSchema, ScoreDefinitionConfigSchema } from '@/schema/tool-inputs'
import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
@@ -1463,6 +1466,104 @@ const llmaSummarizationCreate = (): ToolBase<typeof LlmaSummarizationCreateSchem
},
})
+const LlmaTaggerCreateSchema = TaggersCreateBody
+
+const llmaTaggerCreate = (): ToolBase<typeof LlmaTaggerCreateSchema, WithPostHogUrl<Schemas.Tagger>> => ({
+ name: 'llma-tagger-create',
+ schema: LlmaTaggerCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof LlmaTaggerCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.description !== undefined) {
+ body['description'] = params.description
+ }
+ if (params.enabled !== undefined) {
+ body['enabled'] = params.enabled
+ }
+ if (params.tagger_type !== undefined) {
+ body['tagger_type'] = params.tagger_type
+ }
+ if (params.tagger_config !== undefined) {
+ body['tagger_config'] = params.tagger_config
+ }
+ if (params.conditions !== undefined) {
+ body['conditions'] = params.conditions
+ }
+ if (params.model_configuration !== undefined) {
+ body['model_configuration'] = params.model_configuration
+ }
+ const result = await context.api.request<Schemas.Tagger>({
+ method: 'POST',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/taggers/`,
+ body,
+ })
+ return await withPostHogUrl(context, result, `/llm-analytics/tags/${result.id}`)
+ },
+})
+
+const LlmaTaggerListSchema = TaggersListQueryParams
+
+const llmaTaggerList = (): ToolBase<typeof LlmaTaggerListSchema, WithPostHogUrl<Schemas.PaginatedTaggerList>> => ({
+ name: 'llma-tagger-list',
+ schema: LlmaTaggerListSchema,
+ handler: async (context: Context, params: z.infer<typeof LlmaTaggerListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedTaggerList>({
+ method: 'GET',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/taggers/`,
+ query: {
+ enabled: params.enabled,
+ id__in: params.id__in,
+ limit: params.limit,
+ offset: params.offset,
+ order_by: params.order_by,
+ search: params.search,
+ },
+ })
+ return await withPostHogUrl(
+ context,
+ {
+ ...result,
+ results: await Promise.all(
+ (result.results ?? []).map((item) =>
+ withPostHogUrl(context, item, `/llm-analytics/tags/${item.id}`)
+ )
+ ),
+ },
+ '/llm-analytics'
+ )
+ },
+})
+
+const LlmaTaggerTestHogSchema = TaggersTestHogCreateBody
+
+const llmaTaggerTestHog = (): ToolBase<typeof LlmaTaggerTestHogSchema, Schemas.TestHogTaggerResponse> => ({
+ name: 'llma-tagger-test-hog',
+ schema: LlmaTaggerTestHogSchema,
+ handler: async (context: Context, params: z.infer<typeof LlmaTaggerTestHogSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.source !== undefined) {
+ body['source'] = params.source
+ }
+ if (params.sample_count !== undefined) {
+ body['sample_count'] = params.sample_count
+ }
+ if (params.tags !== undefined) {
+ body['tags'] = params.tags
+ }
+ const result = await context.api.request<Schemas.TestHogTaggerResponse>({
+ method: 'POST',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/taggers/test_hog/`,
+ body,
+ })
+ return result
+ },
+})
+
const LlmaTraceReviewCreateSchema = LlmAnalyticsTraceReviewsCreateBody
const llmaTraceReviewCreate = (): ToolBase<
@@ -1653,6 +1754,9 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'llma-skill-list': llmaSkillList,
'llma-skill-update': llmaSkillUpdate,
'llma-summarization-create': llmaSummarizationCreate,
+ 'llma-tagger-create': llmaTaggerCreate,
+ 'llma-tagger-list': llmaTaggerList,
+ 'llma-tagger-test-hog': llmaTaggerTestHog,
'llma-trace-review-create': llmaTraceReviewCreate,
'llma-trace-review-delete': llmaTraceReviewDelete,
'llma-trace-review-get': llmaTraceReviewGet,
diff --git a/services/mcp/tests/unit/__snapshots__/exec-tool.json b/services/mcp/tests/unit/__snapshots__/exec-tool.json
index 0f425ca8162a..25f97137ad22 100644
--- a/services/mcp/tests/unit/__snapshots__/exec-tool.json
+++ b/services/mcp/tests/unit/__snapshots__/exec-tool.json
@@ -15,7 +15,7 @@
"properties": {
"command": {
"type": "string",
- "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary\nwith drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), you MUST call\n`schema <tool_name> <field_name>` for each field you need to populate BEFORE\nconstructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large),\ndrill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> properties` — to see property filter structure\n- `schema <tool> breakdownFilter` — when using breakdowns\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"Run `schema query-trends series` for full structure\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- batch\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-prompt-duplicate\n- llma-score-definition-new-version\n- llma-skill-archive\n- llma-skill-duplicate\n- llma-skill-file-rename\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first to load its full guidance.\n\n#### Searching for existing entities\n\nAny \"find / which / do we have / what's our X chart\" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.\n\nMap intent to table:\n\n- \"find an insight\" / \"what's our X chart\" / \"is this insight saved\" → `system.insights`\n- \"find a dashboard\" → `system.dashboards`\n- \"find a cohort\" → `system.cohorts`\n- \"find a feature flag\" → `system.feature_flags`\n- \"find an experiment\" → `system.experiments`\n- \"find a survey\" → `system.surveys`\n- \"find a notebook\" → `system.notebooks`\n\nSearch rules:\n\n1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.\n2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.\n3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.\n4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.\n5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.\n\n<example>\nUser: Do we have any insights tracking revenue?\nAssistant: [Calls `execute-sql` with `SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20`]\n[Picks the most plausible match by name, then calls `insight-get` with the candidate's `id` (or `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]\n<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>\n</example>\n\n<bad-example>\nUser: Find me a graph of MAUs.\nAssistant: [Calls `execute-sql` with `SELECT * FROM system.insights WHERE id = 33800 LIMIT 1` after a search SELECT already surfaced id 33800]\nWRONG — verify with `insight-get` (passing `id: 33800`) instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-lifecycle-actors` — List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nAll PostHog app URLs must use relative paths without a domain (no us.posthog.com, eu.posthog.com, app.posthog.com), and omit the `/project/:id/` prefix. Never include `/-/` in URLs.\nUse Markdown with descriptive anchor text, for example \"[Cohorts view](/cohorts)\".\n\nKey URL patterns:\n\n- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`\n- Data management: `/data-management/events`, `/data-management/properties`\n- Billing: `/organization/billing`\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"
+ "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary\nwith drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), you MUST call\n`schema <tool_name> <field_name>` for each field you need to populate BEFORE\nconstructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large),\ndrill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> properties` — to see property filter structure\n- `schema <tool> breakdownFilter` — when using breakdowns\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"Run `schema query-trends series` for full structure\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- batch\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-prompt-duplicate\n- llma-score-definition-new-version\n- llma-skill-archive\n- llma-skill-duplicate\n- llma-skill-file-rename\n- llma-tagger-test-hog\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first to load its full guidance.\n\n#### Searching for existing entities\n\nAny \"find / which / do we have / what's our X chart\" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.\n\nMap intent to table:\n\n- \"find an insight\" / \"what's our X chart\" / \"is this insight saved\" → `system.insights`\n- \"find a dashboard\" → `system.dashboards`\n- \"find a cohort\" → `system.cohorts`\n- \"find a feature flag\" → `system.feature_flags`\n- \"find an experiment\" → `system.experiments`\n- \"find a survey\" → `system.surveys`\n- \"find a notebook\" → `system.notebooks`\n\nSearch rules:\n\n1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.\n2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.\n3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.\n4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.\n5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.\n\n<example>\nUser: Do we have any insights tracking revenue?\nAssistant: [Calls `execute-sql` with `SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20`]\n[Picks the most plausible match by name, then calls `insight-get` with the candidate's `id` (or `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]\n<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>\n</example>\n\n<bad-example>\nUser: Find me a graph of MAUs.\nAssistant: [Calls `execute-sql` with `SELECT * FROM system.insights WHERE id = 33800 LIMIT 1` after a search SELECT already surfaced id 33800]\nWRONG — verify with `insight-get` (passing `id: 33800`) instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-lifecycle-actors` — List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nAll PostHog app URLs must use relative paths without a domain (no us.posthog.com, eu.posthog.com, app.posthog.com), and omit the `/project/:id/` prefix. Never include `/-/` in URLs.\nUse Markdown with descriptive anchor text, for example \"[Cohorts view](/cohorts)\".\n\nKey URL patterns:\n\n- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`\n- Data management: `/data-management/events`, `/data-management/properties`\n- Billing: `/organization/billing`\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"
}
},
"required": ["command"]
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-tagger-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-tagger-create.json
new file mode 100644
index 000000000000..299da5570f4e
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-tagger-create.json
@@ -0,0 +1,187 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "conditions": {
+ "description": "Conditions that scope when the tagger runs",
+ "items": {
+ "properties": {
+ "id": {
+ "description": "Stable identifier for this condition",
+ "maxLength": 100,
+ "type": "string"
+ },
+ "properties": {
+ "description": "Property filters that scope when this condition fires",
+ "items": {
+ "additionalProperties": {},
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "rollout_percentage": {
+ "default": 100,
+ "description": "Percentage of matching events to apply this condition to",
+ "maximum": 100,
+ "minimum": 0,
+ "type": "number"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "description": {
+ "type": "string"
+ },
+ "enabled": {
+ "type": "boolean"
+ },
+ "model_configuration": {
+ "anyOf": [
+ {
+ "properties": {
+ "model": {
+ "description": "Provider model identifier to use for this tagger.",
+ "maxLength": 100,
+ "type": "string"
+ },
+ "provider": {
+ "description": "LLM provider to use for this tagger.\n\n* `openai` - Openai\n* `anthropic` - Anthropic\n* `gemini` - Gemini\n* `openrouter` - Openrouter\n* `fireworks` - Fireworks\n* `azure_openai` - Azure OpenAI\n* `together_ai` - Together AI",
+ "enum": [
+ "openai",
+ "anthropic",
+ "gemini",
+ "openrouter",
+ "fireworks",
+ "azure_openai",
+ "together_ai"
+ ],
+ "type": "string"
+ },
+ "provider_key_id": {
+ "anyOf": [
+ {
+ "format": "uuid",
+ "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Existing LLM provider key UUID for the current project. Do not invent this value; use a real provider key ID returned by PostHog, or omit/null when no provider key should be pinned."
+ }
+ },
+ "required": ["provider", "model"],
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "name": {
+ "maxLength": 400,
+ "type": "string"
+ },
+ "tagger_config": {
+ "anyOf": [
+ {
+ "properties": {
+ "max_tags": {
+ "anyOf": [
+ {
+ "minimum": 1,
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Maximum number of tags to apply (null = no limit)"
+ },
+ "min_tags": {
+ "default": 0,
+ "description": "Minimum number of tags to apply",
+ "minimum": 0,
+ "type": "number"
+ },
+ "prompt": {
+ "description": "Prompt instructing the LLM how to tag generations",
+ "minLength": 1,
+ "type": "string"
+ },
+ "tags": {
+ "description": "Available tags the LLM can assign",
+ "items": {
+ "properties": {
+ "description": {
+ "default": "",
+ "description": "Description to help the LLM classify",
+ "maxLength": 500,
+ "type": "string"
+ },
+ "name": {
+ "description": "Tag identifier",
+ "maxLength": 100,
+ "type": "string"
+ }
+ },
+ "required": ["name"],
+ "type": "object"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["prompt", "tags"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "source": {
+ "description": "Hog source code to classify a generation into tags.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "tags": {
+ "description": "Optional tag whitelist. Leave empty to allow any tag returned by the Hog code.",
+ "items": {
+ "properties": {
+ "description": {
+ "default": "",
+ "description": "Description to help the LLM classify",
+ "maxLength": 500,
+ "type": "string"
+ },
+ "name": {
+ "description": "Tag identifier",
+ "maxLength": 100,
+ "type": "string"
+ }
+ },
+ "required": ["name"],
+ "type": "object"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["source"],
+ "type": "object"
+ }
+ ],
+ "description": "Tagger configuration. For tagger_type 'llm': {prompt, tags, min_tags?, max_tags?}. For tagger_type 'hog': {source, tags?}."
+ },
+ "tagger_type": {
+ "default": "llm",
+ "description": "* `llm` - LLM\n* `hog` - Hog",
+ "enum": ["llm", "hog"],
+ "type": "string"
+ }
+ },
+ "required": ["name", "tagger_config"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-tagger-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-tagger-list.json
new file mode 100644
index 000000000000..3bba74b76799
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-tagger-list.json
@@ -0,0 +1,36 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "enabled": {
+ "description": "Filter by enabled status",
+ "type": "boolean"
+ },
+ "id__in": {
+ "description": "Multiple values may be separated by commas.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "limit": {
+ "description": "Number of results to return per page.",
+ "type": "number"
+ },
+ "offset": {
+ "description": "The initial index from which to return the results.",
+ "type": "number"
+ },
+ "order_by": {
+ "description": "Ordering\n\n* `created_at` - Created At\n* `-created_at` - Created At (descending)\n* `updated_at` - Updated At\n* `-updated_at` - Updated At (descending)\n* `name` - Name\n* `-name` - Name (descending)",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "search": {
+ "description": "Search in name or description",
+ "type": "string"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-tagger-test-hog.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-tagger-test-hog.json
new file mode 100644
index 000000000000..94f146a97d58
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-tagger-test-hog.json
@@ -0,0 +1,40 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "sample_count": {
+ "default": 5,
+ "description": "Number of recent $ai_generation events to test against (1-10, default 5).",
+ "maximum": 10,
+ "minimum": 1,
+ "type": "number"
+ },
+ "source": {
+ "description": "Hog source code to test. Return a tag name string, a list of tag name strings, or null.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "tags": {
+ "description": "Optional tag whitelist. Returned tags outside this list are filtered out.",
+ "items": {
+ "properties": {
+ "description": {
+ "default": "",
+ "description": "Optional description for the tag.",
+ "maxLength": 500,
+ "type": "string"
+ },
+ "name": {
+ "description": "Tag identifier to allow in Hog test results.",
+ "maxLength": 100,
+ "type": "string"
+ }
+ },
+ "required": ["name"],
+ "type": "object"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["source"],
+ "type": "object"
+}