: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): flag a connection for reconnect when its provider rejects the refresh (#80615)
Peter Kirkhamc13dca37f54f
diff --git a/products/mcp_store/README.md b/products/mcp_store/README.mdindex 2311eb4eb75f..f61f2a1aab28 100644--- a/products/mcp_store/README.md+++ b/products/mcp_store/README.md@@ -156,6 +156,11 @@ To show brand icons on a self-hosted instance, create a logo.dev account, genera- **OAuth without DCR** ("shared creds"): an operator registers one OAuth app with the vendor and pastes `client_id`/`client_secret` into Django admin (stored encrypted per template). The sync pre-fills `oauth_metadata` from discovery; installs then share the client while each user gets their own tokens. Redirect URI: `{SITE_URL}/api/mcp_store/oauth_redirect/`.- **API key**: users supply their own key at install; nothing on the template.+When an OAuth token refresh returns `invalid_grant` or `invalid_client`, or there is no refresh token to send, the installation is marked `needs_reauth`.+It drops out of agent runs, and the UI asks the user to reconnect.+Transient failures, including throttling, timeouts, connection errors, and other provider errors, leave the installation alone.+A later successful refresh clears the flag.+OAuth catalog entries can set `oauth_scope_allowlist` to limit registration and authorization to reviewed scopes. Without an allowlist, the client requests every scope advertised by the server. Shared clients derive their token endpoint authentication method from discovered metadata unless `oauth_credentials.token_endpoint_auth_method` overrides it.Slack uses the existing `SLACK_APP_CLIENT_ID` and `SLACK_APP_CLIENT_SECRET` instance settings. Its catalog entry remains suspended until the production Slack app supports MCP and its regional callbacks are live. After the suspension is removed, catalog sync activates Slack only when both settings exist and the shared-client probe passes. Each Desktop user still completes a separate OAuth grant for the catalog's reviewed MCP scopes.diff --git a/products/mcp_store/backend/oauth.py b/products/mcp_store/backend/oauth.pyindex d5f458d2a304..19a9b10bd9d7 100644--- a/products/mcp_store/backend/oauth.py+++ b/products/mcp_store/backend/oauth.py@@ -7,6 +7,8 @@ from collections.abc import Callable, Mapping, Sequencefrom dataclasses import dataclassfrom urllib.parse import urlparse+from django.db import transaction+import requestsimport structlogimport tldextract@@ -22,6 +24,7 @@ logger = structlog.get_logger(__name__)TIMEOUT = 10SUPPORTED_TOKEN_ENDPOINT_AUTH_METHODS = ("none", "client_secret_post", "client_secret_basic")DEFAULT_CONFIDENTIAL_TOKEN_ENDPOINT_AUTH_METHOD = "client_secret_basic"+TOKEN_REFRESH_REJECTION_ERRORS = frozenset({"invalid_client", "invalid_grant"})class SSRFBlockedError(Exception):@@ -447,6 +450,14 @@ class TokenRefreshError(Exception):pass+class TokenRefreshRejectedError(TokenRefreshError):+ """The provider refused the grant, or there is nothing to refresh with.++ Separate from its transient parent because only this one is worth making the user+ reconnect over: retrying it never succeeds.+ """++def _credential_auth_method(credentials: Mapping[str, object], auth_method_key: str, client_secret: str | None, metadata: dict) -> str:@@ -557,6 +568,22 @@ def _token_request_auth(return form, None+def _oauth_error_code(response: requests.Response | None) -> str | None:+ if response is None:+ return None++ try:+ payload: object = response.json()+ except ValueError:+ return None++ if not isinstance(payload, dict):+ return None++ error_code = payload.get("error")+ return error_code if isinstance(error_code, str) else None++def refresh_oauth_token(*,token_url: str,@@ -593,13 +620,17 @@ def refresh_oauth_token(except SSRFBlockedError:raise TokenRefreshError(f"Token refresh URL blocked by SSRF protection: {token_url}")except requests.RequestException as exc:- failed_status_code = getattr(getattr(exc, "response", None), "status_code", None)+ failed_status_code = getattr(exc.response, "status_code", None)+ oauth_error_code = _oauth_error_code(exc.response)logger.warning("OAuth token refresh request failed",token_url=token_url,status_code=failed_status_code,+ oauth_error_code=oauth_error_code,)- raise TokenRefreshError("Token refresh request failed")+ if oauth_error_code in TOKEN_REFRESH_REJECTION_ERRORS:+ raise TokenRefreshRejectedError("Token refresh rejected by the provider") from exc+ raise TokenRefreshError("Token refresh request failed") from exctoken_data = resp.json()if "access_token" not in token_data:@@ -609,12 +640,49 @@ def refresh_oauth_token(return token_data+def _flag_needs_reauth(installation: MCPServerInstallation, *, rejected_refresh_token: str | None) -> None:+ """Record that only a new authorization can revive this credential.++ Everything that mounts or proxies an installation reads this flag, so it takes the+ connection out of agent runs and surfaces a reconnect prompt instead of leaving every+ call to 401 behind a UI that still reads as connected.++ ``rejected_refresh_token`` is the credential the provider turned down, and the row is+ only flagged while it is still the stored one. Nothing serializes refreshes, and+ ``is_token_expiring`` goes true for the whole second half of a token's life, so+ concurrent calls on one installation refresh together. A provider that rotates refresh+ tokens answers every loser of that race with a 4xx for a token the winner has already+ replaced. Flagging on that would take a working connection out of service, and writing+ this request's credentials back would destroy the ones the winner just stored.++ The re-read holds a row lock so the check cannot straddle a concurrent write.+ """+ with transaction.atomic():+ locked = MCPServerInstallation.objects.select_for_update().get(pk=installation.pk)+ sensitive = dict(locked.sensitive_configuration or {})+ if sensitive.get("needs_reauth"):+ return+ if sensitive.get("refresh_token") != rejected_refresh_token:+ logger.info(+ "Skipped reauth flag for an MCP installation refreshed by a concurrent request",+ installation_id=str(installation.id),+ )+ return+ sensitive["needs_reauth"] = True+ locked.sensitive_configuration = sensitive+ locked.save(update_fields=["sensitive_configuration", "updated_at"])++ installation.sensitive_configuration = sensitive+ logger.warning("Flagged MCP installation as needing reauthorization", installation_id=str(installation.id))++def refresh_installation_token(installation: MCPServerInstallation) -> dict:sensitive = installation.sensitive_configuration or {}refresh_token_value = sensitive.get("refresh_token")if not refresh_token_value:logger.warning("No refresh token available for installation", installation_id=str(installation.id))- raise TokenRefreshError("No refresh token available")+ _flag_needs_reauth(installation, rejected_refresh_token=None)+ raise TokenRefreshRejectedError("No refresh token available")try:ctx = resolve_installation_oauth_context(installation)@@ -625,17 +693,23 @@ def refresh_installation_token(installation: MCPServerInstallation) -> dict:if not token_url:raise TokenRefreshError("Missing OAuth metadata for token refresh")- token_data = refresh_oauth_token(- token_url=token_url,- refresh_token=refresh_token_value,- client_id=ctx.client_id,- client_secret=ctx.client_secret,- token_endpoint_auth_method=ctx.token_endpoint_auth_method,- resource=oauth_resource(ctx.metadata),- )+ try:+ token_data = refresh_oauth_token(+ token_url=token_url,+ refresh_token=refresh_token_value,+ client_id=ctx.client_id,+ client_secret=ctx.client_secret,+ token_endpoint_auth_method=ctx.token_endpoint_auth_method,+ resource=oauth_resource(ctx.metadata),+ )+ except TokenRefreshRejectedError:+ _flag_needs_reauth(installation, rejected_refresh_token=refresh_token_value)+ raise- # Preserve non-token keys (needs_reauth, dcr_client_id, dcr_client_secret, etc.) across refresh.+ # Preserve non-token keys (dcr_client_id, dcr_client_secret, etc.) across refresh. A+ # working token clears any earlier rejection.updated: dict = dict(sensitive)+ updated.pop("needs_reauth", None)updated["access_token"] = token_data["access_token"]updated["token_retrieved_at"] = int(time.time())updated["refresh_token"] = token_data.get("refresh_token", refresh_token_value)diff --git a/products/mcp_store/backend/proxy.py b/products/mcp_store/backend/proxy.pyindex 423e933b4418..6d2bf2f37eeb 100644--- a/products/mcp_store/backend/proxy.py+++ b/products/mcp_store/backend/proxy.py@@ -17,7 +17,7 @@ from posthog.settings import SERVER_GATEWAY_INTERFACEfrom ee.hogai.utils.asgi import SyncIterableToAsyncfrom .models import MCPAuditEvent, MCPGatewayServer, MCPServerInstallation, MCPServerInstallationTool-from .oauth import TokenRefreshError, is_token_expiring, refresh_installation_token+from .oauth import TokenRefreshError, TokenRefreshRejectedError, is_token_expiring, refresh_installation_tokenfrom .policy import GatewayCaller, PolicyContextfrom .url_policy import check_mcp_url_policy, trust_environment_proxy@@ -181,6 +181,17 @@ def validate_installation_auth()try:ensure_valid_token(installation)+ except TokenRefreshRejectedError:+ # refresh_installation_token has flagged the installation, unless a concurrent+ # request had already replaced the credential the provider turned down. Say the+ # refresh was rejected either way rather than leaving the caller to read a+ # permanent failure as a retryable one.+ logger.warning("OAuth token refresh rejected", installation_id=str(installation.id))+ return False, HttpResponse(+ '{"error": "Installation needs re-authentication"}',+ content_type="application/json",+ status=401,+ )except TokenRefreshError:logger.warning("OAuth token refresh failed", installation_id=str(installation.id))return False, HttpResponse(diff --git a/products/mcp_store/backend/test/test_oauth.py b/products/mcp_store/backend/test/test_oauth.pyindex 2bc7fbfa2a59..523f5803149c 100644--- a/products/mcp_store/backend/test/test_oauth.py+++ b/products/mcp_store/backend/test/test_oauth.py@@ -18,6 +18,7 @@ from products.mcp_store.backend.oauth import (OAuthTokenExchangeError,SSRFBlockedError,TokenRefreshError,+ TokenRefreshRejectedError,_resolve_issuer,_validate_endpoints_bound_to_issuer,discover_oauth_metadata,@@ -190,10 +191,24 @@ class TestRefreshOauthToken(SimpleTestCase):assert call_kwargs["allow_redirects"] is Falseassert call_kwargs["data"]["resource"] == "https://mcp.example.com/"- def test_http_error_raises_token_refresh_error(self):+ @parameterized.expand(+ [+ ("invalid_grant", 400, {"error": "invalid_grant"}, True),+ ("invalid_client", 401, {"error": "invalid_client"}, True),+ ("request_timeout", 408, {}, False),+ ("temporarily_unavailable", 400, {"error": "temporarily_unavailable"}, False),+ ("too_many_requests", 429, {}, False),+ ("unauthorized_without_oauth_error", 401, {}, False),+ ("server_error", 500, {}, False),+ ]+ )+ def test_http_error_separates_a_rejected_grant_from_a_transient_failure(+ self, _name: str, status_code: int, response_data: dict[str, str], expect_rejected: bool+ ) -> None:mock_resp = MagicMock()- mock_resp.status_code = 401- mock_resp.raise_for_status.side_effect = requests.HTTPError("401 Unauthorized", response=mock_resp)+ mock_resp.status_code = status_code+ mock_resp.json.return_value = response_data+ mock_resp.raise_for_status.side_effect = requests.HTTPError(str(status_code), response=mock_resp)with patch("products.mcp_store.backend.oauth.requests.post", return_value=mock_resp):with self.assertRaises(TokenRefreshError) as ctx:@@ -202,7 +217,8 @@ class TestRefreshOauthToken(SimpleTestCase):refresh_token="bad-refresh",client_id="my-client",)- self.assertIn("Token refresh request failed", str(ctx.exception))++ assert isinstance(ctx.exception, TokenRefreshRejectedError) is expect_rejecteddef test_missing_access_token_raises_token_refresh_error(self):mock_resp = MagicMock()@@ -1540,3 +1556,153 @@ class TestExchangeOauthToken(BaseTest):is_https=lambda url: url.startswith("https://"),)assert result["access_token"] == "abc"+++class TestRefreshInstallationToken(BaseTest):+ def _make_installation(self, **kwargs) -> MCPServerInstallation:+ template = MCPServerTemplate.objects.create(+ name="Refreshable",+ url="https://mcp.refreshable.example.com/mcp",+ auth_type="oauth",+ oauth_metadata={"token_endpoint": "https://auth.refreshable.example.com/token"},+ oauth_credentials={"client_id": "client", "client_secret": "secret"},+ created_by=self.user,+ )+ defaults: dict = {+ "team": self.team,+ "user": self.user,+ "template": template,+ "url": template.url,+ "auth_type": "oauth",+ "sensitive_configuration": {"access_token": "tok", "refresh_token": "refresh"},+ }+ defaults.update(kwargs)+ return MCPServerInstallation.objects.create(**defaults)++ def setUp(self) -> None:+ super().setUp()+ # The fixture token endpoint is not a resolvable host; the SSRF guard is not+ # what these tests are about.+ patcher = patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))+ patcher.start()+ self.addCleanup(patcher.stop)++ @staticmethod+ def _post_answering(status_code: int, response_data: dict[str, str] | None = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.json.return_value = response_data or {}+ response.raise_for_status.side_effect = requests.HTTPError(str(status_code), response=response)+ return response++ @staticmethod+ def _post_failing(error: Exception) -> MagicMock:+ response = MagicMock()+ response.status_code = 200+ response.raise_for_status.side_effect = error+ return response++ @parameterized.expand([("invalid_grant", 400), ("invalid_client", 401)])+ def test_provider_rejecting_the_grant_flags_reauth(self, oauth_error: str, status_code: int) -> None:+ installation = self._make_installation()++ with patch(+ "products.mcp_store.backend.oauth.requests.post",+ return_value=self._post_answering(status_code, {"error": oauth_error}),+ ):+ with self.assertRaises(TokenRefreshRejectedError):+ refresh_installation_token(installation)++ installation.refresh_from_db()+ # EncryptedJSONField stringifies scalars, so every reader of the flag tests truthiness.+ assert installation.sensitive_configuration["needs_reauth"]++ def test_rejection_of_a_token_a_concurrent_refresh_replaced_leaves_the_connection_alone(self) -> None:+ # Providers that rotate refresh tokens reject every loser of a concurrent refresh,+ # because the winner already consumed the token they all sent. Acting on that would+ # flag a working connection and write the consumed credentials over the fresh ones.+ installation = self._make_installation()++ def _win_the_race_then_reject(*args, **kwargs):+ winner = MCPServerInstallation.objects.get(pk=installation.pk)+ winner.sensitive_configuration = {"access_token": "fresh", "refresh_token": "rotated"}+ winner.save(update_fields=["sensitive_configuration", "updated_at"])+ raise TokenRefreshRejectedError("Token refresh rejected by the provider")++ with patch("products.mcp_store.backend.oauth.refresh_oauth_token", side_effect=_win_the_race_then_reject):+ with self.assertRaises(TokenRefreshRejectedError):+ refresh_installation_token(installation)++ installation.refresh_from_db()+ assert "needs_reauth" not in installation.sensitive_configuration+ assert installation.sensitive_configuration["access_token"] == "fresh"+ assert installation.sensitive_configuration["refresh_token"] == "rotated"++ @parameterized.expand(+ [+ ("request_timeout", 408, {}),+ ("temporarily_unavailable", 400, {"error": "temporarily_unavailable"}),+ ("too_many_requests", 429, {}),+ ("server_error", 500, {}),+ ("bad_gateway", 502, {}),+ ("gateway_timeout", 504, {}),+ ]+ )+ def test_provider_outage_leaves_the_connection_alone(+ self, _name: str, status_code: int, response_data: dict[str, str]+ ) -> None:+ installation = self._make_installation()++ with patch(+ "products.mcp_store.backend.oauth.requests.post",+ return_value=self._post_answering(status_code, response_data),+ ):+ with self.assertRaises(TokenRefreshError) as ctx:+ refresh_installation_token(installation)++ assert not isinstance(ctx.exception, TokenRefreshRejectedError)+ installation.refresh_from_db()+ assert "needs_reauth" not in installation.sensitive_configuration++ @parameterized.expand(+ [+ ("connection_error", requests.ConnectionError("connection reset")),+ ("timeout", requests.Timeout("timed out")),+ ]+ )+ def test_network_failure_leaves_the_connection_alone(self, _name: str, error: Exception) -> None:+ installation = self._make_installation()++ with patch("products.mcp_store.backend.oauth.requests.post", return_value=self._post_failing(error)):+ with self.assertRaises(TokenRefreshError) as ctx:+ refresh_installation_token(installation)++ assert not isinstance(ctx.exception, TokenRefreshRejectedError)+ installation.refresh_from_db()+ assert "needs_reauth" not in installation.sensitive_configuration++ def test_missing_refresh_token_flags_reauth(self) -> None:+ # No refresh token means no refresh will ever succeed; only a new authorization can.+ installation = self._make_installation(sensitive_configuration={"access_token": "tok"})++ with self.assertRaises(TokenRefreshRejectedError):+ refresh_installation_token(installation)++ installation.refresh_from_db()+ assert installation.sensitive_configuration["needs_reauth"]++ def test_successful_refresh_clears_a_stale_reauth_flag(self) -> None:+ installation = self._make_installation(+ sensitive_configuration={"access_token": "tok", "refresh_token": "refresh", "needs_reauth": True},+ )+ response = MagicMock()+ response.status_code = 200+ response.raise_for_status = MagicMock()+ response.json.return_value = {"access_token": "fresh", "expires_in": 3600}++ with patch("products.mcp_store.backend.oauth.requests.post", return_value=response):+ refresh_installation_token(installation)++ installation.refresh_from_db()+ assert "needs_reauth" not in installation.sensitive_configuration+ assert installation.sensitive_configuration["access_token"] == "fresh"diff --git a/products/mcp_store/backend/test/test_proxy.py b/products/mcp_store/backend/test/test_proxy.pyindex 49d0f9907a18..f50122e3ad32 100644--- a/products/mcp_store/backend/test/test_proxy.py+++ b/products/mcp_store/backend/test/test_proxy.py@@ -22,6 +22,7 @@ from products.mcp_store.backend.models import (MCPServerInstallationTool,MCPToolPolicy,)+from products.mcp_store.backend.oauth import TokenRefreshRejectedErrorfrom products.mcp_store.backend.proxy import _build_sse_response@@ -277,6 +278,31 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert response.status_code == status.HTTP_401_UNAUTHORIZEDassert response.json()["error"] == "Authentication failed"+ @patch("products.mcp_store.backend.oauth.refresh_oauth_token")+ def test_proxy_takes_a_rejected_connection_out_of_service(self, mock_refresh):+ # Left unflagged, the connection keeps reading as healthy in the UI and every agent+ # run keeps mounting a server whose every call fails.+ installation = self._create_oauth_installation(+ sensitive_configuration={+ "access_token": "expired-token",+ "refresh_token": "revoked-refresh-token",+ "token_retrieved_at": int(time.time()) - 7200,+ "expires_in": 3600,+ },+ )+ mock_refresh.side_effect = TokenRefreshRejectedError("Token refresh rejected by the provider")++ response = self.client.post(+ self._proxy_url(installation.id),+ data={"jsonrpc": "2.0", "id": 1, "method": "tools/list"},+ format="json",+ )++ assert response.status_code == status.HTTP_401_UNAUTHORIZED+ assert response.json()["error"] == "Installation needs re-authentication"+ installation.refresh_from_db()+ assert installation.sensitive_configuration["needs_reauth"]+def test_proxy_returns_403_for_disabled_installation(self):installation = self._create_installation(sensitive_configuration={"api_key": "sk-test-key"},