: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
feat(mcp): make OAuth and MCP auth failures observable (#77558)
Christiaan Hendriksen619526709485
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex 5246a0ce012b..c6c672409027 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -30,7 +30,7 @@ from rest_framework import statusfrom posthog.api.oauth import OAuthAuthorizationSerializerfrom posthog.api.oauth.cimd import CIMD_SUPPORTED_AUTH_METHODSfrom posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARER-from posthog.api.oauth.views import OAuthValidator+from posthog.api.oauth.views import OAuthTokenView, OAuthValidator, _token_error_codefrom posthog.models.oauth import (OAuthAccessToken,OAuthApplication,@@ -4267,6 +4267,275 @@ class TestOAuthAPI(APIBaseTest):self.assertLess(abs((refreshed_access_token.expires - expected_expiry).total_seconds()), 60)+class TestOAuthFunnelInstrumentation(APIBaseTest):+ """The authorization funnel has to stay observable end to end: an authorization that+ completes but never becomes a token is the failure shape support cannot otherwise see,+ so every step reports and each event names the client the same way."""++ def setUp(self):+ super().setUp()+ self.code_verifier = "a" * 64+ self.application = OAuthApplication.objects.create(+ name="Funnel Test App",+ client_id="funnel_test_client_id",+ client_secret="funnel_test_client_secret",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ algorithm=OAuthApplication.RS256_ALGORITHM,+ organization=self.organization,+ user=self.user,+ )++ @property+ def _code_challenge(self) -> str:+ digest = hashlib.sha256(self.code_verifier.encode("utf-8")).digest()+ return base64.urlsafe_b64encode(digest).decode("utf-8").replace("=", "")++ def _post_body(self, **overrides) -> dict:+ return {+ "client_id": self.application.client_id,+ "redirect_uri": "https://example.com/callback",+ "response_type": "code",+ "code_challenge": self._code_challenge,+ "code_challenge_method": "S256",+ "allow": True,+ "access_level": OAuthApplicationAccessLevel.ALL.value,+ "scoped_organizations": [],+ "scoped_teams": [],+ "scope": "openid",+ **overrides,+ }++ def _authorize_url(self, **extra) -> str:+ params = {+ "client_id": self.application.client_id,+ "redirect_uri": "https://example.com/callback",+ "response_type": "code",+ "scope": "openid",+ "code_challenge": self._code_challenge,+ "code_challenge_method": "S256",+ **extra,+ }+ return f"/oauth/authorize/?{urlencode(params)}"++ @staticmethod+ def _events(mock_capture, event: str) -> list:+ return [c for c in mock_capture.call_args_list if c.kwargs.get("event") == event]++ def test_consent_grant_captures_authorization_granted(self):+ with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:+ response = self.client.post("/oauth/authorize/", self._post_body())++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertIn("code=", response.json()["redirect_to"])++ granted = self._events(mock_capture, "oauth_authorization_granted")+ self.assertEqual(len(granted), 1)+ props = granted[0].kwargs["properties"]+ self.assertEqual(props["grant_path"], "consent")+ self.assertEqual(props["client_name"], self.application.name)+ self.assertEqual(props["registration_type"], "manual")+ self.assertEqual(props["granted_scopes"], "openid")+ self.assertEqual(props["granted_scope_count"], 1)+ self.assertFalse(props["has_scoped_organizations"])+ self.assertEqual(self._events(mock_capture, "oauth_authorization_denied"), [])++ def test_declining_consent_captures_denied_not_granted(self):+ with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:+ response = self.client.post("/oauth/authorize/", self._post_body(allow=False))++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(self._events(mock_capture, "oauth_authorization_granted"), [])+ self.assertEqual(len(self._events(mock_capture, "oauth_authorization_denied")), 1)++ def test_consent_missing_required_scope_captures_rejection_with_reason(self):+ # `required_scopes` is derived from `scopes`, so seeding the ceiling is what makes+ # `insight:read` a locked row the grant below is missing.+ self.application.scopes = ["insight:read"]+ self.application.save()++ with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:+ response = self.client.post("/oauth/authorize/", self._post_body(scope="openid"))++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ rejected = self._events(mock_capture, "oauth_authorization_rejected")+ self.assertEqual(len(rejected), 1)+ props = rejected[0].kwargs["properties"]+ self.assertEqual(props["reason"], "missing_required_scopes")+ self.assertEqual(props["missing_scopes"], ["insight:read"])+ # `rejected_scopes` means "outside the ceiling" on the invalid_scope event; reusing+ # it here would make the two reasons indistinguishable in a breakdown.+ self.assertNotIn("rejected_scopes", props)+ self.assertEqual(self._events(mock_capture, "oauth_authorization_granted"), [])++ def test_token_exchange_captures_token_issued_for_the_authorizing_user(self):+ authorize_response = self.client.post("/oauth/authorize/", self._post_body())+ code = authorize_response.json()["redirect_to"].split("code=")[1].split("&")[0]++ with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:+ token_response = self.client.post(+ "/oauth/token/",+ {+ "grant_type": "authorization_code",+ "client_id": self.application.client_id,+ "client_secret": "funnel_test_client_secret",+ "redirect_uri": "https://example.com/callback",+ "code_verifier": self.code_verifier,+ "code": code,+ },+ )++ self.assertEqual(token_response.status_code, status.HTTP_200_OK)+ issued = self._events(mock_capture, "oauth_token_issued")+ self.assertEqual(len(issued), 1)+ self.assertEqual(issued[0].kwargs["distinct_id"], str(self.user.distinct_id))+ props = issued[0].kwargs["properties"]+ self.assertEqual(props["grant_type"], "authorization_code")+ self.assertEqual(props["client_name"], self.application.name)+ self.assertEqual(props["granted_scopes"], "openid")+ self.assertEqual(self._events(mock_capture, "oauth_token_rejected"), [])++ def test_reusing_a_code_captures_token_rejected_with_the_oauth_error(self):+ authorize_response = self.client.post("/oauth/authorize/", self._post_body())+ code = authorize_response.json()["redirect_to"].split("code=")[1].split("&")[0]+ token_body = {+ "grant_type": "authorization_code",+ "client_id": self.application.client_id,+ "client_secret": "funnel_test_client_secret",+ "redirect_uri": "https://example.com/callback",+ "code_verifier": self.code_verifier,+ "code": code,+ }+ self.client.post("/oauth/token/", token_body)++ with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:+ replay = self.client.post("/oauth/token/", token_body)++ self.assertEqual(replay.status_code, status.HTTP_400_BAD_REQUEST)+ rejected = self._events(mock_capture, "oauth_token_rejected")+ self.assertEqual(len(rejected), 1)+ props = rejected[0].kwargs["properties"]+ self.assertEqual(props["error"], "invalid_grant")+ self.assertEqual(props["grant_type"], "authorization_code")+ self.assertEqual(props["client_name"], self.application.name)+ self.assertIs(props["$process_person_profile"], False)+ self.assertEqual(self._events(mock_capture, "oauth_token_issued"), [])++ def test_consent_wildcard_grant_reports_the_narrowed_scopes(self):+ self.application.scopes = ["insight:read"]+ self.application.save()++ with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:+ response = self.client.post("/oauth/authorize/", self._post_body(scope="* insight:read"))++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ granted = self._events(mock_capture, "oauth_authorization_granted")+ self.assertEqual(len(granted), 1)+ props = granted[0].kwargs["properties"]+ self.assertEqual(props["granted_scopes"], "insight:read")+ self.assertEqual(props["granted_scope_count"], 1)++ def test_first_party_grant_reports_the_scoped_organizations_it_mints(self):+ self.application.is_first_party = True+ self.application.save()++ with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:+ response = self.client.get(self._authorize_url())++ self.assertEqual(response.status_code, status.HTTP_302_FOUND)+ granted = self._events(mock_capture, "oauth_authorization_granted")+ self.assertEqual(len(granted), 1)+ props = granted[0].kwargs["properties"]+ self.assertEqual(props["grant_path"], "first_party")+ self.assertTrue(props["has_scoped_organizations"])+ self.assertFalse(props["has_scoped_teams"])++ def test_malformed_json_token_request_captures_token_rejected(self):+ with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:+ response = self.client.post("/oauth/token/", data="{not json", content_type="application/json")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ rejected = self._events(mock_capture, "oauth_token_rejected")+ self.assertEqual(len(rejected), 1)+ props = rejected[0].kwargs["properties"]+ self.assertEqual(props["error"], "invalid_request")+ self.assertEqual(props["grant_type"], "unknown")++ def test_jwt_bearer_without_assertion_captures_token_rejected(self):+ with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:+ response = self.client.post(+ "/oauth/token/",+ {+ "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",+ "client_id": self.application.client_id,+ },+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ rejected = self._events(mock_capture, "oauth_token_rejected")+ self.assertEqual(len(rejected), 1)+ props = rejected[0].kwargs["properties"]+ self.assertEqual(props["error"], "invalid_request")+ self.assertEqual(props["grant_type"], "urn:ietf:params:oauth:grant-type:jwt-bearer")+ self.assertEqual(props["client_name"], self.application.name)++ def test_transient_db_failure_keeps_the_503_when_the_event_lookup_also_fails(self):+ with (+ patch(+ "oauth2_provider.views.base.TokenView.post",+ side_effect=OperationalError("query_wait_timeout"),+ ),+ patch(+ "posthog.api.oauth.views.get_application_by_client_id",+ side_effect=OperationalError("connection failed"),+ ),+ patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture,+ ):+ response = self.client.post(+ "/oauth/token/",+ {+ "grant_type": "authorization_code",+ "client_id": self.application.client_id,+ "code": "irrelevant",+ },+ )++ self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)+ rejected = self._events(mock_capture, "oauth_token_rejected")+ self.assertEqual(len(rejected), 1)+ props = rejected[0].kwargs["properties"]+ self.assertEqual(props["error"], "temporarily_unavailable")+ self.assertNotIn("client_name", props)++ def test_token_issued_without_a_resource_owner_stays_personless(self):+ access_token = OAuthAccessToken(application=self.application, user=None, scope="openid")++ with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:+ OAuthTokenView._capture_token_issued(access_token, "client_credentials", [], [])++ issued = self._events(mock_capture, "oauth_token_issued")+ self.assertEqual(len(issued), 1)+ self.assertEqual(issued[0].kwargs["distinct_id"], self.application.client_id)+ self.assertIs(issued[0].kwargs["properties"]["$process_person_profile"], False)+++class TestTokenErrorCode(SimpleTestCase):+ @parameterized.expand(+ [+ ("json_error", 400, b'{"error": "invalid_grant"}', "invalid_grant"),+ ("html_body", 400, b"<html>nope</html>", "http_400"),+ ("json_without_error_key", 400, b'{"detail": "nope"}', "http_400"),+ ("json_error_not_a_string", 400, b'{"error": {"code": 1}}', "http_400"),+ ("empty_body", 503, b"", "http_503"),+ ]+ )+ def test_reads_the_rfc_error_code_or_falls_back_to_the_status(+ self, _name: str, status_code: int, content: bytes, expected: str+ ):+ self.assertEqual(_token_error_code(HttpResponse(content, status=status_code)), expected)++class TestLocalhostLoopbackRedirectUri(APIBaseTest):"""Tests for RFC 8252 Section 7.3 — loopback redirect URIs must allow any port.diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 06d2da08ceea..496fd784b557 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -4,12 +4,12 @@ import hashlibimport calendarfrom datetime import datetime, timedeltafrom typing import TypedDict, cast-from urllib.parse import urlparse+from urllib.parse import parse_qs, urlparsefrom django.conf import settingsfrom django.core.exceptions import DisallowedRedirect-from django.db import OperationalError-from django.http import JsonResponse+from django.db import DatabaseError, OperationalError+from django.http import HttpResponse, JsonResponsefrom django.shortcuts import renderfrom django.utils import timezonefrom django.utils.decorators import method_decorator@@ -172,6 +172,38 @@ def _impersonator_id_for_request(request) -> int | None:return original_user.pk if original_user else None+def _registration_type(application: OAuthApplication) -> str:+ if application.is_cimd_client:+ return "cimd"+ return "dcr" if application.is_dcr_client else "manual"+++def _oauth_app_event_properties(application: OAuthApplication) -> dict:+ """Client identity shared by every `oauth_*` analytics event, so the funnel from+ `oauth_authorization_requested` through to `oauth_token_issued` breaks down by the+ same client dimensions at every step."""+ return {+ "client_name": application.name,+ "app_id": str(application.pk),+ "registration_type": _registration_type(application),+ "is_verified": application.is_verified,+ "is_first_party": application.is_first_party,+ **({"cimd_url": application.cimd_metadata_url} if application.is_cimd_client else {}),+ }+++def _token_error_code(response: HttpResponse) -> str:+ """RFC 6749 §5.2 error code from a token-endpoint failure, falling back to the status+ code when the body isn't the documented JSON shape."""+ try:+ payload = json.loads(response.content)+ except (json.JSONDecodeError, ValueError, UnicodeDecodeError):+ return f"http_{response.status_code}"+ if isinstance(payload, dict) and isinstance(payload.get("error"), str):+ return payload["error"]+ return f"http_{response.status_code}"++def _scoped_organization_ids(user: User,access_level: str | None,@@ -1000,9 +1032,48 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):@staticmethoddef _registration_type(application: OAuthApplication) -> str:- if application.is_cimd_client:- return "cimd"- return "dcr" if application.is_dcr_client else "manual"+ return _registration_type(application)++ @staticmethod+ def _capture_authorization_granted(+ request,+ application: OAuthApplication,+ requested_scopes: str,+ grant_path: str,+ redirect_uri: str,+ ) -> None:+ """Closes the funnel opened by `oauth_authorization_requested`. Every path that+ mints an authorization code reports here — `grant_path` separates the consent+ screen from the two that bypass it (first-party apps, auto-approval) — so a+ client that completes authorization and then fails downstream is distinguishable+ from one that never got past `/authorize`.++ Scopes and scoping dimensions are read back from the minted grant (via the code+ in `redirect_uri`) rather than from the request, so the event reports what was+ actually stored: `validate_scopes` clamps out-of-ceiling scopes (and `*`) to the+ app's ceiling, and the first-party path injects scoped organizations after the+ request is parsed, so the request-side values drift from the grant on both+ paths."""+ grant = None+ codes = parse_qs(urlparse(redirect_uri).query).get("code")+ if codes:+ grant = (+ OAuthGrant.objects.filter(code=codes[0]).only("scope", "scoped_organizations", "scoped_teams").first()+ )+ granted_scopes = (grant.scope if grant else requested_scopes) or ""+ posthoganalytics.capture(+ distinct_id=str(request.user.distinct_id),+ event="oauth_authorization_granted",+ properties={+ **_oauth_app_event_properties(application),+ "grant_path": grant_path,+ "granted_scopes": granted_scopes,+ "granted_scope_count": len(granted_scopes.split()),+ "has_scoped_organizations": bool(grant.scoped_organizations) if grant else False,+ "has_scoped_teams": bool(grant.scoped_teams) if grant else False,+ **(get_region_info() or {}),+ },+ )def _capture_scopes_clamped(self, request, application: OAuthApplication, submitted_scope: str) -> None:"""Report scopes `validate_scopes` dropped from an issued grant.@@ -1094,14 +1165,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):posthoganalytics.capture(distinct_id=str(request.user.distinct_id),event="oauth_authorization_requested",- properties={- "client_name": application.name,- "app_id": str(application.pk),- "registration_type": registration_type,- "is_verified": application.is_verified,- "is_first_party": application.is_first_party,- **({"cimd_url": application.cimd_metadata_url} if application.is_cimd_client else {}),- },+ properties=_oauth_app_event_properties(application),)# `validate_scopes` narrows a `*` request to the app's ceiling instead of rejecting it@@ -1144,6 +1208,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):request=request, scopes=scope_str, credentials=credentials, allow=True)self._capture_scopes_clamped(request, application, scope_str)+ self._capture_authorization_granted(request, application, scope_str, "first_party", uri)return self.redirect(uri, application)except OAuthToolkitError as error:return self.error_response(error, application, state=request.query_params.get("state"))@@ -1175,6 +1240,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):request=request, scopes=scope_str, credentials=credentials, allow=True)self._capture_scopes_clamped(request, application, scope_str)+ self._capture_authorization_granted(request, application, scope_str, "auto_approval", uri)return self.redirect(uri, application)except OAuthToolkitError as error:return self.error_response(error, application, state=request.query_params.get("state"))@@ -1254,6 +1320,17 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):client_id=serializer.validated_data["client_id"],missing=sorted(missing_required),)+ posthoganalytics.capture(+ distinct_id=str(request.user.distinct_id),+ event="oauth_authorization_rejected",+ properties={+ "reason": "missing_required_scopes",+ **_oauth_app_event_properties(application),+ "requested_scopes": scopes,+ "missing_scopes": sorted(missing_required),+ **(get_region_info() or {}),+ },+ )return Response({"error": "invalid_scope",@@ -1285,16 +1362,42 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):client_id=serializer.validated_data["client_id"],error=str(error),)+ # oauthlib signals a declined consent as an `access_denied` error rather than a+ # normal return, so a user saying no arrives here too — reporting that as a+ # rejection would bury real failures under ordinary declines.+ if serializer.validated_data["allow"]:+ posthoganalytics.capture(+ distinct_id=str(request.user.distinct_id),+ event="oauth_authorization_rejected",+ properties={+ "reason": "toolkit_error",+ **_oauth_app_event_properties(application),+ "requested_scopes": scopes,+ "error": getattr(error.oauthlib_error, "error", None) or "unknown",+ **(get_region_info() or {}),+ },+ )+ else:+ posthoganalytics.capture(+ distinct_id=str(request.user.distinct_id),+ event="oauth_authorization_denied",+ properties={+ **_oauth_app_event_properties(application),+ "requested_scopes": scopes,+ **(get_region_info() or {}),+ },+ )return self.error_response(error, application, no_redirect=True, state=serializer.validated_data.get("state"))logger.debug("Success url for the request: %s", uri)+ redirect = self.redirect(uri, application)+if serializer.validated_data["allow"]:self._capture_scopes_clamped(request, application, scopes)-- redirect = self.redirect(uri, application)+ self._capture_authorization_granted(request, application, scopes, "consent", uri)return Response({@@ -1321,6 +1424,29 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):"""redirect, error_response = super().error_response(error, **kwargs)+ # Surface scope-ceiling rejections so on-call can alert on /authorize failing with invalid_scope.+ if getattr(error_response["error"], "error", None) == "invalid_scope" and application is not None:+ distinct_id = getattr(getattr(self.request, "user", None), "distinct_id", None) or application.client_id+ # invalid_scope only reaches error_response from the GET authorize request, where+ # oauthlib raises it pre-consent (the consent POST returns it as a redirect, not a+ # raise), so the requested scope is always in the query string here.+ requested_scope = self.request.query_params.get("scope") or ""+ rejected_scopes = scopes_outside_ceiling(+ requested_scope.split(),+ application.ceiling_scopes,+ allow_wildcard_under_empty_ceiling=True,+ )+ posthoganalytics.capture(+ distinct_id=str(distinct_id),+ event="oauth_authorization_rejected",+ properties={+ "reason": "invalid_scope",+ **_oauth_app_event_properties(application),+ "requested_scopes": requested_scope,+ "rejected_scopes": rejected_scopes,+ },+ )+if redirect:if no_redirect:return Response(@@ -1363,6 +1489,67 @@ class OAuthTokenView(TokenView):RFC 6749 requires x-www-form-urlencoded, but this endpoint also accepts application/json for convenience."""+ @staticmethod+ def _capture_token_issued(+ access_token: OAuthAccessToken,+ grant_type: str,+ scoped_organizations: list,+ scoped_teams: list,+ ) -> None:+ """The last step of the authorization funnel. `oauth_authorization_granted` without+ a matching `oauth_token_issued` means the client never redeemed its code."""+ properties: dict = {+ "grant_type": grant_type,+ "granted_scopes": access_token.scope or "",+ "granted_scope_count": len((access_token.scope or "").split()),+ "has_scoped_organizations": bool(scoped_organizations),+ "has_scoped_teams": bool(scoped_teams),+ **(get_region_info() or {}),+ }+ if access_token.application:+ properties.update(_oauth_app_event_properties(access_token.application))+ # `user` is nullable on an access token (client-credentials grants have no+ # resource owner), so fall back to the client id and skip person processing.+ if access_token.user is None:+ properties["$process_person_profile"] = False+ distinct_id = access_token.application.client_id if access_token.application else "unknown"+ else:+ distinct_id = str(access_token.user.distinct_id)+ posthoganalytics.capture(+ distinct_id=distinct_id,+ event="oauth_token_issued",+ properties=properties,+ )++ @staticmethod+ def _capture_token_rejected(grant_type: str, client_id: str, error: str) -> None:+ """The token exchange has no authenticated user, so this keys on the client id —+ enough to tell "the client never came back for a token" apart from "it came back+ and we refused", which the authorization events alone cannot distinguish.++ The application lookup is best-effort enrichment: the rejection being reported may+ itself be a database failure, so a lookup error must drop the client identity from+ the event rather than replace the mapped error response with a 500."""+ properties: dict = {+ "grant_type": grant_type,+ "error": error,+ "client_id": client_id,+ # Personless: the client id is not a user, and one person per client would be noise.+ "$process_person_profile": False,+ **(get_region_info() or {}),+ }+ try:+ application = get_application_by_client_id(client_id)+ except (OAuthApplication.DoesNotExist, DatabaseError):+ pass+ else:+ properties.update(_oauth_app_event_properties(application))+ posthoganalytics.capture(+ distinct_id=client_id or "unknown",+ event="oauth_token_rejected",+ properties=properties,+ )+def _handle_jwt_bearer_grant(self, request) -> JsonResponse:"""ID-JAG (XAA) JWT Bearer grant (RFC 7523). The XAA spec puts theID-JAG → access-token exchange at the Authorization Server's@@ -1371,6 +1558,9 @@ class OAuthTokenView(TokenView):`posthog.api.id_jag.issue_access_token`."""assertion = request.POST.get("assertion")if not assertion or not isinstance(assertion, str):+ self._capture_token_rejected(+ id_jag.JWT_BEARER_GRANT_TYPE, request.POST.get("client_id") or "", "invalid_request"+ )return JsonResponse({"error": "invalid_request", "error_description": "assertion is required"},status=400,@@ -1385,11 +1575,28 @@ class OAuthTokenView(TokenView):)except id_jag.IdJagError as e:logger.info("id_jag_token_rejected", error=e.error_code, description=e.description)+ self._capture_token_rejected(id_jag.JWT_BEARER_GRANT_TYPE, request_client_id or "", e.error_code)return JsonResponse({"error": e.error_code, "error_description": e.description},status=e.http_status,)+ # Reported alongside the rejection above so this grant type isn't all-failures in+ # the funnel. There is no resource owner to attribute it to, so it stays personless+ # and keyed on the client.+ posthoganalytics.capture(+ distinct_id=request_client_id or "unknown",+ event="oauth_token_issued",+ properties={+ "grant_type": id_jag.JWT_BEARER_GRANT_TYPE,+ "client_id": request_client_id or "",+ "granted_scopes": " ".join(granted),+ "granted_scope_count": len(granted),+ "$process_person_profile": False,+ **(get_region_info() or {}),+ },+ )+return JsonResponse({"access_token": token,@@ -1407,6 +1614,7 @@ class OAuthTokenView(TokenView):for key, value in json_data.items():request.POST[key] = valueexcept (json.JSONDecodeError, ValueError):+ self._capture_token_rejected("unknown", "", "invalid_request")return JsonResponse({"error": "invalid_request", "error_description": "Invalid JSON payload"},status=400,@@ -1439,6 +1647,7 @@ class OAuthTokenView(TokenView):client_id_prefix=client_id_prefix,redirect_uri=redirect_uri,)+ self._capture_token_rejected(grant_type, client_id, "invalid_grant")return JsonResponse({"error": "invalid_grant",@@ -1459,6 +1668,7 @@ class OAuthTokenView(TokenView):redirect_uri=redirect_uri,error=str(e),)+ self._capture_token_rejected(grant_type, client_id, "temporarily_unavailable")return _temporarily_unavailable_response()except RedisError as e:# Client authentication reads Redis on the private_key_jwt path (JWKS cache, jti@@ -1486,7 +1696,9 @@ class OAuthTokenView(TokenView):access_token_value = response_data.get("access_token")if access_token_value:- access_token = OAuthAccessToken.objects.get(token=access_token_value)+ access_token = OAuthAccessToken.objects.select_related("application", "user").get(+ token=access_token_value+ )scoped_teams = list(access_token.scoped_teams or [])scoped_organizations = list(access_token.scoped_organizations or [])@@ -1509,6 +1721,8 @@ class OAuthTokenView(TokenView):response_data["scoped_teams"] = scoped_teamsresponse_data["scoped_organizations"] = scoped_organizations+ self._capture_token_issued(access_token, grant_type, scoped_organizations, scoped_teams)+if region_info := get_region_info():response_data.update(region_info)return JsonResponse(response_data)@@ -1528,6 +1742,9 @@ class OAuthTokenView(TokenView):else:response["Content-Type"] = "application/json"+ if response.status_code != 200:+ self._capture_token_rejected(grant_type, client_id, _token_error_code(response))+return responsediff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex c113ea750576..fd6bbb7db5b9 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -337,6 +337,11 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {"label": "MCP custom event","description": "A custom MCP analytics event emitted by a server through the SDK's custom-event API. Properties depend on what the caller passed.",},+ "$mcp_auth_failed": {+ "label": "MCP auth failed",+ "description": "Fires when an MCP request is refused before a session is established, because the credential was rejected or lacked a required scope. Emitted by PostHog's own MCP server rather than the SDK, so it is absent for customer-instrumented servers. Carries `$mcp_auth_failure_reason`, `$mcp_auth_method`, and the client identity, so connectors stuck re-authorizing are visible instead of appearing as an absence of traffic. Not a tool-call failure: it never sets `$mcp_is_error`.",+ "primary_property": "$mcp_auth_failure_reason",+ },"$mcp_missing_capability": {"label": "MCP missing capability","description": "Fires when an agent reports functionality it couldn't find via the `get_more_tools` virtual tool (when `reportMissing` is enabled). Carries the agent's reasoning in `$mcp_intent` — a capability gap, not a tool invocation.",@@ -2750,6 +2755,27 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {"description": "Field path the PostHog API's validation error pointed at, with array indexes normalized to N so one failure mode groups to one value. Only set for validation failures.","examples": ["actions__N__inputs__email", "query"],},+ "$mcp_auth_method": {+ "label": "MCP auth method",+ "description": "Which credential the MCP request authenticated with, derived from the bearer token's prefix: oauth, personal_api_key, id_jag, none, or unknown. Stamped on every event by PostHog's own MCP server. Use it to tell an OAuth connector apart from an API-key connection — for example when a user works around a broken OAuth flow by switching to a personal API key.",+ "examples": ["oauth", "personal_api_key"],+ },+ "$mcp_auth_failure_reason": {+ "label": "MCP auth failure reason",+ "description": "Why an MCP request was refused, on $mcp_auth_failed: insufficient_scope (the credential is valid but the API denied the call), inactive_oauth_token, invalid_api_key, or unknown. insufficient_scope also carries $mcp_missing_scope when the API named a scope.",+ "examples": ["insufficient_scope", "invalid_api_key", "inactive_oauth_token"],+ },+ "$mcp_auth_status": {+ "label": "MCP auth status",+ "description": "HTTP status returned to the client when an MCP request was refused (401 for a rejected credential, 403 for a denied scope). Distinct from $mcp_error_status, which is the upstream status of a failed tool call. Only set on $mcp_auth_failed.",+ "type": "Numeric",+ "examples": [401, 403],+ },+ "$mcp_missing_scope": {+ "label": "MCP missing scope",+ "description": "The API scope the PostHog API said was missing when it refused an MCP request. Only set on $mcp_auth_failed with reason insufficient_scope, and only when the API named a specific scope.",+ "examples": ["insight:read", "query:read"],+ },"$mcp_error_message": {"label": "MCP error message","description": "Short, sanitized summary of why a failed MCP tool call errored: a validation code and field, or an HTTP status and path. Never includes caller-supplied input, query text, or upstream response bodies. Truncated to 2048 characters. Only set when $mcp_is_error is true.",diff --git a/products/mcp_analytics/skills/debugging-mcp-analytics/references/event-vocabulary.md b/products/mcp_analytics/skills/debugging-mcp-analytics/references/event-vocabulary.mdindex 7cf206a5fffd..82dfdb56ea0c 100644--- a/products/mcp_analytics/skills/debugging-mcp-analytics/references/event-vocabulary.md+++ b/products/mcp_analytics/skills/debugging-mcp-analytics/references/event-vocabulary.md@@ -13,16 +13,17 @@ dogfood traffic, and exec-mode ones only appear when a server runs a single `exeAll `$`-prefixed — a non-`$` name would be treated as a customer event.-| Event | Notes |-| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `$mcp_tool_call` | The primary event. Almost every metric aggregates over it. |-| `$mcp_tools_list` | A `tools/list` request. Carries the advertised catalog — the basis for zombie-tool queries. |-| `$mcp_initialize` | The `initialize` handshake. **Not emitted by clients on the MCP 2026-07-28 stateless revision**, which removes the handshake — do not use it as a universal session anchor. |-| `$mcp_missing_capability` | The agent wanted something the server does not offer. The clearest roadmap signal in the dataset. |-| `$mcp_resource_read` / `$mcp_resources_list` | Resource access. Not emitted by `instrument()` in either SDK. |-| `$mcp_prompt_get` / `$mcp_prompts_list` | Prompt access. Same caveat as resources. |-| `$identify` | Person identity. Since TS 0.9.1 this fires at most once per session, not before every tool call. |-| `$exception` | Error sibling event. Can be disabled, and is not emitted when no error value is passed — see the failures rule below. |+| Event | Notes |+| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `$mcp_tool_call` | The primary event. Almost every metric aggregates over it. |+| `$mcp_tools_list` | A `tools/list` request. Carries the advertised catalog — the basis for zombie-tool queries. |+| `$mcp_initialize` | The `initialize` handshake. **Not emitted by clients on the MCP 2026-07-28 stateless revision**, which removes the handshake — do not use it as a universal session anchor. |+| `$mcp_missing_capability` | The agent wanted something the server does not offer. The clearest roadmap signal in the dataset. |+| `$mcp_auth_failed` | A request refused before a session existed — a rejected credential, or a scope the API denied. **PostHog's own server only, not the SDK.** The one MCP event with no organization/project, because none was resolved. |+| `$mcp_resource_read` / `$mcp_resources_list` | Resource access. Not emitted by `instrument()` in either SDK. |+| `$mcp_prompt_get` / `$mcp_prompts_list` | Prompt access. Same caveat as resources. |+| `$identify` | Person identity. Since TS 0.9.1 this fires at most once per session, not before every tool call. |+| `$exception` | Error sibling event. Can be disabled, and is not emitted when no error value is passed — see the failures rule below. |`$mcp_custom` is registered in the enum, but `analytics.capture()` sends the verbatim eventname it is given rather than `$mcp_custom`.@@ -60,10 +61,25 @@ Added by PostHog's own server (`services/mcp/src/hono/analytics.ts::buildBaseProserver, so never rely on them in customer-facing queries or docs without checking.`$mcp_session_id` (transport-level), `$mcp_region`, `$mcp_mode`, `$mcp_consumer`,-`$mcp_version`, `$mcp_client_user_agent`, `$mcp_transport`, `$mcp_organization_id`,-`$mcp_project_id`, `$mcp_project_uuid`, `$mcp_project_name`, `$ai_product` (`mcp`), and the-non-`$`-prefixed `mcp_runtime` (`hono`) and `mcp_vendor_client` — the last of which is the-**top-priority harness signal**, so it appears inside harness SQL.+`$mcp_version`, `$mcp_client_user_agent`, `$mcp_transport`, `$mcp_auth_method`,+`$mcp_organization_id`, `$mcp_project_id`, `$mcp_project_uuid`, `$mcp_project_name`,+`$ai_product` (`mcp`), and the non-`$`-prefixed `mcp_runtime` (`hono`) and+`mcp_vendor_client` — the last of which is the **top-priority harness signal**, so it+appears inside harness SQL.++`$mcp_auth_method` (`oauth`, `personal_api_key`, `id_jag`, `none`, `unknown`) comes from the+bearer token's prefix. It is the only way to tell an OAuth connector apart from an API-key+connection, which matters when reading a recovery: a user who works around a broken OAuth+flow by pasting a personal API key produces traffic that otherwise looks identical to the+connector having been fixed.++On `$mcp_auth_failed`: `$mcp_auth_failure_reason` (`insufficient_scope`,+`inactive_oauth_token`, `invalid_api_key`, `unknown`), `$mcp_missing_scope` when the API named+one, and `$mcp_auth_status` (401 or 403). It deliberately does **not** set `$mcp_is_error` or+`$mcp_error_status` — those mean "a tool call failed", and reusing them would fold auth+refusals into tool error rates, which is also why the status has its own field. Its+`distinct_id` is the token hash, not a user id, so it joins to other MCP events by client and+time, never by person.Per-event additions: `$mcp_error_status` (upstream HTTP status), `$mcp_error_code` (machine-readable leaf failure code: the API's validation error code or the exec rejection reason), and `$mcp_error_field` (the validation error's field path, array indexes normalized to `N`, e.g. `actions__N__inputs__email`) — all stamped by `services/mcp/src/hono/tool-executor.ts` — **server-side, despite sitting next to the SDK's typed error properties in queries**; and `tool_count`, `read_only`, `via_sse_redirect` on `$mcp_initialize`. Failed calls may also carry`$mcp_validation_fields` and `$mcp_validation_input_keys` (which fields failed validation, anddiff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md b/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.mdindex ad6556aab8d9..1c628268e507 100644--- a/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md@@ -68,7 +68,13 @@ And two tools cover what SQL can't express at all: `posthog:mcp-analytics-intent| `$mcp_resource_name` | SDK | Name of the MCP resource/prompt/tool the event refers to (resource-read and prompt-get events). || `$mcp_source` | SDK | Constant identifier for the analytics SDK that emitted the event (e.g. `posthog_mcp_analytics`). Lets you separate SDK-emitted events from other/legacy MCP paths. |-**Server-stamped extras (PostHog's own server only, not the SDK):** `$mcp_session_id` (transport-level session handle — see "Three identifiers" below), `$mcp_region` (cloud region that handled the request, e.g. `us`/`eu`), `$mcp_mode` (`cli` for single-exec, `tools` for one-tool-per-name), `$mcp_consumer` (upstream surface, e.g. `posthog-code`/`slack`), and the non-`$`-prefixed `mcp_vendor_client` (vendor/client identity from the `x-anthropic-client` header, e.g. `ClaudeCode`/`ClaudeAI` — used to resolve the harness in the bucketing SQL below) and `mcp_runtime` (server runtime, e.g. `hono`).+**Server-stamped extras (PostHog's own server only, not the SDK):** `$mcp_session_id` (transport-level session handle — see "Three identifiers" below), `$mcp_region` (cloud region that handled the request, e.g. `us`/`eu`), `$mcp_mode` (`cli` for single-exec, `tools` for one-tool-per-name), `$mcp_consumer` (upstream surface, e.g. `posthog-code`/`slack`), and the non-`$`-prefixed `mcp_vendor_client` (vendor/client identity from the `x-anthropic-client` header, e.g. `ClaudeCode`/`ClaudeAI` — used to resolve the harness in the bucketing SQL below) and `mcp_runtime` (server runtime, e.g. `hono`), plus `$mcp_auth_method` (which credential the request authenticated with, from the bearer token's prefix: `oauth`, `personal_api_key`, `id_jag`, `none`, `unknown`).++**Refused requests are a separate event.** A request the PostHog API rejects dies before any session, organization, or project is resolved, so it emits none of the events above — it emits `$mcp_auth_failed` instead, with `$mcp_auth_failure_reason` (`insufficient_scope`, `inactive_oauth_token`, `invalid_api_key`, `unknown`), `$mcp_missing_scope` when the API named a scope, and `$mcp_auth_status` (401/403). Only PostHog's own server emits it, so it is absent for customer-instrumented servers.++It does not set `$mcp_is_error`/`$mcp_error_status`, which mean "a tool call failed against the PostHog API" — so an auth refusal never inflates tool error rates, and the status it did return lives in `$mcp_auth_status` instead.++Two consequences for queries: it has no `$mcp_organization_id`/`$mcp_project_id`, and its `distinct_id` is a hash of the bearer token rather than a user id, so count it with `uniq(distinct_id)` for affected credentials and join to other MCP events by client and time, never by person. A connector looping on authorization shows up here; before this event existed the same outage looked like an absence of traffic.**Three identifiers, not one.** `$session_id` is the materialised column — `GROUP BY`/join on this one. `$mcp_session_id` is the transport-level handle the MCP SDK observed (MCP `extra.sessionId` or a framework session cookie); it rotates on process restart, reconnect, or framework boundary. `$mcp_conversation_id` is agent-echoed and stable across reconnects — reach for it when a "session" needs to survive a client reconnecting mid-task. In practice `$session_id` and `$mcp_session_id` carry the same value; `$mcp_conversation_id` is the more durable one when they diverge.diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.tsindex dddcdb23b9ae..55e85370ceca 100644--- a/services/mcp/src/hono/analytics.ts+++ b/services/mcp/src/hono/analytics.ts@@ -2,6 +2,8 @@ import { randomUUID } from 'node:crypto'import type { MCPAnalyticsIntentSource } from '@posthog/mcp-analytics'+import type { McpAuthFailure } from '@/lib/auth-errors'+import { classifyAuthMethod } from '@/lib/auth-method'import { MCP_ANALYTICS_SOURCE, MCP_SERVER_NAME, MCP_SERVER_VERSION, PRODUCT_DATA_CATALOG_FLAG } from '@/lib/constants'import { getPostHogClient } from '@/lib/posthog'import {@@ -10,6 +12,7 @@ import {MCP_ANALYTICS_VERSION,type MCPAnalyticsContext,} from '@/lib/posthog/analytics'+import type { RequestProperties } from '@/lib/request-properties'import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'import { gatewayServerSlug, isGatewayToolName, THIRD_PARTY_TOOL_CATEGORY } from '@/lib/gateway-tools'import { MAX_CAPTURED_DESCRIPTION_LENGTH, getToolCategory, getToolDescription } from '@/tools/toolDefinitions'@@ -50,6 +53,7 @@ function buildBaseProperties($mcp_consumer: clientIdentity.mcpConsumer,$mcp_mode: requestContext.mode,$mcp_region: requestContext.region,+ $mcp_auth_method: requestContext.authMethod,...(analyticsContext? {$mcp_organization_id: analyticsContext.organizationId,@@ -357,6 +361,54 @@ export async function trackToolSpan(toolName: string, state: ResolvedState, meta}}+/**+ * Emits `$mcp_auth_failed` for a request the PostHog API refused. These requests die+ * before `RequestStateResolver.resolve` returns, so they never reach+ * `trackInitEvent`/`trackToolCall` and are otherwise invisible in analytics — a+ * connector stuck in an authorize loop looks like a gap in the data rather than a+ * failure. Keyed on `userHash` (a hash of the bearer token, never the token itself)+ * so affected credentials can be counted without identifying anyone.+ *+ * Only PostHog's own server emits this; no SDK does. It reuses the canonical `$mcp_*`+ * client-identity fields so one query can group it and real MCP traffic by the same+ * dimensions.+ */+export function trackAuthFailure(props: RequestProperties, failure: McpAuthFailure): void {+ try {+ getPostHogClient().capture({+ distinctId: props.userHash,+ event: '$mcp_auth_failed',+ properties: {+ $ai_product: 'mcp',+ $mcp_source: MCP_ANALYTICS_SOURCE,+ $mcp_server_name: MCP_SERVER_NAME,+ $mcp_server_version: MCP_SERVER_VERSION,+ $mcp_version: MCP_ANALYTICS_VERSION,+ $mcp_client_name: props.mcpClientName,+ $mcp_client_version: props.mcpClientVersion,+ $mcp_client_user_agent: props.clientUserAgent,+ $mcp_protocol_version: props.mcpProtocolVersion,+ $mcp_transport: props.transport,+ $mcp_session_id: props.mcpSessionId,+ $mcp_conversation_id: props.mcpConversationId,+ $mcp_consumer: props.mcpConsumer,+ $mcp_mode: props.mode,+ $mcp_region: props.region,+ $mcp_auth_method: classifyAuthMethod(props.apiToken),+ mcp_runtime: 'hono',+ mcp_vendor_client: props.mcpVendorClient,+ $mcp_auth_failure_reason: failure.reason,+ ...(failure.status ? { $mcp_auth_status: failure.status } : {}),+ ...(failure.missingScope ? { $mcp_missing_scope: failure.missingScope } : {}),+ has_organization_id: !!props.organizationId,+ has_project_id: !!props.projectId,+ },+ })+ } catch {+ // never break the request for analytics+ }+}+export async function trackToolsList(toolNames: string[], state: ResolvedState): Promise<void> {try {const analyticsContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)diff --git a/services/mcp/src/hono/mcp-context.ts b/services/mcp/src/hono/mcp-context.tsindex 1250198e076a..9fddb51ac776 100644--- a/services/mcp/src/hono/mcp-context.ts+++ b/services/mcp/src/hono/mcp-context.ts@@ -1,3 +1,4 @@+import { classifyAuthMethod, type McpAuthMethod } from '@/lib/auth-method'import type { RequestProperties } from '@/lib/request-properties'import type { McpMode } from '@/lib/utils'@@ -24,6 +25,7 @@ export interface MCPRequestContext| 'region'> {mode?: McpMode | undefined+ authMethod: McpAuthMethod}// Identical shape to MCPClientContext but tracked separately to mark values@@ -49,6 +51,7 @@ export function buildMCPRequestContext(props: RequestProperties): MCPRequestContmode: props.mode,region: props.region,mcpVendorClient: props.mcpVendorClient,+ authMethod: classifyAuthMethod(props.apiToken),}}diff --git a/services/mcp/src/hono/request-utils.ts b/services/mcp/src/hono/request-utils.tsindex 6914d01cd174..a172bd53dcb4 100644--- a/services/mcp/src/hono/request-utils.ts+++ b/services/mcp/src/hono/request-utils.ts@@ -1,6 +1,6 @@import { z } from 'zod'-import { mapErrorToAuthResponse, validateBearerToken } from '@/lib/auth-errors'+import { classifyAuthFailure, mapErrorToAuthResponse, validateBearerToken } from '@/lib/auth-errors'import { getPostHogClient } from '@/lib/posthog'import {type ClientInfo,@@ -12,6 +12,7 @@ import { getRegionFromRequest } from '@/lib/routing'import { parseRequestProtocolMeta } from '@/lib/stateless-protocol'import { extractBearerToken, sanitizeHeaderValue } from '@/lib/utils'+import { trackAuthFailure } from './analytics'import { authFailuresTotal } from './metrics'import type { HonoCtx } from './types'@@ -116,6 +117,7 @@ export function handleCatchError(error: unknown, props: RequestProperties): Respif (authResponse) {const reason = authResponse.status === 403 ? 'insufficient_scope' : 'invalid_token'authFailuresTotal.inc({ reason })+ trackAuthFailure(props, classifyAuthFailure(error))return authResponse}try {diff --git a/services/mcp/src/lib/auth-errors.ts b/services/mcp/src/lib/auth-errors.tsindex 55313f11424f..cd806f22a39a 100644--- a/services/mcp/src/lib/auth-errors.ts+++ b/services/mcp/src/lib/auth-errors.ts@@ -38,6 +38,38 @@ export function mapErrorToAuthResponse(error: unknown): Response | null {return null}+export type McpAuthFailureReason =+ | 'insufficient_scope'+ | 'inactive_oauth_token'+ | 'invalid_api_key'+ | 'missing_token'+ | 'invalid_token_format'+ | 'unknown'++export interface McpAuthFailure {+ reason: McpAuthFailureReason+ status: number | undefined+ missingScope: string | undefined+}++export function classifyAuthFailure(error: unknown): McpAuthFailure {+ const status = mapErrorToAuthResponse(error)?.status++ const permissionError = findPostHogPermissionError(error)+ if (permissionError) {+ return { reason: 'insufficient_scope', status, missingScope: permissionError.missingScope }+ }++ const message = error instanceof Error ? error.message : ''+ if (message.includes(ErrorCode.INACTIVE_OAUTH_TOKEN)) {+ return { reason: 'inactive_oauth_token', status, missingScope: undefined }+ }+ if (message.includes(ErrorCode.INVALID_API_KEY)) {+ return { reason: 'invalid_api_key', status, missingScope: undefined }+ }+ return { reason: 'unknown', status, missingScope: undefined }+}+// Map a response body string to an auth response if it embeds a known error code.// Used to translate downstream API errors that surface as 200/4xx with a known// marker in the body (e.g. SDK transport wrappers).diff --git a/services/mcp/src/lib/auth-method.ts b/services/mcp/src/lib/auth-method.tsnew file mode 100644index 000000000000..c1f50d860d31--- /dev/null+++ b/services/mcp/src/lib/auth-method.ts@@ -0,0 +1,19 @@+import { isIdJagAccessToken } from './id-jag'++export type McpAuthMethod = 'oauth' | 'personal_api_key' | 'id_jag' | 'none' | 'unknown'++export function classifyAuthMethod(token: string | undefined): McpAuthMethod {+ if (!token) {+ return 'none'+ }+ if (token.startsWith('pha_')) {+ return 'oauth'+ }+ if (token.startsWith('phx_')) {+ return 'personal_api_key'+ }+ if (isIdJagAccessToken(token)) {+ return 'id_jag'+ }+ return 'unknown'+}diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.tsindex 9c46b9ed19ae..9df25dbdd9f0 100644--- a/services/mcp/tests/hono/analytics.test.ts+++ b/services/mcp/tests/hono/analytics.test.ts@@ -34,6 +34,7 @@ function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {apiKeyScopes: [],clientProfile: {} as any,requestContext: {+ authMethod: 'personal_api_key',sessionId: 'sess-1',organizationId: 'org-request',projectId: 'project-request',@@ -100,6 +101,7 @@ describe('Hono MCP analytics contexts', () => {$mcp_consumer: 'request-consumer',$mcp_mode: 'cli',$mcp_region: 'us',+ $mcp_auth_method: 'personal_api_key',mcp_vendor_client: 'ClaudeAI',mcp_session_client_name: 'claude-code',mcp_session_client_version: '1.0',diff --git a/services/mcp/tests/hono/auth-instrumentation.test.ts b/services/mcp/tests/hono/auth-instrumentation.test.tsnew file mode 100644index 000000000000..6f4c67ab1d33--- /dev/null+++ b/services/mcp/tests/hono/auth-instrumentation.test.ts@@ -0,0 +1,133 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++const { mockCapture, mockCaptureException } = vi.hoisted(() => ({+ mockCapture: vi.fn(),+ mockCaptureException: vi.fn(),+}))++vi.mock('@/lib/posthog', () => ({+ getPostHogClient: vi.fn(() => ({+ capture: mockCapture,+ captureException: mockCaptureException,+ })),+}))++import { handleCatchError } from '@/hono/request-utils'+import { classifyAuthFailure } from '@/lib/auth-errors'+import { classifyAuthMethod } from '@/lib/auth-method'+import { ErrorCode, PostHogPermissionError, wrapError } from '@/lib/errors'+import type { RequestProperties } from '@/lib/request-properties'++function makeProps(overrides: Partial<RequestProperties> = {}): RequestProperties {+ return {+ apiToken: 'pha_oauth-token',+ userHash: 'token-hash',+ mcpClientName: 'claude-ai',+ mcpClientVersion: '0.1.0',+ clientUserAgent: 'Claude-User',+ mcpVendorClient: 'ClaudeAI',+ transport: 'streamable-http',+ region: 'us',+ ...overrides,+ }+}++function permissionError(missingScope?: string): PostHogPermissionError {+ return new PostHogPermissionError({+ detail: 'permission denied',+ missingScope,+ url: '/api/users/@me/',+ method: 'GET',+ })+}++describe('MCP auth instrumentation', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it.each([+ ['pha_abc123', 'oauth'],+ ['phx_abc123', 'personal_api_key'],+ ['', 'none'],+ [undefined, 'none'],+ ['not-a-posthog-token', 'unknown'],+ ])('classifies %s as %s', (token, expected) => {+ expect(classifyAuthMethod(token as string | undefined)).toBe(expected)+ })++ it('classifies an ID-JAG JWT ahead of the unknown fallback', () => {+ const header = Buffer.from(JSON.stringify({ typ: 'at+jwt', alg: 'RS256' })).toString('base64url')+ expect(classifyAuthMethod(`${header}.payload.signature`)).toBe('id_jag')+ })++ it.each([+ [() => permissionError('insight:read'), 'insufficient_scope', 403],+ [() => new Error(`boom ${ErrorCode.INACTIVE_OAUTH_TOKEN}`), 'inactive_oauth_token', 401],+ [() => new Error(`boom ${ErrorCode.INVALID_API_KEY}`), 'invalid_api_key', 401],+ [() => new Error('something else entirely'), 'unknown', undefined],+ ])('labels the failure as %#: %s with status %s', (build, reason, status) => {+ const failure = classifyAuthFailure(build())+ expect(failure.reason).toBe(reason)+ expect(failure.status).toBe(status)+ })++ it('finds the reason and missing scope through a wrapping error', () => {+ const failure = classifyAuthFailure(wrapError('Failed to get user', permissionError('query:read')))++ expect(failure.reason).toBe('insufficient_scope')+ expect(failure.missingScope).toBe('query:read')+ })++ it('captures $mcp_auth_failed for a rejected credential, keyed on the token hash', () => {+ const response = handleCatchError(new Error(`boom ${ErrorCode.INVALID_API_KEY}`), makeProps())++ expect(response.status).toBe(401)+ expect(mockCapture).toHaveBeenCalledTimes(1)+ const call = mockCapture.mock.calls[0]![0]+ expect(call.event).toBe('$mcp_auth_failed')+ expect(call.distinctId).toBe('token-hash')+ expect(call.properties).toMatchObject({+ $mcp_auth_failure_reason: 'invalid_api_key',+ $mcp_auth_status: 401,+ $mcp_auth_method: 'oauth',+ $mcp_client_name: 'claude-ai',+ mcp_vendor_client: 'ClaudeAI',+ })+ expect(call.properties.$mcp_missing_scope).toBeUndefined()+ })++ it('records the missing scope on a permission denial', () => {+ handleCatchError(permissionError('insight:read'), makeProps())++ expect(mockCapture.mock.calls[0]![0].properties).toMatchObject({+ $mcp_auth_failure_reason: 'insufficient_scope',+ $mcp_missing_scope: 'insight:read',+ $mcp_auth_status: 403,+ })+ })++ it('leaves the tool-call failure vocabulary alone', () => {+ // `$mcp_is_error` and `$mcp_error_status` mean "a tool call failed against the+ // PostHog API"; setting them here would fold auth refusals into tool error rates.+ handleCatchError(permissionError('insight:read'), makeProps())++ const properties = mockCapture.mock.calls[0]![0].properties+ expect(properties.$mcp_is_error).toBeUndefined()+ expect(properties.$mcp_error_status).toBeUndefined()+ })++ it('never sends the bearer token itself', () => {+ handleCatchError(permissionError(), makeProps({ apiToken: 'pha_super-secret' }))++ expect(JSON.stringify(mockCapture.mock.calls[0]![0])).not.toContain('pha_super-secret')+ })++ it('leaves non-auth failures on the exception path', () => {+ const response = handleCatchError(new Error('unrelated explosion'), makeProps())++ expect(response.status).toBe(500)+ expect(mockCapture).not.toHaveBeenCalled()+ expect(mockCaptureException).toHaveBeenCalledTimes(1)+ })+})diff --git a/services/mcp/tests/hono/request-context.test.ts b/services/mcp/tests/hono/request-context.test.tsindex f65737b7a67a..849a0a4dd1d3 100644--- a/services/mcp/tests/hono/request-context.test.ts+++ b/services/mcp/tests/hono/request-context.test.ts@@ -252,6 +252,7 @@ describe('RequestContext', () => {)ctx.setMcpContexts({+ authMethod: 'personal_api_key',sessionId: 'sess-1',mcpClientName: 'Claude Desktop',mcpClientVersion: '2.0',diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.tsindex 5998b5de2c04..22b0ef42c6a6 100644--- a/services/mcp/tests/hono/tool-executor-intent.test.ts+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts@@ -57,6 +57,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>isClaudeChatHost: vi.fn(() => false),} as any,requestContext: {+ authMethod: 'personal_api_key',sessionId: 'sess-1',mcpClientName: 'test',mcpClientVersion: '1.0',diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex 5125e402fa69..15c4576a24ee 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -89,6 +89,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>isClaudeChatHost: vi.fn(() => false),} as any,requestContext: {+ authMethod: 'personal_api_key',sessionId: 'sess-1',mcpClientName: 'test',mcpClientVersion: '1.0',diff --git a/services/mcp/tests/hono/tool-executor-tokens.test.ts b/services/mcp/tests/hono/tool-executor-tokens.test.tsindex 8f6dcf224c14..0a3fa5b5f7a6 100644--- a/services/mcp/tests/hono/tool-executor-tokens.test.ts+++ b/services/mcp/tests/hono/tool-executor-tokens.test.ts@@ -60,6 +60,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>isClaudeChatHost: vi.fn(() => false),} as any,requestContext: {+ authMethod: 'personal_api_key',sessionId: 'sess-1',mcpClientName: 'test',mcpClientVersion: '1.0',diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex 247ae4c607f0..524c601e1e73 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -55,6 +55,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>isClaudeChatHost: vi.fn(() => false),} as any,requestContext: {+ authMethod: 'personal_api_key',sessionId: 'sess-1',mcpClientName: 'test',mcpClientVersion: '1.0',