: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(mcp_store): make OAuth DCR client_name strict-provider compatible (#90003)
posthog[bot]ece1539886e1
diff --git a/products/mcp_store/backend/oauth.py b/products/mcp_store/backend/oauth.pyindex e7b1b08e2dc0..c1c8736703e4 100644--- a/products/mcp_store/backend/oauth.py+++ b/products/mcp_store/backend/oauth.py@@ -35,6 +35,17 @@ class OAuthAuthorizeURLError(Exception):pass+class DCRRegistrationRejectedError(Exception):+ """The authorization server rejected the Dynamic Client Registration request.++ Carries a short, provider-supplied message that is safe to show the user.+ """++ def __init__(self, provider_message: str) -> None:+ super().__init__(provider_message)+ self.provider_message = provider_message++def _validate_url(url: str) -> None:allowed, reason = is_url_allowed(url)if not allowed:@@ -311,6 +322,24 @@ class DcrClientRegistration:token_endpoint_auth_method: str+def _describe_dcr_rejection(resp: requests.Response) -> str:+ """Build a short, user-safe message from an RFC 7591 error response."""+ try:+ body = resp.json()+ except ValueError:+ body = None+ if isinstance(body, dict):+ description = body.get("error_description")+ code = body.get("error")+ parts = [str(p).strip() for p in (code, description) if isinstance(p, str) and p.strip()]+ if parts:+ return f"The server rejected registration: {'. '.join(parts)}"[:300]+ text = (resp.text or "").strip()+ if text:+ return f"The server rejected registration (HTTP {resp.status_code}): {text}"[:300]+ return f"The server rejected registration (HTTP {resp.status_code})."++def register_dcr_client(metadata: dict, redirect_uri: str) -> DcrClientRegistration:"""Run RFC 7591 Dynamic Client Registration.@@ -324,7 +353,10 @@ def register_dcr_client(metadata: dict, redirect_uri: str) -> DcrClientRegistrattoken_endpoint_auth_method = select_token_endpoint_auth_method(metadata)payload: dict[str, object] = {- "client_name": "MCP Store (PostHog)",+ # Keep the name plain. Some strict RFC 7591 servers reject a client_name+ # with parentheses, or one that starts with "posthog", and fail+ # registration before authorization.+ "client_name": "MCP Store by PostHog","redirect_uris": [redirect_uri],"grant_types": requested_oauth_grant_types(metadata),"response_types": ["code"],@@ -344,7 +376,7 @@ def register_dcr_client(metadata: dict, redirect_uri: str) -> DcrClientRegistratbody=resp.text[:500],registration_endpoint=registration_endpoint,)- resp.raise_for_status()+ raise DCRRegistrationRejectedError(_describe_dcr_rejection(resp))data = resp.json()client_id = data.get("client_id")diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.pyindex c73ec393078a..09ef4bb420ce 100644--- a/products/mcp_store/backend/presentation/views.py+++ b/products/mcp_store/backend/presentation/views.py@@ -66,6 +66,7 @@ from ..models import ()from ..oauth import (DcrClientRegistration,+ DCRRegistrationRejectedError,OAuthAuthorizeURLError,OAuthTokenExchangeError,discover_oauth_metadata,@@ -107,7 +108,20 @@ class DCRNotSupportedError(Exception):class DCRRegistrationFailedError(Exception):- """Raised when Dynamic Client Registration fails."""+ """Raised when Dynamic Client Registration fails.++ `detail` holds a short, user-safe message from the provider when one exists.+ """++ def __init__(self, detail: str | None = None) -> None:+ super().__init__(detail or "")+ self.detail = detail+++def _dcr_failed_detail(error: "DCRRegistrationFailedError") -> str:+ if error.detail:+ return f"OAuth registration failed. {error.detail}"+ return "OAuth registration failed."def _hash_oauth_state_token(token: str) -> str:@@ -975,6 +989,10 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetlog_context["error"] = str(e)logger.warning("DCR not supported", **log_context)raise DCRNotSupportedError from e+ except DCRRegistrationRejectedError as e:+ log_context["error"] = str(e)+ logger.warning("DCR registration rejected by provider", **log_context)+ raise DCRRegistrationFailedError(e.provider_message) from eexcept Exception as e:log_context["error"] = str(e)logger.exception("DCR registration failed", **log_context)@@ -1426,10 +1444,10 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet{"detail": "This MCP server does not support Dynamic Client Registration (DCR)."},status=status.HTTP_400_BAD_REQUEST,)- except DCRRegistrationFailedError:+ except DCRRegistrationFailedError as e:if created:installation.delete()- return Response({"detail": "OAuth registration failed."}, status=status.HTTP_400_BAD_REQUEST)+ return Response({"detail": _dcr_failed_detail(e)}, status=status.HTTP_400_BAD_REQUEST)client_id = registration.client_id# Cache the discovered metadata and minted per-user client on the@@ -1695,10 +1713,10 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet{"detail": "This MCP server does not support Dynamic Client Registration (DCR)."},status=status.HTTP_400_BAD_REQUEST,)- except DCRRegistrationFailedError:+ except DCRRegistrationFailedError as e:if created:installation.delete()- return Response({"detail": "OAuth registration failed."}, status=status.HTTP_400_BAD_REQUEST)+ return Response({"detail": _dcr_failed_detail(e)}, status=status.HTTP_400_BAD_REQUEST)client_id = registration.client_iddcr_client_secret = registration.client_secrettoken_endpoint_auth_method = registration.token_endpoint_auth_methoddiff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.pyindex 82b9ecc4ffd4..767fcc77c9fd 100644--- a/products/mcp_store/backend/test/test_api.py+++ b/products/mcp_store/backend/test/test_api.py@@ -36,7 +36,7 @@ from products.mcp_store.backend.models import (MCPToolPolicy,TeamMCPGatewayConfig,)-from products.mcp_store.backend.oauth import DcrClientRegistration+from products.mcp_store.backend.oauth import DcrClientRegistration, DCRRegistrationRejectedErrorfrom products.mcp_store.backend.presentation.gateway_views import (MAX_TOOL_POLICIES_PER_REQUEST,GatewayPoliciesUpsertSerializer,@@ -3880,6 +3880,31 @@ class TestInstallTemplateAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest# A half-created installation should not linger after DCR failure.assert not MCPServerInstallation.objects.filter(url=template.url, user=self.user).exists()+ @patch(+ "products.mcp_store.backend.presentation.views.register_dcr_client",+ side_effect=DCRRegistrationRejectedError("The server rejected registration: client_name is invalid"),+ )+ @patch(+ "products.mcp_store.backend.presentation.views.discover_oauth_metadata",+ return_value={+ "authorization_endpoint": "https://auth.discovered.example.com/authorize",+ "token_endpoint": "https://auth.discovered.example.com/token",+ "registration_endpoint": "https://auth.discovered.example.com/register",+ },+ )+ def test_install_template_dcr_rejection_surfaces_provider_message(self, _discover, _register):+ template = self._template(oauth_credentials={}, oauth_metadata={})++ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_server_installations/install_template/",+ data={"template_id": str(template.id)},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "client_name is invalid" in response.json()["detail"]+ assert not MCPServerInstallation.objects.filter(url=template.url, user=self.user).exists()+@parameterized.expand([("row_disabled",), ("default_disabled",)])def test_install_template_refused_when_server_disabled_for_team(self, scenario: str) -> None:template = self._template()diff --git a/products/mcp_store/backend/test/test_oauth.py b/products/mcp_store/backend/test/test_oauth.pyindex 6bbb9dfe55ed..e4c04d1ec667 100644--- a/products/mcp_store/backend/test/test_oauth.py+++ b/products/mcp_store/backend/test/test_oauth.py@@ -12,6 +12,7 @@ from products.mcp_store.backend.models import MCPServerInstallation, MCPServerTefrom products.mcp_store.backend.oauth import (TIMEOUT,DcrClientRegistration,+ DCRRegistrationRejectedError,OAuthTokenExchangeError,SSRFBlockedError,TokenRefreshError,@@ -1057,6 +1058,44 @@ class TestRegisterDCRClient(SimpleTestCase):)assert mock_post.call_args.kwargs["json"]["token_endpoint_auth_method"] == "client_secret_basic"+ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, ""))+ @patch("products.mcp_store.backend.oauth.requests.post")+ def test_client_name_has_no_parentheses(self, mock_post, _allow):+ mock_response = MagicMock()+ mock_response.ok = True+ mock_response.status_code = 201+ mock_response.json.return_value = {"client_id": "abc", "token_endpoint_auth_method": "none"}+ mock_post.return_value = mock_response++ register_dcr_client(+ {"registration_endpoint": "https://auth.example.com/register"},+ "https://app.posthog.com/callback",+ )++ client_name = mock_post.call_args.kwargs["json"]["client_name"]+ assert "(" not in client_name and ")" not in client_name++ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, ""))+ @patch("products.mcp_store.backend.oauth.requests.post")+ def test_surfaces_provider_rejection_message(self, mock_post, _allow):+ mock_response = MagicMock()+ mock_response.ok = False+ mock_response.status_code = 400+ mock_response.json.return_value = {+ "error": "invalid_client_metadata",+ "error_description": "client_name contains invalid characters",+ }+ mock_response.text = '{"error": "invalid_client_metadata"}'+ mock_post.return_value = mock_response++ with self.assertRaises(DCRRegistrationRejectedError) as ctx:+ register_dcr_client(+ {"registration_endpoint": "https://auth.example.com/register"},+ "https://app.posthog.com/callback",+ )++ assert "client_name contains invalid characters" in ctx.exception.provider_message+def test_scope_selection_prefers_protected_resource_scopes(self):metadata = {"scopes_supported": ["admin", "read"],