: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(aio): align evaluation and prompt MCP contracts with accepted inputs (#81415)
posthog[bot]e4a7dfa07eaa
diff --git a/posthog/api/llm_prompt.py b/posthog/api/llm_prompt.pyindex df98c4a8bb4c..9aca0c1bac04 100644--- a/posthog/api/llm_prompt.py+++ b/posthog/api/llm_prompt.py@@ -1,5 +1,6 @@import jsonfrom typing import Any, cast+from uuid import UUIDfrom django.conf import settingsfrom django.db import IntegrityError@@ -123,10 +124,35 @@ class LLMPromptViewSet(def _prompt_not_found_response(self, prompt_name: str) -> Response:return Response(- {"detail": f"Prompt with name '{prompt_name}' not found."},+ {+ "detail": (+ f"No prompt matching '{prompt_name}' in this project. "+ "List the project's prompts to see which names exist."+ )+ },status=status.HTTP_404_NOT_FOUND,)+ def _resolve_prompt_name(self, prompt_name: str) -> str | None:+ """Map the path segment onto a prompt name, accepting the `id` UUID of any of the prompt's+ versions as well as the name itself. Both identify one prompt, and every list and get+ response carries the id, so a caller holding one should not have to look the name up.+ An id resolves to the prompt, never to the version it came from, so callers pin a version+ with `version` or `label` rather than by holding that version's id.+ Returns None when the segment is a UUID matching no prompt in this project."""+ try:+ version_id = UUID(prompt_name)+ except ValueError:+ return prompt_name+ # Nothing stops a prompt from being named like a UUID, so the literal name wins the tie.+ if LLMPrompt.objects.filter(team=self.team, deleted=False, name=prompt_name).exists():+ return prompt_name+ return (+ LLMPrompt.objects.filter(team=self.team, deleted=False, id=version_id)+ .values_list("name", flat=True)+ .first()+ )+def _serialize_prompt(self, prompt: LLMPrompt) -> dict[str, Any]:return cast(dict[str, Any], self.get_serializer(prompt).data)@@ -264,11 +290,29 @@ class LLMPromptViewSet(version = cast(int | None, query_params.get("version"))label = cast(str | None, query_params.get("label"))content_mode = cast(str, query_params.get("content", "full"))- prompt = get_prompt_by_name_from_cache(self.team, prompt_name, version, label=label)+ resolved_name = self._resolve_prompt_name(prompt_name)+ if resolved_name is None:+ return self._prompt_not_found_response(prompt_name)+ prompt = get_prompt_by_name_from_cache(self.team, resolved_name, version, label=label)if prompt is None:if label is not None:return Response(- {"detail": f"Prompt '{prompt_name}' not found or has no label '{label}'."},+ {+ "detail": (+ f"No prompt matching '{prompt_name}' with label '{label}'. "+ "Fetch it without a label to see which labels it has."+ )+ },+ status=status.HTTP_404_NOT_FOUND,+ )+ if version is not None:+ return Response(+ {+ "detail": (+ f"No prompt matching '{prompt_name}' at version {version}. "+ "Fetch it without a version to see which versions it has."+ )+ },status=status.HTTP_404_NOT_FOUND,)return self._prompt_not_found_response(prompt_name)@@ -285,6 +329,11 @@ class LLMPromptViewSet(if auth_error is not None:return auth_error+ # PATCH shares the GET's route, so the segment has to mean the same thing on both verbs.+ resolved_name = self._resolve_prompt_name(prompt_name)+ if resolved_name is None:+ return self._prompt_not_found_response(prompt_name)+payload = LLMPromptPublishSerializer(data=request.data)payload.is_valid(raise_exception=True)@@ -292,7 +341,7 @@ class LLMPromptViewSet(published_prompt = publish_prompt_version(self.team,user=cast(User, request.user),- prompt_name=prompt_name,+ prompt_name=resolved_name,prompt_payload=payload.validated_data.get("prompt"),edits=payload.validated_data.get("edits"),config=payload.validated_data.get("config"),diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.pyindex 3086a7123678..1cca939e6ca4 100644--- a/posthog/api/test/test_llm_prompt.py+++ b/posthog/api/test/test_llm_prompt.py@@ -406,6 +406,23 @@ class TestLLMPromptAPI(APIBaseTest):assert response.status_code == status.HTTP_409_CONFLICTassert response.json()["current_version"] == 2+ @parameterized.expand([("latest_version", 2), ("historical_version", 1)])+ def test_update_prompt_by_version_id_publishes_against_the_prompt(self, _name, version):+ self.create_prompt_version(name="publish-prompt", version=1, is_latest=False, prompt="v1")+ self.create_prompt_version(name="publish-prompt", version=2, is_latest=True, prompt="v2")+ requested = LLMPrompt.objects.get(team=self.team, name="publish-prompt", version=version)++ response = self.client.patch(+ f"/api/environments/{self.team.id}/llm_prompts/name/{requested.id}/",+ data={"prompt": "v3", "base_version": 2},+ format="json",+ )++ # PATCH shares the GET's route, so an id the GET accepts has to publish rather than 404.+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["name"] == "publish-prompt"+ assert response.json()["version"] == 3+def test_update_prompt_by_name_rejects_payload_above_max_size(self):self.create_prompt_version(name="publish-prompt", version=1, is_latest=True, prompt="v1")oversized_prompt = "x" * (MAX_PROMPT_PAYLOAD_BYTES + 1)@@ -803,7 +820,64 @@ class TestLLMPromptAPI(APIBaseTest):response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/non-existent/")assert response.status_code == status.HTTP_404_NOT_FOUND- assert "not found" in response.json()["detail"].lower()+ detail = response.json()["detail"]+ assert "non-existent" in detail+ # The 404 has to name a recovery path for a caller that guessed the name.+ assert "list the project's prompts" in detail.lower()++ def test_fetch_prompt_at_unknown_version_points_at_the_version_not_the_name(self):+ self.create_prompt_version(name="my-prompt", version=1, is_latest=True)++ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/my-prompt/?version=7")++ assert response.status_code == status.HTTP_404_NOT_FOUND+ detail = response.json()["detail"]+ # The name resolved, so sending the caller off to list prompts would be the wrong recovery path.+ assert "version 7" in detail+ assert "list the project's prompts" not in detail.lower()++ @parameterized.expand([("latest_version", 2), ("historical_version", 1)])+ def test_fetch_prompt_by_version_id_resolves_to_the_prompt(self, _name, version):+ self.create_prompt_version(name="by-id", version=1, is_latest=False, prompt="v1")+ self.create_prompt_version(name="by-id", version=2, is_latest=True, prompt="v2")+ requested = LLMPrompt.objects.get(team=self.team, name="by-id", version=version)++ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/{requested.id}/")++ assert response.status_code == status.HTTP_200_OK+ # The id identifies the prompt, not the version, so the route still answers with the latest.+ assert response.json()["name"] == "by-id"+ assert response.json()["version"] == 2++ def test_fetch_prompt_by_unknown_version_id_is_not_found(self):+ self.create_prompt_version(name="by-id")++ response = self.client.get(+ f"/api/environments/{self.team.id}/llm_prompts/name/019f5632-6df1-0000-5093-46d18b1bc987/"+ )++ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_fetch_prompt_named_like_a_uuid_wins_over_the_id_lookup(self):+ other = self.create_prompt_version(name="other", prompt="other content")+ self.create_prompt_version(name=str(other.id), prompt="named like a uuid")++ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/{other.id}/")++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["prompt"] == "named like a uuid"++ def test_fetch_prompt_by_version_id_from_another_team_is_not_found(self):+ from posthog.models import Team++ other_team = Team.objects.create(organization=self.organization, name="Other team")+ other_prompt = LLMPrompt.objects.create(+ team=other_team, name="other-team-prompt", prompt="Content", created_by=self.user+ )++ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/{other_prompt.id}/")++ assert response.status_code == status.HTTP_404_NOT_FOUNDdef test_fetch_prompt_by_name_other_team_not_accessible(self):from posthog.models import Teamdiff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.pyindex 14e0bb778826..180a189f3360 100644--- a/products/ai_observability/backend/api/evaluations.py+++ b/products/ai_observability/backend/api/evaluations.py@@ -2,6 +2,7 @@ from typing import Anyfrom django.db import transactionfrom django.db.models import Q, QuerySet+from django.http import Http404import structlogimport django_filters@@ -9,6 +10,8 @@ from django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.utils import extend_schema, extend_schema_fieldfrom rest_framework import serializers, viewsetsfrom rest_framework.decorators import action+from rest_framework.exceptions import NotFound+from rest_framework.generics import get_object_or_404from rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -992,6 +995,20 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbiqueryset = queryset.filter(deleted=False)return queryset+ def safely_get_object(self, queryset: QuerySet[Evaluation]) -> Evaluation:+ evaluation_id = self.kwargs["pk"]+ try:+ # Matches what DRF's own get_object() does, including coercing an unparseable pk to a+ # 404, so only the message differs.+ return get_object_or_404(queryset, pk=evaluation_id)+ except Http404:+ # DRF's bare "Not found." points a caller at nothing it can act on. A name passed where+ # the id belongs lands here too, since it can't parse as a UUID.+ raise NotFound(+ f"No evaluation '{evaluation_id}' in this project. "+ "List the project's evaluations to look one up by name."+ )+@staticmethoddef _get_config_length(instance) -> int:"""Get the relevant config content length for tracking."""diff --git a/products/ai_observability/backend/api/models.py b/products/ai_observability/backend/api/models.pyindex 5d046e234669..37436de7cdcf 100644--- a/products/ai_observability/backend/api/models.py+++ b/products/ai_observability/backend/api/models.py@@ -1,3 +1,7 @@+from typing import Any++from django.core.exceptions import ValidationError as DjangoValidationError+from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_serializerfrom rest_framework import serializers, status, viewsets@@ -10,24 +14,55 @@ from posthog.api.monitoring import monitorfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.permissions import AccessControlPermission-from ..models.model_configuration import LLMModelConfiguration+from ..models.model_configuration import LLMModelConfiguration, provider_requires_keyfrom ..models.provider_keys import LLMProvider, LLMProviderKeyfrom .metrics import llma_track_latency+SUPPORTED_PROVIDERS: list[str] = [choice[0] for choice in LLMProvider.choices]+class LLMModelInfoSerializer(serializers.Serializer):id = serializers.CharField(help_text="Provider-specific model identifier (e.g. 'gpt-4o-mini', 'claude-3-5-sonnet-20241022').")+ provider = serializers.CharField(+ help_text=(+ "Provider this model belongs to. Pass this value together with `id` when configuring an llm_judge "+ "evaluation."+ )+ )+++class LLMProviderModelsSummarySerializer(serializers.Serializer):+ provider = serializers.CharField(help_text="Supported provider value, exactly as the `provider` param accepts it.")+ model_count = serializers.IntegerField(help_text="How many of this provider's models appear in `models`.")+ requires_provider_key = serializers.BooleanField(+ help_text=(+ "True when this provider's models can only be listed by passing `key_id` for one of the team's provider "+ "keys. PostHog funds no models for it, so `model_count` is 0 until a key is supplied."+ )+ )@extend_schema_serializer(many=False)class LLMModelsListResponseSerializer(serializers.Serializer):- models = LLMModelInfoSerializer(many=True, help_text="Models supported for the requested provider.")+ models = LLMModelInfoSerializer(+ many=True,+ help_text=(+ "Models supported for the requested provider, or for every supported provider when `provider` is omitted."+ ),+ )+ providers = LLMProviderModelsSummarySerializer(+ many=True,+ help_text=(+ "One entry per provider covered by this response. Read it to tell an unsupported provider apart from a "+ "provider whose models need a team key before they can be listed."+ ),+ )class LLMModelsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):- """List available models for a provider."""+ """List available models, for one provider or for every supported provider."""scope_object = "evaluation"serializer_class = _FallbackSerializer@@ -40,9 +75,12 @@ class LLMModelsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):name="provider",type=str,location=OpenApiParameter.QUERY,- required=True,- enum=[choice[0] for choice in LLMProvider.choices],- description="LLM provider to list models for. Must be one of the supported providers.",+ required=False,+ enum=SUPPORTED_PROVIDERS,+ description=(+ "LLM provider to list models for. Omit it to list every supported provider and its models in one "+ "call."+ ),),OpenApiParameter(name="key_id",@@ -52,7 +90,8 @@ class LLMModelsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):description=("Optional provider key UUID. When supplied, models reachable with that specific key are ""returned (useful for Azure OpenAI, where the deployment list depends on the configured "- "endpoint). Must belong to the same provider as the `provider` parameter."+ "endpoint). A key belongs to exactly one provider, so `provider` may be omitted alongside it; "+ "when both are given they must agree."),),],@@ -61,18 +100,17 @@ class LLMModelsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):@llma_track_latency("llma_models_list")@monitor(feature=None, endpoint="llma_models_list", method="GET")def list(self, request: Request, **_kwargs) -> Response:- provider = request.query_params.get("provider")- key_id = request.query_params.get("key_id")+ provider = request.query_params.get("provider") or None+ key_id = request.query_params.get("key_id") or None- if not provider:+ if provider is not None and provider not in SUPPORTED_PROVIDERS:return Response(- {"detail": "provider query param is required"},- status=status.HTTP_400_BAD_REQUEST,- )-- if provider not in [choice[0] for choice in LLMProvider.choices]:- return Response(- {"detail": f"Invalid provider. Must be one of: {', '.join([c[0] for c in LLMProvider.choices])}"},+ {+ "detail": (+ f"Invalid provider '{provider}'. Must be one of: {', '.join(SUPPORTED_PROVIDERS)}. "+ "Omit the provider param to list every supported provider."+ )+ },status=status.HTTP_400_BAD_REQUEST,)@@ -80,24 +118,45 @@ class LLMModelsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):if key_id:try:provider_key = LLMProviderKey.objects.get(id=key_id, team_id=self.team_id)- if provider_key.provider != provider:- return Response(- {- "detail": f"Key provider '{provider_key.provider}' does not match requested provider '{provider}'"- },- status=status.HTTP_400_BAD_REQUEST,- )- except LLMProviderKey.DoesNotExist:+ except (LLMProviderKey.DoesNotExist, DjangoValidationError):+ # DjangoValidationError covers a key_id that isn't a well-formed UUID, which the ORM+ # rejects while building the query rather than returning an empty result.return Response(- {"detail": "Key not found"},+ {"detail": f"No provider key '{key_id}' in this project. List the team's provider keys first."},status=status.HTTP_404_NOT_FOUND,)+ if provider is not None and provider_key.provider != provider:+ return Response(+ {+ "detail": (+ f"Key '{key_id}' belongs to provider '{provider_key.provider}', not '{provider}'. "+ "Omit the provider param to use the key's own provider."+ )+ },+ status=status.HTTP_400_BAD_REQUEST,+ )+ provider = provider_key.provider- config = LLMModelConfiguration(- provider=provider,- provider_key=provider_key,- team_id=self.team_id,- )- available = config.get_available_models()+ requested_providers = [provider] if provider is not None else SUPPORTED_PROVIDERS++ models: list[dict[str, str]] = []+ providers: list[dict[str, Any]] = []+ for candidate in requested_providers:+ config = LLMModelConfiguration(+ provider=candidate,+ provider_key=provider_key,+ team_id=self.team_id,+ )+ available = config.get_available_models()+ models.extend({"id": model, "provider": candidate} for model in available)+ providers.append(+ {+ "provider": candidate,+ "model_count": len(available),+ "requires_provider_key": provider_requires_key(candidate),+ }+ )- return Response({"models": [{"id": model} for model in available]})+ # Serializing rather than returning the dicts directly keeps the wire shape tied to the+ # response schema the generated frontend and MCP types are built from.+ return Response(LLMModelsListResponseSerializer({"models": models, "providers": providers}).data)diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.pyindex c61d280d9198..96cfe8c864f0 100644--- a/products/ai_observability/backend/api/test/test_evaluations.py+++ b/products/ai_observability/backend/api/test/test_evaluations.py@@ -986,6 +986,21 @@ class TestEvaluationConfigsApi(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(len(response.data["results"]), 0)+ @parameterized.expand(+ [+ ("unknown_uuid", "019f5632-6df1-0000-5093-46d18b1bc987"),+ # An agent holding the evaluation's name but not its id puts the name in the id slot. That+ # can't parse as a UUID, so without the ValidationError catch it surfaces as a 500.+ ("name_in_the_id_slot", "answer-faithfulness"),+ ]+ )+ def test_retrieving_a_missing_evaluation_says_how_to_find_a_real_id(self, _name, evaluation_id):+ response = self.client.get(f"/api/environments/{self.team.id}/evaluations/{evaluation_id}/")++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ self.assertIn(evaluation_id, response.data["detail"])+ self.assertIn("list the project's evaluations", response.data["detail"].lower())+def test_validation_requires_required_fields(self):# Missing nameresponse = self.client.post(diff --git a/products/ai_observability/backend/api/test/test_models.py b/products/ai_observability/backend/api/test/test_models.pyindex 1becebb4cf3a..7450dd5191ec 100644--- a/products/ai_observability/backend/api/test/test_models.py+++ b/products/ai_observability/backend/api/test/test_models.py@@ -1,18 +1,26 @@+from typing import Any+from posthog.test.base import APIBaseTestfrom unittest.mock import patchfrom django.test import SimpleTestCase+from parameterized import parameterizedfrom rest_framework import status-from products.ai_observability.backend.api.models import LLMModelInfoSerializer, LLMModelsListResponseSerializer+from products.ai_observability.backend.api.models import (+ SUPPORTED_PROVIDERS,+ LLMModelInfoSerializer,+ LLMModelsListResponseSerializer,+)+from products.ai_observability.backend.models.provider_keys import LLMProviderKeyclass TestLLMModelInfoSerializer(SimpleTestCase):def test_serializes_expected_shape(self):- serializer = LLMModelInfoSerializer(data={"id": "gpt-4o-mini"})+ serializer = LLMModelInfoSerializer(data={"id": "gpt-4o-mini", "provider": "openai"})self.assertTrue(serializer.is_valid(), serializer.errors)- self.assertEqual(serializer.validated_data, {"id": "gpt-4o-mini"})+ self.assertEqual(serializer.validated_data, {"id": "gpt-4o-mini", "provider": "openai"})def test_rejects_missing_id(self):serializer = LLMModelInfoSerializer(data={})@@ -25,41 +33,108 @@ class TestLLMModelsListResponseSerializer(SimpleTestCase):serializer = LLMModelsListResponseSerializer(data={"models": [- {"id": "gpt-4o-mini"},- {"id": "gpt-4o"},- ]+ {"id": "gpt-4o-mini", "provider": "openai"},+ {"id": "gpt-4o", "provider": "openai"},+ ],+ "providers": [{"provider": "openai", "model_count": 2, "requires_provider_key": False}],})self.assertTrue(serializer.is_valid(), serializer.errors)self.assertEqual(len(serializer.validated_data["models"]), 2)self.assertEqual(serializer.validated_data["models"][0]["id"], "gpt-4o-mini")+ self.assertEqual(serializer.validated_data["providers"][0]["model_count"], 2)class TestLLMModelsViewSet(APIBaseTest):- def test_requires_provider_query_param(self):- response = self.client.get(f"/api/environments/{self.team.id}/llm_analytics/models/")- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("provider", response.data["detail"].lower())+ def _list(self, query: str = "") -> Any:+ return self.client.get(f"/api/environments/{self.team.id}/llm_analytics/models/{query}")- def test_rejects_invalid_provider(self):- response = self.client.get(- f"/api/environments/{self.team.id}/llm_analytics/models/?provider=not-a-real-provider"+ def test_lists_every_supported_provider_when_provider_is_omitted(self):+ response = self._list()++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ body = response.json()+ self.assertEqual([entry["provider"] for entry in body["providers"]], SUPPORTED_PROVIDERS)+ # `model_count` is what an agent reads to decide whether a provider is worth pursuing, so it+ # has to agree with what `models` actually holds for that provider.+ self.assertTrue(all(model["provider"] in SUPPORTED_PROVIDERS for model in body["models"]))+ for entry in body["providers"]:+ listed = [model for model in body["models"] if model["provider"] == entry["provider"]]+ self.assertEqual(len(listed), entry["model_count"])++ def test_provider_summary_flags_providers_whose_models_need_a_key(self):+ body = self._list().json()++ needs_key = {entry["provider"] for entry in body["providers"] if entry["requires_provider_key"]}+ self.assertTrue(needs_key, "expected at least one provider to be BYOK-only")+ # A flagged provider is expected to contribute no models until a key is supplied, which is+ # what the flag exists to explain.+ self.assertEqual([model for model in body["models"] if model["provider"] in needs_key], [])+ self.assertTrue(+ {entry["provider"] for entry in body["providers"] if not entry["requires_provider_key"]},+ "expected at least one provider PostHog funds models for",)- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("invalid provider", response.data["detail"].lower())@patch("products.ai_observability.backend.api.models.LLMModelConfiguration")def test_returns_models_for_valid_provider(self, mock_config_cls):mock_config_cls.return_value.get_available_models.return_value = ["gpt-4o-mini", "gpt-4o"]- response = self.client.get(f"/api/environments/{self.team.id}/llm_analytics/models/?provider=openai")+ response = self._list("?provider=openai")self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertIn("models", response.data)- returned_ids = [m["id"] for m in response.data["models"]]- self.assertEqual(returned_ids, ["gpt-4o-mini", "gpt-4o"])+ body = response.json()+ self.assertEqual([m["id"] for m in body["models"]], ["gpt-4o-mini", "gpt-4o"])+ self.assertEqual([m["provider"] for m in body["models"]], ["openai", "openai"])+ self.assertEqual(body["providers"], [{"provider": "openai", "model_count": 2, "requires_provider_key": False}])++ @patch("products.ai_observability.backend.api.models.LLMModelConfiguration")+ def test_key_id_alone_resolves_the_provider_from_the_key(self, mock_config_cls):+ mock_config_cls.return_value.get_available_models.return_value = ["claude-sonnet-4-5"]+ key = LLMProviderKey.objects.create(team=self.team, provider="anthropic", name="team key")++ response = self._list(f"?key_id={key.id}")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ body = response.json()+ self.assertEqual(body["models"], [{"id": "claude-sonnet-4-5", "provider": "anthropic"}])+ self.assertEqual([entry["provider"] for entry in body["providers"]], ["anthropic"])+ self.assertEqual(mock_config_cls.call_args.kwargs["provider_key"], key)++ def test_rejects_key_id_that_belongs_to_another_provider(self):+ key = LLMProviderKey.objects.create(team=self.team, provider="anthropic", name="team key")++ response = self._list(f"?provider=openai&key_id={key.id}")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ detail = response.json()["detail"]+ self.assertIn("anthropic", detail)+ # A key resolves its own provider, so the rejection has to name that as the way out.+ self.assertIn("omit the provider param", detail.lower())++ @parameterized.expand(+ [+ ("unknown_uuid", "019f5632-6df1-0000-5093-46d18b1bc987"),+ # A key_id the ORM can't parse as a UUID reaches the query builder as a ValidationError,+ # which would otherwise surface as a 500 rather than a missing key.+ ("malformed_uuid", "not-a-uuid"),+ ]+ )+ def test_unknown_key_id_returns_404(self, _name, key_id):+ response = self._list(f"?key_id={key_id}")++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ self.assertIn("provider key", response.json()["detail"])++ def test_rejects_invalid_provider(self):+ response = self._list("?provider=not-a-real-provider")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ detail = response.json()["detail"]+ self.assertIn("invalid provider", detail.lower())+ # The rejection has to name the way out, or an agent asking for the catalog retries the same call.+ self.assertIn("omit the provider param", detail.lower())def test_unauthenticated_user_cannot_list_models(self):self.client.logout()- response = self.client.get(f"/api/environments/{self.team.id}/llm_analytics/models/?provider=openai")+ response = self._list("?provider=openai")self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)diff --git a/products/ai_observability/backend/models/model_configuration.py b/products/ai_observability/backend/models/model_configuration.pyindex 55b1a2aaaa50..ae19395b95af 100644--- a/products/ai_observability/backend/models/model_configuration.py+++ b/products/ai_observability/backend/models/model_configuration.py@@ -6,6 +6,16 @@ from posthog.models.utils import UUIDTModelfrom .provider_keys import llm_provider_choices+def provider_requires_key(provider: str) -> bool:+ """Whether this provider's models can only be listed with a BYOK key. PostHog funds no models+ for it, so a keyless lookup has nothing to return."""+ from products.ai_observability.backend.llm import ( # noqa: PLC0415 - keeps the provider SDKs off the import path+ PLAYGROUND_MODELS_BY_PROVIDER,+ )++ return provider not in PLAYGROUND_MODELS_BY_PROVIDER++class LLMModelConfiguration(UUIDTModel):"""Configuration for LLM model selection, used by evals and other features."""diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.tsindex 0c1dba520d43..01f4f9941301 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts@@ -240,7 +240,11 @@ describe('llmEvaluationLogic', () => {},'/api/projects/:teamId/evaluations/:id/': mockEvaluation,'/api/environments/:teamId/llm_analytics/models/': {- models: [{ id: 'gpt-5-mini' }, { id: 'gpt-5' }],+ models: [+ { id: 'gpt-5-mini', provider: 'openai' },+ { id: 'gpt-5', provider: 'openai' },+ ],+ providers: [{ provider: 'openai', model_count: 2, requires_provider_key: false }],},},})diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex 846c023732ce..ae71c91285ea 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -1788,11 +1788,24 @@ export interface PaginatedEvaluationReportRunListApi {export interface LLMModelInfoApi {/** Provider-specific model identifier (e.g. 'gpt-4o-mini', 'claude-3-5-sonnet-20241022'). */id: string+ /** Provider this model belongs to. Pass this value together with `id` when configuring an llm_judge evaluation. */+ provider: string+}++export interface LLMProviderModelsSummaryApi {+ /** Supported provider value, exactly as the `provider` param accepts it. */+ provider: string+ /** How many of this provider's models appear in `models`. */+ model_count: number+ /** True when this provider's models can only be listed by passing `key_id` for one of the team's provider keys. PostHog funds no models for it, so `model_count` is 0 until a key is supplied. */+ requires_provider_key: boolean}export interface LLMModelsListResponseApi {- /** Models supported for the requested provider. */+ /** Models supported for the requested provider, or for every supported provider when `provider` is omitted. */models: LLMModelInfoApi[]+ /** One entry per provider covered by this response. Read it to tell an unsupported provider apart from a provider whose models need a team key before they can be listed. */+ providers: LLMProviderModelsSummaryApi[]}export interface OfflineExperimentItemsRequestApi {@@ -3240,13 +3253,13 @@ export type LlmAnalyticsEvaluationReportsRunsListParams = {export type LlmAnalyticsModelsRetrieveParams = {/**- * Optional provider key UUID. When supplied, models reachable with that specific key are returned (useful for Azure OpenAI, where the deployment list depends on the configured endpoint). Must belong to the same provider as the `provider` parameter.+ * Optional provider key UUID. When supplied, models reachable with that specific key are returned (useful for Azure OpenAI, where the deployment list depends on the configured endpoint). A key belongs to exactly one provider, so `provider` may be omitted alongside it; when both are given they must agree.*/key_id?: string/**- * LLM provider to list models for. Must be one of the supported providers.+ * LLM provider to list models for. Omit it to list every supported provider and its models in one call.*/- provider: LlmAnalyticsModelsRetrieveProvider+ provider?: LlmAnalyticsModelsRetrieveProvider}export type LlmAnalyticsModelsRetrieveProvider =diff --git a/products/ai_observability/frontend/generated/api.ts b/products/ai_observability/frontend/generated/api.tsindex 3eec1ad28204..ba237779ce42 100644--- a/products/ai_observability/frontend/generated/api.ts+++ b/products/ai_observability/frontend/generated/api.ts@@ -1211,7 +1211,7 @@ export const llmAnalyticsEvaluationReportsRunsList = async ()}-export const getLlmAnalyticsModelsRetrieveUrl = (projectId: string, params: LlmAnalyticsModelsRetrieveParams) => {+export const getLlmAnalyticsModelsRetrieveUrl = (projectId: string, params?: LlmAnalyticsModelsRetrieveParams) => {const normalizedParams = new URLSearchParams()Object.entries(params || {}).forEach(([key, value]) => {@@ -1228,11 +1228,11 @@ export const getLlmAnalyticsModelsRetrieveUrl = (projectId: string, params: LlmA}/**- * List available models for a provider.+ * List available models, for one provider or for every supported provider.*/export const llmAnalyticsModelsRetrieve = async (projectId: string,- params: LlmAnalyticsModelsRetrieveParams,+ params?: LlmAnalyticsModelsRetrieveParams,options?: RequestInit): Promise<LLMModelsListResponseApi> => {return apiMutator<LLMModelsListResponseApi>(getLlmAnalyticsModelsRetrieveUrl(projectId, params), {diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yamlindex 532b4ca5ccfa..ad1e318adf3e 100644--- a/products/ai_observability/mcp/tools.yaml+++ b/products/ai_observability/mcp/tools.yaml@@ -514,6 +514,11 @@ tools:description: >Soft-delete an AI observability evaluation. The evaluation stops running and is hidden from list views.Historical evaluation results ($ai_evaluation events) are preserved.+ param_overrides:+ id:+ aliases:+ - evaluationId+ - evaluation_idsoft_delete: truellma-evaluation-directory-create:operation: evaluation_directories_create@@ -590,6 +595,11 @@ tools:Get a specific AI observability evaluation by its UUID. Requires the evaluation `id` (UUID) as a parameter —if you don't have it, call llma-evaluation-list first to look it up by name. Returns the full evaluationconfiguration including type, config, output type, enabled status, and model configuration.+ param_overrides:+ id:+ aliases:+ - evaluationId+ - evaluation_idllma-evaluation-judge-models:operation: llm_analytics_models_retrieveenabled: true@@ -601,11 +611,14 @@ tools:idempotent: truetitle: List supported llm_judge modelsdescription: >- List provider+model combinations supported for llm_judge. `provider` is required and must be exactly one of- these lowercase values: openai, anthropic, gemini, openrouter, fireworks, azure_openai, together_ai,- minimax, zeabur. Optional `key_id` scopes to a key's reachable deployments (mainly azure_openai). Call- before creating an llm_judge eval to pick a valid combo — prefer a provider the team already has a key for- (see llma-provider-key-list).+ List provider+model combinations supported for llm_judge. Call it with no arguments to get every supported+ provider and its models in one response; each model carries the `provider` to pair it with. Pass `provider`+ to narrow to one of these lowercase values: openai, anthropic, gemini, openrouter, fireworks, azure_openai,+ together_ai, minimax, zeabur. Optional `key_id` scopes to a key's reachable deployments (mainly+ azure_openai) and implies that key's provider. The `providers` list in the response flags providers whose+ models only appear once you pass `key_id` for one of the team's keys; those return no models otherwise. Call+ this before creating an llm_judge eval to pick a valid combo, and prefer a provider the team already has a+ key for (see llma-provider-key-list).llma-evaluation-list:operation: evaluations_listenabled: true@@ -753,6 +766,11 @@ tools:asynchronously executes the evaluation and stores the result as a '$ai_evaluation' event. Returns aworkflow_id and status "started". Pair with execute-sql to query results: SELECT * FROM events WHERE event ='$ai_evaluation'.+ param_overrides:+ evaluation_id:+ aliases:+ - evaluationId+ - idllma-evaluation-test-hog:operation: evaluations_test_hog_createenabled: true@@ -791,6 +809,11 @@ tools:editable. provider_key_id may be null when no key is pinned. `target` accepts 'generation', 'trace', or'session'. Pass a `directory_id` returned by llma-evaluation-directory-list to move the evaluation into adirectory, or pass null to move it to the top level.+ param_overrides:+ id:+ aliases:+ - evaluationId+ - evaluation_idllma-evaluation-update-full:operation: evaluations_updateenabled: false@@ -857,8 +880,11 @@ tools:idempotent: truetitle: Get promptdescription: |- Get a specific LLM prompt by name. Requires `prompt_name`, the prompt's exact name — call- llma-prompt-list to discover valid names; an unknown or guessed name returns a 404.+ Get a specific LLM prompt by name. Requires `prompt_name`, which takes either the prompt's exact name or+ the `id` UUID from any llma-prompt-list or llma-prompt-get response. Call llma-prompt-list to discover+ valid names; a guessed name that matches nothing returns a 404.+ An id identifies the prompt, not the version it came from, so passing a specific version's id still+ returns the latest version. Pass `version` or `label` to pin one.Uses the cached endpoint for fast retrieval.Pass `label` (e.g. 'production') to fetch the version that label currently points to, or `version` for anexact version number — not both. With neither, the latest version is returned.@@ -867,6 +893,14 @@ tools:or `content=preview` for a short `prompt_preview` snippet instead of the full prompt.With full content the response also includes `config`, the JSON object of model parameters or agentconfiguration stored with the version (null when the version has none).+ param_overrides:+ prompt_name:+ aliases:+ - name+ - promptName+ - prompt_id+ - promptId+ - idllma-prompt-label-delete:operation: llm_prompts_name_labels_destroyenabled: truediff --git a/products/ai_observability/skills/creating-online-evaluations/SKILL.md b/products/ai_observability/skills/creating-online-evaluations/SKILL.mdindex ecc58acb775f..3ed78621bf1a 100644--- a/products/ai_observability/skills/creating-online-evaluations/SKILL.md+++ b/products/ai_observability/skills/creating-online-evaluations/SKILL.md@@ -222,12 +222,14 @@ Hog and sentiment evaluations skip this step.```jsonposthog:llma-evaluation-config-get // check active_provider_key for an unpinned judgeposthog:llma-provider-key-list // find an ok-state key to pin-posthog:llma-evaluation-judge-models // { "provider": "openai" } → valid models+posthog:llma-evaluation-judge-models // {} → every provider and its models; { "provider": "openai" } narrows it```-Confirm the provider and model with `llma-evaluation-judge-models`. Prefer pinning the chosen key so a later-team-wide active-key change does not change how the evaluation runs. Leave `provider_key_id` as `null` only-after `llma-evaluation-config-get` confirms the active key is usable and its provider matches.+Confirm the provider and model with `llma-evaluation-judge-models`.+Call it with no arguments to see the whole catalog at once.+Providers PostHog funds no models for come back empty unless you pass `key_id` for one of the team's keys; the response's `providers` list flags which ones those are.+Prefer pinning the chosen key so a later team-wide active-key change does not change how the evaluation runs.+Leave `provider_key_id` as `null` only after `llma-evaluation-config-get` confirms the active key is usable and its provider matches.If there is no usable key, you may still create a disabled draft for the user to review. Do not spot-run orenable it. Ask the user to add or validate a key in the UI before continuing.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex c36f097289bd..4cc87f245dc6 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -6124,7 +6124,7 @@}},"llma-evaluation-judge-models": {- "description": "List provider+model combinations supported for llm_judge. `provider` is required and must be exactly one of these lowercase values: openai, anthropic, gemini, openrouter, fireworks, azure_openai, together_ai, minimax, zeabur. Optional `key_id` scopes to a key's reachable deployments (mainly azure_openai). Call before creating an llm_judge eval to pick a valid combo — prefer a provider the team already has a key for (see llma-provider-key-list).",+ "description": "List provider+model combinations supported for llm_judge. Call it with no arguments to get every supported provider and its models in one response; each model carries the `provider` to pair it with. Pass `provider` to narrow to one of these lowercase values: openai, anthropic, gemini, openrouter, fireworks, azure_openai, together_ai, minimax, zeabur. Optional `key_id` scopes to a key's reachable deployments (mainly azure_openai) and implies that key's provider. The `providers` list in the response flags providers whose models only appear once you pass `key_id` for one of the team's keys; those return no models otherwise. Call this before creating an llm_judge eval to pick a valid combo, and prefer a provider the team already has a key for (see llma-provider-key-list).","category": "AI observability","feature": "llm_analytics","summary": "List supported llm_judge models",@@ -6320,7 +6320,7 @@}},"llma-prompt-get": {- "description": "Get a specific LLM prompt by name. Requires `prompt_name`, the prompt's exact name — call\nllma-prompt-list to discover valid names; an unknown or guessed name returns a 404.\nUses the cached endpoint for fast retrieval.\nPass `label` (e.g. 'production') to fetch the version that label currently points to, or `version` for an\nexact version number — not both. With neither, the latest version is returned.\nThe response always includes `outline`, a flat list of markdown headings parsed from the prompt — useful\nas a lightweight table of contents. Pass `content=none` to get the outline without the prompt payload,\nor `content=preview` for a short `prompt_preview` snippet instead of the full prompt.\nWith full content the response also includes `config`, the JSON object of model parameters or agent\nconfiguration stored with the version (null when the version has none).",+ "description": "Get a specific LLM prompt by name. Requires `prompt_name`, which takes either the prompt's exact name or\nthe `id` UUID from any llma-prompt-list or llma-prompt-get response. Call llma-prompt-list to discover\nvalid names; a guessed name that matches nothing returns a 404.\nAn id identifies the prompt, not the version it came from, so passing a specific version's id still\nreturns the latest version. Pass `version` or `label` to pin one.\nUses the cached endpoint for fast retrieval.\nPass `label` (e.g. 'production') to fetch the version that label currently points to, or `version` for an\nexact version number — not both. With neither, the latest version is returned.\nThe response always includes `outline`, a flat list of markdown headings parsed from the prompt — useful\nas a lightweight table of contents. Pass `content=none` to get the outline without the prompt payload,\nor `content=preview` for a short `prompt_preview` snippet instead of the full prompt.\nWith full content the response also includes `config`, the JSON object of model parameters or agent\nconfiguration stored with the version (null when the version has none).","category": "AI observability","feature": "llm_analytics","summary": "Get prompt",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 451e6a402243..b63957c76f73 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -6321,7 +6321,7 @@}},"llma-evaluation-judge-models": {- "description": "List provider+model combinations supported for llm_judge. `provider` is required and must be exactly one of these lowercase values: openai, anthropic, gemini, openrouter, fireworks, azure_openai, together_ai, minimax, zeabur. Optional `key_id` scopes to a key's reachable deployments (mainly azure_openai). Call before creating an llm_judge eval to pick a valid combo — prefer a provider the team already has a key for (see llma-provider-key-list).",+ "description": "List provider+model combinations supported for llm_judge. Call it with no arguments to get every supported provider and its models in one response; each model carries the `provider` to pair it with. Pass `provider` to narrow to one of these lowercase values: openai, anthropic, gemini, openrouter, fireworks, azure_openai, together_ai, minimax, zeabur. Optional `key_id` scopes to a key's reachable deployments (mainly azure_openai) and implies that key's provider. The `providers` list in the response flags providers whose models only appear once you pass `key_id` for one of the team's keys; those return no models otherwise. Call this before creating an llm_judge eval to pick a valid combo, and prefer a provider the team already has a key for (see llma-provider-key-list).","category": "AI observability","feature": "llm_analytics","summary": "List supported llm_judge models",@@ -6545,7 +6545,7 @@}},"llma-prompt-get": {- "description": "Get a specific LLM prompt by name. Requires `prompt_name`, the prompt's exact name — call\nllma-prompt-list to discover valid names; an unknown or guessed name returns a 404.\nUses the cached endpoint for fast retrieval.\nPass `label` (e.g. 'production') to fetch the version that label currently points to, or `version` for an\nexact version number — not both. With neither, the latest version is returned.\nThe response always includes `outline`, a flat list of markdown headings parsed from the prompt — useful\nas a lightweight table of contents. Pass `content=none` to get the outline without the prompt payload,\nor `content=preview` for a short `prompt_preview` snippet instead of the full prompt.\nWith full content the response also includes `config`, the JSON object of model parameters or agent\nconfiguration stored with the version (null when the version has none).",+ "description": "Get a specific LLM prompt by name. Requires `prompt_name`, which takes either the prompt's exact name or\nthe `id` UUID from any llma-prompt-list or llma-prompt-get response. Call llma-prompt-list to discover\nvalid names; a guessed name that matches nothing returns a 404.\nAn id identifies the prompt, not the version it came from, so passing a specific version's id still\nreturns the latest version. Pass `version` or `label` to pin one.\nUses the cached endpoint for fast retrieval.\nPass `label` (e.g. 'production') to fetch the version that label currently points to, or `version` for an\nexact version number — not both. With neither, the latest version is returned.\nThe response always includes `outline`, a flat list of markdown headings parsed from the prompt — useful\nas a lightweight table of contents. Pass `content=none` to get the outline without the prompt payload,\nor `content=preview` for a short `prompt_preview` snippet instead of the full prompt.\nWith full content the response also includes `config`, the JSON object of model parameters or agent\nconfiguration stored with the version (null when the version has none).","category": "AI observability","feature": "llm_analytics","summary": "Get prompt",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c859892b0631..5fb6fadd1556 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -44611,11 +44611,24 @@ export namespace Schemas {export interface LLMModelInfo {/** Provider-specific model identifier (e.g. 'gpt-4o-mini', 'claude-3-5-sonnet-20241022'). */id: string;+ /** Provider this model belongs to. Pass this value together with `id` when configuring an llm_judge evaluation. */+ provider: string;+ }++ export interface LLMProviderModelsSummary {+ /** Supported provider value, exactly as the `provider` param accepts it. */+ provider: string;+ /** How many of this provider's models appear in `models`. */+ model_count: number;+ /** True when this provider's models can only be listed by passing `key_id` for one of the team's provider keys. PostHog funds no models for it, so `model_count` is 0 until a key is supplied. */+ requires_provider_key: boolean;}export interface LLMModelsListResponse {- /** Models supported for the requested provider. */+ /** Models supported for the requested provider, or for every supported provider when `provider` is omitted. */models: LLMModelInfo[];+ /** One entry per provider covered by this response. Read it to tell an unsupported provider apart from a provider whose models need a team key before they can be listed. */+ providers: LLMProviderModelsSummary[];}/**@@ -91365,13 +91378,13 @@ export namespace Schemas {export type LlmAnalyticsModelsRetrieveParams = {/**- * Optional provider key UUID. When supplied, models reachable with that specific key are returned (useful for Azure OpenAI, where the deployment list depends on the configured endpoint). Must belong to the same provider as the `provider` parameter.+ * Optional provider key UUID. When supplied, models reachable with that specific key are returned (useful for Azure OpenAI, where the deployment list depends on the configured endpoint). A key belongs to exactly one provider, so `provider` may be omitted alongside it; when both are given they must agree.*/key_id?: string;/**- * LLM provider to list models for. Must be one of the supported providers.+ * LLM provider to list models for. Omit it to list every supported provider and its models in one call.*/- provider: LlmAnalyticsModelsRetrieveProvider;+ provider?: LlmAnalyticsModelsRetrieveProvider;};export type LlmAnalyticsModelsRetrieveProvider = typeof LlmAnalyticsModelsRetrieveProvider[keyof typeof LlmAnalyticsModelsRetrieveProvider];diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.tsindex 76307355d93a..0ae60fa3693b 100644--- a/services/mcp/src/generated/ai_observability/api.ts+++ b/services/mcp/src/generated/ai_observability/api.ts@@ -1420,7 +1420,7 @@ export const LlmAnalyticsEvaluationReportsRunsListQueryParams = /* @__PURE__ */})/**- * List available models for a provider.+ * List available models, for one provider or for every supported provider.*/export const LlmAnalyticsModelsRetrieveParams = /* @__PURE__ */ zod.object({project_id: zod@@ -1435,7 +1435,7 @@ export const LlmAnalyticsModelsRetrieveQueryParams = /* @__PURE__ */ zod.object(.string().optional().describe(- 'Optional provider key UUID. When supplied, models reachable with that specific key are returned (useful for Azure OpenAI, where the deployment list depends on the configured endpoint). Must belong to the same provider as the `provider` parameter.'+ 'Optional provider key UUID. When supplied, models reachable with that specific key are returned (useful for Azure OpenAI, where the deployment list depends on the configured endpoint). A key belongs to exactly one provider, so `provider` may be omitted alongside it; when both are given they must agree.'),provider: zod.enum([@@ -1449,7 +1449,10 @@ export const LlmAnalyticsModelsRetrieveQueryParams = /* @__PURE__ */ zod.object('together_ai','zeabur',])- .describe('LLM provider to list models for. Must be one of the supported providers.'),+ .optional()+ .describe(+ 'LLM provider to list models for. Omit it to list every supported provider and its models in one call.'+ ),})export const LlmAnalyticsProviderKeysListParams = /* @__PURE__ */ zod.object({diff --git a/services/mcp/src/tools/generated/ai_observability.ts b/services/mcp/src/tools/generated/ai_observability.tsindex 053388696751..94cfe9141e11 100644--- a/services/mcp/src/tools/generated/ai_observability.ts+++ b/services/mcp/src/tools/generated/ai_observability.ts@@ -98,6 +98,7 @@ import {TaggersTestHogCreateBody,} from '@/generated/ai_observability/api'import { PromptListInputSchema, ScoreDefinitionConfigSchema } from '@/schema/tool-inputs'+import { normalizeParamAliases } from '@/tools/cast-helpers'import { createQueryWrapper } from '@/tools/query-wrapper-factory'import {withPostHogUrl,@@ -830,7 +831,10 @@ const llmaEvaluationCreate = (): ToolBase<typeof LlmaEvaluationCreateSchema, Sch},})-const LlmaEvaluationDeleteSchema = EvaluationsDestroyParams.omit({ project_id: true })+const LlmaEvaluationDeleteSchema = z.preprocess(+ normalizeParamAliases({ id: ['evaluationId', 'evaluation_id'] }),+ EvaluationsDestroyParams.omit({ project_id: true })+)const llmaEvaluationDelete = (): ToolBase<typeof LlmaEvaluationDeleteSchema, Schemas.Evaluation> => ({name: 'llma-evaluation-delete',@@ -946,7 +950,10 @@ const llmaEvaluationDirectoryUpdate = (): ToolBase<},})-const LlmaEvaluationGetSchema = EvaluationsRetrieveParams.omit({ project_id: true })+const LlmaEvaluationGetSchema = z.preprocess(+ normalizeParamAliases({ id: ['evaluationId', 'evaluation_id'] }),+ EvaluationsRetrieveParams.omit({ project_id: true })+)const llmaEvaluationGet = (): ToolBase<typeof LlmaEvaluationGetSchema, Schemas.Evaluation> => ({name: 'llma-evaluation-get',@@ -1182,7 +1189,10 @@ const llmaEvaluationReportUpdate = (): ToolBase<},})-const LlmaEvaluationRunSchema = EvaluationRunsCreateBody+const LlmaEvaluationRunSchema = z.preprocess(+ normalizeParamAliases({ evaluation_id: ['evaluationId', 'id'] }),+ EvaluationRunsCreateBody+)const llmaEvaluationRun = (): ToolBase<typeof LlmaEvaluationRunSchema, unknown> => ({name: 'llma-evaluation-run',@@ -1249,8 +1259,9 @@ const llmaEvaluationTestHog = (): ToolBase<typeof LlmaEvaluationTestHogSchema, S},})-const LlmaEvaluationUpdateSchema = EvaluationsPartialUpdateParams.omit({ project_id: true }).extend(- EvaluationsPartialUpdateBody.shape+const LlmaEvaluationUpdateSchema = z.preprocess(+ normalizeParamAliases({ id: ['evaluationId', 'evaluation_id'] }),+ EvaluationsPartialUpdateParams.omit({ project_id: true }).extend(EvaluationsPartialUpdateBody.shape))const llmaEvaluationUpdate = (): ToolBase<typeof LlmaEvaluationUpdateSchema, Schemas.Evaluation> => ({@@ -1380,8 +1391,9 @@ const llmaPromptDuplicate = (): ToolBase<typeof LlmaPromptDuplicateSchema, Schem},})-const LlmaPromptGetSchema = LlmPromptsNameRetrieveParams.omit({ project_id: true }).extend(- LlmPromptsNameRetrieveQueryParams.shape+const LlmaPromptGetSchema = z.preprocess(+ normalizeParamAliases({ prompt_name: ['name', 'promptName', 'prompt_id', 'promptId', 'id'] }),+ LlmPromptsNameRetrieveParams.omit({ project_id: true }).extend(LlmPromptsNameRetrieveQueryParams.shape))const llmaPromptGet = (): ToolBase<typeof LlmaPromptGetSchema, Schemas.LLMPromptPublic> => ({diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-judge-models.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-judge-models.jsonindex 6fa9a98774b8..51d148e109ab 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-judge-models.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-judge-models.json@@ -2,11 +2,11 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"key_id": {- "description": "Optional provider key UUID. When supplied, models reachable with that specific key are returned (useful for Azure OpenAI, where the deployment list depends on the configured endpoint). Must belong to the same provider as the `provider` parameter.",+ "description": "Optional provider key UUID. When supplied, models reachable with that specific key are returned (useful for Azure OpenAI, where the deployment list depends on the configured endpoint). A key belongs to exactly one provider, so `provider` may be omitted alongside it; when both are given they must agree.","type": "string"},"provider": {- "description": "LLM provider to list models for. Must be one of the supported providers.",+ "description": "LLM provider to list models for. Omit it to list every supported provider and its models in one call.","enum": ["anthropic","azure_openai",@@ -21,6 +21,5 @@"type": "string"}},- "required": ["provider"],"type": "object"}diff --git a/services/mcp/tests/unit/llma-identifier-contracts.test.ts b/services/mcp/tests/unit/llma-identifier-contracts.test.tsnew file mode 100644index 000000000000..b8c84fee1b69--- /dev/null+++ b/services/mcp/tests/unit/llma-identifier-contracts.test.ts@@ -0,0 +1,149 @@+import { describe, expect, it, vi } from 'vitest'++import { GENERATED_TOOLS } from '@/tools/generated/ai_observability'+import type { Context } from '@/tools/types'++function createContext(): { context: Context; requestMock: ReturnType<typeof vi.fn> } {+ const requestMock = vi.fn().mockResolvedValue({})+ const context = {+ api: { request: requestMock },+ stateManager: { getProjectId: vi.fn().mockResolvedValue('17') },+ } as unknown as Context+ return { context, requestMock }+}++// Production traces show these tools rejecting their failed calls at the schema, before any request+// goes out: the evaluation tools and `llma-prompt-get` because the agent named the identifier+// something the schema didn't declare, and `llma-evaluation-judge-models` because it demanded a+// single `provider` while agents were asking for the whole catalog. The inputs below are the keys+// and values those traces record, so dropping an alias map or making `provider` required again+// fails here.+describe('llma identifier contracts', () => {+ // The write tools share the mismatch, so they share the alias map. Without that, an agent that+ // succeeds with `evaluationId` on get is rejected the moment it updates or deletes.+ describe.each([['llma-evaluation-get'], ['llma-evaluation-update'], ['llma-evaluation-delete']])(+ '%s normalizes aliases to `id`',+ (toolName) => {+ const schema = GENERATED_TOOLS[toolName]!().schema+ const ALIAS_KEYS = ['evaluationId', 'evaluation_id'] as const++ it.each([+ ['id', { id: 'e1' }, 'e1'],+ ['evaluationId', { evaluationId: 'e1' }, 'e1'],+ ['evaluation_id', { evaluation_id: 'e1' }, 'e1'],+ ['id over aliases on conflict', { id: 'e1', evaluationId: 'e2' }, 'e1'],+ ['first-listed alias on alias conflict', { evaluationId: 'e1', evaluation_id: 'e2' }, 'e1'],+ ])('accepts %s', (_label, input, expected) => {+ const result = schema.safeParse(input)+ expect(result.success).toBe(true)+ const data = result.data as Record<string, unknown>+ expect(data.id).toBe(expected)+ for (const alias of ALIAS_KEYS) {+ expect(data).not.toHaveProperty(alias)+ }+ })++ it('still rejects a call with no identifier', () => {+ expect(schema.safeParse({}).success).toBe(false)+ })+ }+ )++ describe('llma-evaluation-run normalizes aliases to `evaluation_id`', () => {+ const schema = GENERATED_TOOLS['llma-evaluation-run']!().schema+ const runInput = {+ target_event_id: '019f5632-6df1-0000-5093-46d18b1bc987',+ timestamp: '2026-01-01T00:00:00Z',+ }++ it.each([+ ['evaluation_id', { evaluation_id: 'e1' }, 'e1'],+ ['evaluationId', { evaluationId: 'e1' }, 'e1'],+ ['id', { id: 'e1' }, 'e1'],+ ['evaluation_id over aliases on conflict', { evaluation_id: 'e1', evaluationId: 'e2' }, 'e1'],+ ])('accepts %s', (_label, identifier, expected) => {+ const result = schema.safeParse({ ...runInput, ...identifier })+ expect(result.success).toBe(true)+ expect((result.data as Record<string, unknown>).evaluation_id).toBe(expected)+ })++ it('still rejects a call with no identifier', () => {+ expect(schema.safeParse(runInput).success).toBe(false)+ })+ })++ describe('llma-prompt-get normalizes aliases to `prompt_name`', () => {+ const schema = GENERATED_TOOLS['llma-prompt-get']!().schema+ const ALIAS_KEYS = ['name', 'promptName', 'prompt_id', 'promptId', 'id'] as const++ it.each([+ ['prompt_name', { prompt_name: 'greeting' }, 'greeting'],+ ['name', { name: 'greeting' }, 'greeting'],+ ['promptName', { promptName: 'greeting' }, 'greeting'],+ ['prompt_id', { prompt_id: 'greeting' }, 'greeting'],+ ['promptId', { promptId: 'greeting' }, 'greeting'],+ ['id', { id: 'greeting' }, 'greeting'],+ ['prompt_name over aliases on conflict', { prompt_name: 'greeting', name: 'other' }, 'greeting'],+ ['first-listed alias on alias conflict', { name: 'greeting', id: 'other' }, 'greeting'],+ ])('accepts %s', (_label, input, expected) => {+ const result = schema.safeParse(input)+ expect(result.success).toBe(true)+ const data = result.data as Record<string, unknown>+ expect(data.prompt_name).toBe(expected)+ for (const alias of ALIAS_KEYS) {+ expect(data).not.toHaveProperty(alias)+ }+ })++ it('keeps query params alongside a normalized alias', () => {+ const result = schema.safeParse({ name: 'greeting', label: 'production', content: 'none' })+ expect(result.success).toBe(true)+ expect(result.data).toMatchObject({ prompt_name: 'greeting', label: 'production', content: 'none' })+ })++ it('still rejects a call with no identifier', () => {+ expect(schema.safeParse({}).success).toBe(false)+ })+ })++ describe('llma-evaluation-judge-models treats `provider` as a filter', () => {+ const schema = GENERATED_TOOLS['llma-evaluation-judge-models']!().schema++ it('accepts a call with no arguments so the whole catalog is reachable', () => {+ const result = schema.safeParse({})+ expect(result.success).toBe(true)+ expect(result.data).not.toHaveProperty('provider')+ })++ it('accepts key_id on its own, since a key implies its provider', () => {+ const result = schema.safeParse({ key_id: 'k1' })+ expect(result.success).toBe(true)+ expect(result.data).toMatchObject({ key_id: 'k1' })+ })++ it.each([['openai'], ['azure_openai'], ['gemini']])('still accepts the supported provider %s', (provider) => {+ expect(schema.safeParse({ provider }).success).toBe(true)+ })++ it.each([['google'], ['OpenAI'], ['all']])('still rejects the unsupported provider %s', (provider) => {+ expect(schema.safeParse({ provider }).success).toBe(false)+ })+ })++ // Both dispatchers parse first and hand the parsed value to the handler. If either passed the+ // raw input instead, an aliased call would clear validation and then build+ // `.../name/undefined/`, so the caller would get a 404 that hides which field was wrong.+ describe.each([+ ['llma-prompt-get', { name: 'greeting' }, '/api/projects/17/llm_prompts/name/greeting/'],+ ['llma-evaluation-get', { evaluationId: 'e1' }, '/api/projects/17/evaluations/e1/'],+ ])('%s puts the aliased identifier in the request path', (toolName, input, expectedPath) => {+ it('builds the path from the normalized param', async () => {+ const { context, requestMock } = createContext()+ const tool = GENERATED_TOOLS[toolName]!()++ await tool.handler(context, tool.schema.parse(input) as never)++ expect(requestMock).toHaveBeenCalledWith(expect.objectContaining({ path: expectedPath }))+ })+ })+})diff --git a/services/mcp/tests/unit/prompts-generated.test.ts b/services/mcp/tests/unit/prompts-generated.test.tsindex 89a1dd5b2ab4..2eebff67f2ec 100644--- a/services/mcp/tests/unit/prompts-generated.test.ts+++ b/services/mcp/tests/unit/prompts-generated.test.ts@@ -20,12 +20,13 @@ function createContext(requestReturnValue: unknown): { context: Context; request}describe('Generated llma-prompt-* tools', () => {- it('uses prompt_name (not name) in generated prompt-get schema', () => {+ // prompt-get also accepts `name` and the other identifier aliases, normalized to `prompt_name`+ // before the handler sees them — see llma-identifier-contracts.test.ts.+ it('uses prompt_name in generated prompt-get schema', () => {const tool = getToolByName(GENERATED_TOOLS, 'llma-prompt-get')const parsed = tool.schema.parse({ prompt_name: 'checkout_prompt', version: 2 })expect(parsed).toEqual({ prompt_name: 'checkout_prompt', version: 2, content: 'full' })- expect(() => tool.schema.parse({ name: 'checkout_prompt' })).toThrow()})it('exposes content mode on the prompt-get schema so agents can fetch outline-only', () => {