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): expose scorer definitions as MCP tools (#57513)

Carlos Marchalbcd36ec230ef
diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.py
index 2414a75b41d4..5f3acc4d35b6 100644
--- a/posthog/hogql/database/schema/system.py
+++ b/posthog/hogql/database/schema/system.py
@@ -939,6 +939,24 @@ trace_review_scores: PostgresTable = PostgresTable(
},
)
+score_definitions: PostgresTable = PostgresTable(
+ name="score_definitions",
+ postgres_table_name="llm_analytics_scoredefinition",
+ access_scope="llm_analytics",
+ fields={
+ "id": UUIDDatabaseField(name="id"),
+ "team_id": IntegerDatabaseField(name="team_id"),
+ "name": StringDatabaseField(name="name"),
+ "description": StringDatabaseField(name="description"),
+ "kind": StringDatabaseField(name="kind"),
+ "archived": BooleanDatabaseField(name="archived"),
+ "current_version_id": UUIDDatabaseField(name="current_version_id", nullable=True),
+ "created_by_id": IntegerDatabaseField(name="created_by_id", nullable=True),
+ "created_at": DateTimeDatabaseField(name="created_at"),
+ "updated_at": DateTimeDatabaseField(name="updated_at", nullable=True),
+ },
+)
+
early_access_features: PostgresTable = PostgresTable(
name="early_access_features",
postgres_table_name="posthog_earlyaccessfeature",
@@ -1117,6 +1135,7 @@ class SystemTables(TableNode):
"sandbox_environments": TableNode(name="sandbox_environments", table=sandbox_environments),
"review_queue_items": TableNode(name="review_queue_items", table=review_queue_items),
"review_queues": TableNode(name="review_queues", table=review_queues),
+ "score_definitions": TableNode(name="score_definitions", table=score_definitions),
"session_recording_playlists": TableNode(name="session_recording_playlists", table=session_recording_playlists),
"session_recordings": TableNode(name="session_recordings", table=session_recordings),
"source_schemas": TableNode(name="source_schemas", table=source_schemas),
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index 6848d6c617c3..6bd77abf5b93 100644
--- a/posthog/hogql/database/schema/test/test_system_tables.py
+++ b/posthog/hogql/database/schema/test/test_system_tables.py
@@ -379,6 +379,22 @@ def _create_trace_review(team: Team, label: str) -> TraceReview:
)
+def _create_score_definition(team: Team, label: str) -> ScoreDefinition:
+ user = _get_or_create_user_for_team(team, label)
+ definition = ScoreDefinition.objects.create(
+ team=team,
+ name=f"score_definition_{label}",
+ description="",
+ kind=ScoreDefinition.Kind.BOOLEAN,
+ created_by=user,
+ )
+ definition.create_new_version(
+ config={"true_label": "Yes", "false_label": "No"},
+ created_by=user,
+ )
+ return definition
+
+
def _create_trace_review_score(team: Team, label: str) -> TraceReviewScore:
user = _get_or_create_user_for_team(team, label)
review = TraceReview.objects.create(
@@ -536,6 +552,7 @@ SYSTEM_TABLE_FACTORIES = [
("review_queue_items", _create_review_queue_item),
("review_queues", _create_review_queue),
("sandbox_environments", _create_sandbox_environment),
+ ("score_definitions", _create_score_definition),
("session_recording_playlists", _create_session_recording_playlist),
("session_recordings", _create_session_recording),
("source_schemas", _create_source_schema),
diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambr
index 471c3e836f8a..eae9f5e9c579 100644
--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr
+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr
@@ -6184,6 +6184,84 @@
"row_count": null,
"type": "system"
},
+ "system.score_definitions": {
+ "fields": {
+ "name": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "name",
+ "id": null,
+ "name": "name",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "description": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "description",
+ "id": null,
+ "name": "description",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "kind": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "kind",
+ "id": null,
+ "name": "kind",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "archived": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "archived",
+ "id": null,
+ "name": "archived",
+ "schema_valid": true,
+ "table": null,
+ "type": "boolean"
+ },
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
+ "created_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_at",
+ "id": null,
+ "name": "created_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ },
+ "updated_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "updated_at",
+ "id": null,
+ "name": "updated_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ }
+ },
+ "id": "system.score_definitions",
+ "name": "system.score_definitions",
+ "row_count": null,
+ "type": "system"
+ },
"system.session_recording_playlists": {
"fields": {
"id": {
@@ -13368,6 +13446,84 @@
"row_count": null,
"type": "system"
},
+ "system.score_definitions": {
+ "fields": {
+ "name": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "name",
+ "id": null,
+ "name": "name",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "description": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "description",
+ "id": null,
+ "name": "description",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "kind": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "kind",
+ "id": null,
+ "name": "kind",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "archived": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "archived",
+ "id": null,
+ "name": "archived",
+ "schema_valid": true,
+ "table": null,
+ "type": "boolean"
+ },
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
+ "created_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_at",
+ "id": null,
+ "name": "created_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ },
+ "updated_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "updated_at",
+ "id": null,
+ "name": "updated_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ }
+ },
+ "id": "system.score_definitions",
+ "name": "system.score_definitions",
+ "row_count": null,
+ "type": "system"
+ },
"system.session_recording_playlists": {
"fields": {
"id": {
diff --git a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr
index 4b59eafdfff8..7b67fbd60823 100644
--- a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr
+++ b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr
@@ -110,7 +110,7 @@
This is a list of all the available tables in the database:
```
- ['events', 'groups', 'persons', 'sessions', 'logs', 'query_log', 'system.activity_logs', 'system.actions', 'system.alerts', 'system.annotations', 'system.batch_export_backfills', 'system.batch_exports', 'system.cohort_calculation_history', 'system.cohorts', 'system.dashboards', 'system.data_modeling_jobs', 'system.data_modeling_views', 'system.data_modeling_endpoint_versions', 'system.data_modeling_endpoints', 'system.data_warehouse_sources', 'system.data_warehouse_tables', 'system.error_tracking_assignment_rules', 'system.error_tracking_issue_assignments', 'system.error_tracking_issue_fingerprints', 'system.error_tracking_issues', 'system.error_tracking_releases', 'system.error_tracking_symbol_sets', 'system.error_tracking_suppression_rules', 'system.early_access_features', 'system.experiments', 'system.exports', 'system.feature_flags', 'system.groups', 'system.group_type_mappings', 'system.hog_flows', 'system.hog_functions', 'system.ingestion_warnings', 'system.integrations', 'system.integration_repository_cache', 'system.insight_variables', 'system.logs_alerts', 'system.logs_views', 'system.insights', 'system.notebooks', 'system.sandbox_environments', 'system.review_queue_items', 'system.review_queues', 'system.session_recording_playlists', 'system.session_recordings', 'system.source_schemas', 'system.source_sync_jobs', 'system.support_tickets', 'system.surveys', 'system.task_runs', 'system.tasks', 'system.teams', 'system.trace_review_scores', 'system.trace_reviews', 'system.usage_metrics']
+ ['events', 'groups', 'persons', 'sessions', 'logs', 'query_log', 'system.activity_logs', 'system.actions', 'system.alerts', 'system.annotations', 'system.batch_export_backfills', 'system.batch_exports', 'system.cohort_calculation_history', 'system.cohorts', 'system.dashboards', 'system.data_modeling_jobs', 'system.data_modeling_views', 'system.data_modeling_endpoint_versions', 'system.data_modeling_endpoints', 'system.data_warehouse_sources', 'system.data_warehouse_tables', 'system.error_tracking_assignment_rules', 'system.error_tracking_issue_assignments', 'system.error_tracking_issue_fingerprints', 'system.error_tracking_issues', 'system.error_tracking_releases', 'system.error_tracking_symbol_sets', 'system.error_tracking_suppression_rules', 'system.early_access_features', 'system.experiments', 'system.exports', 'system.feature_flags', 'system.groups', 'system.group_type_mappings', 'system.hog_flows', 'system.hog_functions', 'system.ingestion_warnings', 'system.integrations', 'system.integration_repository_cache', 'system.insight_variables', 'system.logs_alerts', 'system.logs_views', 'system.insights', 'system.notebooks', 'system.sandbox_environments', 'system.review_queue_items', 'system.review_queues', 'system.score_definitions', 'system.session_recording_playlists', 'system.session_recordings', 'system.source_schemas', 'system.source_sync_jobs', 'system.support_tickets', 'system.surveys', 'system.task_runs', 'system.tasks', 'system.teams', 'system.trace_review_scores', 'system.trace_reviews', 'system.usage_metrics']
```
`person` or `event` metadata unspecified above (emails, names, etc.) is stored in `properties` fields, accessed like: `properties.foo.bar`.
diff --git a/products/llm_analytics/backend/api/score_definitions.py b/products/llm_analytics/backend/api/score_definitions.py
index a7d7654b5503..b031e4ed5bad 100644
--- a/products/llm_analytics/backend/api/score_definitions.py
+++ b/products/llm_analytics/backend/api/score_definitions.py
@@ -27,7 +27,7 @@ from posthog.models import Team, User
from posthog.permissions import AccessControlPermission
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
-from products.llm_analytics.backend.models.score_definitions import ScoreDefinition
+from products.llm_analytics.backend.models.score_definitions import ScoreDefinition, StaleScoreDefinitionVersion
from products.llm_analytics.backend.score_definition_configs import ScoreDefinitionConfigField
HUMAN_REVIEWS_FEATURE_FLAG = "llma-trace-review"
@@ -64,6 +64,11 @@ class ScoreDefinitionSerializer(serializers.ModelSerializer):
read_only=True,
help_text="Current immutable configuration version number.",
)
+ current_version_id = serializers.UUIDField(
+ read_only=True,
+ allow_null=True,
+ help_text="UUID of the current version row. Matches `system.score_definitions.current_version_id` in HogQL.",
+ )
config = ScoreDefinitionConfigField(
source="current_version.config",
read_only=True,
@@ -79,6 +84,7 @@ class ScoreDefinitionSerializer(serializers.ModelSerializer):
"kind",
"archived",
"current_version",
+ "current_version_id",
"config",
"created_by",
"created_at",
@@ -141,6 +147,15 @@ class ScoreDefinitionMetadataSerializer(serializers.Serializer):
class ScoreDefinitionNewVersionSerializer(serializers.Serializer):
config = ScoreDefinitionConfigField(help_text="Next immutable scorer configuration.")
+ base_version = serializers.IntegerField(
+ required=False,
+ min_value=1,
+ help_text=(
+ "Version number the caller observed before requesting this bump. "
+ "If provided and it does not match the scorer's current version, the request fails with 409. "
+ "Omit to skip the optimistic-concurrency check."
+ ),
+ )
class ScoreDefinitionFilter(django_filters.FilterSet):
@@ -199,10 +214,18 @@ class ScoreDefinitionViewSet(
def safely_get_queryset(
self, queryset: QuerySet[ScoreDefinition, ScoreDefinition]
) -> QuerySet[ScoreDefinition, ScoreDefinition]:
- return (
+ queryset = (
queryset.filter(team_id=self.team_id).select_related("current_version", "created_by").order_by("name", "id")
)
+ # List defaults to active scorers to mirror the UI; non-boolean `?archived=` values keep that default.
+ if self.action == "list":
+ archived_param = (self.request.query_params.get("archived") or "").strip().lower()
+ if archived_param not in {"true", "false", "1", "0"}:
+ queryset = queryset.filter(archived=False)
+
+ return queryset
+
@staticmethod
def _event_properties(definition: ScoreDefinition) -> dict[str, str | bool | int]:
current_version = definition.current_version.version if definition.current_version else 0
@@ -251,7 +274,11 @@ class ScoreDefinitionViewSet(
def _create_definition_version(
self, definition: ScoreDefinition, validated_data: dict[str, Any]
) -> ScoreDefinition:
- definition.create_new_version(config=validated_data["config"], created_by=cast(User, self.request.user))
+ definition.create_new_version(
+ config=validated_data["config"],
+ created_by=cast(User, self.request.user),
+ base_version=validated_data.get("base_version"),
+ )
definition.refresh_from_db(fields=["current_version", "updated_at"])
return definition
@@ -331,7 +358,12 @@ class ScoreDefinitionViewSet(
return Response(self.get_serializer(definition).data, status=status.HTTP_200_OK)
@extend_schema(request=ScoreDefinitionNewVersionSerializer, responses=ScoreDefinitionSerializer)
- @action(detail=True, methods=["post"], url_path="new_version")
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="new_version",
+ required_scopes=["llm_analytics:write"],
+ )
def new_version(self, request: Request, *args: Any, **kwargs: Any) -> Response:
definition = self.get_object()
serializer = ScoreDefinitionNewVersionSerializer(
@@ -339,7 +371,17 @@ class ScoreDefinitionViewSet(
context={**self.get_serializer_context(), "score_definition_kind": definition.kind},
)
serializer.is_valid(raise_exception=True)
- definition = self._create_definition_version(definition, dict(serializer.validated_data))
+
+ try:
+ definition = self._create_definition_version(definition, dict(serializer.validated_data))
+ except StaleScoreDefinitionVersion as err:
+ return Response(
+ {
+ "detail": "The scorer changed since you opened it. Reload the latest version and try again.",
+ "current_version": err.current_version,
+ },
+ status=status.HTTP_409_CONFLICT,
+ )
report_user_action(
request.user,
diff --git a/products/llm_analytics/backend/api/test/test_score_definitions.py b/products/llm_analytics/backend/api/test/test_score_definitions.py
index 87df2b7055fd..bd897a51f42f 100644
--- a/products/llm_analytics/backend/api/test/test_score_definitions.py
+++ b/products/llm_analytics/backend/api/test/test_score_definitions.py
@@ -4,7 +4,11 @@ from unittest.mock import ANY, patch
from parameterized import parameterized
from rest_framework import status
-from products.llm_analytics.backend.models.score_definitions import ScoreDefinition, ScoreDefinitionVersion
+from products.llm_analytics.backend.models.score_definitions import (
+ ScoreDefinition,
+ ScoreDefinitionVersion,
+ StaleScoreDefinitionVersion,
+)
class TestScoreDefinitionsApi(APIBaseTest):
@@ -126,6 +130,57 @@ class TestScoreDefinitionsApi(APIBaseTest):
definition = ScoreDefinition.objects.get(pk=response.data["id"])
self.assertFalse(definition.archived)
+ @parameterized.expand(
+ [
+ (
+ "numeric_with_categorical_keys",
+ "numeric",
+ {"options": [{"key": "a", "label": "A"}]},
+ ),
+ (
+ "boolean_with_numeric_keys",
+ "boolean",
+ {"min": 0, "max": 1},
+ ),
+ (
+ "categorical_with_boolean_keys",
+ "categorical",
+ {"true_label": "Yes", "false_label": "No"},
+ ),
+ ]
+ )
+ def test_create_rejects_config_keys_that_do_not_match_kind(self, _name: str, kind: str, config: dict):
+ response = self.client.post(
+ self._endpoint(),
+ {"name": "Mismatch", "kind": kind, "config": config},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.data["attr"], "config")
+ self.assertIn("Unsupported keys", response.data["detail"])
+
+ def test_response_exposes_current_version_id(self):
+ response = self.client.post(
+ self._endpoint(),
+ {
+ "name": "Quality",
+ "kind": "categorical",
+ "config": {
+ "options": [
+ {"key": "good", "label": "Good"},
+ {"key": "bad", "label": "Bad"},
+ ]
+ },
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ definition = ScoreDefinition.objects.get(pk=response.data["id"])
+ self.assertEqual(response.data["current_version"], 1)
+ self.assertEqual(response.data["current_version_id"], str(definition.current_version_id))
+
def test_create_rejects_archived_scorers(self):
response = self.client.post(
self._endpoint(),
@@ -218,6 +273,174 @@ class TestScoreDefinitionsApi(APIBaseTest):
},
)
+ def test_new_version_with_matching_base_version_advances_to_v2(self):
+ definition = self._create_definition()
+
+ response = self.client.post(
+ f"{self._endpoint()}{definition.id}/new_version/",
+ {
+ "base_version": 1,
+ "config": {
+ "options": [
+ {"key": "pass", "label": "Pass"},
+ {"key": "fail", "label": "Fail"},
+ ]
+ },
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ definition.refresh_from_db()
+ self.assertEqual(self._current_version(definition).version, 2)
+
+ def test_create_new_version_raises_when_base_version_is_stale_at_lock_time(self):
+ """Lower-level guarantee: the base_version check happens inside `select_for_update`.
+
+ A regression that moves the check above the lock would let two concurrent writers with the
+ same `base_version` both pass — exactly what OCC must prevent. Asserting the model contract
+ here keeps that fix in place even if the view layer changes.
+ """
+ definition = self._create_definition()
+ # Another writer advances the scorer to v2 — equivalent to "the row was bumped between when
+ # the caller observed v1 and when the caller's transaction acquired the lock".
+ definition.create_new_version(
+ config={"options": [{"key": "winner", "label": "Winner"}]},
+ created_by=self.user,
+ )
+
+ with self.assertRaises(StaleScoreDefinitionVersion) as cm:
+ definition.create_new_version(
+ config={"options": [{"key": "loser", "label": "Loser"}]},
+ created_by=self.user,
+ base_version=1,
+ )
+
+ self.assertEqual(cm.exception.current_version, 2)
+ # No third version was created.
+ self.assertEqual(ScoreDefinitionVersion.objects.filter(definition=definition).count(), 2)
+
+ def test_new_version_with_stale_base_version_returns_409(self):
+ definition = self._create_definition()
+ # Someone else bumps the scorer to v2 first.
+ definition.create_new_version(
+ config={"options": [{"key": "intermediate", "label": "Intermediate"}]},
+ created_by=self.user,
+ )
+
+ response = self.client.post(
+ f"{self._endpoint()}{definition.id}/new_version/",
+ {
+ "base_version": 1,
+ "config": {
+ "options": [
+ {"key": "stale", "label": "Stale"},
+ ]
+ },
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
+ self.assertEqual(response.data["current_version"], 2)
+ definition.refresh_from_db()
+ # Scorer still at v2 — the stale request did not bump it.
+ self.assertEqual(self._current_version(definition).version, 2)
+
+ @parameterized.expand(
+ [
+ ("smuggle_boolean_kind_with_boolean_config", "categorical", "boolean", {"true_label": "Yes"}),
+ ("smuggle_numeric_kind_with_numeric_config", "categorical", "numeric", {"min": 0, "max": 1}),
+ (
+ "smuggle_categorical_kind_with_categorical_config",
+ "boolean",
+ "categorical",
+ {"options": [{"key": "a", "label": "A"}]},
+ ),
+ ]
+ )
+ def test_new_version_ignores_kind_smuggled_in_body(
+ self, _name: str, scorer_kind: str, smuggled_kind: str, config: dict
+ ):
+ definition = self._create_definition(kind=scorer_kind)
+
+ response = self.client.post(
+ f"{self._endpoint()}{definition.id}/new_version/",
+ {"kind": smuggled_kind, "config": config},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.data["attr"], "config")
+ self.assertIn("Unsupported keys", response.data["detail"])
+ definition.refresh_from_db()
+ self.assertEqual(self._current_version(definition).version, 1)
+
+ # The /new_version/ custom @action has to declare required_scopes explicitly;
+ # without it the default scope resolver returns None for non-CRUD action names and PAK
+ # requests are rejected with "This action does not support personal API key access".
+ @parameterized.expand(
+ [
+ ("write_scope_allowed", ["llm_analytics:write"], status.HTTP_200_OK),
+ ("read_scope_denied", ["llm_analytics:read"], status.HTTP_403_FORBIDDEN),
+ ("wrong_scope_denied", ["insight:write"], status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ def test_new_version_pak_scope(self, _name: str, scopes: list[str], expected_status: int) -> None:
+ definition = self._create_definition()
+ api_key = self.create_personal_api_key_with_scopes(scopes)
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")
+
+ response = self.client.post(
+ f"{self._endpoint()}{definition.id}/new_version/",
+ {
+ "config": {
+ "options": [
+ {"key": "pak-pass", "label": "Pass"},
+ ]
+ }
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, expected_status)
+
+ def test_list_defaults_to_active_only_and_respects_archived_param(self):
+ active = self._create_definition(name="Active scorer", kind="categorical")
+ archived = self._create_definition(name="Archived scorer", kind="categorical", archived=True)
+
+ # Default — no archived param → active only
+ response = self.client.get(self._endpoint())
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ ids = [result["id"] for result in response.data["results"]]
+ self.assertIn(str(active.id), ids)
+ self.assertNotIn(str(archived.id), ids)
+
+ # archived=false → active only (same as default)
+ response = self.client.get(self._endpoint(), {"archived": "false"})
+ ids = [result["id"] for result in response.data["results"]]
+ self.assertIn(str(active.id), ids)
+ self.assertNotIn(str(archived.id), ids)
+
+ # archived=true → archived only
+ response = self.client.get(self._endpoint(), {"archived": "true"})
+ ids = [result["id"] for result in response.data["results"]]
+ self.assertNotIn(str(active.id), ids)
+ self.assertIn(str(archived.id), ids)
+
+ @parameterized.expand([("empty", ""), ("whitespace", " "), ("unparseable", "invalid")])
+ def test_list_treats_non_boolean_archived_param_as_default_active_only(self, _name: str, value: str):
+ active = self._create_definition(name="Active scorer", kind="categorical")
+ archived = self._create_definition(name="Archived scorer", kind="categorical", archived=True)
+
+ response = self.client.get(self._endpoint(), {"archived": value})
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ ids = [result["id"] for result in response.data["results"]]
+ self.assertIn(str(active.id), ids)
+ self.assertNotIn(str(archived.id), ids)
+
def test_list_supports_search_kind_archived_and_ordering(self):
active = self._create_definition(name="Quality", kind="categorical")
archived = self._create_definition(
@@ -307,6 +530,20 @@ class TestScoreDefinitionsApi(APIBaseTest):
request=ANY,
)
+ def _default_config_for_kind(self, kind: str) -> dict:
+ if kind == "categorical":
+ return {
+ "options": [
+ {"key": "good", "label": "Good"},
+ {"key": "bad", "label": "Bad"},
+ ]
+ }
+ if kind == "numeric":
+ return {"min": 0, "max": 1, "step": 0.1}
+ if kind == "boolean":
+ return {"true_label": "Yes", "false_label": "No"}
+ raise ValueError(f"Unsupported kind: {kind}")
+
def _create_definition(
self,
*,
@@ -318,13 +555,7 @@ class TestScoreDefinitionsApi(APIBaseTest):
payload = {
"name": name,
"kind": kind,
- "config": config
- or {
- "options": [
- {"key": "good", "label": "Good"},
- {"key": "bad", "label": "Bad"},
- ]
- },
+ "config": config or self._default_config_for_kind(kind),
}
response = self.client.post(self._endpoint(), payload, format="json")
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
diff --git a/products/llm_analytics/backend/models/score_definitions.py b/products/llm_analytics/backend/models/score_definitions.py
index eeca55679d12..f682f1978185 100644
--- a/products/llm_analytics/backend/models/score_definitions.py
+++ b/products/llm_analytics/backend/models/score_definitions.py
@@ -9,6 +9,14 @@ from posthog.models.user import User
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
+class StaleScoreDefinitionVersion(Exception):
+ """Raised when a caller's `base_version` no longer matches the scorer's current version."""
+
+ def __init__(self, current_version: int) -> None:
+ super().__init__(f"Scorer current version is {current_version}.")
+ self.current_version = current_version
+
+
class ScoreDefinition(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
class Kind(models.TextChoices):
CATEGORICAL = "categorical", "categorical"
@@ -33,13 +41,22 @@ class ScoreDefinition(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
indexes = [models.Index(fields=["team", "kind", "archived"], name="llma_score_def_team_kind_idx")]
@transaction.atomic
- def create_new_version(self, *, config: dict[str, Any], created_by: User | None) -> ScoreDefinitionVersion:
- definition = ScoreDefinition.objects.select_for_update().get(pk=self.pk)
- current_version_number = (
- ScoreDefinitionVersion.objects.only("version").get(pk=definition.current_version_id).version
- if definition.current_version_id is not None
- else 0
+ def create_new_version(
+ self,
+ *,
+ config: dict[str, Any],
+ created_by: User | None,
+ base_version: int | None = None,
+ ) -> ScoreDefinitionVersion:
+ definition = (
+ ScoreDefinition.objects.select_for_update(of=("self",)).select_related("current_version").get(pk=self.pk)
)
+ current_version_number = definition.current_version.version if definition.current_version is not None else 0
+
+ # Optimistic concurrency check inside the row lock — two writers seeing the same `base_version`
+ # before the lock would otherwise both pass; one must lose here once the lock serializes them.
+ if base_version is not None and base_version != current_version_number:
+ raise StaleScoreDefinitionVersion(current_version=current_version_number)
version = ScoreDefinitionVersion.objects.create(
definition=definition,
diff --git a/products/llm_analytics/backend/score_definition_configs.py b/products/llm_analytics/backend/score_definition_configs.py
index 3ff5ce3cc836..e217bc0490e1 100644
--- a/products/llm_analytics/backend/score_definition_configs.py
+++ b/products/llm_analytics/backend/score_definition_configs.py
@@ -171,6 +171,15 @@ class ScoreDefinitionConfigField(serializers.Field):
def to_internal_value(self, data: Any) -> dict[str, Any]:
kind = self._get_score_definition_kind()
serializer = build_score_definition_config_serializer(kind, data=data)
+
+ if isinstance(data, dict):
+ allowed_keys = set(serializer.fields.keys())
+ unknown_keys = sorted(set(data.keys()) - allowed_keys)
+ if unknown_keys:
+ raise serializers.ValidationError(
+ f"Unsupported keys for `kind` `{kind}`: {unknown_keys}. Allowed keys: {sorted(allowed_keys)}."
+ )
+
serializer.is_valid(raise_exception=True)
return dict(serializer.validated_data)
@@ -178,6 +187,11 @@ class ScoreDefinitionConfigField(serializers.Field):
return value
def _get_score_definition_kind(self) -> str:
+ # Context wins over body to prevent a smuggled `kind` from validating `config` against the wrong schema.
+ kind = self.context.get("score_definition_kind")
+ if isinstance(kind, str) and kind:
+ return kind
+
initial_data = getattr(self.parent, "initial_data", None)
if isinstance(initial_data, dict):
kind = initial_data.get("kind")
@@ -190,8 +204,4 @@ class ScoreDefinitionConfigField(serializers.Field):
if isinstance(kind, str) and kind:
return kind
- kind = self.context.get("score_definition_kind")
- if isinstance(kind, str) and kind:
- return kind
-
raise serializers.ValidationError({"kind": "Set `kind` before validating `config`."})
diff --git a/products/llm_analytics/frontend/generated/api.schemas.ts b/products/llm_analytics/frontend/generated/api.schemas.ts
index 631fea249ab0..351bff59e067 100644
--- a/products/llm_analytics/frontend/generated/api.schemas.ts
+++ b/products/llm_analytics/frontend/generated/api.schemas.ts
@@ -1087,6 +1087,11 @@ export interface ScoreDefinitionApi {
readonly archived: boolean
/** Current immutable configuration version number. */
readonly current_version: number
+ /**
+ * UUID of the current version row. Matches `system.score_definitions.current_version_id` in HogQL.
+ * @nullable
+ */
+ readonly current_version_id: string | null
/** Current immutable scorer configuration. */
readonly config: ScoreDefinitionConfigApi
/** User who created the scorer. */
@@ -1147,6 +1152,11 @@ export interface PatchedScoreDefinitionMetadataApi {
export interface ScoreDefinitionNewVersionApi {
/** Next immutable scorer configuration. */
config: ScoreDefinitionConfigApi
+ /**
+ * Version number the caller observed before requesting this bump. If provided and it does not match the scorer's current version, the request fails with 409. Omit to skip the optimistic-concurrency check.
+ * @minimum 1
+ */
+ base_version?: number
}
/**
diff --git a/products/llm_analytics/frontend/generated/api.zod.ts b/products/llm_analytics/frontend/generated/api.zod.ts
index 40d54d866397..762a98dcad5a 100644
--- a/products/llm_analytics/frontend/generated/api.zod.ts
+++ b/products/llm_analytics/frontend/generated/api.zod.ts
@@ -1067,6 +1067,13 @@ export const LlmAnalyticsScoreDefinitionsNewVersionCreateBody = /* @__PURE__ */
}),
])
.describe('Next immutable scorer configuration.'),
+ base_version: zod
+ .number()
+ .min(1)
+ .optional()
+ .describe(
+ "Version number the caller observed before requesting this bump. If provided and it does not match the scorer's current version, the request fails with 409. Omit to skip the optimistic-concurrency check."
+ ),
})
export const llmAnalyticsSentimentCreateBodyIdsMax = 5
diff --git a/products/llm_analytics/frontend/scoreDefinitions/llmAnalyticsScoreDefinitionsLogic.test.ts b/products/llm_analytics/frontend/scoreDefinitions/llmAnalyticsScoreDefinitionsLogic.test.ts
index cba529f9fe96..427aa9de7ffe 100644
--- a/products/llm_analytics/frontend/scoreDefinitions/llmAnalyticsScoreDefinitionsLogic.test.ts
+++ b/products/llm_analytics/frontend/scoreDefinitions/llmAnalyticsScoreDefinitionsLogic.test.ts
@@ -27,6 +27,7 @@ const mockScoreDefinition: ScoreDefinition = {
kind: 'categorical',
archived: false,
current_version: 2,
+ current_version_id: null,
config: {
options: [
{ key: 'good', label: 'Good' },
diff --git a/products/llm_analytics/frontend/scoreDefinitions/scoreDefinitionModalLogic.test.ts b/products/llm_analytics/frontend/scoreDefinitions/scoreDefinitionModalLogic.test.ts
index 86f8603cb1f1..edb25598837d 100644
--- a/products/llm_analytics/frontend/scoreDefinitions/scoreDefinitionModalLogic.test.ts
+++ b/products/llm_analytics/frontend/scoreDefinitions/scoreDefinitionModalLogic.test.ts
@@ -29,6 +29,7 @@ const mockScoreDefinition: ScoreDefinition = {
kind: 'categorical',
archived: false,
current_version: 2,
+ current_version_id: null,
config: {
options: [
{ key: 'good', label: 'Good' },
diff --git a/products/llm_analytics/frontend/traceReviews/traceReviewModalLogic.test.ts b/products/llm_analytics/frontend/traceReviews/traceReviewModalLogic.test.ts
index 33124cfc9618..94367faf85b9 100644
--- a/products/llm_analytics/frontend/traceReviews/traceReviewModalLogic.test.ts
+++ b/products/llm_analytics/frontend/traceReviews/traceReviewModalLogic.test.ts
@@ -40,6 +40,7 @@ describe('traceReviewModalLogic', () => {
kind: 'boolean',
archived: false,
current_version: 1,
+ current_version_id: null,
config: {
true_label: 'Yes',
false_label: 'No',
@@ -57,6 +58,7 @@ describe('traceReviewModalLogic', () => {
kind: 'numeric',
archived: false,
current_version: 1,
+ current_version_id: null,
config: {
min: 0,
max: 10,
diff --git a/products/llm_analytics/frontend/traceReviews/traceReviewModalLogic.ts b/products/llm_analytics/frontend/traceReviews/traceReviewModalLogic.ts
index 02ab7122f8d6..58b67c83dcb8 100644
--- a/products/llm_analytics/frontend/traceReviews/traceReviewModalLogic.ts
+++ b/products/llm_analytics/frontend/traceReviews/traceReviewModalLogic.ts
@@ -100,6 +100,7 @@ function buildScoreDefinitionFromReviewScore(score: TraceReviewScore, teamId: nu
kind: score.definition_kind,
archived: score.definition_archived,
current_version: score.definition_version,
+ current_version_id: score.definition_version_id,
config: score.definition_config,
created_by: null,
created_at: score.created_at,
diff --git a/products/llm_analytics/mcp/tools.yaml b/products/llm_analytics/mcp/tools.yaml
index 9b21c7dc1ac3..41041c01fff8 100644
--- a/products/llm_analytics/mcp/tools.yaml
+++ b/products/llm_analytics/mcp/tools.yaml
@@ -667,19 +667,87 @@ tools:
Rename an existing review queue. The updated name must stay unique among active queues in the project.
llma-score-definition-create:
operation: llm_analytics_score_definitions_create
- enabled: false
+ enabled: true
+ scopes:
+ - llm_analytics:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Create scorer
+ description: >
+ Create a new scorer (a.k.a. score definition) used by trace reviews. Pass `name`, `kind` (`categorical`,
+ `numeric`, or `boolean`), and `config` matching the kind. `kind` is immutable after creation. Categorical
+ scorers need an `options` array with unique keys and optional
+ `selection_mode`/`min_selections`/`max_selections` (for `multiple`). Numeric scorers can set `min`, `max`,
+ `step`. Boolean scorers can override `true_label`/`false_label`. Scorers always start active (not archived)
+ and at version 1.
+ param_overrides:
+ config:
+ input_schema: ScoreDefinitionConfigSchema
llma-score-definition-get:
operation: llm_analytics_score_definitions_retrieve
- enabled: false
+ enabled: true
+ scopes:
+ - llm_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get scorer
+ description: >
+ Retrieve a scorer by ID, including its current immutable `config` payload, `current_version` number, kind,
+ archived state, and timestamps.
llma-score-definition-list:
operation: llm_analytics_score_definitions_list
- enabled: false
+ enabled: true
+ scopes:
+ - llm_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List scorers
+ description: >
+ List active scorers for the current project. By default only active rows are returned — pass `archived=true`
+ to see only archived scorers. Other filters: `kind` (`categorical`, `numeric`, `boolean`) and `search` over
+ name/description. Returns metadata plus the current config snapshot.
+ mcp_version: 1
llma-score-definition-new-version:
operation: llm_analytics_score_definitions_new_version_create
- enabled: false
+ enabled: true
+ scopes:
+ - llm_analytics:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Bump scorer to a new version
+ description: >
+ Publish a new immutable `config` version for an existing scorer. Use this whenever the scoring rules change
+ (add/remove categorical options, tweak numeric bounds, rename boolean labels). Existing trace reviews keep
+ their snapshot of the previous version, so historical scores remain stable. The `config` shape must match
+ the scorer's `kind`. Each call increments `current_version` by one. Pass `base_version` (the version number
+ you observed before bumping) for optimistic concurrency — the request returns 409 if another writer already
+ advanced the scorer.
+ param_overrides:
+ config:
+ input_schema: ScoreDefinitionConfigSchema
llma-score-definition-update:
operation: llm_analytics_score_definitions_partial_update
- enabled: false
+ enabled: true
+ scopes:
+ - llm_analytics:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Update scorer metadata
+ description: >
+ Update a scorer's metadata: rename via `name`, edit `description`, or toggle `archived` to hide (`true`) or
+ restore (`false`). Archiving is reversible — there is no destroy endpoint. To change the scoring rules
+ instead, call `llma-score-definition-new-version`. `kind` cannot be changed.
llma-sentiment-create:
operation: llm_analytics_sentiment_create
enabled: true
diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-llm-analytics-reviews.md b/products/posthog_ai/skills/querying-posthog-data/references/models-llm-analytics-reviews.md
index 3fadfe70e3e8..6b053f7df369 100644
--- a/products/posthog_ai/skills/querying-posthog-data/references/models-llm-analytics-reviews.md
+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-llm-analytics-reviews.md
@@ -102,6 +102,38 @@ Column | Type | Nullable | Description
---
+## Score definition (`system.score_definitions`)
+
+Score definitions (a.k.a. "scorers") are reusable structured-score fields used by trace reviews.
+Each scorer has a stable identity but config is versioned and immutable — bumping config creates a new version row.
+
+### Columns
+
+Column | Type | Nullable | Description
+`id` | uuid | NOT NULL | Stable scorer ID
+`team_id` | integer | NOT NULL | Owning team
+`name` | varchar(255) | NOT NULL | Display name
+`description` | text | NOT NULL | Optional description (defaults to empty string)
+`kind` | varchar(32) | NOT NULL | One of `categorical`, `numeric`, `boolean`. Immutable after creation
+`archived` | boolean | NOT NULL | Whether the scorer is archived (hidden from default lists)
+`current_version_id` | uuid | NULL | FK to the latest `score_definition_versions` row (config + version number)
+`created_by_id` | integer | NULL | User ID that created the scorer
+`created_at` | timestamp with tz | NOT NULL | Creation timestamp
+`updated_at` | timestamp with tz | NULL | Last metadata update timestamp
+
+### Key relationships
+
+- **Score values**: `system.trace_review_scores.definition_id` references `id` and `definition_version` references the current/historical version
+- **Versions**: `current_version_id` points to the current immutable config; the version table itself is not exposed via HogQL — fetch full version detail through the REST API tools
+
+### Important notes
+
+- `kind` is immutable. Create a new scorer of the desired kind and archive the old one (there is no destroy endpoint)
+- Filter on `archived = false` to mirror the default product UX
+- Use the REST `llma-score-definition-get` tool when you need the full `config` payload — only metadata is exposed here
+
+---
+
## Common query patterns
**List active trace reviews with their saved score counts:**
@@ -167,3 +199,19 @@ WHERE r.deleted = 0
ORDER BY r.updated_at DESC, s.created_at ASC
LIMIT 100
```
+
+**List active scorers with how many times each has been used:**
+
+```sql
+SELECT
+ d.id,
+ d.name,
+ d.kind,
+ count(s.id) AS uses
+FROM system.score_definitions AS d
+LEFT JOIN system.trace_review_scores AS s ON s.definition_id = d.id
+WHERE d.archived = false
+GROUP BY d.id, d.name, d.kind
+ORDER BY uses DESC, d.name ASC
+LIMIT 50
+```
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index ede3711c4e2b..1a86680bf819 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2899,6 +2899,81 @@
"readOnlyHint": false
}
},
+ "llma-score-definition-create": {
+ "description": "Create a new scorer (a.k.a. score definition) used by trace reviews. Pass `name`, `kind` (`categorical`, `numeric`, or `boolean`), and `config` matching the kind. `kind` is immutable after creation. Categorical scorers need an `options` array with unique keys and optional `selection_mode`/`min_selections`/`max_selections` (for `multiple`). Numeric scorers can set `min`, `max`, `step`. Boolean scorers can override `true_label`/`false_label`. Scorers always start active (not archived) and at version 1.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "Create scorer",
+ "title": "Create scorer",
+ "required_scopes": ["llm_analytics:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "llma-score-definition-get": {
+ "description": "Retrieve a scorer by ID, including its current immutable `config` payload, `current_version` number, kind, archived state, and timestamps.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "Get scorer",
+ "title": "Get scorer",
+ "required_scopes": ["llm_analytics:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "llma-score-definition-list": {
+ "description": "List active scorers for the current project. By default only active rows are returned — pass `archived=true` to see only archived scorers. Other filters: `kind` (`categorical`, `numeric`, `boolean`) and `search` over name/description. Returns metadata plus the current config snapshot.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "List scorers",
+ "title": "List scorers",
+ "required_scopes": ["llm_analytics:read"],
+ "new_mcp": false,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "llma-score-definition-new-version": {
+ "description": "Publish a new immutable `config` version for an existing scorer. Use this whenever the scoring rules change (add/remove categorical options, tweak numeric bounds, rename boolean labels). Existing trace reviews keep their snapshot of the previous version, so historical scores remain stable. The `config` shape must match the scorer's `kind`. Each call increments `current_version` by one. Pass `base_version` (the version number you observed before bumping) for optimistic concurrency — the request returns 409 if another writer already advanced the scorer.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "Bump scorer to a new version",
+ "title": "Bump scorer to a new version",
+ "required_scopes": ["llm_analytics:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "llma-score-definition-update": {
+ "description": "Update a scorer's metadata: rename via `name`, edit `description`, or toggle `archived` to hide (`true`) or restore (`false`). Archiving is reversible — there is no destroy endpoint. To change the scoring rules instead, call `llma-score-definition-new-version`. `kind` cannot be changed.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "Update scorer metadata",
+ "title": "Update scorer metadata",
+ "required_scopes": ["llm_analytics:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"llma-sentiment-create": {
"description": "Classify sentiment of LLM trace or generation user messages as positive, neutral, or negative. Pass a list of trace or generation IDs and an analysis_level (\"trace\" or \"generation\"). Returns per-ID sentiment labels with confidence scores and per-message breakdowns. Results are cached — use force_refresh to recompute. Rate-limited.",
"category": "LLM analytics",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 1b5127ef6858..ad9b007732f2 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3212,6 +3212,81 @@
"readOnlyHint": false
}
},
+ "llma-score-definition-create": {
+ "description": "Create a new scorer (a.k.a. score definition) used by trace reviews. Pass `name`, `kind` (`categorical`, `numeric`, or `boolean`), and `config` matching the kind. `kind` is immutable after creation. Categorical scorers need an `options` array with unique keys and optional `selection_mode`/`min_selections`/`max_selections` (for `multiple`). Numeric scorers can set `min`, `max`, `step`. Boolean scorers can override `true_label`/`false_label`. Scorers always start active (not archived) and at version 1.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "Create scorer",
+ "title": "Create scorer",
+ "required_scopes": ["llm_analytics:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "llma-score-definition-get": {
+ "description": "Retrieve a scorer by ID, including its current immutable `config` payload, `current_version` number, kind, archived state, and timestamps.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "Get scorer",
+ "title": "Get scorer",
+ "required_scopes": ["llm_analytics:read"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "llma-score-definition-list": {
+ "description": "List active scorers for the current project. By default only active rows are returned — pass `archived=true` to see only archived scorers. Other filters: `kind` (`categorical`, `numeric`, `boolean`) and `search` over name/description. Returns metadata plus the current config snapshot.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "List scorers",
+ "title": "List scorers",
+ "required_scopes": ["llm_analytics:read"],
+ "new_mcp": false,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "llma-score-definition-new-version": {
+ "description": "Publish a new immutable `config` version for an existing scorer. Use this whenever the scoring rules change (add/remove categorical options, tweak numeric bounds, rename boolean labels). Existing trace reviews keep their snapshot of the previous version, so historical scores remain stable. The `config` shape must match the scorer's `kind`. Each call increments `current_version` by one. Pass `base_version` (the version number you observed before bumping) for optimistic concurrency — the request returns 409 if another writer already advanced the scorer.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "Bump scorer to a new version",
+ "title": "Bump scorer to a new version",
+ "required_scopes": ["llm_analytics:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "llma-score-definition-update": {
+ "description": "Update a scorer's metadata: rename via `name`, edit `description`, or toggle `archived` to hide (`true`) or restore (`false`). Archiving is reversible — there is no destroy endpoint. To change the scoring rules instead, call `llma-score-definition-new-version`. `kind` cannot be changed.",
+ "category": "LLM analytics",
+ "feature": "llm_analytics",
+ "summary": "Update scorer metadata",
+ "title": "Update scorer metadata",
+ "required_scopes": ["llm_analytics:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"llma-sentiment-create": {
"description": "Classify sentiment of LLM trace or generation user messages as positive, neutral, or negative. Pass a list of trace or generation IDs and an analysis_level (\"trace\" or \"generation\"). Returns per-ID sentiment labels with confidence scores and per-message breakdowns. Results are cached — use force_refresh to recompute. Rate-limited.",
"category": "LLM analytics",
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index 14f6eb4e447e..74aa7417f84a 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -3142,6 +3142,96 @@
"properties": {},
"description": "No input required. Returns core data warehouse schemas."
},
+ "ScoreDefinitionConfigSchema": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "options": {
+ "minItems": 1,
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "key": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "description": "Stable option key — lowercase letters, numbers, underscores, hyphens. Sent back when this option is selected."
+ },
+ "label": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 256,
+ "description": "Human-readable label shown in the review UI."
+ }
+ },
+ "required": ["key", "label"]
+ },
+ "description": "Ordered categorical options. Must contain at least one option with unique keys."
+ },
+ "selection_mode": {
+ "description": "Whether reviewers select one option or many. Defaults to \"single\".",
+ "type": "string",
+ "enum": ["single", "multiple"]
+ },
+ "min_selections": {
+ "description": "Minimum selections required. Only valid when selection_mode is \"multiple\".",
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 9007199254740991
+ },
+ "max_selections": {
+ "description": "Maximum selections allowed. Only valid when selection_mode is \"multiple\".",
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 9007199254740991
+ }
+ },
+ "required": ["options"],
+ "additionalProperties": false,
+ "description": "Config shape used when kind is \"categorical\"."
+ },
+ {
+ "type": "object",
+ "properties": {
+ "min": {
+ "description": "Optional inclusive minimum score.",
+ "type": "number"
+ },
+ "max": {
+ "description": "Optional inclusive maximum score (must be ≥ min).",
+ "type": "number"
+ },
+ "step": {
+ "description": "Optional increment step for numeric input, e.g. 1 or 0.5.",
+ "type": "number",
+ "exclusiveMinimum": 0
+ }
+ },
+ "additionalProperties": false,
+ "description": "Config shape used when kind is \"numeric\"."
+ },
+ {
+ "type": "object",
+ "properties": {
+ "true_label": {
+ "description": "Optional label shown for the true branch (e.g. \"Yes\").",
+ "type": "string",
+ "minLength": 1
+ },
+ "false_label": {
+ "description": "Optional label shown for the false branch (e.g. \"No\").",
+ "type": "string",
+ "minLength": 1
+ }
+ },
+ "additionalProperties": false,
+ "description": "Config shape used when kind is \"boolean\"."
+ }
+ ],
+ "description": "Immutable scorer configuration. Pick the shape matching the scorer kind: categorical (options + selection_mode), numeric (min/max/step), or boolean (true_label/false_label). The server validates the shape against the kind on the parent scorer and returns 400 on a mismatch."
+ },
"SurveyResponseCountsSchema": {
"type": "object",
"properties": {}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b72b6e4585f8..e302d34bd3fd 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25406,6 +25406,11 @@ export namespace Schemas {
readonly archived: boolean;
/** Current immutable configuration version number. */
readonly current_version: number;
+ /**
+ * UUID of the current version row. Matches `system.score_definitions.current_version_id` in HogQL.
+ * @nullable
+ */
+ readonly current_version_id: string | null;
/** Current immutable scorer configuration. */
readonly config: ScoreDefinitionConfig;
/** User who created the scorer. */
@@ -36946,6 +36951,11 @@ export namespace Schemas {
export interface ScoreDefinitionNewVersion {
/** Next immutable scorer configuration. */
config: ScoreDefinitionConfig;
+ /**
+ * Version number the caller observed before requesting this bump. If provided and it does not match the scorer's current version, the request fails with 409. Omit to skip the optimistic-concurrency check.
+ * @minimum 1
+ */
+ base_version?: number;
}
/**
diff --git a/services/mcp/src/generated/llm_analytics/api.ts b/services/mcp/src/generated/llm_analytics/api.ts
index 95a1a5b2b95e..78d2efa39bc4 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 51 enabled ops
+ * PostHog API - MCP 56 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -808,6 +808,216 @@ export const LlmAnalyticsReviewQueuesDestroyParams = /* @__PURE__ */ zod.object(
),
})
+export const LlmAnalyticsScoreDefinitionsListParams = /* @__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 LlmAnalyticsScoreDefinitionsListQueryParams = /* @__PURE__ */ zod.object({
+ archived: zod.boolean().optional().describe('Filter by archived state.'),
+ kind: zod.string().optional().describe('Filter by scorer kind.'),
+ 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.string().optional().describe('Sort by name, kind, created_at, updated_at, or current_version.'),
+ search: zod.string().optional().describe('Search scorers by name or description.'),
+})
+
+export const LlmAnalyticsScoreDefinitionsCreateParams = /* @__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 llmAnalyticsScoreDefinitionsCreateBodyNameMax = 255
+
+export const llmAnalyticsScoreDefinitionsCreateBodyArchivedDefault = false
+export const llmAnalyticsScoreDefinitionsCreateBodyConfigOneOneOptionsItemKeyMax = 128
+
+export const llmAnalyticsScoreDefinitionsCreateBodyConfigOneOneOptionsItemLabelMax = 256
+
+export const LlmAnalyticsScoreDefinitionsCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(llmAnalyticsScoreDefinitionsCreateBodyNameMax).describe('Human-readable scorer name.'),
+ description: zod.string().nullish().describe('Optional human-readable description.'),
+ kind: zod
+ .enum(['categorical', 'numeric', 'boolean'])
+ .describe('* `categorical` - categorical\n* `numeric` - numeric\n* `boolean` - boolean')
+ .describe(
+ 'Scorer kind. This cannot be changed after creation.\n\n* `categorical` - categorical\n* `numeric` - numeric\n* `boolean` - boolean'
+ ),
+ archived: zod
+ .boolean()
+ .default(llmAnalyticsScoreDefinitionsCreateBodyArchivedDefault)
+ .describe('New scorers are always created as active.'),
+ config: zod
+ .union([
+ zod.object({
+ options: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .max(llmAnalyticsScoreDefinitionsCreateBodyConfigOneOneOptionsItemKeyMax)
+ .describe(
+ 'Stable option key. Use lowercase letters, numbers, underscores, or hyphens.'
+ ),
+ label: zod
+ .string()
+ .max(llmAnalyticsScoreDefinitionsCreateBodyConfigOneOneOptionsItemLabelMax)
+ .describe('Human-readable option label.'),
+ })
+ )
+ .describe('Ordered categorical options available to the scorer.'),
+ selection_mode: zod
+ .enum(['single', 'multiple'])
+ .describe('* `single` - single\n* `multiple` - multiple')
+ .optional()
+ .describe(
+ 'Whether reviewers can select one option or multiple options. Defaults to `single`.\n\n* `single` - single\n* `multiple` - multiple'
+ ),
+ min_selections: zod
+ .number()
+ .min(1)
+ .nullish()
+ .describe(
+ 'Optional minimum number of options that can be selected when `selection_mode` is `multiple`.'
+ ),
+ max_selections: zod
+ .number()
+ .min(1)
+ .nullish()
+ .describe(
+ 'Optional maximum number of options that can be selected when `selection_mode` is `multiple`.'
+ ),
+ }),
+ zod.object({
+ min: zod.number().nullish().describe('Optional inclusive minimum score.'),
+ max: zod.number().nullish().describe('Optional inclusive maximum score.'),
+ step: zod
+ .number()
+ .nullish()
+ .describe('Optional increment step for numeric input, for example 1 or 0.5.'),
+ }),
+ zod.object({
+ true_label: zod.string().optional().describe('Optional label for a true value.'),
+ false_label: zod.string().optional().describe('Optional label for a false value.'),
+ }),
+ ])
+ .describe('Initial immutable scorer configuration.'),
+})
+
+export const LlmAnalyticsScoreDefinitionsRetrieveParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this score definition.'),
+ 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 LlmAnalyticsScoreDefinitionsPartialUpdateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this score definition.'),
+ 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 llmAnalyticsScoreDefinitionsPartialUpdateBodyNameMax = 255
+
+export const LlmAnalyticsScoreDefinitionsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(llmAnalyticsScoreDefinitionsPartialUpdateBodyNameMax)
+ .optional()
+ .describe('Updated scorer name.'),
+ description: zod.string().nullish().describe('Updated scorer description.'),
+ archived: zod.boolean().optional().describe('Whether the scorer is archived.'),
+})
+
+export const LlmAnalyticsScoreDefinitionsNewVersionCreateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this score definition.'),
+ 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 llmAnalyticsScoreDefinitionsNewVersionCreateBodyConfigOneOneOptionsItemKeyMax = 128
+
+export const llmAnalyticsScoreDefinitionsNewVersionCreateBodyConfigOneOneOptionsItemLabelMax = 256
+
+export const LlmAnalyticsScoreDefinitionsNewVersionCreateBody = /* @__PURE__ */ zod.object({
+ config: zod
+ .union([
+ zod.object({
+ options: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .max(llmAnalyticsScoreDefinitionsNewVersionCreateBodyConfigOneOneOptionsItemKeyMax)
+ .describe(
+ 'Stable option key. Use lowercase letters, numbers, underscores, or hyphens.'
+ ),
+ label: zod
+ .string()
+ .max(llmAnalyticsScoreDefinitionsNewVersionCreateBodyConfigOneOneOptionsItemLabelMax)
+ .describe('Human-readable option label.'),
+ })
+ )
+ .describe('Ordered categorical options available to the scorer.'),
+ selection_mode: zod
+ .enum(['single', 'multiple'])
+ .describe('* `single` - single\n* `multiple` - multiple')
+ .optional()
+ .describe(
+ 'Whether reviewers can select one option or multiple options. Defaults to `single`.\n\n* `single` - single\n* `multiple` - multiple'
+ ),
+ min_selections: zod
+ .number()
+ .min(1)
+ .nullish()
+ .describe(
+ 'Optional minimum number of options that can be selected when `selection_mode` is `multiple`.'
+ ),
+ max_selections: zod
+ .number()
+ .min(1)
+ .nullish()
+ .describe(
+ 'Optional maximum number of options that can be selected when `selection_mode` is `multiple`.'
+ ),
+ }),
+ zod.object({
+ min: zod.number().nullish().describe('Optional inclusive minimum score.'),
+ max: zod.number().nullish().describe('Optional inclusive maximum score.'),
+ step: zod
+ .number()
+ .nullish()
+ .describe('Optional increment step for numeric input, for example 1 or 0.5.'),
+ }),
+ zod.object({
+ true_label: zod.string().optional().describe('Optional label for a true value.'),
+ false_label: zod.string().optional().describe('Optional label for a false value.'),
+ }),
+ ])
+ .describe('Next immutable scorer configuration.'),
+ base_version: zod
+ .number()
+ .min(1)
+ .optional()
+ .describe(
+ "Version number the caller observed before requesting this bump. If provided and it does not match the scorer's current version, the request fails with 409. Omit to skip the optimistic-concurrency check."
+ ),
+})
+
export const LlmAnalyticsSentimentCreateParams = /* @__PURE__ */ zod.object({
project_id: zod
.string()
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 5834764a5623..2132d391206c 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -70,6 +70,74 @@ export const UsageMetricFiltersSchema = z
'Filter definition. Pick exactly one branch: `data_warehouse` (set `source: "data_warehouse"` plus `table_name`/`timestamp_field`/`key_field`) or `events` (HogFunction filter shape with an `events` array).'
)
+const CategoricalScoreOptionSchema = z.object({
+ key: z
+ .string()
+ .min(1)
+ .max(128)
+ .describe(
+ 'Stable option key — lowercase letters, numbers, underscores, hyphens. Sent back when this option is selected.'
+ ),
+ label: z.string().min(1).max(256).describe('Human-readable label shown in the review UI.'),
+})
+
+const CategoricalScoreDefinitionConfigSchema = z
+ .object({
+ options: z
+ .array(CategoricalScoreOptionSchema)
+ .min(1)
+ .refine(
+ (options) => new Set(options.map((option) => option.key)).size === options.length,
+ 'Categorical option keys must be unique.'
+ )
+ .describe('Ordered categorical options. Must contain at least one option with unique keys.'),
+ selection_mode: z
+ .enum(['single', 'multiple'])
+ .optional()
+ .describe('Whether reviewers select one option or many. Defaults to "single".'),
+ min_selections: z
+ .number()
+ .int()
+ .min(1)
+ .optional()
+ .describe('Minimum selections required. Only valid when selection_mode is "multiple".'),
+ max_selections: z
+ .number()
+ .int()
+ .min(1)
+ .optional()
+ .describe('Maximum selections allowed. Only valid when selection_mode is "multiple".'),
+ })
+ .strict()
+ .describe('Config shape used when kind is "categorical".')
+
+const NumericScoreDefinitionConfigSchema = z
+ .object({
+ min: z.number().optional().describe('Optional inclusive minimum score.'),
+ max: z.number().optional().describe('Optional inclusive maximum score (must be ≥ min).'),
+ step: z.number().positive().optional().describe('Optional increment step for numeric input, e.g. 1 or 0.5.'),
+ })
+ .strict()
+ .describe('Config shape used when kind is "numeric".')
+
+const BooleanScoreDefinitionConfigSchema = z
+ .object({
+ true_label: z.string().min(1).optional().describe('Optional label shown for the true branch (e.g. "Yes").'),
+ false_label: z.string().min(1).optional().describe('Optional label shown for the false branch (e.g. "No").'),
+ })
+ .strict()
+ .describe('Config shape used when kind is "boolean".')
+
+export const ScoreDefinitionConfigSchema = z
+ .union([
+ CategoricalScoreDefinitionConfigSchema,
+ NumericScoreDefinitionConfigSchema,
+ BooleanScoreDefinitionConfigSchema,
+ ])
+ .describe(
+ 'Immutable scorer configuration. Pick the shape matching the scorer kind: categorical (options + selection_mode), numeric (min/max/step), or boolean (true_label/false_label). The server validates the shape against the kind on the parent scorer and returns 400 on a mismatch.'
+ )
+
export const PromptListInputSchema = z.object({
search: z.string().optional().describe('Optional substring filter applied to prompt names and prompt content.'),
content: z
diff --git a/services/mcp/src/tools/generated/llm_analytics.ts b/services/mcp/src/tools/generated/llm_analytics.ts
index 9caa272078a7..ae9a93660e65 100644
--- a/services/mcp/src/tools/generated/llm_analytics.ts
+++ b/services/mcp/src/tools/generated/llm_analytics.ts
@@ -37,6 +37,13 @@ import {
LlmAnalyticsReviewQueuesPartialUpdateBody,
LlmAnalyticsReviewQueuesPartialUpdateParams,
LlmAnalyticsReviewQueuesRetrieveParams,
+ LlmAnalyticsScoreDefinitionsCreateBody,
+ LlmAnalyticsScoreDefinitionsListQueryParams,
+ LlmAnalyticsScoreDefinitionsNewVersionCreateBody,
+ LlmAnalyticsScoreDefinitionsNewVersionCreateParams,
+ LlmAnalyticsScoreDefinitionsPartialUpdateBody,
+ LlmAnalyticsScoreDefinitionsPartialUpdateParams,
+ LlmAnalyticsScoreDefinitionsRetrieveParams,
LlmAnalyticsSentimentCreateBody,
LlmAnalyticsSummarizationCreateBody,
LlmAnalyticsTraceReviewsCreateBody,
@@ -69,7 +76,7 @@ import {
LlmSkillsNameRetrieveParams,
LlmSkillsNameRetrieveQueryParams,
} from '@/generated/llm_analytics/api'
-import { PromptListInputSchema } from '@/schema/tool-inputs'
+import { PromptListInputSchema, ScoreDefinitionConfigSchema } from '@/schema/tool-inputs'
import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
@@ -974,6 +981,140 @@ const llmaReviewQueueUpdate = (): ToolBase<
},
})
+const LlmaScoreDefinitionCreateSchema = LlmAnalyticsScoreDefinitionsCreateBody.extend({
+ config: ScoreDefinitionConfigSchema,
+})
+
+const llmaScoreDefinitionCreate = (): ToolBase<typeof LlmaScoreDefinitionCreateSchema, Schemas.ScoreDefinition> => ({
+ name: 'llma-score-definition-create',
+ schema: LlmaScoreDefinitionCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof LlmaScoreDefinitionCreateSchema>) => {
+ 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.kind !== undefined) {
+ body['kind'] = params.kind
+ }
+ if (params.archived !== undefined) {
+ body['archived'] = params.archived
+ }
+ if (params.config !== undefined) {
+ body['config'] = params.config
+ }
+ const result = await context.api.request<Schemas.ScoreDefinition>({
+ method: 'POST',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/llm_analytics/score_definitions/`,
+ body,
+ })
+ return result
+ },
+})
+
+const LlmaScoreDefinitionGetSchema = LlmAnalyticsScoreDefinitionsRetrieveParams.omit({ project_id: true })
+
+const llmaScoreDefinitionGet = (): ToolBase<typeof LlmaScoreDefinitionGetSchema, Schemas.ScoreDefinition> => ({
+ name: 'llma-score-definition-get',
+ schema: LlmaScoreDefinitionGetSchema,
+ handler: async (context: Context, params: z.infer<typeof LlmaScoreDefinitionGetSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.ScoreDefinition>({
+ method: 'GET',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/llm_analytics/score_definitions/${encodeURIComponent(String(params.id))}/`,
+ })
+ return result
+ },
+})
+
+const LlmaScoreDefinitionListSchema = LlmAnalyticsScoreDefinitionsListQueryParams
+
+const llmaScoreDefinitionList = (): ToolBase<
+ typeof LlmaScoreDefinitionListSchema,
+ WithPostHogUrl<Schemas.PaginatedScoreDefinitionList>
+> => ({
+ name: 'llma-score-definition-list',
+ schema: LlmaScoreDefinitionListSchema,
+ mcpVersion: 1,
+ handler: async (context: Context, params: z.infer<typeof LlmaScoreDefinitionListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedScoreDefinitionList>({
+ method: 'GET',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/llm_analytics/score_definitions/`,
+ query: {
+ archived: params.archived,
+ kind: params.kind,
+ limit: params.limit,
+ offset: params.offset,
+ order_by: params.order_by,
+ search: params.search,
+ },
+ })
+ return await withPostHogUrl(context, result, '/llm-analytics')
+ },
+})
+
+const LlmaScoreDefinitionNewVersionSchema = LlmAnalyticsScoreDefinitionsNewVersionCreateParams.omit({
+ project_id: true,
+})
+ .extend(LlmAnalyticsScoreDefinitionsNewVersionCreateBody.shape)
+ .extend({ config: ScoreDefinitionConfigSchema })
+
+const llmaScoreDefinitionNewVersion = (): ToolBase<
+ typeof LlmaScoreDefinitionNewVersionSchema,
+ Schemas.ScoreDefinition
+> => ({
+ name: 'llma-score-definition-new-version',
+ schema: LlmaScoreDefinitionNewVersionSchema,
+ handler: async (context: Context, params: z.infer<typeof LlmaScoreDefinitionNewVersionSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.config !== undefined) {
+ body['config'] = params.config
+ }
+ if (params.base_version !== undefined) {
+ body['base_version'] = params.base_version
+ }
+ const result = await context.api.request<Schemas.ScoreDefinition>({
+ method: 'POST',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/llm_analytics/score_definitions/${encodeURIComponent(String(params.id))}/new_version/`,
+ body,
+ })
+ return result
+ },
+})
+
+const LlmaScoreDefinitionUpdateSchema = LlmAnalyticsScoreDefinitionsPartialUpdateParams.omit({
+ project_id: true,
+}).extend(LlmAnalyticsScoreDefinitionsPartialUpdateBody.shape)
+
+const llmaScoreDefinitionUpdate = (): ToolBase<typeof LlmaScoreDefinitionUpdateSchema, Schemas.ScoreDefinition> => ({
+ name: 'llma-score-definition-update',
+ schema: LlmaScoreDefinitionUpdateSchema,
+ handler: async (context: Context, params: z.infer<typeof LlmaScoreDefinitionUpdateSchema>) => {
+ 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.archived !== undefined) {
+ body['archived'] = params.archived
+ }
+ const result = await context.api.request<Schemas.ScoreDefinition>({
+ method: 'PATCH',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/llm_analytics/score_definitions/${encodeURIComponent(String(params.id))}/`,
+ body,
+ })
+ return result
+ },
+})
+
const LlmaSentimentCreateSchema = LlmAnalyticsSentimentCreateBody
const llmaSentimentCreate = (): ToolBase<typeof LlmaSentimentCreateSchema, Schemas.SentimentBatchResponse> => ({
@@ -1475,6 +1616,11 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'llma-review-queue-item-update': llmaReviewQueueItemUpdate,
'llma-review-queue-list': llmaReviewQueueList,
'llma-review-queue-update': llmaReviewQueueUpdate,
+ 'llma-score-definition-create': llmaScoreDefinitionCreate,
+ 'llma-score-definition-get': llmaScoreDefinitionGet,
+ 'llma-score-definition-list': llmaScoreDefinitionList,
+ 'llma-score-definition-new-version': llmaScoreDefinitionNewVersion,
+ 'llma-score-definition-update': llmaScoreDefinitionUpdate,
'llma-sentiment-create': llmaSentimentCreate,
'llma-skill-create': llmaSkillCreate,
'llma-skill-duplicate': llmaSkillDuplicate,
diff --git a/services/mcp/tests/unit/__snapshots__/exec-tool.json b/services/mcp/tests/unit/__snapshots__/exec-tool.json
index dace4150fc32..3b0084ecf60c 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-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-issues` — Error 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-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-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-issues` — Error 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-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-score-definition-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-score-definition-create.json
new file mode 100644
index 000000000000..a772e298cea5
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-score-definition-create.json
@@ -0,0 +1,123 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "archived": {
+ "default": false,
+ "description": "New scorers are always created as active.",
+ "type": "boolean"
+ },
+ "config": {
+ "anyOf": [
+ {
+ "additionalProperties": false,
+ "description": "Config shape used when kind is \"categorical\".",
+ "properties": {
+ "max_selections": {
+ "description": "Maximum selections allowed. Only valid when selection_mode is \"multiple\".",
+ "maximum": 9007199254740991,
+ "minimum": 1,
+ "type": "integer"
+ },
+ "min_selections": {
+ "description": "Minimum selections required. Only valid when selection_mode is \"multiple\".",
+ "maximum": 9007199254740991,
+ "minimum": 1,
+ "type": "integer"
+ },
+ "options": {
+ "description": "Ordered categorical options. Must contain at least one option with unique keys.",
+ "items": {
+ "properties": {
+ "key": {
+ "description": "Stable option key — lowercase letters, numbers, underscores, hyphens. Sent back when this option is selected.",
+ "maxLength": 128,
+ "minLength": 1,
+ "type": "string"
+ },
+ "label": {
+ "description": "Human-readable label shown in the review UI.",
+ "maxLength": 256,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": ["key", "label"],
+ "type": "object"
+ },
+ "minItems": 1,
+ "type": "array"
+ },
+ "selection_mode": {
+ "description": "Whether reviewers select one option or many. Defaults to \"single\".",
+ "enum": ["single", "multiple"],
+ "type": "string"
+ }
+ },
+ "required": ["options"],
+ "type": "object"
+ },
+ {
+ "additionalProperties": false,
+ "description": "Config shape used when kind is \"numeric\".",
+ "properties": {
+ "max": {
+ "description": "Optional inclusive maximum score (must be ≥ min).",
+ "type": "number"
+ },
+ "min": {
+ "description": "Optional inclusive minimum score.",
+ "type": "number"
+ },
+ "step": {
+ "description": "Optional increment step for numeric input, e.g. 1 or 0.5.",
+ "exclusiveMinimum": 0,
+ "type": "number"
+ }
+ },
+ "type": "object"
+ },
+ {
+ "additionalProperties": false,
+ "description": "Config shape used when kind is \"boolean\".",
+ "properties": {
+ "false_label": {
+ "description": "Optional label shown for the false branch (e.g. \"No\").",
+ "minLength": 1,
+ "type": "string"
+ },
+ "true_label": {
+ "description": "Optional label shown for the true branch (e.g. \"Yes\").",
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "type": "object"
+ }
+ ],
+ "description": "Immutable scorer configuration. Pick the shape matching the scorer kind: categorical (options + selection_mode), numeric (min/max/step), or boolean (true_label/false_label). The server validates the shape against the kind on the parent scorer and returns 400 on a mismatch."
+ },
+ "description": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional human-readable description."
+ },
+ "kind": {
+ "description": "Scorer kind. This cannot be changed after creation.\n\n* `categorical` - categorical\n* `numeric` - numeric\n* `boolean` - boolean",
+ "enum": ["categorical", "numeric", "boolean"],
+ "type": "string"
+ },
+ "name": {
+ "description": "Human-readable scorer name.",
+ "maxLength": 255,
+ "type": "string"
+ }
+ },
+ "required": ["name", "kind", "config"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-score-definition-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-score-definition-get.json
new file mode 100644
index 000000000000..cb54518bb666
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-score-definition-get.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this score definition.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-score-definition-new-version.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-score-definition-new-version.json
new file mode 100644
index 000000000000..c7ceef1d22d3
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-score-definition-new-version.json
@@ -0,0 +1,106 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "base_version": {
+ "description": "Version number the caller observed before requesting this bump. If provided and it does not match the scorer's current version, the request fails with 409. Omit to skip the optimistic-concurrency check.",
+ "minimum": 1,
+ "type": "number"
+ },
+ "config": {
+ "anyOf": [
+ {
+ "additionalProperties": false,
+ "description": "Config shape used when kind is \"categorical\".",
+ "properties": {
+ "max_selections": {
+ "description": "Maximum selections allowed. Only valid when selection_mode is \"multiple\".",
+ "maximum": 9007199254740991,
+ "minimum": 1,
+ "type": "integer"
+ },
+ "min_selections": {
+ "description": "Minimum selections required. Only valid when selection_mode is \"multiple\".",
+ "maximum": 9007199254740991,
+ "minimum": 1,
+ "type": "integer"
+ },
+ "options": {
+ "description": "Ordered categorical options. Must contain at least one option with unique keys.",
+ "items": {
+ "properties": {
+ "key": {
+ "description": "Stable option key — lowercase letters, numbers, underscores, hyphens. Sent back when this option is selected.",
+ "maxLength": 128,
+ "minLength": 1,
+ "type": "string"
+ },
+ "label": {
+ "description": "Human-readable label shown in the review UI.",
+ "maxLength": 256,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": ["key", "label"],
+ "type": "object"
+ },
+ "minItems": 1,
+ "type": "array"
+ },
+ "selection_mode": {
+ "description": "Whether reviewers select one option or many. Defaults to \"single\".",
+ "enum": ["single", "multiple"],
+ "type": "string"
+ }
+ },
+ "required": ["options"],
+ "type": "object"
+ },
+ {
+ "additionalProperties": false,
+ "description": "Config shape used when kind is \"numeric\".",
+ "properties": {
+ "max": {
+ "description": "Optional inclusive maximum score (must be ≥ min).",
+ "type": "number"
+ },
+ "min": {
+ "description": "Optional inclusive minimum score.",
+ "type": "number"
+ },
+ "step": {
+ "description": "Optional increment step for numeric input, e.g. 1 or 0.5.",
+ "exclusiveMinimum": 0,
+ "type": "number"
+ }
+ },
+ "type": "object"
+ },
+ {
+ "additionalProperties": false,
+ "description": "Config shape used when kind is \"boolean\".",
+ "properties": {
+ "false_label": {
+ "description": "Optional label shown for the false branch (e.g. \"No\").",
+ "minLength": 1,
+ "type": "string"
+ },
+ "true_label": {
+ "description": "Optional label shown for the true branch (e.g. \"Yes\").",
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "type": "object"
+ }
+ ],
+ "description": "Immutable scorer configuration. Pick the shape matching the scorer kind: categorical (options + selection_mode), numeric (min/max/step), or boolean (true_label/false_label). The server validates the shape against the kind on the parent scorer and returns 400 on a mismatch."
+ },
+ "id": {
+ "description": "A UUID string identifying this score definition.",
+ "type": "string"
+ }
+ },
+ "required": ["id", "config"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-score-definition-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-score-definition-update.json
new file mode 100644
index 000000000000..fe6bda3fbaa2
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-score-definition-update.json
@@ -0,0 +1,31 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "archived": {
+ "description": "Whether the scorer is archived.",
+ "type": "boolean"
+ },
+ "description": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Updated scorer description."
+ },
+ "id": {
+ "description": "A UUID string identifying this score definition.",
+ "type": "string"
+ },
+ "name": {
+ "description": "Updated scorer name.",
+ "maxLength": 255,
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/v1/llma-score-definition-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/v1/llma-score-definition-list.json
new file mode 100644
index 000000000000..38a96747127c
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/v1/llma-score-definition-list.json
@@ -0,0 +1,30 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "archived": {
+ "description": "Filter by archived state.",
+ "type": "boolean"
+ },
+ "kind": {
+ "description": "Filter by scorer kind.",
+ "type": "string"
+ },
+ "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": "Sort by name, kind, created_at, updated_at, or current_version.",
+ "type": "string"
+ },
+ "search": {
+ "description": "Search scorers by name or description.",
+ "type": "string"
+ }
+ },
+ "type": "object"
+}