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 Slack's MCP server with a configured Slack app (#15066)
Bently3582dd995839
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.defaultindex 5b2f84b343..6e76e67802 100644--- a/autogpt_platform/backend/.env.default+++ b/autogpt_platform/backend/.env.default@@ -207,6 +207,11 @@ LINEAR_FEATURE_REQUEST_TEAM_ID=LINEAR_CLIENT_ID=LINEAR_CLIENT_SECRET=+# Slack app for signing in to Slack's MCP server (mcp.slack.com), which does not+# support dynamic client registration+SLACK_MCP_CLIENT_ID=+SLACK_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 514fdfe1a0..c86448ad1d 100644--- a/autogpt_platform/backend/backend/api/features/mcp/oauth_registration.py+++ b/autogpt_platform/backend/backend/api/features/mcp/oauth_registration.py@@ -1,6 +1,29 @@+from urllib.parse import urlsplit+from pydantic import BaseModel, Field, SecretStr, model_validatorfrom backend.blocks.mcp.oauth import MCPTokenEndpointAuthMethod+from backend.util.settings import Secrets+++class PreregisteredApp(BaseModel):+ # The ``Secrets`` fields holding the app's client id and secret.+ client_id_field: str+ client_secret_field: str+ # Hosts the discovered authorize and token endpoints must be on. The secret+ # is posted to the token endpoint, which comes from the server's metadata.+ endpoint_hosts: frozenset[str]+++# MCP servers that refuse Dynamic Client Registration and only accept an OAuth+# app registered with them in advance, keyed by server host.+PREREGISTERED_APPS: dict[str, PreregisteredApp] = {+ "mcp.slack.com": PreregisteredApp(+ client_id_field="slack_mcp_client_id",+ client_secret_field="slack_mcp_client_secret",+ endpoint_hosts=frozenset({"slack.com"}),+ ),+}class MCPClientRegistration(BaseModel):@@ -32,3 +55,69 @@ def select_client_auth_method(raise ValueError("This MCP server requires an unsupported client authentication method")+++def preregistered_client(server_url: str, secrets: Secrets) -> tuple[str, str] | None:+ """The configured ``(client_id, client_secret)`` for a server that needs a+ pre-registered OAuth app, ``("", "")`` when it needs one but none is+ configured, or ``None`` when the server is not one of them.++ Matches the URL's exact hostname, so a look-alike such as+ ``mcp.slack.com.evil.example`` never receives the platform's Slack app.+ """+ app = _preregistered_app(server_url)+ if not app:+ return None+ return getattr(secrets, app.client_id_field), getattr(+ secrets, app.client_secret_field+ )+++def check_preregistered_endpoints(server_url: str, metadata: dict[str, object]):+ """Raise ``ValueError`` unless the discovered authorize and token endpoints+ are HTTPS URLs on the hosts the server's pre-registered app expects, so+ the platform's client secret is only ever sent to the provider itself."""+ app = _preregistered_app(server_url)+ if not app:+ return+ for key in ("authorization_endpoint", "token_endpoint"):+ if not _is_https_on(metadata.get(key), app.endpoint_hosts):+ raise ValueError(+ f"The {key} advertised by {urlsplit(server_url).hostname} is not "+ f"an HTTPS URL on {', '.join(sorted(app.endpoint_hosts))}"+ )+++def preregistered_revocation_endpoint(+ server_url: str, revoke_url: str | None+) -> str | None:+ """The revocation endpoint to keep for ``server_url``. Revocation also+ authenticates with the client secret, so for a pre-registered app one that+ is not HTTPS on the provider's hosts is dropped; revocation is best-effort."""+ app = _preregistered_app(server_url)+ if not app or _is_https_on(revoke_url, app.endpoint_hosts):+ return revoke_url+ return None+++def _preregistered_app(server_url: str) -> PreregisteredApp | None:+ try:+ parts = urlsplit(server_url)+ host = parts.hostname+ except ValueError:+ return None+ # Discovery decides where the secret is posted, so never over cleartext.+ if parts.scheme != "https":+ return None+ return PREREGISTERED_APPS.get(host or "")+++def _is_https_on(url: object, hosts: frozenset[str]) -> bool:+ if not isinstance(url, str):+ return False+ try:+ parts = urlsplit(url)+ host = parts.hostname+ except ValueError:+ return False+ return parts.scheme == "https" and host in hostsdiff --git a/autogpt_platform/backend/backend/api/features/mcp/routes.py b/autogpt_platform/backend/backend/api/features/mcp/routes.pyindex 4a7d142eb6..1c4826e4f6 100644--- a/autogpt_platform/backend/backend/api/features/mcp/routes.py+++ b/autogpt_platform/backend/backend/api/features/mcp/routes.py@@ -21,6 +21,9 @@ from backend.api.features.integrations.router import ()from backend.api.features.mcp.oauth_registration import (MCPClientRegistration,+ check_preregistered_endpoints,+ preregistered_client,+ preregistered_revocation_endpoint,select_client_auth_method,)from backend.blocks.mcp.client import (@@ -408,6 +411,37 @@ async def mcp_oauth_login(client_id = registration.client_idclient_secret = registration.client_secret.get_secret_value()token_endpoint_auth_method = registration.token_endpoint_auth_method+ elif (+ preregistered := preregistered_client(server_url, settings.secrets)+ ) is not None:+ client_id, client_secret = preregistered+ if not (client_id and client_secret):+ raise fastapi.HTTPException(+ status_code=400,+ detail={+ "code": NO_OAUTH_CODE,+ "message": f"Sign-in to {server_host(server_url)} is not "+ "set up on this platform yet: the server only accepts an "+ "OAuth app registered with it in advance. "+ "You may need to provide an auth credential manually.",+ },+ )+ try:+ check_preregistered_endpoints(server_url, metadata)+ except ValueError as e:+ logger.warning("Refusing pre-registered client sign-in: %s", e)+ raise fastapi.HTTPException(status_code=400, detail=str(e))+ trusted_revoke_url = preregistered_revocation_endpoint(server_url, revoke_url)+ if revoke_url and not trusted_revoke_url:+ logger.warning(+ "Ignoring off-host revocation endpoint advertised by %s",+ server_host(server_url),+ )+ revoke_url = trusted_revoke_url+ try:+ token_endpoint_auth_method = select_client_auth_method(metadata)+ except ValueError as e:+ raise fastapi.HTTPException(status_code=400, detail=str(e))if not client_id:client_id = "autogpt-platform"diff --git a/autogpt_platform/backend/backend/api/features/mcp/test_routes.py b/autogpt_platform/backend/backend/api/features/mcp/test_routes.pyindex e64dae8b42..b5e0085be0 100644--- a/autogpt_platform/backend/backend/api/features/mcp/test_routes.py+++ b/autogpt_platform/backend/backend/api/features/mcp/test_routes.py@@ -6,6 +6,7 @@ to avoid creating blocking portals that can corrupt pytest-asyncio's session eveimport asynciofrom unittest.mock import AsyncMock, MagicMock, patch+from urllib.parse import parse_qs, urlsplitimport fastapiimport httpx@@ -14,6 +15,7 @@ import pytest_asynciofrom autogpt_libs.auth import get_user_idfrom pydantic import SecretStr+from backend.api.features.mcp.oauth_registration import preregistered_clientfrom backend.api.features.mcp.routes import NO_OAUTH_CODE, routerfrom backend.blocks.mcp.client import MCPClientError, MCPToolfrom backend.data.model import OAuth2Credentials@@ -383,6 +385,233 @@ class TestOAuthLogin:data = response.json()assert "autogpt-platform" in data["login_url"]+ @staticmethod+ def _mock_slack_discovery(MockClient, **metadata_overrides):+ # What mcp.slack.com serves: no registration_endpoint, confidential+ # clients only.+ instance = MockClient.return_value+ instance.discover_auth = AsyncMock(+ return_value={+ "authorization_servers": ["https://mcp.slack.com"],+ "resource": "https://mcp.slack.com",+ "scopes_supported": ["search:read.public", "users:read"],+ }+ )+ instance.discover_auth_server_metadata = AsyncMock(+ return_value=(+ {+ "issuer": "https://mcp.slack.com",+ "authorization_endpoint": "https://slack.com/oauth/v2_user/authorize",+ "token_endpoint": "https://slack.com/api/oauth.v2.user.access",+ "token_endpoint_auth_methods_supported": ["client_secret_post"],+ **metadata_overrides,+ },+ "https://mcp.slack.com",+ )+ )++ @pytest.mark.asyncio(loop_scope="session")+ async def test_oauth_login_slack_uses_configured_client(self, client):+ """Slack has no DCR, so sign-in must send the platform's Slack app id,+ not the placeholder Slack rejects with "Invalid client_id parameter"."""+ with (+ patch("backend.api.features.mcp.routes.MCPClient") as MockClient,+ patch("backend.api.features.mcp.routes.creds_manager") as mock_cm,+ patch("backend.api.features.mcp.routes.settings") as mock_settings,+ ):+ self._mock_slack_discovery(MockClient)+ mock_cm.store.store_state_token = AsyncMock(+ return_value=("state-abc", "challenge-xyz")+ )+ mock_settings.config.frontend_base_url = "http://localhost:3000"+ mock_settings.secrets.slack_mcp_client_id = "1234.5678"+ mock_settings.secrets.slack_mcp_client_secret = "slack-secret"++ response = await client.post(+ "/oauth/login",+ json={"server_url": "https://mcp.slack.com/mcp"},+ )++ assert response.status_code == 200+ login_url = urlsplit(response.json()["login_url"])+ assert login_url.scheme == "https"+ assert login_url.hostname == "slack.com"+ assert login_url.path == "/oauth/v2_user/authorize"+ query = parse_qs(login_url.query)+ assert query["client_id"] == ["1234.5678"]+ assert "client_secret" not in query+ assert "slack-secret" not in login_url.query+ state_metadata = mock_cm.store.store_state_token.call_args.kwargs[+ "state_metadata"+ ]+ assert state_metadata["client_id"] == "1234.5678"+ assert state_metadata["client_secret"] == "slack-secret"+ assert state_metadata["token_endpoint_auth_method"] == "client_secret_post"++ @pytest.mark.asyncio(loop_scope="session")+ async def test_oauth_login_slack_unconfigured_is_no_oauth(self, client):+ """Without a Slack app configured, say so instead of sending Slack a+ client id it will reject after the user has left the platform."""+ with (+ patch("backend.api.features.mcp.routes.MCPClient") as MockClient,+ patch("backend.api.features.mcp.routes.creds_manager") as mock_cm,+ patch("backend.api.features.mcp.routes.settings") as mock_settings,+ ):+ self._mock_slack_discovery(MockClient)+ mock_cm.store.store_state_token = AsyncMock(+ return_value=("state-abc", "challenge-xyz")+ )+ mock_settings.config.frontend_base_url = "http://localhost:3000"+ mock_settings.secrets.slack_mcp_client_id = ""+ mock_settings.secrets.slack_mcp_client_secret = ""++ response = await client.post(+ "/oauth/login",+ json={"server_url": "https://mcp.slack.com/mcp"},+ )++ assert response.status_code == 400+ detail = response.json()["detail"]+ assert detail["code"] == NO_OAUTH_CODE+ assert detail["message"] == (+ "Sign-in to mcp.slack.com is not set up on this platform yet: the "+ "server only accepts an OAuth app registered with it in advance. "+ "You may need to provide an auth credential manually."+ )+ mock_cm.store.store_state_token.assert_not_called()++ @pytest.mark.parametrize(+ "server_url",+ [+ "https://mcp.slack.com.evil.example/mcp",+ "https://evilmcp.slack.com/mcp",+ "https://[email protected]/mcp",+ "http://mcp.slack.com/mcp",+ ],+ )+ def test_preregistered_client_matches_exact_host(self, server_url):+ secrets = MagicMock(+ slack_mcp_client_id="1234.5678", slack_mcp_client_secret="slack-secret"+ )+ assert preregistered_client(server_url, secrets) is None+ assert preregistered_client("https://mcp.slack.com/mcp", secrets) == (+ "1234.5678",+ "slack-secret",+ )++ @pytest.mark.parametrize(+ "endpoint",+ [+ {"token_endpoint": "http://slack.com/api/oauth.v2.user.access"},+ {"token_endpoint": "https://collector.example/token"},+ {"token_endpoint": "https://slack.com.evil.example/token"},+ {"token_endpoint": "https://[email protected]/token"},+ {"authorization_endpoint": "http://slack.com/oauth/v2_user/authorize"},+ {"authorization_endpoint": "https://evil.example/oauth/authorize"},+ ],+ )+ @pytest.mark.asyncio(loop_scope="session")+ async def test_oauth_login_slack_refuses_untrusted_endpoints(+ self, client, endpoint+ ):+ """The secret is posted to the discovered token endpoint, so a Slack+ sign-in whose endpoints are not Slack's own over HTTPS is refused+ before the secret is stored for the callback."""+ with (+ patch("backend.api.features.mcp.routes.MCPClient") as MockClient,+ patch("backend.api.features.mcp.routes.creds_manager") as mock_cm,+ patch("backend.api.features.mcp.routes.settings") as mock_settings,+ ):+ self._mock_slack_discovery(MockClient, **endpoint)+ mock_cm.store.store_state_token = AsyncMock(+ return_value=("state-abc", "challenge-xyz")+ )+ mock_settings.config.frontend_base_url = "http://localhost:3000"+ mock_settings.secrets.slack_mcp_client_id = "1234.5678"+ mock_settings.secrets.slack_mcp_client_secret = "slack-secret"++ response = await client.post(+ "/oauth/login",+ json={"server_url": "https://mcp.slack.com/mcp"},+ )++ assert response.status_code == 400+ assert "slack-secret" not in response.text+ mock_cm.store.store_state_token.assert_not_called()++ @pytest.mark.parametrize(+ "revocation_endpoint,expected",+ [+ ("https://collector.example/revoke", None),+ ("https://slack.com.evil.example/revoke", None),+ ("https://slack.com/api/auth.revoke", "https://slack.com/api/auth.revoke"),+ ],+ )+ @pytest.mark.asyncio(loop_scope="session")+ async def test_oauth_login_slack_drops_off_host_revocation_endpoint(+ self, client, revocation_endpoint, expected+ ):+ """Revocation authenticates with the client secret too, so an off-host+ revocation endpoint is dropped while sign-in itself still works."""+ with (+ patch("backend.api.features.mcp.routes.MCPClient") as MockClient,+ patch("backend.api.features.mcp.routes.creds_manager") as mock_cm,+ patch("backend.api.features.mcp.routes.settings") as mock_settings,+ ):+ self._mock_slack_discovery(+ MockClient, revocation_endpoint=revocation_endpoint+ )+ mock_cm.store.store_state_token = AsyncMock(+ return_value=("state-abc", "challenge-xyz")+ )+ mock_settings.config.frontend_base_url = "http://localhost:3000"+ mock_settings.secrets.slack_mcp_client_id = "1234.5678"+ mock_settings.secrets.slack_mcp_client_secret = "slack-secret"++ response = await client.post(+ "/oauth/login",+ json={"server_url": "https://mcp.slack.com/mcp"},+ )++ assert response.status_code == 200+ state_metadata = mock_cm.store.store_state_token.call_args.kwargs[+ "state_metadata"+ ]+ assert state_metadata["client_secret"] == "slack-secret"+ assert state_metadata["revoke_url"] == expected++ @pytest.mark.asyncio(loop_scope="session")+ async def test_oauth_login_cleartext_slack_url_never_gets_the_secret(self, client):+ """Over plain HTTP the discovery answer can be rewritten in transit,+ so the platform's Slack app is not used at all."""+ with (+ patch("backend.api.features.mcp.routes.MCPClient") as MockClient,+ patch("backend.api.features.mcp.routes.creds_manager") as mock_cm,+ patch("backend.api.features.mcp.routes.settings") as mock_settings,+ ):+ self._mock_slack_discovery(+ MockClient, token_endpoint="https://collector.example/token"+ )+ mock_cm.store.store_state_token = AsyncMock(+ return_value=("state-abc", "challenge-xyz")+ )+ mock_settings.config.frontend_base_url = "http://localhost:3000"+ mock_settings.secrets.slack_mcp_client_id = "1234.5678"+ mock_settings.secrets.slack_mcp_client_secret = "slack-secret"++ response = await client.post(+ "/oauth/login",+ 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"] == ""+@pytest.mark.asyncio(loop_scope="session")async def test_oauth_login_binds_issuer_and_iss_requirement(self, client):with (diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.pyindex e877108db1..078124aa47 100644--- a/autogpt_platform/backend/backend/util/settings.py+++ b/autogpt_platform/backend/backend/util/settings.py@@ -1333,6 +1333,16 @@ class Secrets(UpdateTrackingModel["Secrets"], BaseSettings):linear_client_id: str = Field(default="", description="Linear client ID")linear_client_secret: str = Field(default="", description="Linear client secret")+ slack_mcp_client_id: str = Field(+ default="",+ description="Client ID of the Slack app used to sign in to Slack's MCP "+ "server (mcp.slack.com). Slack does not support dynamic client "+ "registration, so MCP sign-in to Slack is unavailable until this is set.",+ )+ slack_mcp_client_secret: str = Field(+ default="", description="Client secret of the Slack MCP sign-in app"+ )+todoist_client_id: str = Field(default="", description="Todoist client ID")todoist_client_secret: str = Field(default="", description="Todoist client secret")