AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(backend): sign in to HubSpot's MCP server with a configured app, and refuse the placeholder client for servers that need a secret (#15366)
Bentlyfff62ed3128e
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.defaultindex 6e76e67802..b260df9d9f 100644--- a/autogpt_platform/backend/.env.default+++ b/autogpt_platform/backend/.env.default@@ -212,6 +212,11 @@ LINEAR_CLIENT_SECRET=SLACK_MCP_CLIENT_ID=SLACK_MCP_CLIENT_SECRET=+# HubSpot MCP auth app for signing in to HubSpot's MCP server (mcp.hubspot.com),+# which does not support dynamic client registration+HUBSPOT_MCP_CLIENT_ID=+HUBSPOT_MCP_CLIENT_SECRET=+# To obtain Todoist API credentials:# 1. Create a Todoist account at todoist.com# 2. Visit the Developer Console: https://developer.todoist.com/appconsole.htmldiff --git a/autogpt_platform/backend/backend/api/features/mcp/oauth_registration.py b/autogpt_platform/backend/backend/api/features/mcp/oauth_registration.pyindex c86448ad1d..2f5fb06f1b 100644--- a/autogpt_platform/backend/backend/api/features/mcp/oauth_registration.py+++ b/autogpt_platform/backend/backend/api/features/mcp/oauth_registration.py@@ -23,6 +23,11 @@ PREREGISTERED_APPS: dict[str, PreregisteredApp] = {client_secret_field="slack_mcp_client_secret",endpoint_hosts=frozenset({"slack.com"}),),+ "mcp.hubspot.com": PreregisteredApp(+ client_id_field="hubspot_mcp_client_id",+ client_secret_field="hubspot_mcp_client_secret",+ endpoint_hosts=frozenset({"mcp.hubspot.com"}),+ ),}@@ -57,6 +62,14 @@ def select_client_auth_method()+def requires_registered_client(metadata: dict[str, object]) -> bool:+ """Whether the server's token endpoint only takes clients that authenticate+ with a secret, so the public placeholder client can never sign in. A server+ that does not list its methods keeps the placeholder, as before."""+ supported = metadata.get("token_endpoint_auth_methods_supported")+ return isinstance(supported, list) and "none" not in supported++def preregistered_client(server_url: str, secrets: Secrets) -> tuple[str, str] | None:"""The configured ``(client_id, client_secret)`` for a server that needs apre-registered OAuth app, ``("", "")`` when it needs one but none isdiff --git a/autogpt_platform/backend/backend/api/features/mcp/routes.py b/autogpt_platform/backend/backend/api/features/mcp/routes.pyindex 1c4826e4f6..ce22447ef7 100644--- a/autogpt_platform/backend/backend/api/features/mcp/routes.py+++ b/autogpt_platform/backend/backend/api/features/mcp/routes.py@@ -24,6 +24,7 @@ from backend.api.features.mcp.oauth_registration import (check_preregistered_endpoints,preregistered_client,preregistered_revocation_endpoint,+ requires_registered_client,select_client_auth_method,)from backend.blocks.mcp.client import (@@ -444,6 +445,21 @@ async def mcp_oauth_login(raise fastapi.HTTPException(status_code=400, detail=str(e))if not client_id:+ # A server with no DCR that only takes secret-holding clients rejects+ # the placeholder with "invalid client id" on its own page, after the+ # user has left the platform. Say so here instead.+ if requires_registered_client(metadata):+ raise fastapi.HTTPException(+ status_code=400,+ detail={+ "code": NO_OAUTH_CODE,+ "message": f"Sign-in to {server_host(server_url)} is not "+ "available on this platform: the server only accepts an "+ "OAuth app registered with it in advance, and none is "+ "registered for it here. "+ "You may need to provide an auth credential manually.",+ },+ )client_id = "autogpt-platform"# Step 4: Store state token with OAuth metadata for the callbackdiff --git a/autogpt_platform/backend/backend/api/features/mcp/test_oauth_no_dcr.py b/autogpt_platform/backend/backend/api/features/mcp/test_oauth_no_dcr.pynew file mode 100644index 0000000000..40bdfcde41--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/mcp/test_oauth_no_dcr.py@@ -0,0 +1,184 @@+"""Sign-in to MCP servers that offer no Dynamic Client Registration.++The HubSpot metadata below is what mcp.hubspot.com served on 2026-10-10: no+``registration_endpoint`` and confidential clients only.+"""++from unittest.mock import AsyncMock, patch+from urllib.parse import parse_qs, urlsplit++import fastapi+import httpx+import pytest+import pytest_asyncio+from autogpt_libs.auth import get_user_id++from backend.api.features.mcp.routes import NO_OAUTH_CODE, router++app = fastapi.FastAPI()+app.include_router(router)+app.dependency_overrides[get_user_id] = lambda: "test-user-id"++HUBSPOT_PROTECTED_RESOURCE = {+ "resource": "https://mcp.hubspot.com",+ "authorization_servers": ["https://mcp.hubspot.com"],+ "scopes_supported": [],+}+HUBSPOT_AUTH_SERVER = {+ "issuer": "https://mcp.hubspot.com",+ "authorization_endpoint": "https://mcp.hubspot.com/oauth/authorize/user",+ "token_endpoint": "https://mcp.hubspot.com/oauth/v3/token",+ "scopes_supported": [],+ "response_types_supported": ["code"],+ "grant_types_supported": ["authorization_code", "refresh_token"],+ "token_endpoint_auth_methods_supported": ["client_secret_post"],+ "code_challenge_methods_supported": ["S256"],+}+++@pytest_asyncio.fixture(scope="module")+async def client():+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as c:+ yield c+++def login():+ with (+ patch("backend.api.features.mcp.routes.MCPClient") as mcp_client,+ patch("backend.api.features.mcp.routes.creds_manager") as manager,+ patch("backend.api.features.mcp.routes.settings") as settings,+ patch(+ "backend.api.features.mcp.routes.validate_url_host",+ new_callable=AsyncMock,+ ),+ ):+ auth_server = dict(HUBSPOT_AUTH_SERVER)+ mcp_client.return_value.discover_auth = AsyncMock(+ return_value=HUBSPOT_PROTECTED_RESOURCE+ )+ mcp_client.return_value.discover_auth_server_metadata = AsyncMock(+ return_value=(auth_server, "https://mcp.hubspot.com")+ )+ manager.store.store_state_token = AsyncMock(+ return_value=("state-abc", "challenge-xyz")+ )+ settings.config.frontend_base_url = "https://platform.example.com"+ settings.secrets.hubspot_mcp_client_id = ""+ settings.secrets.hubspot_mcp_client_secret = ""+ yield auth_server, settings, manager++[email protected](loop_scope="session")+async def test_hubspot_signs_in_with_the_configured_app(client, login):+ _, settings, manager = login+ settings.secrets.hubspot_mcp_client_id = "hubspot-client-id"+ settings.secrets.hubspot_mcp_client_secret = "hubspot-secret"++ response = await client.post(+ "/oauth/login", json={"server_url": "https://mcp.hubspot.com"}+ )++ assert response.status_code == 200+ login_url = urlsplit(response.json()["login_url"])+ assert (login_url.scheme, login_url.hostname, login_url.path) == (+ "https",+ "mcp.hubspot.com",+ "/oauth/authorize/user",+ )+ query = parse_qs(login_url.query)+ assert query["client_id"] == ["hubspot-client-id"]+ assert query["code_challenge"] == ["challenge-xyz"]+ assert query["code_challenge_method"] == ["S256"]+ assert query["resource"] == ["https://mcp.hubspot.com"]+ assert query["redirect_uri"] == [+ "https://platform.example.com/auth/integrations/mcp_callback"+ ]+ assert "hubspot-secret" not in login_url.query+ state = manager.store.store_state_token.call_args.kwargs["state_metadata"]+ assert state["client_id"] == "hubspot-client-id"+ assert state["client_secret"] == "hubspot-secret"+ assert state["token_endpoint_auth_method"] == "client_secret_post"+ assert state["token_url"] == "https://mcp.hubspot.com/oauth/v3/token"++[email protected](loop_scope="session")+async def test_hubspot_without_an_app_says_sign_in_is_not_set_up(client, login):+ _, _, manager = login++ response = await client.post(+ "/oauth/login", json={"server_url": "https://mcp.hubspot.com/"}+ )++ assert response.status_code == 400+ detail = response.json()["detail"]+ assert detail["code"] == NO_OAUTH_CODE+ assert detail["message"].startswith(+ "Sign-in to mcp.hubspot.com is not set up on this platform yet"+ )+ manager.store.store_state_token.assert_not_called()+++ "methods", [["client_secret_post"], ["client_secret_basic", "private_key_jwt"]]+)[email protected](loop_scope="session")+async def test_unlisted_secret_only_server_is_refused_not_sent_a_placeholder(+ client, login, methods+):+ auth_server, _, manager = login+ auth_server["token_endpoint_auth_methods_supported"] = methods++ response = await client.post(+ "/oauth/login", json={"server_url": "https://mcp.vendor.example/mcp"}+ )++ assert response.status_code == 400+ detail = response.json()["detail"]+ assert detail["code"] == NO_OAUTH_CODE+ assert detail["message"] == (+ "Sign-in to mcp.vendor.example is not available on this platform: the "+ "server only accepts an OAuth app registered with it in advance, and "+ "none is registered for it here. "+ "You may need to provide an auth credential manually."+ )+ manager.store.store_state_token.assert_not_called()++[email protected](loop_scope="session")+async def test_cleartext_hubspot_url_is_refused_without_the_secret(client, login):+ _, settings, manager = login+ settings.secrets.hubspot_mcp_client_id = "hubspot-client-id"+ settings.secrets.hubspot_mcp_client_secret = "hubspot-secret"++ response = await client.post(+ "/oauth/login", json={"server_url": "http://mcp.hubspot.com"}+ )++ assert response.status_code == 400+ assert response.json()["detail"]["code"] == NO_OAUTH_CODE+ manager.store.store_state_token.assert_not_called()++[email protected]("methods", [["none"], ["client_secret_post", "none"], None])[email protected](loop_scope="session")+async def test_server_accepting_public_clients_keeps_the_placeholder(+ client, login, methods+):+ auth_server, _, manager = login+ if methods is None:+ auth_server.pop("token_endpoint_auth_methods_supported")+ else:+ auth_server["token_endpoint_auth_methods_supported"] = methods++ response = await client.post(+ "/oauth/login", json={"server_url": "https://mcp.vendor.example/mcp"}+ )++ assert response.status_code == 200+ query = parse_qs(urlsplit(response.json()["login_url"]).query)+ assert query["client_id"] == ["autogpt-platform"]+ state = manager.store.store_state_token.call_args.kwargs["state_metadata"]+ assert state["client_secret"] == ""+ assert state["token_endpoint_auth_method"] == "none"diff --git a/autogpt_platform/backend/backend/api/features/mcp/test_routes.py b/autogpt_platform/backend/backend/api/features/mcp/test_routes.pyindex b5e0085be0..4989a975d6 100644--- a/autogpt_platform/backend/backend/api/features/mcp/test_routes.py+++ b/autogpt_platform/backend/backend/api/features/mcp/test_routes.py@@ -604,13 +604,13 @@ class TestOAuthLogin:json={"server_url": "http://mcp.slack.com/mcp"},)- assert response.status_code == 200- assert "1234.5678" not in response.json()["login_url"]- state_metadata = mock_cm.store.store_state_token.call_args.kwargs[- "state_metadata"- ]- assert state_metadata["client_id"] == "autogpt-platform"- assert state_metadata["client_secret"] == ""+ # Slack only takes secret-holding clients, so with its app ruled out+ # the placeholder cannot sign in either: refused, nothing stored.+ assert response.status_code == 400+ assert response.json()["detail"]["code"] == NO_OAUTH_CODE+ assert "1234.5678" not in response.text+ assert "slack-secret" not in response.text+ mock_cm.store.store_state_token.assert_not_called()@pytest.mark.asyncio(loop_scope="session")async def test_oauth_login_binds_issuer_and_iss_requirement(self, client):diff --git a/autogpt_platform/backend/backend/blocks/mcp/oauth.py b/autogpt_platform/backend/backend/blocks/mcp/oauth.pyindex 8625453d8f..0fa07dd98a 100644--- a/autogpt_platform/backend/backend/blocks/mcp/oauth.py+++ b/autogpt_platform/backend/backend/blocks/mcp/oauth.py@@ -17,7 +17,7 @@ from pydantic import SecretStrfrom backend.data.model import OAuth2Credentialsfrom backend.integrations.oauth.base import BaseOAuthHandler, parse_granted_scopesfrom backend.integrations.providers import ProviderName-from backend.util.request import Requests+from backend.util.request import Requests, Responselogger = logging.getLogger(__name__)@@ -116,11 +116,7 @@ class MCPOAuthHandler(BaseOAuthHandler):if self.resource_url:data["resource"] = self.resource_url- response = await Requests(raise_for_status=True).post(- self.token_url,- data=data,- headers=headers,- )+ response = await _post_client_form(self.token_url, data, headers)tokens = response.json()if "error" in tokens:@@ -168,11 +164,7 @@ class MCPOAuthHandler(BaseOAuthHandler):if self.resource_url:data["resource"] = self.resource_url- response = await Requests(raise_for_status=True).post(- self.token_url,- data=data,- headers=headers,- )+ response = await _post_client_form(self.token_url, data, headers)tokens = response.json()if "error" in tokens:@@ -213,11 +205,7 @@ class MCPOAuthHandler(BaseOAuthHandler):"token": credentials.access_token.get_secret_value(),"token_type_hint": "access_token",}- await Requests(raise_for_status=True).post(- self.revoke_url,- data=data,- headers=headers,- )+ await _post_client_form(self.revoke_url, data, headers)return Trueexcept Exception:logger.warning("Failed to revoke MCP OAuth tokens", exc_info=True)@@ -242,3 +230,23 @@ class MCPOAuthHandler(BaseOAuthHandler):elif self.token_endpoint_auth_method != "none":raise ValueError("Unsupported MCP client authentication method")return data, headers+++async def _post_client_form(+ url: str, data: dict[str, str], headers: dict[str, str]+) -> Response:+ """POST to a token or revocation endpoint without following redirects.++ The form carries the client secret, the code or a token, and ``Requests``+ re-sends the body on every hop, so a redirect would hand them to a host+ outside the endpoints checked for the server's pre-registered app.+ """+ response = await Requests(raise_for_status=True).post(+ url, data=data, headers=headers, allow_redirects=False+ )+ if response.status in (301, 302, 303, 307, 308):+ raise RuntimeError(+ f"OAuth endpoint {url} answered with a redirect (HTTP "+ f"{response.status}), which is not followed with client credentials"+ )+ return responsediff --git a/autogpt_platform/backend/backend/blocks/mcp/test_oauth.py b/autogpt_platform/backend/backend/blocks/mcp/test_oauth.pyindex 2266c27681..a2987c986f 100644--- a/autogpt_platform/backend/backend/blocks/mcp/test_oauth.py+++ b/autogpt_platform/backend/backend/blocks/mcp/test_oauth.py@@ -5,11 +5,13 @@ Tests for MCP OAuth handler.from unittest.mock import AsyncMock, MagicMock, patchimport pytest+from aiohttp import webfrom pydantic import SecretStrfrom backend.blocks.mcp.client import MCPClientfrom backend.blocks.mcp.oauth import MCPOAuthHandlerfrom backend.data.model import OAuth2Credentials+from backend.util.request import Requestsdef _mock_response(json_data: dict, status: int = 200) -> MagicMock:@@ -272,3 +274,85 @@ class TestMCPClientDiscovery:result = await client.discover_auth_server_metadata(issuer)assert result == (metadata, issuer)+++class TestMCPOAuthRedirects:+ """The token and revocation POSTs carry the client secret, the code or a+ token in the form body, and ``Requests`` re-sends the body on every hop, so+ a redirect from the endpoint must not be followed."""++ @pytest.mark.parametrize("call", ["exchange", "refresh", "revoke"])+ @pytest.mark.asyncio(loop_scope="session")+ async def test_redirect_does_not_forward_client_form(self, call: str):+ received: list[dict[str, str]] = []++ async def collect(request: web.Request) -> web.Response:+ form = await request.post()+ received.append({key: str(value) for key, value in form.items()})+ return web.json_response({"access_token": "attacker-token"})++ attacker = web.Application()+ attacker.router.add_post("/collect", collect)+ attacker_runner = web.AppRunner(attacker)+ await attacker_runner.setup()+ await web.TCPSite(attacker_runner, "127.0.0.1", 0).start()+ attacker_port = attacker_runner.addresses[0][1]++ async def redirect(_request: web.Request) -> web.Response:+ raise web.HTTPTemporaryRedirect(f"http://127.0.0.1:{attacker_port}/collect")++ origin = web.Application()+ origin.router.add_post("/token", redirect)+ origin.router.add_post("/revoke", redirect)+ origin_runner = web.AppRunner(origin)+ await origin_runner.setup()+ await web.TCPSite(origin_runner, "127.0.0.1", 0).start()+ origin_port = origin_runner.addresses[0][1]++ handler = MCPOAuthHandler(+ client_id="client",+ client_secret="<platform-app-secret>",+ redirect_uri="https://app.example.com/callback",+ authorize_url="",+ token_url=f"http://127.0.0.1:{origin_port}/token",+ revoke_url=f"http://127.0.0.1:{origin_port}/revoke",+ token_endpoint_auth_method="client_secret_post",+ )+ credentials = OAuth2Credentials(+ provider="mcp",+ access_token=SecretStr("<access-token>"),+ refresh_token=SecretStr("<refresh-token>"),+ scopes=[],+ )++ def local_requests(**kwargs):+ return Requests(trusted_origins=["127.0.0.1"], **kwargs)++ async def attempt() -> bool | None:+ if call == "exchange":+ await handler.exchange_code_for_tokens(+ code="<code>", scopes=[], code_verifier="<verifier>"+ )+ elif call == "refresh":+ await handler._refresh_tokens(credentials)+ else:+ return await handler.revoke_tokens(credentials)+ return None++ error: RuntimeError | None = None+ revoked: bool | None = None+ try:+ with patch("backend.blocks.mcp.oauth.Requests", local_requests):+ try:+ revoked = await attempt()+ except RuntimeError as e:+ error = e+ finally:+ await origin_runner.cleanup()+ await attacker_runner.cleanup()++ assert received == []+ if call == "revoke":+ assert revoked is False+ else:+ assert error is not None and "redirect" in str(error)diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.pyindex 078124aa47..e5b3d67a30 100644--- a/autogpt_platform/backend/backend/util/settings.py+++ b/autogpt_platform/backend/backend/util/settings.py@@ -1342,6 +1342,16 @@ class Secrets(UpdateTrackingModel["Secrets"], BaseSettings):slack_mcp_client_secret: str = Field(default="", description="Client secret of the Slack MCP sign-in app")+ hubspot_mcp_client_id: str = Field(+ default="",+ description="Client ID of the HubSpot MCP auth app used to sign in to "+ "HubSpot's MCP server (mcp.hubspot.com). HubSpot does not support "+ "dynamic client registration, so MCP sign-in to HubSpot is unavailable "+ "until this is set.",+ )+ hubspot_mcp_client_secret: str = Field(+ default="", description="Client secret of the HubSpot MCP auth app"+ )todoist_client_id: str = Field(default="", description="Todoist client ID")todoist_client_secret: str = Field(default="", description="Todoist client secret")