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.
feat(platform): support Basic authentication for MCP servers (#14075)
Toran Bruce Richards40eef54403a0
diff --git a/autogpt_platform/backend/backend/api/features/integrations/codex_test.py b/autogpt_platform/backend/backend/api/features/integrations/codex_test.pyindex 12696b5ac1..10d2c61428 100644--- a/autogpt_platform/backend/backend/api/features/integrations/codex_test.py+++ b/autogpt_platform/backend/backend/api/features/integrations/codex_test.py@@ -240,6 +240,7 @@ def test_codex_callback_persists_one_safe_credential():"scopes": [],"username": "[email protected]","host": None,+ "mcp_auth_scheme": None,"is_managed": False,}raw_response = response.textdiff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.pyindex 2f27c65f94..9316538b0b 100644--- a/autogpt_platform/backend/backend/api/features/integrations/router.py+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py@@ -3,7 +3,7 @@ import loggingimport secretsfrom contextlib import suppressfrom datetime import datetime, timedelta, timezone-from typing import TYPE_CHECKING, Annotated, Any, List, Literal+from typing import TYPE_CHECKING, Annotated, Any, List, Literal, TypeGuard, get_argsfrom autogpt_libs.auth import get_optional_user_id, get_user_idfrom fastapi import (@@ -223,6 +223,9 @@ async def _start_codex_login()+MCPAuthScheme = Literal["basic", "bearer"]++class CredentialsMetaResponse(BaseModel):id: strprovider: str@@ -234,6 +237,10 @@ class CredentialsMetaResponse(BaseModel):default=None,description="Host pattern for host-scoped or MCP server URL for MCP credentials",)+ mcp_auth_scheme: MCPAuthScheme | None = Field(+ default=None,+ description="Manual authorization scheme for MCP credentials",+ )is_managed: bool = False@model_validator(mode="before")@@ -255,16 +262,27 @@ class CredentialsMetaResponse(BaseModel):"""Extract host from credential: HostScoped host or MCP server URL."""if isinstance(cred, HostScopedCredentials):return cred.host- if isinstance(cred, OAuth2Credentials) and cred.provider in (- ProviderName.MCP,- ProviderName.MCP.value,- "ProviderName.MCP",- ):+ if _is_mcp_credential(cred):return (cred.metadata or {}).get("mcp_server_url")return None+def _is_mcp_credential(cred: Credentials) -> TypeGuard[OAuth2Credentials]:+ """Whether this is an MCP credential, across the provider spellings in use."""+ return isinstance(cred, OAuth2Credentials) and cred.provider in (+ ProviderName.MCP,+ ProviderName.MCP.value,+ "ProviderName.MCP",+ )++def to_meta_response(cred: Credentials) -> CredentialsMetaResponse:+ mcp_auth_scheme = None+ if _is_mcp_credential(cred):+ stored_scheme = (cred.metadata or {}).get("mcp_auth_scheme")+ if stored_scheme in get_args(MCPAuthScheme):+ mcp_auth_scheme = stored_scheme+return CredentialsMetaResponse(id=cred.id,provider=cred.provider,@@ -273,6 +291,7 @@ def to_meta_response(cred: Credentials) -> CredentialsMetaResponse:scopes=cred.scopes if isinstance(cred, OAuth2Credentials) else None,username=cred.username if isinstance(cred, OAuth2Credentials) else None,host=CredentialsMetaResponse.get_host(cred),+ mcp_auth_scheme=mcp_auth_scheme,is_managed=cred.is_managed,)diff --git a/autogpt_platform/backend/backend/api/features/mcp/routes.py b/autogpt_platform/backend/backend/api/features/mcp/routes.pyindex 4972535886..a13ebc0e33 100644--- a/autogpt_platform/backend/backend/api/features/mcp/routes.py+++ b/autogpt_platform/backend/backend/api/features/mcp/routes.py@@ -13,10 +13,19 @@ from autogpt_libs.auth import get_user_idfrom fastapi import Securityfrom pydantic import BaseModel, Field, SecretStr-from backend.api.features.integrations.router import CredentialsMetaResponse-from backend.blocks.mcp.client import MCPClient, MCPClientError+from backend.api.features.integrations.router import (+ CredentialsMetaResponse,+ to_meta_response,+)+from backend.blocks.mcp.client import (+ MCPClient,+ MCPClientError,+ normalize_mcp_authorization,+)from backend.blocks.mcp.helpers import (auto_lookup_mcp_credential,+ is_manual_mcp_credential,+ mcp_authorization_header,normalize_mcp_url,server_host,)@@ -37,13 +46,23 @@ creds_manager = IntegrationCredentialsManager()# ====================== Tool Discovery ====================== #+# Bounds the per-character scan in `normalize_mcp_authorization`.+_MAX_CREDENTIAL_LENGTH = 8192++class DiscoverToolsRequest(BaseModel):"""Request to discover tools on an MCP server."""server_url: str = Field(description="URL of the MCP server")- auth_token: str | None = Field(+ auth_token: SecretStr | None = Field(default=None,- description="Optional Bearer token for authenticated MCP servers",+ min_length=1,+ max_length=_MAX_CREDENTIAL_LENGTH,+ description=(+ "Optional bare Bearer token, Basic/Bearer value, or complete "+ "Authorization header. Omit the field (or send null) for an "+ "unauthenticated server; an empty string is rejected."+ ),)@@ -76,7 +95,7 @@ async def discover_tools(Connect to an MCP server and return its available tools.If the user has a stored MCP credential for this server URL, it will be- used automatically — no need to pass an explicit auth token.+ used automatically — no need to pass an explicit auth credential."""# Validate URL to prevent SSRF — blocks loopback and private IP ranges.try:@@ -84,17 +103,24 @@ async def discover_tools(except ValueError as e:raise fastapi.HTTPException(status_code=400, detail=f"Invalid server URL: {e}")- auth_token = request.auth_token-- # Auto-use stored MCP credential when no explicit token is provided.- if not auth_token:- best_cred = await auto_lookup_mcp_credential(+ authorization: str | None = None+ explicit_token = (+ request.auth_token.get_secret_value() if request.auth_token else None+ )+ if explicit_token:+ try:+ authorization = normalize_mcp_authorization(explicit_token)+ except ValueError as e:+ raise fastapi.HTTPException(status_code=422, detail=str(e)) from e+ else:+ # Auto-use stored MCP credential when no explicit token is provided.+ stored_credential = await auto_lookup_mcp_credential(user_id, normalize_mcp_url(request.server_url))- if best_cred:- auth_token = best_cred.access_token.get_secret_value()+ if stored_credential:+ authorization = mcp_authorization_header(stored_credential)- client = MCPClient(request.server_url, auth_token=auth_token)+ client = MCPClient(request.server_url, authorization=authorization)try:init_result = await client.initialize()@@ -104,7 +130,7 @@ async def discover_tools(raise fastapi.HTTPException(status_code=401,detail="This MCP server requires authentication. "- "Please provide a valid auth token.",+ "Please provide a valid auth credential.",)raise fastapi.HTTPException(status_code=502, detail=str(e))except MCPClientError as e:@@ -212,7 +238,7 @@ async def mcp_oauth_login(raise fastapi.HTTPException(status_code=400,detail="This MCP server does not advertise OAuth support. "- "You may need to provide an auth token manually.",+ "You may need to provide an auth credential manually.",)authorize_url = metadata["authorization_endpoint"]@@ -232,7 +258,7 @@ async def mcp_oauth_login(client_id = ""client_secret = ""if registration_endpoint:- # Validate the registration endpoint to prevent SSRF via metadata.+ # Validate the registration endpoint from metadata to prevent SSRF.try:await validate_url_host(registration_endpoint)except ValueError:@@ -382,50 +408,53 @@ async def mcp_oauth_callback(await creds_manager.create(user_id, credentials)- return CredentialsMetaResponse(- id=credentials.id,- provider=credentials.provider,- type=credentials.type,- title=credentials.title,- scopes=credentials.scopes,- username=credentials.username,- host=credentials.metadata.get("mcp_server_url"),- )+ return to_meta_response(credentials)-# ======================== Bearer Token ======================== #+# ======================== Manual Authentication ======================== #class MCPStoreTokenRequest(BaseModel):- """Request to store a bearer token for an MCP server that doesn't support OAuth."""+ """Request to store a manual Basic/Bearer credential or Authorization header."""server_url: str = Field(- description="MCP server URL the token authenticates against"+ description="MCP server URL the credential authenticates against")token: SecretStr = Field(- min_length=1, description="Bearer token / API key for the MCP server"+ min_length=1,+ max_length=_MAX_CREDENTIAL_LENGTH,+ description=(+ "Bare Bearer token, Basic/Bearer value, or complete Authorization header"+ ),)@router.post("/token",+ # The summary names the generated client method, so it stays as is.summary="Store a bearer token for an MCP server",+ description=(+ "Store a manually entered MCP credential. Accepts a bare token "+ "(sent as Bearer, unchanged from before), an explicit `Basic <value>` "+ "or `Bearer <value>`, or a complete `Authorization:` header."+ ),)async def mcp_store_token(request: MCPStoreTokenRequest,user_id: Annotated[str, Security(get_user_id)],) -> CredentialsMetaResponse:"""- Store a manually provided bearer token as an MCP credential.+ Store a Basic/Bearer credential or complete Authorization header for an MCP server.Used by the Copilot MCPSetupCard when the server doesn't support the MCPOAuth discovery flow (returns 400 from /oauth/login). Subsequent- ``run_mcp_tool`` calls will automatically pick up the token via+ ``run_mcp_tool`` calls will automatically pick up the credential via``_auto_lookup_credential``."""- token = request.token.get_secret_value().strip()- if not token:- raise fastapi.HTTPException(status_code=422, detail="Token must not be blank.")+ try:+ authorization = normalize_mcp_authorization(request.token.get_secret_value())+ except ValueError as e:+ raise fastapi.HTTPException(status_code=422, detail=str(e)) from e# Validate URL to prevent SSRF — blocks loopback and private IP ranges.try:@@ -437,54 +466,67 @@ async def mcp_store_token(server_url = normalize_mcp_url(request.server_url)hostname = server_host(server_url)- # Collect IDs of old credentials to clean up after successful create.- old_cred_ids: list[str] = []+ # Rotate the existing manual credential in place so saved graphs keep their+ # credential ID. OAuth rows are left alone: rewriting one would drop its+ # refresh token, and deleting one here would not revoke it.+ manual_credentials: list[OAuth2Credentials] = []try:old_creds = await creds_manager.store.get_creds_by_provider(user_id, ProviderName.MCP.value)- old_cred_ids = [- old.id- for old in old_creds- if isinstance(old, OAuth2Credentials)- and normalize_mcp_url((old.metadata or {}).get("mcp_server_url", ""))- == server_url- ]- except Exception:- logger.debug("Could not query old MCP token credentials", exc_info=True)-- credentials = OAuth2Credentials(- provider=ProviderName.MCP.value,- title=f"MCP: {hostname}",- access_token=SecretStr(token),- scopes=[],- metadata={"mcp_server_url": server_url},- )- await creds_manager.create(user_id, credentials)+ for old in old_creds:+ if (+ not isinstance(old, OAuth2Credentials)+ or old.is_managed+ or normalize_mcp_url((old.metadata or {}).get("mcp_server_url", ""))+ != server_url+ ):+ continue+ if is_manual_mcp_credential(old):+ manual_credentials.append(old)+ except Exception as e:+ logger.exception("Could not query existing MCP credentials")+ raise fastapi.HTTPException(+ status_code=503,+ detail="Could not safely update the MCP credential. Please try again.",+ ) from e++ auth_scheme = authorization.split(" ", 1)[0].lower()+ metadata = {"mcp_server_url": server_url, "mcp_auth_scheme": auth_scheme}+ manual_credentials.sort(key=lambda cred: cred.id)+ survivor = manual_credentials[-1] if manual_credentials else None+ superseded_ids = [old.id for old in manual_credentials[:-1]]+ if survivor is not None:+ credentials = survivor.model_copy(+ update={+ "title": f"MCP: {hostname}",+ "username": None,+ "access_token": SecretStr(authorization),+ "access_token_expires_at": None,+ "scopes": [],+ "metadata": metadata,+ }+ )+ await creds_manager.update(user_id, credentials)+ else:+ credentials = OAuth2Credentials(+ provider=ProviderName.MCP.value,+ title=f"MCP: {hostname}",+ access_token=SecretStr(authorization),+ scopes=[],+ metadata=metadata,+ )+ await creds_manager.create(user_id, credentials)- # Only delete old credentials after the new one is safely stored.- for old_id in old_cred_ids:+ # Deleted only after the new credential is stored, and through+ # `creds_manager.delete` so the lock and credentials-changed hook run.+ for old_id in superseded_ids:try:- await creds_manager.store.delete_creds_by_id(user_id, old_id)+ await creds_manager.delete(user_id, old_id)except Exception:- logger.debug("Could not clean up old MCP token credential", exc_info=True)-- return CredentialsMetaResponse(- id=credentials.id,- provider=credentials.provider,- type=credentials.type,- title=credentials.title,- scopes=credentials.scopes,- username=credentials.username,- # Use the full ``mcp_server_url`` for parity with the OAuth callback- # response and with ``to_meta_response``'s ``get_host`` (which reads- # the same metadata key for MCP creds). The list endpoint already- # normalizes both flows to full URL via ``get_host``, so the matching- # logic in ``MCPSetupCard.liveHasCred`` works either way — but- # returning the same shape from POST keeps the contract consistent- # for any consumer that uses the immediate POST response.- host=credentials.metadata.get("mcp_server_url"),- )+ logger.debug("Could not clean up superseded MCP credential", exc_info=True)++ return to_meta_response(credentials)# ======================== Helpers ======================== #diff --git a/autogpt_platform/backend/backend/api/features/mcp/test_routes.py b/autogpt_platform/backend/backend/api/features/mcp/test_routes.pyindex 3b3665f903..77d9dc4c3e 100644--- a/autogpt_platform/backend/backend/api/features/mcp/test_routes.py+++ b/autogpt_platform/backend/backend/api/features/mcp/test_routes.py@@ -116,7 +116,7 @@ class TestDiscoverTools:assert response.status_code == 200MockClient.assert_called_once_with("https://mcp.example.com/mcp",- auth_token="my-secret-token",+ authorization="Bearer my-secret-token",)@pytest.mark.asyncio(loop_scope="session")@@ -155,7 +155,7 @@ class TestDiscoverTools:assert response.status_code == 200MockClient.assert_called_once_with("https://mcp.example.com/mcp",- auth_token="stored-token-123",+ authorization="Bearer stored-token-123",)@pytest.mark.asyncio(loop_scope="session")@@ -483,6 +483,61 @@ class TestStoreToken:assert data["host"] == "https://mcp.example.com/mcp"mock_cm.create.assert_called_once()+ @pytest.mark.asyncio(loop_scope="session")+ async def test_stored_manual_token_is_reused_by_discovery(self, client):+ """A manual token must survive the real auto-lookup path on retry."""+ with patch("backend.api.features.mcp.routes.creds_manager") as mock_cm:+ mock_cm.store.get_creds_by_provider = AsyncMock(return_value=[])+ mock_cm.create = AsyncMock()++ store_response = await client.post(+ "/token",+ json={+ "server_url": "https://mcp.example.com/mcp",+ "token": "Basic encoded-value",+ },+ )++ assert store_response.status_code == 200+ create_call = mock_cm.create.await_args+ assert create_call is not None+ stored_credential = create_call.args[1]+ assert isinstance(stored_credential, OAuth2Credentials)+ assert stored_credential.access_token_expires_at is None++ with (+ patch(+ "backend.blocks.mcp.helpers.IntegrationCredentialsManager"+ ) as manager_cls,+ patch("backend.api.features.mcp.routes.MCPClient") as client_cls,+ ):+ manager = manager_cls.return_value+ manager.store.get_creds_by_provider = AsyncMock(+ return_value=[stored_credential]+ )+ manager.refresh_if_needed = AsyncMock(+ side_effect=AssertionError("manual credentials must not refresh")+ )+ mcp_client = client_cls.return_value+ mcp_client.initialize = AsyncMock(+ return_value={+ "protocolVersion": "2025-03-26",+ "serverInfo": {"name": "test-server"},+ }+ )+ mcp_client.list_tools = AsyncMock(return_value=[])++ discover_response = await client.post(+ "/discover-tools",+ json={"server_url": "https://mcp.example.com/mcp"},+ )++ assert discover_response.status_code == 200+ client_cls.assert_called_once_with(+ "https://mcp.example.com/mcp", authorization="Basic encoded-value"+ )+ manager.refresh_if_needed.assert_not_awaited()+@pytest.mark.asyncio(loop_scope="session")async def test_store_token_blank_rejected(self, client):"""Blank token string (after stripping) should return 422."""@@ -497,7 +552,7 @@ class TestStoreToken:assert response.status_code == 422@pytest.mark.asyncio(loop_scope="session")- async def test_store_token_replaces_old_credential(self, client):+ async def test_store_token_updates_existing_credential_in_place(self, client):old_cred = OAuth2Credentials(provider="mcp",title="MCP: mcp.example.com",@@ -508,7 +563,8 @@ class TestStoreToken:with patch("backend.api.features.mcp.routes.creds_manager") as mock_cm:mock_cm.store.get_creds_by_provider = AsyncMock(return_value=[old_cred])mock_cm.create = AsyncMock()- mock_cm.store.delete_creds_by_id = AsyncMock()+ mock_cm.update = AsyncMock()+ mock_cm.delete = AsyncMock()response = await client.post("/token",@@ -519,9 +575,209 @@ class TestStoreToken:)assert response.status_code == 200- mock_cm.store.delete_creds_by_id.assert_called_once_with(- "test-user-id", old_cred.id+ assert response.json()["id"] == old_cred.id+ mock_cm.create.assert_not_awaited()+ mock_cm.update.assert_awaited_once()+ update_call = mock_cm.update.await_args+ assert update_call is not None+ user_id, updated = update_call.args+ assert user_id == "test-user-id"+ assert updated.id == old_cred.id+ assert updated.access_token.get_secret_value() == "Bearer new-token"+ assert updated.metadata["mcp_auth_scheme"] == "bearer"+ mock_cm.delete.assert_not_awaited()++ @pytest.mark.asyncio(loop_scope="session")+ async def test_store_token_rotates_one_row_and_prunes_duplicates(self, client):+ """Rotation touches exactly one row and lets the duplicates go.++ Every ``update`` is a read-modify-write of the user's whole credential+ set, so updating each duplicate in turn multiplied the writes by the+ number of stale rows and left the row count growing forever.+ """+ old_creds = [+ OAuth2Credentials(+ provider="mcp",+ title=f"MCP credential {index}",+ access_token=SecretStr(f"old-token-{index}"),+ scopes=["existing-scope"],+ metadata={"mcp_server_url": "https://mcp.example.com/mcp"},+ )+ for index in range(2)+ ]+ with patch("backend.api.features.mcp.routes.creds_manager") as mock_cm:+ mock_cm.store.get_creds_by_provider = AsyncMock(return_value=old_creds)+ mock_cm.create = AsyncMock()+ mock_cm.update = AsyncMock()+ mock_cm.delete = AsyncMock()++ response = await client.post(+ "/token",+ json={+ "server_url": "https://mcp.example.com/mcp",+ "token": "Basic encoded-value",+ },+ )++ # `get_creds_by_provider` promises no ordering, so the survivor is+ # picked by an explicit key rather than by position in the response.+ survivor, superseded = sorted(old_creds, key=lambda cred: cred.id)[::-1]++ assert response.status_code == 200+ assert response.json()["id"] == survivor.id+ assert response.json()["mcp_auth_scheme"] == "basic"+ mock_cm.create.assert_not_awaited()+ mock_cm.update.assert_awaited_once()+ assert mock_cm.update.await_args is not None+ updated = mock_cm.update.await_args.args[1]+ assert updated.id == survivor.id+ assert updated.access_token.get_secret_value() == "Basic encoded-value"+ # A static pasted credential carries no OAuth scopes.+ assert updated.scopes == []+ mock_cm.delete.assert_awaited_once_with("test-user-id", superseded.id)++ @pytest.mark.asyncio(loop_scope="session")+ async def test_store_token_replaces_an_oauth_credential_instead_of_converting_it(+ self, client+ ):+ """An OAuth row is neither rewritten in place nor deleted.++ Rewriting one would keep its id and ``type="oauth2"`` while discarding+ the refresh token and the client registration behind it, so a saved+ graph would silently start running on a pasted static secret.++ Deleting it is no better: neither ``creds_manager.delete`` nor+ ``delete_acquired`` calls ``handler.revoke_tokens`` -- that lives in+ ``DELETE /credentials`` -- so the row would go while a live refresh+ token stayed at the provider with nothing left to revoke it with, and+ every saved graph node bound to its id would break. The manual+ credential wins in ``auto_lookup_mcp_credential`` instead.+ """+ oauth_cred = OAuth2Credentials(+ provider="mcp",+ title="MCP: mcp.example.com",+ access_token=SecretStr("oauth-access"),+ refresh_token=SecretStr("oauth-refresh"),+ scopes=["read"],+ metadata={+ "mcp_server_url": "https://mcp.example.com/mcp",+ "mcp_token_url": "https://mcp.example.com/token",+ "mcp_client_id": "client-abc",+ },)+ with patch("backend.api.features.mcp.routes.creds_manager") as mock_cm:+ mock_cm.store.get_creds_by_provider = AsyncMock(return_value=[oauth_cred])+ mock_cm.create = AsyncMock()+ mock_cm.update = AsyncMock()+ mock_cm.delete = AsyncMock()++ response = await client.post(+ "/token",+ json={+ "server_url": "https://mcp.example.com/mcp",+ "token": "pasted-token",+ },+ )++ assert response.status_code == 200+ mock_cm.update.assert_not_awaited()+ mock_cm.create.assert_awaited_once()+ assert mock_cm.create.await_args is not None+ created = mock_cm.create.await_args.args[1]+ assert created.id != oauth_cred.id+ assert created.refresh_token is None+ assert created.scopes == []+ mock_cm.delete.assert_not_awaited()++ @pytest.mark.asyncio(loop_scope="session")+ async def test_store_token_clears_stale_expiry_on_rotation(self, client):+ """Positive guard: a rotated manual credential must not stay expiring.++ Deleting the clearing left every assertion green, because only the+ negative "refresh is not attempted" case was covered.+ """+ old_cred = OAuth2Credentials(+ provider="mcp",+ title="MCP: mcp.example.com",+ access_token=SecretStr("old-token"),+ access_token_expires_at=1,+ username="someone",+ scopes=[],+ metadata={"mcp_server_url": "https://mcp.example.com/mcp"},+ )+ with patch("backend.api.features.mcp.routes.creds_manager") as mock_cm:+ mock_cm.store.get_creds_by_provider = AsyncMock(return_value=[old_cred])+ mock_cm.create = AsyncMock()+ mock_cm.update = AsyncMock()+ mock_cm.delete = AsyncMock()++ response = await client.post(+ "/token",+ json={+ "server_url": "https://mcp.example.com/mcp",+ "token": "new-token",+ },+ )++ assert response.status_code == 200+ assert mock_cm.update.await_args is not None+ updated = mock_cm.update.await_args.args[1]+ assert updated.access_token_expires_at is None+ assert updated.username is None++ @pytest.mark.asyncio(loop_scope="session")+ async def test_store_token_does_not_mutate_managed_matching_credential(+ self, client+ ):+ managed = OAuth2Credentials(+ provider="mcp",+ title="Managed MCP",+ access_token=SecretStr("managed-token"),+ scopes=[],+ metadata={"mcp_server_url": "https://mcp.example.com/mcp"},+ is_managed=True,+ )+ with patch("backend.api.features.mcp.routes.creds_manager") as mock_cm:+ mock_cm.store.get_creds_by_provider = AsyncMock(return_value=[managed])+ mock_cm.create = AsyncMock()+ mock_cm.update = AsyncMock()++ response = await client.post(+ "/token",+ json={+ "server_url": "https://mcp.example.com/mcp",+ "token": "user-token",+ },+ )++ assert response.status_code == 200+ mock_cm.update.assert_not_awaited()+ mock_cm.create.assert_awaited_once()+ create_call = mock_cm.create.await_args+ assert create_call is not None+ created = create_call.args[1]+ assert created.id != managed.id++ @pytest.mark.asyncio(loop_scope="session")+ async def test_store_token_fails_closed_when_existing_lookup_fails(self, client):+ with patch("backend.api.features.mcp.routes.creds_manager") as mock_cm:+ mock_cm.store.get_creds_by_provider = AsyncMock(+ side_effect=RuntimeError("database unavailable")+ )+ mock_cm.create = AsyncMock()+ mock_cm.update = AsyncMock()++ response = await client.post(+ "/token",+ json={+ "server_url": "https://mcp.example.com/mcp",+ "token": "new-token",+ },+ )++ assert response.status_code == 503+ mock_cm.create.assert_not_awaited()+ mock_cm.update.assert_not_awaited()class TestSSRFValidation:diff --git a/autogpt_platform/backend/backend/blocks/mcp/block.py b/autogpt_platform/backend/backend/blocks/mcp/block.pyindex de628a194f..8948f07b1a 100644--- a/autogpt_platform/backend/backend/blocks/mcp/block.py+++ b/autogpt_platform/backend/backend/blocks/mcp/block.py@@ -21,6 +21,7 @@ from backend.blocks._base import (from backend.blocks.mcp.client import MCPClient, MCPClientErrorfrom backend.blocks.mcp.helpers import (auto_lookup_mcp_credential,+ mcp_authorization_header,normalize_mcp_url,parse_mcp_content,)@@ -172,10 +173,10 @@ class MCPToolBlock(Block):server_url: str,tool_name: str,arguments: dict[str, Any],- auth_token: str | None = None,+ authorization: str | None = None,) -> Any:"""Call a tool on the MCP server. Extracted for easy mocking in tests."""- client = MCPClient(server_url, auth_token=auth_token)+ client = MCPClient(server_url, authorization=authorization)await client.initialize()result = await client.call_tool(tool_name, arguments)@@ -226,9 +227,12 @@ class MCPToolBlock(Block):if required:missing = required - set(input_data.tool_arguments.keys())if missing:- yield "error", (- f"Missing required argument(s): {', '.join(sorted(missing))}. "- f"Please fill in all required fields marked with * in the block form."+ yield (+ "error",+ (+ f"Missing required argument(s): {', '.join(sorted(missing))}. "+ f"Please fill in all required fields marked with * in the block form."+ ),)return@@ -240,16 +244,14 @@ class MCPToolBlock(Block):user_id, normalize_mcp_url(input_data.server_url))- auth_token = (- credentials.access_token.get_secret_value() if credentials else None- )+ authorization = mcp_authorization_header(credentials) if credentials else Nonetry:result = await self._call_mcp_tool(server_url=input_data.server_url,tool_name=input_data.selected_tool,arguments=input_data.tool_arguments,- auth_token=auth_token,+ authorization=authorization,)yield "result", resultexcept MCPClientError as e:diff --git a/autogpt_platform/backend/backend/blocks/mcp/client.py b/autogpt_platform/backend/backend/blocks/mcp/client.pyindex 6272c81d83..aceb14b46d 100644--- a/autogpt_platform/backend/backend/blocks/mcp/client.py+++ b/autogpt_platform/backend/backend/blocks/mcp/client.py@@ -18,6 +18,66 @@ from backend.util.request import Requestslogger = logging.getLogger(__name__)+_SUPPORTED_AUTH_SCHEMES = {+ "basic": "Basic",+ "bearer": "Bearer",+}+++def normalize_mcp_authorization(value: str) -> str:+ """Turn a user-supplied credential into a canonical Authorization value.++ Accepts a bare token (sent as Bearer for backward compatibility), an+ explicit ``Basic``/``Bearer`` prefix, or a complete ``Authorization:``+ header. Runs once, where user input enters the system; stored values go+ through ``helpers.mcp_authorization_header`` and are never re-parsed.+ """+ candidate = value.strip()+ if any(ord(character) < 32 or ord(character) == 127 for character in candidate):+ raise ValueError("Authentication credential must be a single line.")+ if not candidate:+ raise ValueError("Authentication credential must not be blank.")++ header_name, separator, header_value = candidate.partition(":")+ included_header_name = (+ bool(separator) and header_name.strip().casefold() == "authorization"+ )+ if included_header_name:+ candidate = header_value.strip()+ if not candidate:+ raise ValueError("Authorization header must include a credential.")++ parts = candidate.split(None, 1)+ scheme_key = parts[0].casefold()+ known_scheme = scheme_key in _SUPPORTED_AUTH_SCHEMES+ remainder = parts[1].strip() if len(parts) == 2 else ""+ if known_scheme and remainder:+ scheme = _SUPPORTED_AUTH_SCHEMES[scheme_key]+ credential = remainder+ elif known_scheme:+ scheme_name = _SUPPORTED_AUTH_SCHEMES[scheme_key]+ raise ValueError(f"{scheme_name} authentication requires a credential.")+ elif included_header_name:+ raise ValueError(+ "Authorization header must use Basic or Bearer authentication."+ )+ else:+ scheme = "Bearer"+ credential = candidate++ if scheme == "Basic":+ # RFC 7617: the wire value is Base64 of user:password, so neither+ # character can appear in a valid credential.+ if ":" in credential:+ raise ValueError(+ "Basic authentication expects the Base64 of user:password, "+ "not the pair itself."+ )+ if " " in credential:+ raise ValueError("A Basic credential must not contain spaces.")++ return f"{scheme} {credential}"+@dataclassclass MCPTool:@@ -47,18 +107,19 @@ class MCPClient:Async HTTP client for the MCP Streamable HTTP transport.Communicates with MCP servers using JSON-RPC 2.0 over HTTP POST.- Supports optional Bearer token authentication.+ ``authorization`` is sent verbatim as the ``Authorization`` header; callers+ pass an already-canonical value."""def __init__(self,server_url: str,- auth_token: str | None = None,+ authorization: str | None = None,):from backend.blocks.mcp.helpers import normalize_mcp_urlself.server_url = normalize_mcp_url(server_url)- self.auth_token = auth_token+ self.authorization = authorizationself._request_id = 0self._session_id: str | None = None@@ -71,8 +132,8 @@ class MCPClient:"Content-Type": "application/json","Accept": "application/json, text/event-stream",}- if self.auth_token:- headers["Authorization"] = f"Bearer {self.auth_token}"+ if self.authorization:+ headers["Authorization"] = self.authorizationif self._session_id:headers["Mcp-Session-Id"] = self._session_idreturn headersdiff --git a/autogpt_platform/backend/backend/blocks/mcp/helpers.py b/autogpt_platform/backend/backend/blocks/mcp/helpers.pyindex 863463484f..a350488b1b 100644--- a/autogpt_platform/backend/backend/blocks/mcp/helpers.py+++ b/autogpt_platform/backend/backend/blocks/mcp/helpers.py@@ -37,6 +37,34 @@ def server_host(server_url: str) -> str:return server_url+def is_manual_mcp_credential(credentials: OAuth2Credentials) -> bool:+ """Whether an MCP credential was pasted by the user rather than obtained via OAuth.++ Manual credentials are ``OAuth2Credentials`` rows with no refresh token and+ no OAuth client metadata, so they must not be refreshed or rewritten as if+ they were OAuth grants.+ """+ metadata = credentials.metadata or {}+ return (+ credentials.refresh_token is None+ and not metadata.get("mcp_token_url")+ and not metadata.get("mcp_client_id")+ )+++def mcp_authorization_header(credentials: OAuth2Credentials) -> str:+ """Build the Authorization value for a *stored* MCP credential.++ Reads the scheme from metadata and never re-parses the secret. Rows with+ ``mcp_auth_scheme`` hold a canonical ``"<Scheme> <credential>"``; older+ rows hold a bare token that was always sent as Bearer.+ """+ token = credentials.access_token.get_secret_value()+ if (credentials.metadata or {}).get("mcp_auth_scheme"):+ return token+ return f"Bearer {token}"++def parse_mcp_content(content: list[dict[str, Any]]) -> Any:"""Parse MCP tool response content into a plain Python value.@@ -116,32 +144,34 @@ async def auto_lookup_mcp_credential(so the comparison with ``mcp_server_url`` in credential metadata matches.Returns the credential with the latest ``access_token_expires_at``, refreshed- if needed, or ``None`` when no match is found.+ if it can expire and needs it, or ``None`` when no match is found."""try:mgr = IntegrationCredentialsManager()mcp_creds = await mgr.store.get_creds_by_provider(user_id, ProviderName.MCP.value)- # Collect all matching credentials and pick the best one.- # Primary sort: latest access_token_expires_at (tokens with expiry- # are preferred over non-expiring ones). Secondary sort: last in- # iteration order, which corresponds to the most recently created- # row — this acts as a tiebreaker when multiple bearer tokens have- # no expiry (e.g. after a failed old-credential cleanup).++ # Best match: a manually pasted credential outranks an OAuth row, then+ # the latest expiry, then the last row in iteration order.+ def rank(cred: OAuth2Credentials) -> tuple[int, float]:+ return (+ 1 if is_manual_mcp_credential(cred) else 0,+ cred.access_token_expires_at or 0,+ )+best: OAuth2Credentials | None = Nonefor cred in mcp_creds:if (isinstance(cred, OAuth2Credentials)and (cred.metadata or {}).get("mcp_server_url") == server_url):- if best is None or (- (cred.access_token_expires_at or 0)- >= (best.access_token_expires_at or 0)- ):+ if best is None or rank(cred) >= rank(best):best = cred- if best:+ # Manual credentials have no token endpoint to refresh against.+ if best and not is_manual_mcp_credential(best):best = await mgr.refresh_if_needed(user_id, best)+ if best:logger.info("Auto-resolved MCP credential %s for %s", best.id, server_url)return bestexcept Exception:diff --git a/autogpt_platform/backend/backend/blocks/mcp/mcp_auth_cases.json b/autogpt_platform/backend/backend/blocks/mcp/mcp_auth_cases.jsonnew file mode 100644index 0000000000..acf1598a26--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/mcp/mcp_auth_cases.json@@ -0,0 +1,154 @@+{+ "$comment": [+ "Shared contract for reading a pasted MCP credential, asserted by both",+ "backend/blocks/mcp/test_auth_schemes.py and frontend/src/lib/mcp-auth.test.ts.",+ "scheme: the explicit scheme a value carries, or null for a bare credential.",+ "canonical: what the backend stores and sends. The frontend skips the",+ "canonical check for headerForm inputs, which it passes through verbatim."+ ],+ "accepted": [+ {+ "input": "sk-abc123",+ "scheme": null,+ "canonical": "Bearer sk-abc123"+ },+ {+ "input": " sk-abc123 ",+ "scheme": null,+ "canonical": "Bearer sk-abc123"+ },+ {+ "input": "sk-abc123\n",+ "scheme": null,+ "canonical": "Bearer sk-abc123"+ },+ {+ "input": "token:with:colons",+ "scheme": null,+ "canonical": "Bearer token:with:colons"+ },+ {+ "input": "orgid api-key",+ "scheme": null,+ "canonical": "Bearer orgid api-key"+ },+ {+ "input": "bearerish-token",+ "scheme": null,+ "canonical": "Bearer bearerish-token"+ },+ {+ "input": "Bearer sk-abc123",+ "scheme": "bearer",+ "canonical": "Bearer sk-abc123"+ },+ {+ "input": "BEARER sk-abc123",+ "scheme": "bearer",+ "canonical": "Bearer sk-abc123"+ },+ {+ "input": " Bearer sk-abc123 ",+ "scheme": "bearer",+ "canonical": "Bearer sk-abc123"+ },+ {+ "input": "Bearer orgid api-key",+ "scheme": "bearer",+ "canonical": "Bearer orgid api-key"+ },+ {+ "input": "basic dXNlcjpwYXNzd29yZA==",+ "scheme": "basic",+ "canonical": "Basic dXNlcjpwYXNzd29yZA=="+ },+ {+ "input": "Authorization: Basic dXNlcjpwYXNzd29yZA==",+ "scheme": "basic",+ "canonical": "Basic dXNlcjpwYXNzd29yZA==",+ "headerForm": true+ },+ {+ "input": "Authorization : Basic dXNlcjpwYXNzd29yZA==",+ "scheme": "basic",+ "canonical": "Basic dXNlcjpwYXNzd29yZA==",+ "headerForm": true+ },+ {+ "input": "AUTHORIZATION:bearer sk-abc123",+ "scheme": "bearer",+ "canonical": "Bearer sk-abc123",+ "headerForm": true+ }+ ],+ "rejectedByBackend": [+ {+ "input": "",+ "reason": "blank"+ },+ {+ "input": " ",+ "reason": "blank"+ },+ {+ "input": "Bearer",+ "reason": "scheme word with no credential"+ },+ {+ "input": "Basic",+ "reason": "scheme word with no credential"+ },+ {+ "input": "Authorization:",+ "reason": "header with no credential"+ },+ {+ "input": "Authorization : ",+ "reason": "header with no credential"+ },+ {+ "input": "Authorization: Basic",+ "reason": "header with no credential"+ },+ {+ "input": "Authorization: Bearer",+ "reason": "header with no credential"+ },+ {+ "input": "Authorization: Digest abc",+ "reason": "complete header naming an unsupported scheme"+ },+ {+ "input": "sk-abc\nX-Injected: 1",+ "reason": "interior newline"+ },+ {+ "input": "Bearer token\rX-Evil: 1",+ "reason": "interior carriage return"+ },+ {+ "input": "Bearer token\tX-Evil: 1",+ "reason": "interior tab"+ },+ {+ "input": "Bearer token\u0000X-Evil: 1",+ "reason": "interior NUL"+ },+ {+ "input": "Bearer token\u001fX-Evil: 1",+ "reason": "interior C0 control"+ },+ {+ "input": "Bearer token\u007fX-Evil: 1",+ "reason": "interior DEL"+ },+ {+ "input": "Basic user:password",+ "reason": "unencoded user:password stored as a working Basic credential"+ },+ {+ "input": "Basic dXNlcjpw YXNz",+ "reason": "Base64 alphabet contains no space"+ }+ ]+}diff --git a/autogpt_platform/backend/backend/blocks/mcp/test_auth_schemes.py b/autogpt_platform/backend/backend/blocks/mcp/test_auth_schemes.pynew file mode 100644index 0000000000..410ead6230--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/mcp/test_auth_schemes.py@@ -0,0 +1,252 @@+"""Focused tests for MCP manual authentication schemes."""++import json+import pathlib+from collections.abc import AsyncGenerator+from unittest.mock import AsyncMock, MagicMock, patch++import fastapi+import httpx+import pytest+import pytest_asyncio+from autogpt_libs.auth import get_user_id+from pydantic import SecretStr++from backend.api.features.mcp.routes import router+from backend.blocks.mcp.block import TEST_CREDENTIALS_INPUT, MCPToolBlock+from backend.blocks.mcp.client import MCPClient, normalize_mcp_authorization+from backend.blocks.mcp.helpers import mcp_authorization_header+from backend.data.model import OAuth2Credentials+from backend.executor.utils import _validate_node_input_credentials++_AUTH_CASES = json.loads(+ (pathlib.Path(__file__).parent / "mcp_auth_cases.json").read_text()+)+++ "case", _AUTH_CASES["accepted"], ids=lambda case: repr(case["input"])+)+def test_shared_auth_cases_are_normalized_as_the_frontend_reads_them(+ case: dict,+) -> None:+ """Same table as ``frontend/src/lib/mcp-auth.test.ts``."""+ assert normalize_mcp_authorization(case["input"]) == case["canonical"]+++ "case", _AUTH_CASES["rejectedByBackend"], ids=lambda case: repr(case["input"])+)+def test_shared_auth_cases_that_must_be_rejected(case: dict) -> None:+ with pytest.raises(ValueError):+ normalize_mcp_authorization(case["input"])+++def test_mcp_client_sends_the_authorization_it_was_given() -> None:+ for authorization in (+ "Basic cGstbGYtYWJjZA==",+ "Bearer legacy-token",+ "Bearer orgid api-key",+ ):+ client = MCPClient("https://mcp.example.com/mcp", authorization=authorization)+ assert client._build_headers()["Authorization"] == authorization+++def test_stored_credential_round_trips_without_double_prefixing() -> None:+ stored = OAuth2Credentials(+ provider="mcp",+ title="MCP: mcp.example.com",+ access_token=SecretStr(normalize_mcp_authorization("orgid api-key")),+ scopes=[],+ metadata={+ "mcp_server_url": "https://mcp.example.com/mcp",+ "mcp_auth_scheme": "bearer",+ },+ )+ client = MCPClient(+ "https://mcp.example.com/mcp",+ authorization=mcp_authorization_header(stored),+ )+ assert client._build_headers()["Authorization"] == "Bearer orgid api-key"+++def test_legacy_row_without_scheme_metadata_is_sent_as_bearer() -> None:+ legacy = OAuth2Credentials(+ provider="mcp",+ title="MCP: mcp.example.com",+ access_token=SecretStr("basic auth key"),+ scopes=[],+ metadata={"mcp_server_url": "https://mcp.example.com/mcp"},+ )+ assert mcp_authorization_header(legacy) == "Bearer basic auth key"+++def test_mcp_client_omits_auth_when_not_provided() -> None:+ client = MCPClient("https://mcp.example.com/mcp")+ assert "Authorization" not in client._build_headers()+++ "input_default",+ [{}, {"credentials": TEST_CREDENTIALS_INPUT}],+ ids=["anonymous", "bound-credential"],+)+async def test_schema_optional_mcp_credentials_do_not_skip_execution(+ input_default: dict,+) -> None:+ """MCP's schema-level optional credential must not skip the whole node."""+ node = MagicMock()+ node.id = "mcp-node"+ node.block = MCPToolBlock()+ node.credentials_optional = False+ node.input_default = input_default+ graph = MagicMock(nodes=[node])++ errors, nodes_to_skip = await _validate_node_input_credentials(+ graph=graph,+ user_id="test-user-id",+ nodes_input_masks=None,+ )++ assert errors == {}+ assert nodes_to_skip == set()+++app = fastapi.FastAPI()+app.include_router(router)+app.dependency_overrides[get_user_id] = lambda: "test-user-id"+++@pytest_asyncio.fixture(scope="module")+async def client() -> AsyncGenerator[httpx.AsyncClient, None]:+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as c:+ yield c++[email protected](loop_scope="session")+async def test_discover_rejects_empty_explicit_auth_token(+ client: httpx.AsyncClient,+) -> None:+ with patch(+ "backend.api.features.mcp.routes.auto_lookup_mcp_credential",+ new_callable=AsyncMock,+ ) as lookup_credential:+ response = await client.post(+ "/discover-tools",+ json={+ "server_url": "https://mcp.example.com/mcp",+ "auth_token": "",+ },+ )++ assert response.status_code == 422+ lookup_credential.assert_not_awaited()++[email protected](loop_scope="session")+ ("token", "expected", "scheme"),+ [+ (+ "Authorization: Basic cGstbGYtYWJjZA==",+ "Basic cGstbGYtYWJjZA==",+ "basic",+ ),+ ("orgid api-key", "Bearer orgid api-key", "bearer"),+ ],+)+async def test_store_manual_credential(+ client: httpx.AsyncClient,+ token: str,+ expected: str,+ scheme: str,+) -> None:+ with (+ patch(+ "backend.api.features.mcp.routes.validate_url_host",+ new_callable=AsyncMock,+ ),+ patch("backend.api.features.mcp.routes.creds_manager") as mock_cm,+ ):+ create_credential = AsyncMock()+ mock_cm.store.get_creds_by_provider = AsyncMock(return_value=[])+ mock_cm.create = create_credential++ response = await client.post(+ "/token",+ json={+ "server_url": "https://mcp.example.com/mcp",+ "token": token,+ },+ )++ assert response.status_code == 200+ create_credential.assert_awaited_once()+ create_call = create_credential.await_args+ assert create_call is not None+ created = create_call.args[1]+ assert created.access_token.get_secret_value() == expected+ assert created.metadata["mcp_auth_scheme"] == scheme+ assert response.json()["mcp_auth_scheme"] == scheme++[email protected](loop_scope="session")+async def test_store_rejects_header_injection(client: httpx.AsyncClient) -> None:+ with patch(+ "backend.api.features.mcp.routes.validate_url_host",+ new_callable=AsyncMock,+ ) as validate_url_host:+ response = await client.post(+ "/token",+ json={+ "server_url": "https://mcp.example.com/mcp",+ "token": "Bearer token\nX-Evil: injected",+ },+ )++ assert response.status_code == 422+ assert "single line" in response.json()["detail"].lower()+ validate_url_host.assert_not_awaited()+++async def test_block_uses_the_credential_it_was_given():+ block = MCPToolBlock()+ credentials = OAuth2Credentials(+ provider="mcp",+ title="MCP: mcp.example.com",+ access_token=SecretStr("Basic cWE6YmFzaWM="),+ scopes=[],+ metadata={+ "mcp_server_url": "https://mcp.example.com/mcp",+ "mcp_auth_scheme": "basic",+ },+ )++ with (+ patch.object(block, "_call_mcp_tool", new_callable=AsyncMock) as call_tool,+ patch(+ "backend.blocks.mcp.block.auto_lookup_mcp_credential",+ new_callable=AsyncMock,+ ) as auto_lookup,+ ):+ call_tool.return_value = "ok"+ outputs = [+ output+ async for output in block.run(+ MCPToolBlock.Input(+ server_url="https://mcp.example.com/mcp",+ selected_tool="a_tool",+ tool_arguments={},+ ),+ user_id="test-user-id",+ credentials=credentials,+ )+ ]++ auto_lookup.assert_not_awaited()+ assert call_tool.await_args is not None+ assert call_tool.await_args.kwargs["authorization"] == "Basic cWE6YmFzaWM="+ assert ("result", "ok") in outputsdiff --git a/autogpt_platform/backend/backend/blocks/mcp/test_helpers.py b/autogpt_platform/backend/backend/blocks/mcp/test_helpers.pyindex f04f8b5a53..e43600fcbc 100644--- a/autogpt_platform/backend/backend/blocks/mcp/test_helpers.py+++ b/autogpt_platform/backend/backend/blocks/mcp/test_helpers.py@@ -1,6 +1,18 @@"""Unit tests for the shared MCP helpers."""-from backend.blocks.mcp.helpers import normalize_mcp_url, parse_mcp_content, server_host+from unittest.mock import AsyncMock, patch++import pytest+from pydantic import SecretStr++from backend.blocks.mcp.helpers import (+ auto_lookup_mcp_credential,+ is_manual_mcp_credential,+ normalize_mcp_url,+ parse_mcp_content,+ server_host,+)+from backend.data.model import OAuth2Credentials# ---------------------------------------------------------------------------# normalize_mcp_url@@ -96,3 +108,130 @@ def test_parse_multi_item():def test_parse_empty():assert parse_mcp_content([]) is None+++# ---------------------------------------------------------------------------+# is_manual_mcp_credential / auto_lookup_mcp_credential refresh gate+# ---------------------------------------------------------------------------+++def _mcp_credential(**overrides) -> OAuth2Credentials:+ fields: dict = {+ "provider": "mcp",+ "title": "MCP: mcp.example.com",+ "access_token": SecretStr("token"),+ "scopes": [],+ "metadata": {"mcp_server_url": "https://mcp.example.com/mcp"},+ }+ fields.update(overrides)+ return OAuth2Credentials(**fields)+++def test_manual_credential_is_distinguished_from_oauth():+ manual = _mcp_credential()+ oauth = _mcp_credential(+ refresh_token=SecretStr("refresh"),+ metadata={+ "mcp_server_url": "https://mcp.example.com/mcp",+ "mcp_token_url": "https://mcp.example.com/token",+ "mcp_client_id": "client-abc",+ },+ )+ assert is_manual_mcp_credential(manual) is True+ assert is_manual_mcp_credential(oauth) is False+++def test_oauth_metadata_alone_marks_a_credential_as_non_manual():+ """A row with client registration but no refresh token is still OAuth's."""+ assert (+ is_manual_mcp_credential(+ _mcp_credential(+ metadata={+ "mcp_server_url": "https://mcp.example.com/mcp",+ "mcp_token_url": "https://mcp.example.com/token",+ }+ )+ )+ is False+ )+++async def test_expiring_credential_is_refreshed():+ """Positive guard for the refresh gate.++ Only the negative case ("a manual credential is never refreshed") was+ covered, so deleting the ``refresh_if_needed`` call entirely left the+ whole backend suite green.+ """+ expiring = _mcp_credential(+ access_token_expires_at=1,+ refresh_token=SecretStr("refresh"),+ metadata={+ "mcp_server_url": "https://mcp.example.com/mcp",+ "mcp_token_url": "https://mcp.example.com/token",+ },+ )+ refreshed = _mcp_credential(access_token=SecretStr("refreshed-token"))++ with patch(+ "backend.blocks.mcp.helpers.IntegrationCredentialsManager"+ ) as manager_cls:+ manager = manager_cls.return_value+ manager.store.get_creds_by_provider = AsyncMock(return_value=[expiring])+ manager.refresh_if_needed = AsyncMock(return_value=refreshed)++ result = await auto_lookup_mcp_credential(+ "test-user-id", "https://mcp.example.com/mcp"+ )++ manager.refresh_if_needed.assert_awaited_once()+ assert result is not None+ assert result.access_token.get_secret_value() == "refreshed-token"+++async def test_a_manual_credential_outranks_a_surviving_oauth_row():+ """Ranking by expiry alone pinned execution to a stale OAuth grant.++ A manual credential never has an ``access_token_expires_at``, so+ ``cred.access_token_expires_at or 0`` made it lose to *any* OAuth row for+ the same server. Storing a manual credential leaves the OAuth row in place+ (deleting it there would orphan the refresh token at the provider), and the+ supersede loop swallows delete failures, so this is reachable rather than+ theoretical: the user pastes a working credential, all three UIs probe it+ and report "Connected", and every execution still goes out on the old token.+ """+ oauth = _mcp_credential(+ access_token=SecretStr("oauth-token"),+ access_token_expires_at=2_000_000_000,+ refresh_token=SecretStr("refresh"),+ metadata={+ "mcp_server_url": "https://mcp.example.com/mcp",+ "mcp_token_url": "https://mcp.example.com/token",+ "mcp_client_id": "client-abc",+ },+ )+ manual = _mcp_credential(+ access_token=SecretStr("Basic encoded-value"),+ metadata={+ "mcp_server_url": "https://mcp.example.com/mcp",+ "mcp_auth_scheme": "basic",+ },+ )++ with patch(+ "backend.blocks.mcp.helpers.IntegrationCredentialsManager"+ ) as manager_cls:+ manager = manager_cls.return_value+ manager.store.get_creds_by_provider = AsyncMock(return_value=[oauth, manual])+ manager.refresh_if_needed = AsyncMock()++ result = await auto_lookup_mcp_credential(+ "test-user-id", "https://mcp.example.com/mcp"+ )++ assert result is not None+ assert result.id == manual.id+ # And a manual credential is never put through the OAuth refresh path.+ manager.refresh_if_needed.assert_not_awaited()diff --git a/autogpt_platform/backend/backend/blocks/mcp/test_integration.py b/autogpt_platform/backend/backend/blocks/mcp/test_integration.pyindex 70658dbaaf..601de28900 100644--- a/autogpt_platform/backend/backend/blocks/mcp/test_integration.py+++ b/autogpt_platform/backend/backend/blocks/mcp/test_integration.py@@ -112,7 +112,8 @@ def _allow_localhost():def _make_client(url: str, auth_token: str | None = None) -> MCPClient:"""Create an MCPClient for integration tests."""- return MCPClient(url, auth_token=auth_token)+ authorization = f"Bearer {auth_token}" if auth_token else None+ return MCPClient(url, authorization=authorization)# ── MCPClient integration tests ──────────────────────────────────────diff --git a/autogpt_platform/backend/backend/blocks/mcp/test_mcp.py b/autogpt_platform/backend/backend/blocks/mcp/test_mcp.pyindex 8cb49b0fee..d0a5632b85 100644--- a/autogpt_platform/backend/backend/blocks/mcp/test_mcp.py+++ b/autogpt_platform/backend/backend/blocks/mcp/test_mcp.py@@ -18,11 +18,7 @@ class TestSSEParsing:"""Tests for SSE (text/event-stream) response parsing."""def test_parse_sse_simple(self):- sse = (- "event: message\n"- 'data: {"jsonrpc":"2.0","result":{"tools":[]},"id":1}\n'- "\n"- )+ sse = 'event: message\ndata: {"jsonrpc":"2.0","result":{"tools":[]},"id":1}\n\n'body = MCPClient._parse_sse_response(sse)assert body["result"] == {"tools": []}assert body["id"] == 1@@ -94,7 +90,7 @@ class TestMCPClient:assert headers["Content-Type"] == "application/json"def test_build_headers_with_auth(self):- client = MCPClient("https://mcp.example.com", auth_token="my-token")+ client = MCPClient("https://mcp.example.com", authorization="Bearer my-token")headers = client._build_headers()assert headers["Authorization"] == "Bearer my-token"@@ -572,8 +568,8 @@ class TestMCPToolBlock:captured_tokens: list[str | None] = []- async def mock_call(server_url, tool_name, arguments, auth_token=None):- captured_tokens.append(auth_token)+ async def mock_call(server_url, tool_name, arguments, authorization=None):+ captured_tokens.append(authorization)return "ok"block._call_mcp_tool = mock_call # type: ignore@@ -592,7 +588,7 @@ class TestMCPToolBlock:):pass- assert captured_tokens == ["resolved-token"]+ assert captured_tokens == ["Bearer resolved-token"]@pytest.mark.asyncio(loop_scope="session")async def test_run_without_credentials(self):@@ -605,8 +601,8 @@ class TestMCPToolBlock:captured_tokens: list[str | None] = []- async def mock_call(server_url, tool_name, arguments, auth_token=None):- captured_tokens.append(auth_token)+ async def mock_call(server_url, tool_name, arguments, authorization=None):+ captured_tokens.append(authorization)return "ok"block._call_mcp_tool = mock_call # type: ignorediff --git a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.pyindex b8efb11159..29fc4fce5f 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py@@ -10,6 +10,7 @@ from backend.blocks.mcp.client import MCPClient, MCPClientErrorfrom backend.blocks.mcp.helpers import (auto_lookup_mcp_credential,invalidate_mcp_credential,+ mcp_authorization_header,normalize_mcp_url,parse_mcp_content,server_host,@@ -215,7 +216,11 @@ class RunMCPToolTool(BaseTool):# Fast DB lookup — no network call.# Normalize for matching because stored credentials use normalized URLs.creds = await auto_lookup_mcp_credential(user_id, normalize_mcp_url(server_url))- auth_token = creds.access_token.get_secret_value() if creds else None+ client = (+ MCPClient(server_url, authorization=mcp_authorization_header(creds))+ if creds is not None+ else None+ )# "Just connect" intent: return only the setup card so the user# gets a visible Connect/Reconnect affordance even when there's@@ -236,8 +241,8 @@ class RunMCPToolTool(BaseTool):# real tool call will self-correct via the same invalidate path.if surface_connect_card:connected = creds is not None- if creds is not None:- probe_client = MCPClient(server_url, auth_token=auth_token)+ if client is not None and creds is not None:+ probe_client = clienttry:try:await probe_client.initialize()@@ -278,7 +283,8 @@ class RunMCPToolTool(BaseTool):server_url, session_id, connected=connected)- client = MCPClient(server_url, auth_token=auth_token)+ if client is None:+ client = MCPClient(server_url)try:await client.initialize()diff --git a/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py b/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.pyindex d7093f7c95..68f87c6f06 100644--- a/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py+++ b/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py@@ -8,6 +8,7 @@ from pydantic import SecretStrfrom backend.blocks.mcp.helpers import server_hostfrom backend.copilot.sdk.file_ref import FileRefExpansionError+from backend.data.model import OAuth2Credentialsfrom ._test_data import make_sessionfrom .models import (@@ -160,11 +161,6 @@ async def test_non_dict_tool_arguments_returns_error():assert "json object" in response.message.lower()-# ----------------------------------------------------------------------------# Stage 1 — Discovery-# -----------------------------------------------------------------------------@pytest.mark.asyncio(loop_scope="session")async def test_discover_tools_returns_discovered_response():"""Calling with only server_url triggers discovery and returns tool list."""@@ -204,12 +200,22 @@ async def test_discover_tools_returns_discovered_response():@pytest.mark.asyncio(loop_scope="session")async def test_discover_tools_with_credentials():- """Stored credentials are passed as Bearer token to MCPClient."""+ """A legacy stored credential is sent as a Bearer header.++ A real credential rather than a ``MagicMock``: the header is built from+ ``mcp_auth_scheme`` metadata, and a mock answers every attribute lookup+ truthily, which silently exercises the wrong branch.+ """tool = RunMCPToolTool()session = make_session(_USER_ID)- mock_creds = MagicMock()- mock_creds.access_token = SecretStr("test-token-abc")+ mock_creds = OAuth2Credentials(+ provider="mcp",+ title="MCP: remote.mcpservers.org",+ access_token=SecretStr("test-token-abc"),+ scopes=[],+ metadata={"mcp_server_url": _SERVER_URL},+ )mock_tools = _make_tool_list("push_notification")with patch(@@ -232,9 +238,9 @@ async def test_discover_tools_with_credentials():session=session,server_url=_SERVER_URL,)- # Verify MCPClient was created with the resolved auth token+ # Verify MCPClient was created with the resolved auth headerMockMCPClient.assert_called_once_with(- _SERVER_URL, auth_token="test-token-abc"+ _SERVER_URL, authorization="Bearer test-token-abc")assert isinstance(response, MCPToolsDiscoveredResponse)@@ -1213,17 +1219,22 @@ async def test_agptfile_ref_expanded_before_mcp_call():schema = {"type": "object", "properties": {"content": {"type": "string"}}}tool_schema = _make_tool_schema("notion-update-page", schema)- with patch(- "backend.copilot.tools.run_mcp_tool.validate_url_host", new_callable=AsyncMock- ), patch(- "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",- new_callable=AsyncMock,- return_value=None,- ), patch(- "backend.copilot.tools.run_mcp_tool.expand_file_refs_in_args",- new_callable=AsyncMock,- return_value=expanded,- ) as mock_expand:+ with (+ patch(+ "backend.copilot.tools.run_mcp_tool.validate_url_host",+ new_callable=AsyncMock,+ ),+ patch(+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",+ new_callable=AsyncMock,+ return_value=None,+ ),+ patch(+ "backend.copilot.tools.run_mcp_tool.expand_file_refs_in_args",+ new_callable=AsyncMock,+ return_value=expanded,+ ) as mock_expand,+ ):mock_client = AsyncMock()mock_client.list_tools = AsyncMock(return_value=[tool_schema])mock_client.call_tool = AsyncMock(@@ -1259,16 +1270,21 @@ async def test_agptfile_expansion_failure_returns_error():tool = RunMCPToolTool()session = make_session(_USER_ID)- with patch(- "backend.copilot.tools.run_mcp_tool.validate_url_host", new_callable=AsyncMock- ), patch(- "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",- new_callable=AsyncMock,- return_value=None,- ), patch(- "backend.copilot.tools.run_mcp_tool.expand_file_refs_in_args",- new_callable=AsyncMock,- side_effect=FileRefExpansionError("missing.md not found"),+ with (+ patch(+ "backend.copilot.tools.run_mcp_tool.validate_url_host",+ new_callable=AsyncMock,+ ),+ patch(+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",+ new_callable=AsyncMock,+ return_value=None,+ ),+ patch(+ "backend.copilot.tools.run_mcp_tool.expand_file_refs_in_args",+ new_callable=AsyncMock,+ side_effect=FileRefExpansionError("missing.md not found"),+ ),):mock_client = AsyncMock()mock_client.list_tools = AsyncMock(return_value=[])@@ -1296,12 +1312,16 @@ async def test_no_agptfile_ref_skips_schema_lookup():session = make_session(_USER_ID)raw_args = {"url": "https://example.com"}- with patch(- "backend.copilot.tools.run_mcp_tool.validate_url_host", new_callable=AsyncMock- ), patch(- "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",- new_callable=AsyncMock,- return_value=None,+ with (+ patch(+ "backend.copilot.tools.run_mcp_tool.validate_url_host",+ new_callable=AsyncMock,+ ),+ patch(+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",+ new_callable=AsyncMock,+ return_value=None,+ ),):mock_client = AsyncMock()mock_client.list_tools = AsyncMock(return_value=[])diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/MCPToolDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/MCPToolDialog.tsxindex 3b17510495..3d0415b0d6 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/MCPToolDialog.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/MCPToolDialog.tsx@@ -27,9 +27,28 @@ import {postV2DiscoverAvailableToolsOnAnMcpServer,postV2InitiateOauthLoginForAnMcpServer,postV2ExchangeOauthCodeForMcpTokens,+ postV2StoreABearerTokenForAnMcpServer,} from "@/app/api/__generated__/endpoints/mcp/mcp";import { openOAuthPopup } from "@/lib/oauth-popup";import { CredentialsProvidersContext } from "@/providers/agent-credentials/credentials-provider";+import { MCPAuthSchemeField } from "@/components/contextual/MCPAuthSchemeField/MCPAuthSchemeField";+import {+ mcpAuthTokenHint,+ mcpAuthTokenLabel,+ mcpAuthTokenPlaceholder,+} from "@/components/contextual/MCPAuthSchemeField/helpers";+import { useMCPAuthScheme } from "@/components/contextual/MCPAuthSchemeField/useMCPAuthScheme";+import {+ prepareMCPAuthCredential,+ validateMCPAuthCredential,+ type MCPAuthScheme,+} from "@/lib/mcp-auth";+import {+ getAPIResponseError,+ getErrorMessage,+ getErrorStatus,+} from "@/lib/mcp-errors";+import { mcpServerIdentity, normalizeMcpUrl } from "@/lib/mcp-url";import { ArrowDown01Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";@@ -39,7 +58,7 @@ export type MCPToolDialogResult = {selectedTool: string;toolInputSchema: Record<string, any>;availableTools: Record<string, any>;- /** Credentials meta from OAuth flow, null for public servers. */+ /** Credentials meta from the completed authentication flow, null for public servers. */credentials: CredentialsMetaInput | null;};@@ -74,6 +93,24 @@ export function MCPToolDialog({const [credentials, setCredentials] = useState<CredentialsMetaInput | null>(null,);+ const [credentialServerUrl, setCredentialServerUrl] = useState<string | null>(+ null,+ );++ const storedAuthScheme: MCPAuthScheme =+ allProviders?.["mcp"]?.savedCredentials.find(+ (credential) =>+ typeof credential.host === "string" &&+ normalizeMcpUrl(credential.host) === normalizeMcpUrl(serverUrl),+ )?.mcp_auth_scheme === "basic"+ ? "basic"+ : "bearer";+ const {+ scheme: manualAuthScheme,+ selectScheme,+ detectSchemeFrom,+ resetScheme,+ } = useMCPAuthScheme(storedAuthScheme, manualToken);const startOAuthRef = useRef(false);const oauthAbortRef = useRef<((reason?: string) => void) | null>(null);@@ -91,6 +128,7 @@ export function MCPToolDialog({setStep("url");setServerUrl("");setManualToken("");+ resetScheme();setTools([]);setServerName(null);setLoading(false);@@ -100,51 +138,139 @@ export function MCPToolDialog({setShowManualToken(false);setSelectedTool(null);setCredentials(null);- }, []);+ setCredentialServerUrl(null);+ }, [resetScheme]);const handleClose = useCallback(() => {reset();onClose();}, [reset, onClose]);- const discoverTools = useCallback(async (url: string, authToken?: string) => {- setLoading(true);- setError(null);- try {- const response = await postV2DiscoverAvailableToolsOnAnMcpServer({- server_url: url,- auth_token: authToken || null,- });- if (response.status !== 200) throw response.data;+ const applyDiscoveredTools = useCallback(+ (response: {+ data: {+ tools: MCPToolResponse[];+ server_name?: string | null;+ };+ }) => {setTools(response.data.tools);setServerName(response.data.server_name ?? null);setAuthRequired(false);setShowManualToken(false);+ setManualToken("");+ resetScheme();setStep("tool");- } catch (e: any) {- if (e?.status === 401 || e?.status === 403) {- setAuthRequired(true);- setError(null);- // Automatically start OAuth sign-in instead of requiring a second click+ },+ [resetScheme],+ );++ const discoverTools = useCallback(+ async (url: string) => {+ setLoading(true);+ setError(null);+ try {+ const response = await postV2DiscoverAvailableToolsOnAnMcpServer({+ server_url: url,+ auth_token: null,+ });+ if (response.status !== 200) {+ throw getAPIResponseError(response.status, response.data);+ }+ applyDiscoveredTools(response);+ } catch (error: unknown) {+ const status = getErrorStatus(error);+ if (status === 401 || status === 403) {+ setAuthRequired(true);+ setError(null);+ // Automatically start OAuth sign-in instead of requiring a second click+ setLoading(false);+ startOAuthRef.current = true;+ return;+ }+ setError(getErrorMessage(error, "Failed to connect to MCP server"));+ } finally {setLoading(false);- startOAuthRef.current = true;- return;+ }+ },+ [applyDiscoveredTools],+ );++ const connectWithManualCredential = useCallback(async () => {+ const url = serverUrl.trim();+ const credential = manualToken.trim();+ if (!url || !credential) return;++ const invalid = validateMCPAuthCredential(credential, manualAuthScheme);+ if (invalid) {+ setError(invalid);+ return;+ }++ setLoading(true);+ setError(null);+ try {+ const authValue = prepareMCPAuthCredential(credential, manualAuthScheme);++ // Probe before storing so a rejected credential never replaces a working one.+ const toolsResponse = await postV2DiscoverAvailableToolsOnAnMcpServer({+ server_url: url,+ auth_token: authValue,+ });+ if (toolsResponse.status !== 200) {+ throw getAPIResponseError(toolsResponse.status, toolsResponse.data);+ }++ // Store through the provider so the builder can resolve the new ID.+ const mcpProvider = allProviders?.["mcp"];+ let storedCredential;+ if (mcpProvider) {+ storedCredential = await mcpProvider.mcpStoreToken(url, authValue);} else {- const message =- e?.message || e?.detail || "Failed to connect to MCP server";- setError(- typeof message === "string" ? message : JSON.stringify(message),- );+ const credentialResponse = await postV2StoreABearerTokenForAnMcpServer({+ server_url: url,+ token: authValue,+ });+ if (credentialResponse.status !== 200) {+ throw getAPIResponseError(+ credentialResponse.status,+ credentialResponse.data,+ );+ }+ storedCredential = credentialResponse.data;}++ setCredentials({+ id: storedCredential.id,+ provider: storedCredential.provider,+ type: storedCredential.type,+ title: storedCredential.title,+ });+ setCredentialServerUrl(url);++ applyDiscoveredTools(toolsResponse);+ } catch (error: unknown) {+ setError(+ getErrorMessage(error, "Failed to connect with this credential"),+ );} finally {setLoading(false);}- }, []);+ }, [+ allProviders,+ applyDiscoveredTools,+ manualAuthScheme,+ manualToken,+ serverUrl,+ ]);const handleDiscoverTools = useCallback(() => {if (!serverUrl.trim()) return;- discoverTools(serverUrl.trim(), manualToken.trim() || undefined);- }, [serverUrl, manualToken, discoverTools]);+ if (showManualToken) {+ void connectWithManualCredential();+ return;+ }+ void discoverTools(serverUrl.trim());+ }, [connectWithManualCredential, discoverTools, serverUrl, showManualToken]);const handleOAuthSignIn = useCallback(async () => {if (!serverUrl.trim()) return;@@ -159,7 +285,9 @@ export function MCPToolDialog({const loginResponse = await postV2InitiateOauthLoginForAnMcpServer({server_url: serverUrl.trim(),});- if (loginResponse.status !== 200) throw loginResponse.data;+ if (loginResponse.status !== 200) {+ throw getAPIResponseError(loginResponse.status, loginResponse.data);+ }const { login_url, state_token } = loginResponse.data;const { promise, cleanup } = openOAuthPopup(login_url, {@@ -186,7 +314,9 @@ export function MCPToolDialog({code: result.code,state_token,});- if (cbResponse.status !== 200) throw cbResponse.data;+ if (cbResponse.status !== 200) {+ throw getAPIResponseError(cbResponse.status, cbResponse.data);+ }callbackResult = cbResponse.data;}@@ -196,51 +326,48 @@ export function MCPToolDialog({type: callbackResult.type,title: callbackResult.title,});+ setCredentialServerUrl(serverUrl.trim());setAuthRequired(false);// Discover tools now that we're authenticatedconst toolsResponse = await postV2DiscoverAvailableToolsOnAnMcpServer({server_url: serverUrl.trim(),});- if (toolsResponse.status !== 200) throw toolsResponse.data;- setTools(toolsResponse.data.tools);- setServerName(toolsResponse.data.server_name ?? null);- setStep("tool");- } catch (e: any) {+ if (toolsResponse.status !== 200) {+ throw getAPIResponseError(toolsResponse.status, toolsResponse.data);+ }+ applyDiscoveredTools(toolsResponse);+ } catch (error: unknown) {+ const status = getErrorStatus(error);+ const message = getErrorMessage(error, "Failed to complete sign-in");// If server doesn't support OAuth → show manual token entry- if (e?.status === 400) {+ if (status === 400) {setShowManualToken(true);setError(- "This server does not support OAuth sign-in. Please enter a token manually.",+ "This server does not support OAuth sign-in. Choose how its API credential should be sent.",);- } else if (e?.message === "OAuth flow timed out") {+ } else if (message === "OAuth flow timed out") {setError("OAuth sign-in timed out. Please try again.");- } else {- const status = e?.status;- let message: string;- if (status === 401 || status === 403) {- message =- "Authentication succeeded but the server still rejected the request. " +- "The token audience may not match. Please try again.";- } else {- message = e?.message || e?.detail || "Failed to complete sign-in";- }+ } else if (status === 401 || status === 403) {setError(- typeof message === "string" ? message : JSON.stringify(message),+ "Authentication succeeded but the server still rejected the request. " ++ "The token audience may not match. Please try again.",);+ } else {+ setError(message);}} finally {setOauthLoading(false);setLoading(false);oauthAbortRef.current = null;}- }, [serverUrl, allProviders]);+ }, [serverUrl, allProviders, applyDiscoveredTools]);// Auto-start OAuth sign-in when server returns 401/403useEffect(() => {if (authRequired && startOAuthRef.current) {startOAuthRef.current = false;- handleOAuthSignIn();+ void handleOAuthSignIn();}}, [authRequired, handleOAuthSignIn]);@@ -261,7 +388,8 @@ export function MCPToolDialog({selectedTool: selectedTool.name,toolInputSchema: selectedTool.input_schema,availableTools,- credentials,+ credentials:+ credentialServerUrl === serverUrl.trim() ? credentials : null,});reset();}, [@@ -270,6 +398,7 @@ export function MCPToolDialog({serverUrl,serverName,credentials,+ credentialServerUrl,onConfirm,reset,]);@@ -299,8 +428,27 @@ export function MCPToolDialog({type="url"placeholder="https://mcp.example.com/mcp"value={serverUrl}- onChange={(e) => setServerUrl(e.target.value)}+ onChange={(e) => {+ const nextUrl = e.target.value;+ // Only a change of server identity discards the credential.+ const serverChanged =+ mcpServerIdentity(serverUrl) !== mcpServerIdentity(nextUrl);+ setServerUrl(nextUrl);+ if (!serverChanged) return;++ if (credentialServerUrl !== nextUrl.trim()) {+ setCredentials(null);+ setCredentialServerUrl(null);+ }+ setManualToken("");+ resetScheme();+ setAuthRequired(false);+ setShowManualToken(false);+ setError(null);+ startOAuthRef.current = false;+ }}onKeyDown={(e) => e.key === "Enter" && handleDiscoverTools()}+ disabled={loading || oauthLoading}autoFocus/></div>@@ -309,31 +457,57 @@ export function MCPToolDialog({{authRequired && !showManualToken && (<buttononClick={() => setShowManualToken(true)}- className="text-xs text-gray-500 underline hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"+ className="text-xs text-gray-500 underline hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200">- or enter a token manually+ or enter an API credential manually</button>)}- {/* Manual token entry — only visible when expanded */}+ {/* Manual credential entry — only visible when expanded */}{showManualToken && (<div className="flex flex-col gap-2">+ <MCPAuthSchemeField+ value={manualAuthScheme}+ onChange={selectScheme}+ disabled={loading || oauthLoading}+ className="flex flex-col gap-2"+ labelClassName="text-sm font-medium"+ selectClassName="h-10 rounded-md border border-input bg-background px-3 text-sm"+ />+<Label htmlFor="mcp-auth-token" className="text-sm">- Bearer Token+ {mcpAuthTokenLabel(manualAuthScheme)}</Label><Inputid="mcp-auth-token"+ aria-describedby="mcp-auth-token-hint"type="password"- placeholder="Paste your auth token here"+ placeholder={mcpAuthTokenPlaceholder(manualAuthScheme)}value={manualToken}- onChange={(e) => setManualToken(e.target.value)}+ onChange={(e) => {+ const value = e.target.value;+ setManualToken(value);+ detectSchemeFrom(value);+ }}onKeyDown={(e) => e.key === "Enter" && handleDiscoverTools()}+ disabled={loading || oauthLoading}autoFocus/>+ <p id="mcp-auth-token-hint" className="text-xs text-gray-500">+ {mcpAuthTokenHint(manualAuthScheme)}+ </p></div>)}- {error && <p className="text-sm text-red-500">{error}</p>}+ {error && (+ <p+ role="alert"+ aria-live="polite"+ className="text-sm text-red-700 dark:text-red-400"+ >+ {error}+ </p>+ )}</div>)}@@ -374,7 +548,12 @@ export function MCPToolDialog({? handleOAuthSignIn: handleDiscoverTools}- disabled={!serverUrl.trim() || loading || oauthLoading}+ disabled={+ !serverUrl.trim() ||+ loading ||+ oauthLoading ||+ (showManualToken && !manualToken.trim())+ }>{loading || oauthLoading ? (<span className="flex items-center gap-2">@@ -383,6 +562,8 @@ export function MCPToolDialog({</span>) : authRequired && !showManualToken ? ("Sign in & Connect"+ ) : showManualToken ? (+ "Connect & Discover") : ("Discover Tools")}diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/__tests__/MCPToolDialog.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/__tests__/MCPToolDialog.test.tsxnew file mode 100644index 0000000000..f10aab85dc--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/__tests__/MCPToolDialog.test.tsx@@ -0,0 +1,360 @@+import {+ fireEvent,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";+import { beforeEach, describe, expect, it, vi } from "vitest";++import {+ CredentialsProvidersContext,+ type CredentialsProvidersContextType,+} from "@/providers/agent-credentials/credentials-provider";++import { MCPToolDialog } from "../MCPToolDialog";++vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({+ postV2DiscoverAvailableToolsOnAnMcpServer: vi.fn(),+ postV2InitiateOauthLoginForAnMcpServer: vi.fn(),+ postV2ExchangeOauthCodeForMcpTokens: vi.fn(),+ postV2StoreABearerTokenForAnMcpServer: vi.fn(),+}));++vi.mock("@/lib/oauth-popup", () => ({+ openOAuthPopup: vi.fn(),+}));++const PRIVATE_SERVER_URL = "https://private.example.com/mcp";+const PUBLIC_SERVER_URL = "https://public.example.com/mcp";+const CREDENTIAL = {+ id: "credential-id",+ provider: "mcp",+ type: "oauth2",+ title: "private.example.com",+};+const PRIVATE_TOOL = {+ name: "private-tool",+ description: "A private tool",+ input_schema: { type: "object", properties: {} },+};+const PUBLIC_TOOL = {+ name: "public-tool",+ description: "A public tool",+ input_schema: { type: "object", properties: {} },+};++function apiResponse(status: number, data: unknown) {+ return { status, data, headers: new Headers() } as never;+}++async function connectPrivateServer() {+ const {+ postV2DiscoverAvailableToolsOnAnMcpServer,+ postV2InitiateOauthLoginForAnMcpServer,+ postV2StoreABearerTokenForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");++ vi.mocked(postV2DiscoverAvailableToolsOnAnMcpServer)+ .mockResolvedValueOnce(+ apiResponse(401, { detail: "Authentication required" }),+ )+ .mockResolvedValueOnce(+ apiResponse(200, {+ tools: [PRIVATE_TOOL],+ server_name: "Private Server",+ }),+ );+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce(+ apiResponse(400, { detail: "OAuth not supported" }),+ );+ vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce(+ apiResponse(200, CREDENTIAL),+ );++ fireEvent.change(screen.getByLabelText("Server URL"), {+ target: { value: PRIVATE_SERVER_URL },+ });+ fireEvent.click(screen.getByRole("button", { name: "Discover Tools" }));++ const tokenInput = await screen.findByLabelText("API token");+ fireEvent.change(tokenInput, { target: { value: "private-secret" } });+ fireEvent.click(screen.getByRole("button", { name: "Connect & Discover" }));++ await screen.findByRole("button", { name: /private-tool/i });+}++describe("MCPToolDialog credential binding", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("attaches a manually stored credential to a tool from the same server", async () => {+ const {+ postV2DiscoverAvailableToolsOnAnMcpServer,+ postV2StoreABearerTokenForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");+ const onConfirm = vi.fn();+ render(<MCPToolDialog open onClose={() => {}} onConfirm={onConfirm} />);++ await connectPrivateServer();+ fireEvent.click(screen.getByRole("button", { name: /private-tool/i }));+ fireEvent.click(screen.getByRole("button", { name: "Add Block" }));++ expect(onConfirm).toHaveBeenCalledWith(+ expect.objectContaining({+ serverUrl: PRIVATE_SERVER_URL,+ selectedTool: PRIVATE_TOOL.name,+ credentials: CREDENTIAL,+ }),+ );+ expect(postV2DiscoverAvailableToolsOnAnMcpServer).toHaveBeenNthCalledWith(+ 2,+ {+ server_url: PRIVATE_SERVER_URL,+ auth_token: "Bearer private-secret",+ },+ );+ expect(postV2StoreABearerTokenForAnMcpServer).toHaveBeenCalledWith({+ server_url: PRIVATE_SERVER_URL,+ token: "Bearer private-secret",+ });+ });++ it("stores a manual credential through the credentials provider", async () => {+ // Storing via the endpoint directly leaves the provider map without the+ // credential the node is about to be bound to, and the builder renders+ // that binding as "was removed" until the next page load.+ const { postV2StoreABearerTokenForAnMcpServer } = await import(+ "@/app/api/__generated__/endpoints/mcp/mcp"+ );+ const mcpStoreToken = vi.fn().mockResolvedValue(CREDENTIAL);+ const providers = {+ mcp: { mcpStoreToken, savedCredentials: [] },+ } as unknown as CredentialsProvidersContextType;+ const onConfirm = vi.fn();++ render(+ <CredentialsProvidersContext.Provider value={providers}>+ <MCPToolDialog open onClose={() => {}} onConfirm={onConfirm} />+ </CredentialsProvidersContext.Provider>,+ );++ await connectPrivateServer();+ fireEvent.click(screen.getByRole("button", { name: /private-tool/i }));+ fireEvent.click(screen.getByRole("button", { name: "Add Block" }));++ expect(mcpStoreToken).toHaveBeenCalledWith(+ PRIVATE_SERVER_URL,+ "Bearer private-secret",+ );+ expect(postV2StoreABearerTokenForAnMcpServer).not.toHaveBeenCalled();+ expect(onConfirm).toHaveBeenCalledWith(+ expect.objectContaining({ credentials: CREDENTIAL }),+ );+ });++ it("sends a Basic credential with the selected scheme", async () => {+ // Hardcoding "bearer" at the prepare call survived the whole dialog suite:+ // no Basic case existed on this surface.+ const {+ postV2DiscoverAvailableToolsOnAnMcpServer,+ postV2StoreABearerTokenForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");+ const { postV2InitiateOauthLoginForAnMcpServer } = await import(+ "@/app/api/__generated__/endpoints/mcp/mcp"+ );++ vi.mocked(postV2DiscoverAvailableToolsOnAnMcpServer)+ .mockResolvedValueOnce(+ apiResponse(401, { detail: "Authentication required" }),+ )+ .mockResolvedValueOnce(+ apiResponse(200, {+ tools: [PRIVATE_TOOL],+ server_name: "Private Server",+ }),+ );+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce(+ apiResponse(400, { detail: "OAuth not supported" }),+ );+ vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce(+ apiResponse(200, CREDENTIAL),+ );++ render(<MCPToolDialog open onClose={() => {}} onConfirm={vi.fn()} />);++ fireEvent.change(screen.getByLabelText("Server URL"), {+ target: { value: PRIVATE_SERVER_URL },+ });+ fireEvent.click(screen.getByRole("button", { name: "Discover Tools" }));++ await screen.findByLabelText("Authentication type");+ fireEvent.change(screen.getByLabelText("Authentication type"), {+ target: { value: "basic" },+ });+ fireEvent.change(screen.getByLabelText("Basic authentication token"), {+ target: { value: "cGstbGYtYWJjZA==" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Connect & Discover" }));++ await screen.findByRole("button", { name: /private-tool/i });+ expect(postV2StoreABearerTokenForAnMcpServer).toHaveBeenCalledWith({+ server_url: PRIVATE_SERVER_URL,+ token: "Basic cGstbGYtYWJjZA==",+ });+ });++ it("seeds the selector from the scheme already stored for the server", async () => {+ // This dialog was the only surface that never read `mcp_auth_scheme`, so+ // reconnecting a Basic credential silently downgraded it to Bearer.+ const {+ postV2DiscoverAvailableToolsOnAnMcpServer,+ postV2InitiateOauthLoginForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");+ vi.mocked(postV2DiscoverAvailableToolsOnAnMcpServer).mockResolvedValueOnce(+ apiResponse(401, { detail: "Authentication required" }),+ );+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce(+ apiResponse(400, { detail: "OAuth not supported" }),+ );++ const providers = {+ mcp: {+ savedCredentials: [+ {+ id: "c1",+ provider: "mcp",+ type: "oauth2",+ title: "MCP",+ host: PRIVATE_SERVER_URL,+ mcp_auth_scheme: "basic",+ },+ ],+ },+ } as unknown as CredentialsProvidersContextType;++ render(+ <CredentialsProvidersContext.Provider value={providers}>+ <MCPToolDialog open onClose={() => {}} onConfirm={vi.fn()} />+ </CredentialsProvidersContext.Provider>,+ );++ fireEvent.change(screen.getByLabelText("Server URL"), {+ target: { value: PRIVATE_SERVER_URL },+ });+ fireEvent.click(screen.getByRole("button", { name: "Discover Tools" }));++ const select = (await screen.findByLabelText(+ "Authentication type",+ )) as HTMLSelectElement;+ expect(select.value).toBe("basic");+ });++ it("does not store a manual credential rejected by discovery", async () => {+ const {+ postV2DiscoverAvailableToolsOnAnMcpServer,+ postV2InitiateOauthLoginForAnMcpServer,+ postV2StoreABearerTokenForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");+ vi.mocked(postV2DiscoverAvailableToolsOnAnMcpServer)+ .mockResolvedValueOnce(+ apiResponse(401, { detail: "Authentication required" }),+ )+ .mockResolvedValueOnce(+ apiResponse(401, { detail: "Invalid API credential" }),+ );+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce(+ apiResponse(400, { detail: "OAuth not supported" }),+ );++ render(<MCPToolDialog open onClose={() => {}} onConfirm={() => {}} />);++ fireEvent.change(screen.getByLabelText("Server URL"), {+ target: { value: PRIVATE_SERVER_URL },+ });+ fireEvent.click(screen.getByRole("button", { name: "Discover Tools" }));++ const tokenInput = await screen.findByLabelText("API token");+ fireEvent.change(tokenInput, { target: { value: "invalid-secret" } });+ fireEvent.click(screen.getByRole("button", { name: "Connect & Discover" }));++ expect(await screen.findByText("Invalid API credential")).toBeDefined();+ expect(postV2StoreABearerTokenForAnMcpServer).not.toHaveBeenCalled();+ });++ it("keeps the typed credential while the path of the same server is edited", async () => {+ const {+ postV2DiscoverAvailableToolsOnAnMcpServer,+ postV2InitiateOauthLoginForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");+ vi.mocked(postV2DiscoverAvailableToolsOnAnMcpServer).mockResolvedValueOnce(+ apiResponse(401, { detail: "Authentication required" }),+ );+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce(+ apiResponse(400, { detail: "OAuth not supported" }),+ );++ render(<MCPToolDialog open onClose={() => {}} onConfirm={() => {}} />);++ const urlInput = screen.getByLabelText("Server URL");+ fireEvent.change(urlInput, {+ target: { value: "https://private.example.com" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Discover Tools" }));++ const tokenInput = await screen.findByLabelText("API token");+ fireEvent.change(tokenInput, { target: { value: "secret-token" } });++ // Appending the `/mcp` suffix one character at a time. The reset guard+ // compared trimmed URLs, so every one of these keystrokes cleared the+ // credential and collapsed the panel, forcing another discover → 401 →+ // OAuth-probe round trip to get back to where the user already was.+ for (const url of [+ "https://private.example.com/",+ "https://private.example.com/m",+ "https://private.example.com/mc",+ PRIVATE_SERVER_URL,+ ]) {+ fireEvent.change(urlInput, { target: { value: url } });+ }++ expect((screen.getByLabelText("API token") as HTMLInputElement).value).toBe(+ "secret-token",+ );+ });++ it("does not reuse a credential after changing to a public server", async () => {+ const { postV2DiscoverAvailableToolsOnAnMcpServer } = await import(+ "@/app/api/__generated__/endpoints/mcp/mcp"+ );+ const onConfirm = vi.fn();+ render(<MCPToolDialog open onClose={() => {}} onConfirm={onConfirm} />);++ await connectPrivateServer();+ fireEvent.click(screen.getByRole("button", { name: "Back" }));+ fireEvent.change(screen.getByLabelText("Server URL"), {+ target: { value: PUBLIC_SERVER_URL },+ });+ vi.mocked(postV2DiscoverAvailableToolsOnAnMcpServer).mockResolvedValueOnce(+ apiResponse(200, {+ tools: [PUBLIC_TOOL],+ server_name: "Public Server",+ }),+ );++ fireEvent.click(screen.getByRole("button", { name: "Discover Tools" }));+ await screen.findByRole("button", { name: /public-tool/i });+ fireEvent.click(screen.getByRole("button", { name: /public-tool/i }));+ fireEvent.click(screen.getByRole("button", { name: "Add Block" }));++ await waitFor(() => {+ expect(onConfirm).toHaveBeenCalledWith(+ expect.objectContaining({+ serverUrl: PUBLIC_SERVER_URL,+ selectedTool: PUBLIC_TOOL.name,+ credentials: null,+ }),+ );+ });+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/McpConnectorRow.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/McpConnectorRow.tsxindex a93f6d3a4a..c7e70e1687 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/McpConnectorRow.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/McpConnectorRow.tsx@@ -3,8 +3,19 @@import { Button } from "@/components/atoms/Button/Button";import { Icon } from "@/components/atoms/Icon/Icon";import { ProviderAvatar } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ProviderAvatar";+import { MCPAuthSchemeField } from "@/components/contextual/MCPAuthSchemeField/MCPAuthSchemeField";+import {+ mcpAuthTokenHint,+ mcpAuthTokenLabel,+ mcpAuthTokenPlaceholder,+} from "@/components/contextual/MCPAuthSchemeField/helpers";+import { useMCPAuthScheme } from "@/components/contextual/MCPAuthSchemeField/useMCPAuthScheme";+import {+ prepareMCPAuthCredential,+ validateMCPAuthCredential,+} from "@/lib/mcp-auth";import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";-import { useState } from "react";+import { useId, useState } from "react";import type { McpConnectorRequest } from "./helpers";function hostOf(serverUrl: string): string | null {@@ -19,7 +30,15 @@ function hostOf(serverUrl: string): string | null {* ConnectorRow but connects through the MCP OAuth/token flow the hidden* MCPSetupCard drives via the request callbacks. */export function McpConnectorRow({ request }: { request: McpConnectorRequest }) {+ const hintId = useId();+ const errorId = useId();const [token, setToken] = useState("");+ const [validationError, setValidationError] = useState<string | null>(null);+ const {+ scheme: authScheme,+ selectScheme,+ detectSchemeFrom,+ } = useMCPAuthScheme(request.authScheme, token);const host = hostOf(request.serverUrl);// "mcp.notion.com" → "notion" so existing /integrations/*.png icons// resolve; unknown services fall back to the avatar's initial.@@ -28,6 +47,15 @@ export function McpConnectorRow({ request }: { request: McpConnectorRequest }) {.split(".")[0].toLowerCase();+ function submitCredential() {+ const message = validateMCPAuthCredential(token, authScheme);+ setValidationError(message);+ if (message) return;++ const credential = prepareMCPAuthCredential(token, authScheme);+ if (credential) request.onUseToken(credential);+ }+return (<div className="flex flex-col"><div className="flex items-center gap-3 px-4 py-3">@@ -69,29 +97,61 @@ export function McpConnectorRow({ request }: { request: McpConnectorRequest }) {)}{request.showManualToken && !request.connected && (- <div className="mx-4 mb-3 flex gap-2">- <input- type="password"- aria-label={`API token for ${request.service}`}- placeholder="Paste API token"- value={token}- onChange={(e) => setToken(e.target.value)}- onKeyDown={(e) =>- e.key === "Enter" &&- !request.loading &&- token.trim() &&- request.onUseToken(token.trim())- }- className="flex-1 rounded-2xl bg-zinc-50 px-3 py-2 text-sm text-zinc-800 ring-1 ring-zinc-100 transition-shadow placeholder:text-zinc-400 focus:outline-none focus:ring-zinc-300"+ <div className="mx-4 mb-3 grid gap-2">+ <MCPAuthSchemeField+ value={authScheme}+ onChange={selectScheme}+ disabled={request.loading}+ nameSuffix={request.service}+ className="grid gap-1"+ labelClassName="text-xs font-medium text-zinc-700"+ selectClassName="rounded-xl bg-zinc-50 px-3 py-2 text-sm text-zinc-800 ring-1 ring-zinc-100"/>- <Button- variant="secondary"- size="small"- disabled={request.loading || !token.trim()}- onClick={() => request.onUseToken(token.trim())}- >- Use Token- </Button>+ <p id={hintId} className="text-xs text-zinc-500">+ {mcpAuthTokenHint(authScheme)}+ </p>+ <div className="flex gap-2">+ <input+ type="password"+ aria-describedby={+ validationError ? `${hintId} ${errorId}` : hintId+ }+ aria-label={`${mcpAuthTokenLabel(authScheme)} for ${request.service}`}+ placeholder={mcpAuthTokenPlaceholder(authScheme)}+ value={token}+ onChange={(e) => {+ const nextToken = e.target.value;+ setToken(nextToken);+ detectSchemeFrom(nextToken);+ setValidationError(null);+ }}+ onKeyDown={(e) =>+ e.key === "Enter" &&+ !request.loading &&+ token.trim() &&+ submitCredential()+ }+ className="flex-1 rounded-2xl bg-zinc-50 px-3 py-2 text-sm text-zinc-800 ring-1 ring-zinc-100 transition-shadow placeholder:text-zinc-400 focus:outline-none focus:ring-zinc-300"+ />+ <Button+ variant="secondary"+ size="small"+ disabled={request.loading || !token.trim()}+ onClick={submitCredential}+ >+ Use Token+ </Button>+ </div>+ {validationError && (+ <p+ id={errorId}+ role="alert"+ aria-live="polite"+ className="text-xs text-red-700"+ >+ {validationError}+ </p>+ )}</div>)}</div>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsxindex fbc5cb3593..3705b1d07f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/__tests__/ChainActionCard.test.tsx@@ -96,6 +96,7 @@ function mcpRequest(loading: false,error: null,showManualToken: false,+ authScheme: "bearer",onConnect: vi.fn(),onUseToken: vi.fn(),...overrides,@@ -385,7 +386,7 @@ describe("ChainActionCard", () => {expect(useToken?.disabled).toBe(false);fireEvent.click(useToken!);- expect(request.onUseToken).toHaveBeenCalledWith("secret-token");+ expect(request.onUseToken).toHaveBeenCalledWith("Bearer secret-token");});it("submits the manual token on Enter", () => {@@ -396,7 +397,77 @@ describe("ChainActionCard", () => {fireEvent.change(input, { target: { value: "secret-token" } });fireEvent.keyDown(input, { key: "Enter" });- expect(request.onUseToken).toHaveBeenCalledWith("secret-token");+ expect(request.onUseToken).toHaveBeenCalledWith("Bearer secret-token");+ });++ it("prefixes a Basic credential selected in the chain row", () => {+ const request = mcpRequest({ showManualToken: true });+ renderCard({ mcp: [request] });++ fireEvent.change(+ screen.getByLabelText("Authentication type for Notion"),+ { target: { value: "basic" } },+ );+ fireEvent.change(+ screen.getByLabelText("Basic authentication token for Notion"),+ { target: { value: " cGstbGYtYWJjZA== " } },+ );+ fireEvent.click(screen.getByText("Use Token"));++ expect(request.onUseToken).toHaveBeenCalledWith("Basic cGstbGYtYWJjZA==");+ });++ it("refuses an unencoded user:password before calling onUseToken", () => {+ // The other three manual-credential surfaces validate before storing.+ // Without it this one sent the raw pair, and the user got the backend's+ // 422 instead of the message that names the Base64 step.+ const request = mcpRequest({ showManualToken: true });+ renderCard({ mcp: [request] });++ fireEvent.change(+ screen.getByLabelText("Authentication type for Notion"),+ { target: { value: "basic" } },+ );+ fireEvent.change(+ screen.getByLabelText("Basic authentication token for Notion"),+ { target: { value: "pk-lf-abc:sk-lf-xyz" } },+ );+ fireEvent.click(screen.getByText("Use Token"));++ expect(request.onUseToken).not.toHaveBeenCalled();+ expect(screen.getByRole("alert").textContent).toMatch(+ /unencoded user:password/,+ );+ });++ it("points the credential input at both its hint and its error", () => {+ const request = mcpRequest({ showManualToken: true });+ renderCard({ mcp: [request] });++ const input = screen.getByLabelText("API token for Notion");+ const hintId = input.getAttribute("aria-describedby");+ expect(hintId).toBeTruthy();+ // The hint is the only place the Base64 step is explained, and nothing+ // carried the id the input pointed at.+ expect(document.getElementById(hintId as string)?.textContent).toMatch(+ /Bearer authentication/,+ );+ });++ it("uses the selector when it differs from a pasted prefix", () => {+ const request = mcpRequest({ showManualToken: true });+ renderCard({ mcp: [request] });++ fireEvent.change(screen.getByLabelText("API token for Notion"), {+ target: { value: "Basic encoded-value" },+ });+ fireEvent.change(+ screen.getByLabelText("Authentication type for Notion"),+ { target: { value: "bearer" } },+ );+ fireEvent.click(screen.getByText("Use Token"));++ expect(request.onUseToken).toHaveBeenCalledWith("Bearer encoded-value");});});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/helpers.tsindex ef24af3aa4..52109f5530 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChainActionCard/helpers.ts@@ -50,6 +50,7 @@ export interface McpConnectorRequest {loading: boolean;error: string | null;showManualToken: boolean;+ authScheme: "basic" | "bearer";onConnect: () => void;onUseToken: (token: string) => void;}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/styleguide/page.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/styleguide/page.tsxindex b704ff55fb..ca9738bb48 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/styleguide/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/styleguide/page.tsx@@ -123,6 +123,7 @@ function makeMockProvider(isSystemProvider: false,oAuthCallback: noop as CredentialsProviderData["oAuthCallback"],mcpOAuthCallback: noop as CredentialsProviderData["mcpOAuthCallback"],+ mcpStoreToken: noop as CredentialsProviderData["mcpStoreToken"],createAPIKeyCredentials:noop as CredentialsProviderData["createAPIKeyCredentials"],createUserPasswordCredentials:diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsxindex 335fbe1623..f24da2f17d 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx@@ -2,12 +2,27 @@import { useGetV1ListCredentials } from "@/app/api/__generated__/endpoints/integrations/integrations";import {+ postV2DiscoverAvailableToolsOnAnMcpServer,postV2ExchangeOauthCodeForMcpTokens,postV2InitiateOauthLoginForAnMcpServer,postV2StoreABearerTokenForAnMcpServer,} from "@/app/api/__generated__/endpoints/mcp/mcp";import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";import { Button } from "@/components/atoms/Button/Button";+import { MCPAuthSchemeField } from "@/components/contextual/MCPAuthSchemeField/MCPAuthSchemeField";+import {+ mcpAuthTokenHint,+ mcpAuthTokenLabel,+ mcpAuthTokenPlaceholder,+} from "@/components/contextual/MCPAuthSchemeField/helpers";+import { useMCPAuthScheme } from "@/components/contextual/MCPAuthSchemeField/useMCPAuthScheme";+import {+ detectMCPAuthScheme,+ prepareMCPAuthCredential,+ validateMCPAuthCredential,+ type MCPAuthScheme,+} from "@/lib/mcp-auth";+import { normalizeMcpUrl } from "@/lib/mcp-url";import { openOAuthPopup } from "@/lib/oauth-popup";import { CredentialsProvidersContext } from "@/providers/agent-credentials/credentials-provider";import { useContext, useEffect, useId, useRef, useState } from "react";@@ -15,12 +30,6 @@ import { useCopilotChatActions } from "../../../../components/CopilotChatActionsimport { ContentMessage } from "../../../../components/ToolAccordion/AccordionContent";import { ChainActionsContext } from "../../../../components/ToolChain/chainActions";-function normalizeMcpUrl(url: string): string {- // Mirrors backend ``normalize_mcp_url`` (helpers.py) so a stored cred- // for ``https://mcp.sentry.dev/mcp`` matches a card emitted with the- // same URL whether or not the trailing slash is present.- return url.trim().replace(/\/+$/, "");-}interface Props {output: SetupRequirementsResponse;/**@@ -37,13 +46,15 @@ interface Props {** OAuth flow: initiate login → popup → exchange code for tokens.* Fallback: if the server doesn't support MCP OAuth (400), prompts the user- * to provide an API token manually.+ * to provide an API credential manually.*/export function MCPSetupCard({ output, retryInstruction }: Props) {const { onSend } = useCopilotChatActions();const allProviders = useContext(CredentialsProvidersContext);const chainActions = useContext(ChainActionsContext);const actionId = useId();+ const manualTokenInputId = `${actionId}-manual-auth-token`;+ const manualTokenHintId = `${actionId}-manual-auth-hint`;// setup_info.agent_id is set to the server_url in the backendconst serverUrl = output.setup_info.agent_id;@@ -87,19 +98,29 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {// a still-valid persisted snapshot — see review for the// initiallyConnected=false + 5xx race that surfaces a bare Connect// button despite an existing cred.- const liveHasCred: boolean | "unknown" = !Array.isArray(liveCredsRes)- ? "unknown"- : liveCredsRes.some(+ const liveCredential = !Array.isArray(liveCredsRes)+ ? null+ : liveCredsRes.find((c) =>c.provider === "mcp" &&typeof c.host === "string" &&normalizeMcpUrl(c.host) === normalizedServer,);+ const liveHasCred: boolean | "unknown" = !Array.isArray(liveCredsRes)+ ? "unknown"+ : Boolean(liveCredential);+ const storedManualAuthScheme: MCPAuthScheme =+ liveCredential?.mcp_auth_scheme === "basic" ? "basic" : "bearer";const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const [showManualToken, setShowManualToken] = useState(false);const [manualToken, setManualToken] = useState("");+ const {+ scheme: manualAuthScheme,+ selectScheme,+ detectSchemeFrom,+ } = useMCPAuthScheme(storedManualAuthScheme, manualToken);// ``localConnected`` is set ONLY when the user successfully completes// OAuth / manual-token in this component instance. It is NOT seeded// from ``initiallyConnected`` — that path is handled via ``liveSays``@@ -209,7 +230,7 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {if (err?.status === 400) {setShowManualToken(true);setError(- "This server does not support OAuth sign-in. Please enter an API token manually.",+ "This server does not support OAuth sign-in. Choose how its API credential should be sent.",);} else if (typeof err?.message === "string" &&@@ -234,17 +255,56 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {// present the same shape to readers. See the comment on// ``handleConnect``'s guard for the double-click race this prevents.if (loading) return;- const token = (tokenArg ?? manualToken).trim();+ // Chain rows pass an already-prepared value; do not prepare it again.+ const token =+ tokenArg === undefined+ ? prepareMCPAuthCredential(manualToken, manualAuthScheme)+ : tokenArg.trim();if (!token) return;++ const invalid = validateMCPAuthCredential(+ token,+ detectMCPAuthScheme(token) ?? manualAuthScheme,+ );+ if (invalid) {+ setForceDisconnected(true);+ setError(invalid);+ return;+ }+setLoading(true);setError(null);try {+ // Probe before storing so a rejected credential never shows as Connected.+ const probe = await postV2DiscoverAvailableToolsOnAnMcpServer({+ server_url: serverUrl,+ auth_token: token,+ });+ if (probe.status !== 200) {+ const probeDetail =+ probe.data && typeof probe.data === "object" && "detail" in probe.data+ ? probe.data.detail+ : null;+ throw new Error(+ typeof probeDetail === "string"+ ? probeDetail+ : "This server did not accept the credential.",+ );+ }+const res = await postV2StoreABearerTokenForAnMcpServer({server_url: serverUrl,token,});- if (!(res.status >= 200 && res.status < 300))- throw new Error("Failed to store token");+ if (!(res.status >= 200 && res.status < 300)) {+ const detail =+ res.data && typeof res.data === "object" && "detail" in res.data+ ? res.data.detail+ : null;+ throw new Error(+ typeof detail === "string" ? detail : "Failed to store token",+ );+ }// Only clear the force-disconnect override AFTER the API confirms// the token was stored. Clearing it before the await would let// ``liveHasCred=true`` (from an existing stale cred) re-render the@@ -269,6 +329,14 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {}}+ const handleConnectRef = useRef(handleConnect);+ const handleManualTokenRef = useRef(handleManualToken);++ useEffect(() => {+ handleConnectRef.current = handleConnect;+ handleManualTokenRef.current = handleManualToken;+ });+// Inside a tool chain the card renders nothing itself — it registers an// MCP row with the chain's connectors table and stays mounted (hidden)// as the state machine driving that row's callbacks.@@ -286,15 +354,15 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {loading,error,showManualToken,- onConnect: handleConnect,+ authScheme: manualAuthScheme,+ onConnect: () => void handleConnectRef.current(),onUseToken: (token) => {setManualToken(token);- void handleManualToken(token);+ void handleManualTokenRef.current(token);},},});return () => chainActions.unregister(actionId);- // eslint-disable-next-line react-hooks/exhaustive-deps -- handleConnect/handleManualToken capture latest state each registration}, [chainActions,actionId,@@ -302,6 +370,7 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {loading,error,showManualToken,+ manualAuthScheme,serverUrl,service,]);@@ -350,32 +419,61 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {</Button>{error && (- <div className="mt-2 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">+ <div+ role="alert"+ aria-live="polite"+ className="mt-2 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700"+ >{error}</div>)}{showManualToken && (- <div className="mt-3 flex gap-2">- <input- type="password"- aria-label={`API token for ${service}`}- placeholder="Paste API token"- value={manualToken}- onChange={(e) => setManualToken(e.target.value)}- onKeyDown={(e) =>- e.key === "Enter" && !loading && handleManualToken()- }- className="flex-1 rounded border px-2 py-1 text-sm"+ <div className="mt-3 grid gap-2">+ <MCPAuthSchemeField+ value={manualAuthScheme}+ onChange={selectScheme}+ disabled={loading}+ nameSuffix={service}+ className="grid gap-1"+ labelClassName="text-xs font-medium text-gray-700"+ selectClassName="rounded border bg-background px-2 py-1.5 text-sm"/>- <Button- variant="secondary"- size="small"- onClick={() => handleManualToken()}- disabled={loading || !manualToken.trim()}+ <label+ htmlFor={manualTokenInputId}+ className="text-xs font-medium text-gray-700">- Use Token- </Button>+ {`${mcpAuthTokenLabel(manualAuthScheme)} for ${service}`}+ </label>+ <p id={manualTokenHintId} className="text-xs text-gray-500">+ {mcpAuthTokenHint(manualAuthScheme)}+ </p>+ <div className="flex gap-2">+ <input+ id={manualTokenInputId}+ aria-describedby={manualTokenHintId}+ type="password"+ placeholder={mcpAuthTokenPlaceholder(manualAuthScheme)}+ value={manualToken}+ onChange={(e) => {+ const nextToken = e.target.value;+ setManualToken(nextToken);+ detectSchemeFrom(nextToken);+ }}+ onKeyDown={(e) =>+ e.key === "Enter" && !loading && handleManualToken()+ }+ className="flex-1 rounded border px-2 py-1 text-sm"+ />+ <Button+ variant="secondary"+ size="small"+ onClick={() => handleManualToken()}+ disabled={loading || !manualToken.trim()}+ >+ Use Token+ </Button>+ </div></div>)}</div>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/__tests__/MCPSetupCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/__tests__/MCPSetupCard.test.tsxindex ee66bcf7b7..09b05fa099 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/__tests__/MCPSetupCard.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/__tests__/MCPSetupCard.test.tsx@@ -1,19 +1,29 @@import {+ act,render,screen,fireEvent,waitFor,cleanup,} from "@/tests/integrations/test-utils";-import { afterEach, describe, expect, it, vi } from "vitest";+import {+ CredentialsProvidersContext,+ type CredentialsProvidersContextType,+} from "@/providers/agent-credentials/credentials-provider";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ ChainActionsContext,+ type ChainActionEntry,+} from "../../../../../components/ToolChain/chainActions";import { MCPSetupCard } from "../MCPSetupCard";// Mock the copilot chat actions used by MCPSetupCardconst mockOnSend = vi.fn();+let currentOnSend = mockOnSend;vi.mock("../../../../../components/CopilotChatActionsProvider/useCopilotChatActions",() => ({- useCopilotChatActions: () => ({ onSend: mockOnSend }),+ useCopilotChatActions: () => ({ onSend: currentOnSend }),}),);@@ -24,6 +34,7 @@ vi.mock("@/lib/oauth-popup", () => ({// Mock the generated API functionsvi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({+ postV2DiscoverAvailableToolsOnAnMcpServer: vi.fn(),postV2InitiateOauthLoginForAnMcpServer: vi.fn(),postV2ExchangeOauthCodeForMcpTokens: vi.fn(),postV2StoreABearerTokenForAnMcpServer: vi.fn(),@@ -34,9 +45,17 @@ vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({// ``has_all_credentials=false`` snapshot so the existing tests don't have// to thread a connected state through MSW. ``setMockLiveCreds`` lets// individual tests override the live state to verify the refresh path.-let mockLiveCreds: Array<{ provider: string; host?: string | null }> = [];+let mockLiveCreds: Array<{+ provider: string;+ host?: string | null;+ mcp_auth_scheme?: "basic" | "bearer" | null;+}> = [];function setMockLiveCreds(- next: Array<{ provider: string; host?: string | null }>,+ next: Array<{+ provider: string;+ host?: string | null;+ mcp_auth_scheme?: "basic" | "bearer" | null;+ }>,) {mockLiveCreds = next;}@@ -74,10 +93,32 @@ function makeSetupOutput(};}+// The placeholder tracks the selected scheme: "Paste API token" under Bearer,+// and the Base64 wording under Basic, so it stops restating the mistake the+// hint below it exists to prevent. These queries match either.+const manualTokenPlaceholder = /paste (api token|base64 of user:password)/i;+describe("MCPSetupCard", () => {+ // Storing a manual credential probes the server first, so the default is an+ // accepting server; the tests that care override it.+ beforeEach(async () => {+ const { postV2DiscoverAvailableToolsOnAnMcpServer } = await import(+ "@/app/api/__generated__/endpoints/mcp/mcp"+ );+ vi.mocked(postV2DiscoverAvailableToolsOnAnMcpServer).mockResolvedValue({+ status: 200,+ data: { tools: [], server_name: "Example" },+ headers: new Headers(),+ } as never);+ });+afterEach(() => {cleanup();+ // Without this, call history leaks between tests and any+ // `not.toHaveBeenCalled()` assertion silently depends on declaration order.+ vi.clearAllMocks();setMockLiveCreds([]);+ currentOnSend = mockOnSend;});it("renders setup message and connect button", () => {@@ -153,11 +194,59 @@ describe("MCPSetupCard", () => {);await waitFor(() => {- expect(screen.getByPlaceholderText("Paste API token")).toBeDefined();+ expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();});expect(screen.getByText(/does not support OAuth/)).toBeDefined();});+ it("uses a unique manual credential input id for each mounted card", async () => {+ const { postV2InitiateOauthLoginForAnMcpServer } = await import(+ "@/app/api/__generated__/endpoints/mcp/mcp"+ );+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer)+ .mockResolvedValueOnce({+ status: 400,+ data: { detail: "No OAuth support" },+ headers: new Headers(),+ } as never)+ .mockResolvedValueOnce({+ status: 400,+ data: { detail: "No OAuth support" },+ headers: new Headers(),+ } as never);++ render(+ <>+ <MCPSetupCard output={makeSetupOutput()} />+ <MCPSetupCard output={makeSetupOutput()} />+ </>,+ );+ fireEvent.click(+ screen.getAllByRole("button", { name: /connect example\.com/i })[0],+ );+ await waitFor(() => {+ expect(+ screen.getAllByPlaceholderText(manualTokenPlaceholder),+ ).toHaveLength(1);+ });+ fireEvent.click(+ screen.getAllByRole("button", { name: /connect example\.com/i })[1],+ );+ await waitFor(() => {+ expect(+ screen.getAllByPlaceholderText(manualTokenPlaceholder),+ ).toHaveLength(2);+ });++ const inputs = screen.getAllByPlaceholderText(manualTokenPlaceholder);+ expect(inputs[0].id).toBeTruthy();+ expect(inputs[1].id).toBeTruthy();+ expect(inputs[0].id).not.toBe(inputs[1].id);+ for (const input of inputs) {+ expect(document.querySelector(`label[for="${input.id}"]`)).not.toBeNull();+ }+ });+it("shows connected state after manual token", async () => {const {postV2InitiateOauthLoginForAnMcpServer,@@ -177,7 +266,7 @@ describe("MCPSetupCard", () => {);await waitFor(() => {- expect(screen.getByPlaceholderText("Paste API token")).toBeDefined();+ expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();});// Mock the token store endpoint@@ -194,7 +283,7 @@ describe("MCPSetupCard", () => {} as never);// Enter token and submit- fireEvent.change(screen.getByPlaceholderText("Paste API token"), {+ fireEvent.change(screen.getByPlaceholderText(manualTokenPlaceholder), {target: { value: "my-secret-token" },});fireEvent.click(screen.getByRole("button", { name: /use token/i }));@@ -202,6 +291,111 @@ describe("MCPSetupCard", () => {await waitFor(() => {expect(screen.getByText(/connected to example\.com/i)).toBeDefined();});+ expect(postV2StoreABearerTokenForAnMcpServer).toHaveBeenCalledWith({+ server_url: "https://mcp.example.com/mcp",+ token: "Bearer my-secret-token",+ });+ });++ it("stores a selected Basic credential with an explicit prefix", async () => {+ const {+ postV2InitiateOauthLoginForAnMcpServer,+ postV2StoreABearerTokenForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");++ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({+ status: 400,+ data: { detail: "No OAuth" },+ headers: new Headers(),+ } as never);+ vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce({+ status: 200,+ data: {+ id: "cred-basic",+ provider: "mcp",+ type: "oauth2",+ title: "MCP: mcp.example.com",+ scopes: [],+ },+ headers: new Headers(),+ } as never);++ render(<MCPSetupCard output={makeSetupOutput()} />);+ fireEvent.click(+ screen.getByRole("button", { name: /connect example\.com/i }),+ );+ await waitFor(() => {+ expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();+ });++ fireEvent.change(+ screen.getByLabelText("Authentication type for example.com"),+ { target: { value: "basic" } },+ );+ fireEvent.change(+ screen.getByLabelText("Basic authentication token for example.com"),+ { target: { value: " cGstbGYtYWJjZA== " } },+ );+ fireEvent.click(screen.getByRole("button", { name: /use token/i }));++ await waitFor(() => {+ expect(postV2StoreABearerTokenForAnMcpServer).toHaveBeenCalledWith({+ server_url: "https://mcp.example.com/mcp",+ token: "Basic cGstbGYtYWJjZA==",+ });+ });+ });++ it("restores Basic for a saved manual credential during reconnect", async () => {+ setMockLiveCreds([+ {+ provider: "mcp",+ host: "https://mcp.example.com/mcp",+ mcp_auth_scheme: "basic",+ },+ ]);+ const {+ postV2InitiateOauthLoginForAnMcpServer,+ postV2StoreABearerTokenForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({+ status: 400,+ data: { detail: "No OAuth" },+ headers: new Headers(),+ } as never);+ vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce({+ status: 200,+ data: {+ id: "cred-basic",+ provider: "mcp",+ type: "oauth2",+ title: "MCP: mcp.example.com",+ scopes: [],+ },+ headers: new Headers(),+ } as never);++ render(<MCPSetupCard output={makeSetupOutput(undefined, true)} />);+ fireEvent.click(screen.getByRole("button", { name: /reconnect/i }));+ await waitFor(() => {+ expect(screen.getByLabelText(/authentication type/i)).toBeDefined();+ });++ expect(+ (screen.getByLabelText(/authentication type/i) as HTMLSelectElement)+ .value,+ ).toBe("basic");+ fireEvent.change(screen.getByPlaceholderText(manualTokenPlaceholder), {+ target: { value: "new-encoded-value" },+ });+ fireEvent.click(screen.getByRole("button", { name: /use token/i }));++ await waitFor(() => {+ expect(postV2StoreABearerTokenForAnMcpServer).toHaveBeenCalledWith({+ server_url: "https://mcp.example.com/mcp",+ token: "Basic new-encoded-value",+ });+ });});it("drops Connected state and surfaces manual token input when Reconnect hits HTTP 400", async () => {@@ -230,7 +424,7 @@ describe("MCPSetupCard", () => {// After 400, the not-connected branch must render: error banner + manual// token input. The Connected/Reconnect banner must be gone.await waitFor(() => {- expect(screen.getByPlaceholderText("Paste API token")).toBeDefined();+ expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();});expect(screen.getByText(/does not support OAuth/)).toBeDefined();expect(screen.queryByText(/connected to example\.com/i)).toBeNull();@@ -261,7 +455,7 @@ describe("MCPSetupCard", () => {fireEvent.click(reconnectBtn);await waitFor(() => {- expect(screen.getByPlaceholderText("Paste API token")).toBeDefined();+ expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();});expect(screen.queryByText(/connected to example\.com/i)).toBeNull();});@@ -302,7 +496,7 @@ describe("MCPSetupCard", () => {headers: new Headers(),});await waitFor(() => {- expect(screen.getByPlaceholderText("Paste API token")).toBeDefined();+ expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();});});@@ -357,7 +551,7 @@ describe("MCPSetupCard", () => {).toBeDefined();});// Manual-token input must NOT appear — that's the 400-only branch.- expect(screen.queryByPlaceholderText("Paste API token")).toBeNull();+ expect(screen.queryByPlaceholderText(manualTokenPlaceholder)).toBeNull();});it("submits manual token via Enter key", async () => {@@ -379,7 +573,7 @@ describe("MCPSetupCard", () => {screen.getByRole("button", { name: /connect example\.com/i }),);await waitFor(() => {- expect(screen.getByPlaceholderText("Paste API token")).toBeDefined();+ expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();});vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce({@@ -394,7 +588,7 @@ describe("MCPSetupCard", () => {headers: new Headers(),} as never);- const input = screen.getByPlaceholderText("Paste API token");+ const input = screen.getByPlaceholderText(manualTokenPlaceholder);fireEvent.change(input, { target: { value: "my-token" } });fireEvent.keyDown(input, { key: "Enter" });@@ -403,6 +597,77 @@ describe("MCPSetupCard", () => {});});+ it("does not report Connected for a credential the server rejects", async () => {+ // A 2xx from ``/mcp/token`` only says the row was written. Without a probe+ // the card claims Connected, the very next copilot call 401s, and the card,+ // the database and the assistant all disagree about the state.+ const {+ postV2DiscoverAvailableToolsOnAnMcpServer,+ postV2InitiateOauthLoginForAnMcpServer,+ postV2StoreABearerTokenForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({+ status: 400,+ data: { detail: "No OAuth" },+ headers: new Headers(),+ } as never);+ vi.mocked(postV2DiscoverAvailableToolsOnAnMcpServer).mockResolvedValue({+ status: 401,+ data: { detail: "Server rejected the credential" },+ headers: new Headers(),+ } as never);++ render(<MCPSetupCard output={makeSetupOutput(undefined, true)} />);+ fireEvent.click(screen.getByRole("button", { name: /connect example/i }));+ await waitFor(() => {+ expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();+ });++ fireEvent.change(screen.getByPlaceholderText(manualTokenPlaceholder), {+ target: { value: "wrong-token" },+ });+ fireEvent.click(screen.getByRole("button", { name: /use token/i }));++ await waitFor(() => {+ expect(screen.getByText(/server rejected the credential/i)).toBeDefined();+ });+ expect(postV2StoreABearerTokenForAnMcpServer).not.toHaveBeenCalled();+ expect(screen.queryByText(/connected to example\.com/i)).toBeNull();+ });++ it("refuses an unencoded user:password before any request", async () => {+ const {+ postV2DiscoverAvailableToolsOnAnMcpServer,+ postV2InitiateOauthLoginForAnMcpServer,+ postV2StoreABearerTokenForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({+ status: 400,+ data: { detail: "No OAuth" },+ headers: new Headers(),+ } as never);++ render(<MCPSetupCard output={makeSetupOutput(undefined, true)} />);+ fireEvent.click(screen.getByRole("button", { name: /connect example/i }));+ await waitFor(() => {+ expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();+ });++ fireEvent.change(screen.getByLabelText(/authentication type/i), {+ target: { value: "basic" },+ });+ fireEvent.change(screen.getByPlaceholderText(manualTokenPlaceholder), {+ target: { value: "pk-lf-abc:sk-lf-xyz" },+ });+ fireEvent.click(screen.getByRole("button", { name: /use token/i }));++ await waitFor(() => {+ expect(screen.getByText(/unencoded user:password/i)).toBeDefined();+ });+ expect(postV2DiscoverAvailableToolsOnAnMcpServer).not.toHaveBeenCalled();+ expect(postV2StoreABearerTokenForAnMcpServer).not.toHaveBeenCalled();+ });+it("re-renders not-connected branch when manual token POST fails (forceDisconnected flips on)", async () => {// ``handleManualToken`` catch must flip ``forceDisconnected=true`` —// otherwise an existing live cred would re-show the Connected pill@@ -423,7 +688,7 @@ describe("MCPSetupCard", () => {render(<MCPSetupCard output={makeSetupOutput(undefined, true)} />);fireEvent.click(screen.getByRole("button", { name: /reconnect/i }));await waitFor(() => {- expect(screen.getByPlaceholderText("Paste API token")).toBeDefined();+ expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();});// Token endpoint rejects with non-2xx → catch fires → forceDisconnected stays on.@@ -433,18 +698,139 @@ describe("MCPSetupCard", () => {headers: new Headers(),} as never);- fireEvent.change(screen.getByPlaceholderText("Paste API token"), {+ fireEvent.change(screen.getByPlaceholderText(manualTokenPlaceholder), {target: { value: "bad-token" },});fireEvent.click(screen.getByRole("button", { name: /use token/i }));await waitFor(() => {- // ``handleManualToken`` throws ``new Error("Failed to store token")``- // on non-2xx, which becomes the displayed error message.- expect(screen.getByText(/failed to store token/i)).toBeDefined();+ expect(screen.getByText(/invalid token format/i)).toBeDefined();});// Crucial: live creds say "connected" but the failed token attempt// must keep the not-connected branch rendered so the user can retry.expect(screen.queryByText(/connected to example\.com/i)).toBeNull();});++ it("uses current provider and chat actions from a previously registered chain callback", async () => {+ const { postV2InitiateOauthLoginForAnMcpServer } = await import(+ "@/app/api/__generated__/endpoints/mcp/mcp"+ );+ const { openOAuthPopup } = await import("@/lib/oauth-popup");+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({+ status: 200,+ data: {+ login_url: "https://example.com/oauth",+ state_token: "latest-state",+ },+ headers: new Headers(),+ } as never);+ vi.mocked(openOAuthPopup).mockReturnValueOnce({+ promise: Promise.resolve({ code: "latest-code", state: "latest-state" }),+ cleanup: { abort: vi.fn(), signal: new AbortController().signal },+ popupBlocked: false,+ fallbackBlocked: false,+ });++ const initialProviderCallback = vi.fn().mockResolvedValue({});+ const latestProviderCallback = vi.fn().mockResolvedValue({});+ const initialOnSend = vi.fn();+ const latestOnSend = vi.fn();+ currentOnSend = initialOnSend;++ const initialProviders = {+ mcp: { mcpOAuthCallback: initialProviderCallback },+ } as unknown as CredentialsProvidersContextType;+ const latestProviders = {+ mcp: { mcpOAuthCallback: latestProviderCallback },+ } as unknown as CredentialsProvidersContextType;+ let registeredEntry: ChainActionEntry | null = null;+ const chainActions = {+ register: vi.fn((entry: ChainActionEntry) => {+ registeredEntry = entry;+ }),+ unregister: vi.fn((_id: string) => {}),+ };++ function setupCard(+ providers: CredentialsProvidersContextType,+ retryInstruction: string,+ ) {+ return (+ <CredentialsProvidersContext.Provider value={providers}>+ <ChainActionsContext.Provider value={chainActions}>+ <MCPSetupCard+ output={makeSetupOutput()}+ retryInstruction={retryInstruction}+ />+ </ChainActionsContext.Provider>+ </CredentialsProvidersContext.Provider>+ );+ }++ const { rerender } = render(+ setupCard(initialProviders, "Initial retry instruction"),+ );+ await waitFor(() => expect(registeredEntry?.mcp).toBeDefined());+ const previouslyRegisteredOnConnect = registeredEntry!.mcp!.onConnect;++ currentOnSend = latestOnSend;+ rerender(setupCard(latestProviders, "Latest retry instruction"));+ expect(chainActions.register).toHaveBeenCalledOnce();++ await act(async () => {+ previouslyRegisteredOnConnect();+ });++ await waitFor(() => {+ expect(latestProviderCallback).toHaveBeenCalledWith(+ "latest-code",+ "latest-state",+ );+ expect(latestOnSend).toHaveBeenCalledWith("Latest retry instruction");+ });+ expect(initialProviderCallback).not.toHaveBeenCalled();+ expect(initialOnSend).not.toHaveBeenCalled();+ });++ it("does not reinterpret an already prepared Basic chain credential", async () => {+ const { postV2StoreABearerTokenForAnMcpServer } = await import(+ "@/app/api/__generated__/endpoints/mcp/mcp"+ );+ vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce({+ status: 200,+ data: {+ id: "cred-chain-basic",+ provider: "mcp",+ type: "oauth2",+ title: "MCP: mcp.example.com",+ scopes: [],+ },+ headers: new Headers(),+ } as never);++ let registeredEntry: ChainActionEntry | null = null;+ const chainActions = {+ register: vi.fn((entry: ChainActionEntry) => {+ registeredEntry = entry;+ }),+ unregister: vi.fn(),+ };+ render(+ <ChainActionsContext.Provider value={chainActions}>+ <MCPSetupCard output={makeSetupOutput()} />+ </ChainActionsContext.Provider>,+ );+ await waitFor(() => expect(registeredEntry?.mcp).toBeDefined());++ await act(async () => {+ registeredEntry!.mcp!.onUseToken("Basic encoded-chain-value");+ });++ await waitFor(() => {+ expect(postV2StoreABearerTokenForAnMcpServer).toHaveBeenCalledWith({+ server_url: "https://mcp.example.com/mcp",+ token: "Basic encoded-chain-value",+ });+ });+ });});diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 65d36f2595..2cea971589 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -9926,7 +9926,7 @@"post": {"tags": ["v2", "mcp", "mcp"],"summary": "Discover available tools on an MCP server",- "description": "Connect to an MCP server and return its available tools.\n\nIf the user has a stored MCP credential for this server URL, it will be\nused automatically — no need to pass an explicit auth token.",+ "description": "Connect to an MCP server and return its available tools.\n\nIf the user has a stored MCP credential for this server URL, it will be\nused automatically — no need to pass an explicit auth credential.","operationId": "postV2Discover available tools on an mcp server","requestBody": {"content": {@@ -10048,7 +10048,7 @@"post": {"tags": ["v2", "mcp", "mcp"],"summary": "Store a bearer token for an MCP server",- "description": "Store a manually provided bearer token as an MCP credential.\n\nUsed by the Copilot MCPSetupCard when the server doesn't support the MCP\nOAuth discovery flow (returns 400 from /oauth/login). Subsequent\n``run_mcp_tool`` calls will automatically pick up the token via\n``_auto_lookup_credential``.",+ "description": "Store a manually entered MCP credential. Accepts a bare token (sent as Bearer, unchanged from before), an explicit `Basic <value>` or `Bearer <value>`, or a complete `Authorization:` header.","operationId": "postV2Store a bearer token for an mcp server","requestBody": {"content": {@@ -18586,6 +18586,14 @@"title": "Host","description": "Host pattern for host-scoped or MCP server URL for MCP credentials"},+ "mcp_auth_scheme": {+ "anyOf": [+ { "type": "string", "enum": ["basic", "bearer"] },+ { "type": "null" }+ ],+ "title": "Mcp Auth Scheme",+ "description": "Manual authorization scheme for MCP credentials"+ },"is_managed": {"type": "boolean","title": "Is Managed",@@ -18801,9 +18809,18 @@"description": "URL of the MCP server"},"auth_token": {- "anyOf": [{ "type": "string" }, { "type": "null" }],+ "anyOf": [+ {+ "type": "string",+ "maxLength": 8192,+ "minLength": 1,+ "format": "password",+ "writeOnly": true+ },+ { "type": "null" }+ ],"title": "Auth Token",- "description": "Optional Bearer token for authenticated MCP servers"+ "description": "Optional bare Bearer token, Basic/Bearer value, or complete Authorization header. Omit the field (or send null) for an unauthenticated server; an empty string is rejected."}},"type": "object",@@ -22772,21 +22789,22 @@"server_url": {"type": "string","title": "Server Url",- "description": "MCP server URL the token authenticates against"+ "description": "MCP server URL the credential authenticates against"},"token": {"type": "string",+ "maxLength": 8192,"minLength": 1,"format": "password","title": "Token",- "description": "Bearer token / API key for the MCP server",+ "description": "Bare Bearer token, Basic/Bearer value, or complete Authorization header","writeOnly": true}},"type": "object","required": ["server_url", "token"],"title": "MCPStoreTokenRequest",- "description": "Request to store a bearer token for an MCP server that doesn't support OAuth."+ "description": "Request to store a manual Basic/Bearer credential or Authorization header."},"MCPToolInfo": {"properties": {diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/McpConnectPanel.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/McpConnectPanel.tsxindex b47dbdf2cf..bf6ef303a5 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/McpConnectPanel.tsx+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/McpConnectPanel.tsx@@ -4,15 +4,35 @@ import { useEffect, useRef, useState } from "react";import { useQueryClient } from "@tanstack/react-query";import {+ postV2DiscoverAvailableToolsOnAnMcpServer,postV2ExchangeOauthCodeForMcpTokens,postV2InitiateOauthLoginForAnMcpServer,postV2StoreABearerTokenForAnMcpServer,} from "@/app/api/__generated__/endpoints/mcp/mcp";+import { useGetV1ListCredentials } from "@/app/api/__generated__/endpoints/integrations/integrations";import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";import type { MCPOAuthLoginResponse } from "@/app/api/__generated__/models/mCPOAuthLoginResponse";import { Button } from "@/components/atoms/Button/Button";import { Input } from "@/components/atoms/Input/Input";import { Text } from "@/components/atoms/Text/Text";+import { MCPAuthSchemeField } from "@/components/contextual/MCPAuthSchemeField/MCPAuthSchemeField";+import {+ mcpAuthTokenHint,+ mcpAuthTokenLabel,+ mcpAuthTokenPlaceholder,+} from "@/components/contextual/MCPAuthSchemeField/helpers";+import { useMCPAuthScheme } from "@/components/contextual/MCPAuthSchemeField/useMCPAuthScheme";+import {+ prepareMCPAuthCredential,+ validateMCPAuthCredential,+ type MCPAuthScheme,+} from "@/lib/mcp-auth";+import {+ getAPIResponseError,+ getErrorMessage,+ getErrorStatus,+} from "@/lib/mcp-errors";+import { mcpServerIdentity, normalizeMcpUrl } from "@/lib/mcp-url";import { openOAuthPopup } from "@/lib/oauth-popup";import { invalidateConnectionQueries } from "@/lib/react-query/invalidateConnections";@@ -24,6 +44,11 @@ type Phase = "form" | "manual-token";export function McpConnectPanel({ onSuccess }: Props) {const queryClient = useQueryClient();+ const { data: savedCredentials } = useGetV1ListCredentials({+ query: {+ select: (response) => (response.status === 200 ? response.data : []),+ },+ });const [serverUrl, setServerUrl] = useState("");const [token, setToken] = useState("");const [phase, setPhase] = useState<Phase>("form");@@ -38,6 +63,22 @@ export function McpConnectPanel({ onSuccess }: Props) {const isUrlValid = isValidHttpUrl(trimmedUrl);const canConnect = isUrlValid && !isSubmitting;const canSubmitToken = isUrlValid && trimmedToken.length > 0 && !isSubmitting;+ const savedCredential = Array.isArray(savedCredentials)+ ? savedCredentials.find(+ (credential) =>+ credential.provider === "mcp" &&+ typeof credential.host === "string" &&+ normalizeMcpUrl(credential.host) === normalizeMcpUrl(trimmedUrl),+ )+ : null;+ const savedAuthScheme: MCPAuthScheme =+ savedCredential?.mcp_auth_scheme === "basic" ? "basic" : "bearer";+ const {+ scheme: authScheme,+ selectScheme,+ detectSchemeFrom,+ resetScheme,+ } = useMCPAuthScheme(savedAuthScheme, token);async function invalidateCredentials() {await invalidateConnectionQueries(queryClient);@@ -61,11 +102,14 @@ export function McpConnectPanel({ onSuccess }: Props) {loginRes = await postV2InitiateOauthLoginForAnMcpServer({server_url: trimmedUrl,});+ if (loginRes.status !== 200) {+ throw getAPIResponseError(loginRes.status, loginRes.data);+ }} catch (e: unknown) {if (getErrorStatus(e) === 400) {setPhase("manual-token");setError(- "This server doesn't support OAuth sign-in. Paste a bearer token instead.",+ "This server doesn't support OAuth sign-in. Choose how its API credential should be sent.",);return;}@@ -86,9 +130,12 @@ export function McpConnectPanel({ onSuccess }: Props) {code: result.code,state_token,});+ if (exchanged.status !== 200) {+ throw getAPIResponseError(exchanged.status, exchanged.data);+ }await invalidateCredentials();- onSuccess(exchanged.status === 200 ? exchanged.data : undefined);+ onSuccess(exchanged.data);} catch (e: unknown) {const message = getErrorMessage(e);if (message === "OAuth flow timed out") {@@ -104,17 +151,38 @@ export function McpConnectPanel({ onSuccess }: Props) {async function handleSubmitToken() {if (!canSubmitToken) return;++ const invalid = validateMCPAuthCredential(trimmedToken, authScheme);+ if (invalid) {+ setError(invalid);+ return;+ }+setError(null);setIsSubmitting(true);try {+ const authValue = prepareMCPAuthCredential(trimmedToken, authScheme);++ // Probe before storing so a rejected credential never replaces a working one.+ const probe = await postV2DiscoverAvailableToolsOnAnMcpServer({+ server_url: trimmedUrl,+ auth_token: authValue,+ });+ if (probe.status !== 200) {+ throw getAPIResponseError(probe.status, probe.data);+ }+const stored = await postV2StoreABearerTokenForAnMcpServer({server_url: trimmedUrl,- token: trimmedToken,+ token: authValue,});+ if (stored.status !== 200) {+ throw getAPIResponseError(stored.status, stored.data);+ }await invalidateCredentials();- onSuccess(stored.status === 200 ? stored.data : undefined);+ onSuccess(stored.data);} catch (e: unknown) {setError(getErrorMessage(e));} finally {@@ -125,6 +193,20 @@ export function McpConnectPanel({ onSuccess }: Props) {function handleSwitchToOAuth() {setPhase("form");setToken("");+ resetScheme();+ setError(null);+ }++ function handleServerUrlChange(nextUrl: string) {+ const serverIdentityChanged =+ mcpServerIdentity(serverUrl) !== mcpServerIdentity(nextUrl);++ setServerUrl(nextUrl);+ if (!serverIdentityChanged) return;++ setToken("");+ resetScheme();+ setPhase("form");setError(null);}@@ -132,7 +214,8 @@ export function McpConnectPanel({ onSuccess }: Props) {<div className="flex flex-col gap-4"><Text variant="body" className="text-zinc-600">Enter the URL of your MCP server. We'll try OAuth first and fall- back to a bearer token if the server doesn't support OAuth.+ back to a manual API credential if the server doesn't support+ OAuth.</Text><Input@@ -141,22 +224,36 @@ export function McpConnectPanel({ onSuccess }: Props) {type="url"placeholder="https://mcp.example.com"value={serverUrl}- onChange={(e) => setServerUrl(e.target.value)}+ onChange={(e) => handleServerUrlChange(e.target.value)}disabled={isSubmitting}autoFocus/>{phase === "manual-token" ? (- <Input- id="mcp-bearer-token"- label="Bearer token"- type="password"- placeholder="Paste API token"- value={token}- onChange={(e) => setToken(e.target.value)}- disabled={isSubmitting}- hint="Used as a Bearer Authorization header when calling tools."- />+ <>+ <MCPAuthSchemeField+ value={authScheme}+ onChange={selectScheme}+ disabled={isSubmitting}+ className="flex flex-col gap-1"+ labelClassName="text-sm font-medium text-zinc-700"+ selectClassName="rounded-lg border border-zinc-300 bg-white px-3 py-2 text-zinc-900"+ />+ <Input+ id="mcp-auth-token"+ label={mcpAuthTokenLabel(authScheme)}+ type="password"+ placeholder={mcpAuthTokenPlaceholder(authScheme)}+ value={token}+ onChange={(e) => {+ const nextToken = e.target.value;+ setToken(nextToken);+ detectSchemeFrom(nextToken);+ }}+ disabled={isSubmitting}+ hint={mcpAuthTokenHint(authScheme)}+ />+ </>) : null}{error ? (@@ -206,25 +303,6 @@ export function McpConnectPanel({ onSuccess }: Props) {);}-function getErrorMessage(error: unknown): string {- if (error instanceof Error && error.message) return error.message;- if (typeof error === "object" && error !== null) {- const detail = (error as { detail?: unknown }).detail;- if (typeof detail === "string") return detail;- const message = (error as { message?: unknown }).message;- if (typeof message === "string") return message;- }- return "Something went wrong. Please try again.";-}--function getErrorStatus(error: unknown): number | null {- if (typeof error === "object" && error !== null) {- const status = (error as { status?: unknown }).status;- if (typeof status === "number") return status;- }- return null;-}-function isValidHttpUrl(value: string): boolean {if (!value) return false;try {diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/McpConnectPanel.test.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/McpConnectPanel.test.tsxindex 0acd7a2f7e..4378b0d21e 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/McpConnectPanel.test.tsx+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/McpConnectPanel.test.tsx@@ -5,7 +5,7 @@ import {screen,waitFor,} from "@/tests/integrations/test-utils";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { McpConnectPanel } from "../McpConnectPanel";@@ -14,11 +14,22 @@ vi.mock("@/lib/oauth-popup", () => ({}));vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({+ postV2DiscoverAvailableToolsOnAnMcpServer: vi.fn(),postV2InitiateOauthLoginForAnMcpServer: vi.fn(),postV2ExchangeOauthCodeForMcpTokens: vi.fn(),postV2StoreABearerTokenForAnMcpServer: vi.fn(),}));+let mockSavedCredentials: Array<{+ provider: string;+ host?: string | null;+ mcp_auth_scheme?: "basic" | "bearer" | null;+}> = [];+vi.mock("@/app/api/__generated__/endpoints/integrations/integrations", () => ({+ getGetV1ListCredentialsQueryKey: () => ["credentials"],+ useGetV1ListCredentials: () => ({ data: mockSavedCredentials }),+}));+function makeApiError(status: number, detail = "boom"): Error {const err = new Error(detail) as Error & {status: number;@@ -30,9 +41,28 @@ function makeApiError(status: number, detail = "boom"): Error {return err;}+// The placeholder tracks the selected scheme: "Paste API token" under Bearer,+// and the Base64 wording under Basic, so it stops restating the mistake the+// hint below it exists to prevent. These queries match either.+const manualTokenPlaceholder = /paste (api token|base64 of user:password)/i;+describe("McpConnectPanel", () => {+ // Saving a manual credential probes the server first, so the default is an+ // accepting server; the tests that care override it.+ beforeEach(async () => {+ const { postV2DiscoverAvailableToolsOnAnMcpServer } = await import(+ "@/app/api/__generated__/endpoints/mcp/mcp"+ );+ vi.mocked(postV2DiscoverAvailableToolsOnAnMcpServer).mockResolvedValue({+ status: 200,+ data: { tools: [], server_name: "Example" },+ headers: new Headers(),+ } as never);+ });+afterEach(() => {- vi.clearAllMocks();+ vi.resetAllMocks();+ mockSavedCredentials = [];cleanup();});@@ -63,9 +93,11 @@ describe("McpConnectPanel", () => {"@/app/api/__generated__/endpoints/mcp/mcp");- vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockRejectedValueOnce(- makeApiError(400, "OAuth not supported"),- );+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({+ status: 400,+ data: { detail: "OAuth not supported" },+ headers: new Headers(),+ } as never);render(<McpConnectPanel onSuccess={() => {}} />);@@ -75,7 +107,7 @@ describe("McpConnectPanel", () => {fireEvent.click(screen.getByRole("button", { name: /connect/i }));await waitFor(() => {- expect(screen.getByPlaceholderText(/paste api token/i)).toBeDefined();+ expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();});expect(screen.getByText(/server doesn't support oauth sign-in/i),@@ -100,9 +132,11 @@ describe("McpConnectPanel", () => {cleanup: { abort: vi.fn() },} as never);- vi.mocked(postV2ExchangeOauthCodeForMcpTokens).mockRejectedValueOnce(- makeApiError(400, "bad code"),- );+ vi.mocked(postV2ExchangeOauthCodeForMcpTokens).mockResolvedValueOnce({+ status: 400,+ data: { detail: "bad code" },+ headers: new Headers(),+ } as never);render(<McpConnectPanel onSuccess={() => {}} />);@@ -115,7 +149,7 @@ describe("McpConnectPanel", () => {expect(screen.getByText(/bad code/i)).toBeDefined();});- expect(screen.queryByPlaceholderText(/paste api token/i)).toBeNull();+ expect(screen.queryByPlaceholderText(manualTokenPlaceholder)).toBeNull();});it("submits a bearer token then calls onSuccess", async () => {@@ -137,7 +171,7 @@ describe("McpConnectPanel", () => {fireEvent.click(screen.getByRole("button", { name: /connect/i }));await waitFor(() => {- expect(screen.getByPlaceholderText(/paste api token/i)).toBeDefined();+ expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();});vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce({@@ -146,7 +180,7 @@ describe("McpConnectPanel", () => {headers: new Headers(),} as never);- fireEvent.change(screen.getByPlaceholderText(/paste api token/i), {+ fireEvent.change(screen.getByPlaceholderText(manualTokenPlaceholder), {target: { value: "secret-bearer-token" },});fireEvent.click(screen.getByRole("button", { name: /save token/i }));@@ -156,8 +190,255 @@ describe("McpConnectPanel", () => {});expect(postV2StoreABearerTokenForAnMcpServer).toHaveBeenCalledWith({server_url: "https://mcp.example.com",- token: "secret-bearer-token",+ token: "Bearer secret-bearer-token",+ });+ });++ it("submits a selected Basic credential with an explicit prefix", async () => {+ const {+ postV2InitiateOauthLoginForAnMcpServer,+ postV2StoreABearerTokenForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");++ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({+ status: 400,+ data: { detail: "OAuth not supported" },+ headers: new Headers(),+ } as never);+ vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce({+ status: 200,+ data: { ok: true },+ headers: new Headers(),+ } as never);++ render(<McpConnectPanel onSuccess={() => {}} />);+ fireEvent.change(screen.getByLabelText(/server url/i), {+ target: { value: "https://mcp.example.com" },+ });+ fireEvent.click(screen.getByRole("button", { name: /connect/i }));+ await waitFor(() => {+ expect(screen.getByLabelText("Authentication type")).toBeDefined();+ });++ fireEvent.change(screen.getByLabelText("Authentication type"), {+ target: { value: "basic" },+ });+ expect(screen.getByText("Basic authentication token")).toBeDefined();+ fireEvent.change(screen.getByPlaceholderText(manualTokenPlaceholder), {+ target: { value: " cGstbGYtYWJjZA== " },+ });+ fireEvent.click(screen.getByRole("button", { name: /save token/i }));++ await waitFor(() => {+ expect(postV2StoreABearerTokenForAnMcpServer).toHaveBeenCalledWith({+ server_url: "https://mcp.example.com",+ token: "Basic cGstbGYtYWJjZA==",+ });+ });+ });++ it("restores the saved Basic scheme for the same server", async () => {+ mockSavedCredentials = [+ {+ provider: "mcp",+ host: "https://mcp.example.com",+ mcp_auth_scheme: "basic",+ },+ ];+ const {+ postV2InitiateOauthLoginForAnMcpServer,+ postV2StoreABearerTokenForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({+ status: 400,+ data: { detail: "OAuth not supported" },+ headers: new Headers(),+ } as never);+ vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce({+ status: 200,+ data: { ok: true },+ headers: new Headers(),+ } as never);++ render(<McpConnectPanel onSuccess={() => {}} />);+ fireEvent.change(screen.getByLabelText(/server url/i), {+ target: { value: "https://mcp.example.com/" },+ });+ fireEvent.click(screen.getByRole("button", { name: /connect/i }));+ await waitFor(() => {+ expect(screen.getByLabelText("Authentication type")).toBeDefined();+ });+ expect(+ (screen.getByLabelText("Authentication type") as HTMLSelectElement).value,+ ).toBe("basic");++ fireEvent.change(screen.getByPlaceholderText(manualTokenPlaceholder), {+ target: { value: "new-encoded-value" },+ });+ fireEvent.click(screen.getByRole("button", { name: /save token/i }));++ await waitFor(() => {+ expect(postV2StoreABearerTokenForAnMcpServer).toHaveBeenCalledWith({+ server_url: "https://mcp.example.com/",+ token: "Basic new-encoded-value",+ });+ });+ });++ it("hands the stored credential to onSuccess", async () => {+ // The payload, not just the fact of being called: the dialog binds what it+ // receives here, so returning undefined silently unbinds the connection.+ const {+ postV2InitiateOauthLoginForAnMcpServer,+ postV2StoreABearerTokenForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");+ const stored = {+ id: "cred-1",+ provider: "mcp",+ type: "oauth2",+ title: "MCP: mcp.example.com",+ host: "https://mcp.example.com",+ mcp_auth_scheme: "basic",+ };+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({+ status: 400,+ data: { detail: "OAuth not supported" },+ headers: new Headers(),+ } as never);+ vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce({+ status: 200,+ data: stored,+ headers: new Headers(),+ } as never);++ const onSuccess = vi.fn();+ render(<McpConnectPanel onSuccess={onSuccess} />);+ fireEvent.change(screen.getByLabelText(/server url/i), {+ target: { value: "https://mcp.example.com" },+ });+ fireEvent.click(screen.getByRole("button", { name: /connect/i }));+ await waitFor(() => {+ expect(screen.getByLabelText("Authentication type")).toBeDefined();+ });++ fireEvent.change(screen.getByPlaceholderText(manualTokenPlaceholder), {+ target: { value: "cGstbGYtYWJjZA==" },+ });+ fireEvent.click(screen.getByRole("button", { name: /save token/i }));++ await waitFor(() => {+ expect(onSuccess).toHaveBeenCalledWith(stored);+ });+ });++ it("rejects an unencoded user:password before any request", async () => {+ const {+ postV2DiscoverAvailableToolsOnAnMcpServer,+ postV2InitiateOauthLoginForAnMcpServer,+ postV2StoreABearerTokenForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({+ status: 400,+ data: { detail: "OAuth not supported" },+ headers: new Headers(),+ } as never);++ render(<McpConnectPanel onSuccess={() => {}} />);+ fireEvent.change(screen.getByLabelText(/server url/i), {+ target: { value: "https://mcp.example.com" },+ });+ fireEvent.click(screen.getByRole("button", { name: /connect/i }));+ await waitFor(() => {+ expect(screen.getByLabelText("Authentication type")).toBeDefined();+ });++ fireEvent.change(screen.getByLabelText("Authentication type"), {+ target: { value: "basic" },+ });+ fireEvent.change(screen.getByPlaceholderText(manualTokenPlaceholder), {+ target: { value: "pk-lf-abc:sk-lf-xyz" },+ });+ fireEvent.click(screen.getByRole("button", { name: /save token/i }));++ const alert = await screen.findByRole("alert");+ expect(alert.textContent).toMatch(/unencoded user:password/i);+ expect(postV2DiscoverAvailableToolsOnAnMcpServer).not.toHaveBeenCalled();+ expect(postV2StoreABearerTokenForAnMcpServer).not.toHaveBeenCalled();+ });++ it("does not store a credential the server rejects", async () => {+ const {+ postV2DiscoverAvailableToolsOnAnMcpServer,+ postV2InitiateOauthLoginForAnMcpServer,+ postV2StoreABearerTokenForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");++ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({+ status: 400,+ data: { detail: "OAuth not supported" },+ headers: new Headers(),+ } as never);+ vi.mocked(postV2DiscoverAvailableToolsOnAnMcpServer).mockResolvedValue({+ status: 401,+ data: { detail: "Bad credential" },+ headers: new Headers(),+ } as never);++ const onSuccess = vi.fn();+ render(<McpConnectPanel onSuccess={onSuccess} />);+ fireEvent.change(screen.getByLabelText(/server url/i), {+ target: { value: "https://mcp.example.com" },});+ fireEvent.click(screen.getByRole("button", { name: /connect/i }));+ await waitFor(() => {+ expect(screen.getByLabelText("Authentication type")).toBeDefined();+ });++ fireEvent.change(screen.getByPlaceholderText(manualTokenPlaceholder), {+ target: { value: "wrong-token" },+ });+ fireEvent.click(screen.getByRole("button", { name: /save token/i }));++ const alert = await screen.findByRole("alert");+ expect(alert.textContent).toContain("Bad credential");+ expect(postV2StoreABearerTokenForAnMcpServer).not.toHaveBeenCalled();+ expect(onSuccess).not.toHaveBeenCalled();+ });++ it("rejects a Basic credential containing whitespace before any request", async () => {+ const {+ postV2DiscoverAvailableToolsOnAnMcpServer,+ postV2InitiateOauthLoginForAnMcpServer,+ postV2StoreABearerTokenForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");++ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({+ status: 400,+ data: { detail: "OAuth not supported" },+ headers: new Headers(),+ } as never);++ render(<McpConnectPanel onSuccess={() => {}} />);+ fireEvent.change(screen.getByLabelText(/server url/i), {+ target: { value: "https://mcp.example.com" },+ });+ fireEvent.click(screen.getByRole("button", { name: /connect/i }));+ await waitFor(() => {+ expect(screen.getByLabelText("Authentication type")).toBeDefined();+ });++ fireEvent.change(screen.getByLabelText("Authentication type"), {+ target: { value: "basic" },+ });+ fireEvent.change(screen.getByPlaceholderText(manualTokenPlaceholder), {+ target: { value: "user pass" },+ });+ fireEvent.click(screen.getByRole("button", { name: /save token/i }));++ const alert = await screen.findByRole("alert");+ expect(alert.textContent).toContain("cannot contain spaces");+ expect(postV2DiscoverAvailableToolsOnAnMcpServer).not.toHaveBeenCalled();+ expect(postV2StoreABearerTokenForAnMcpServer).not.toHaveBeenCalled();});it("lets the user switch from manual-token back to OAuth", async () => {@@ -177,19 +458,84 @@ describe("McpConnectPanel", () => {fireEvent.click(screen.getByRole("button", { name: /connect/i }));await waitFor(() => {- expect(screen.getByPlaceholderText(/paste api token/i)).toBeDefined();+ expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();});- fireEvent.change(screen.getByPlaceholderText(/paste api token/i), {+ fireEvent.change(screen.getByPlaceholderText(manualTokenPlaceholder), {target: { value: "stale-token" },});fireEvent.click(screen.getByRole("button", { name: /try oauth/i }));- expect(screen.queryByPlaceholderText(/paste api token/i)).toBeNull();+ expect(screen.queryByPlaceholderText(manualTokenPlaceholder)).toBeNull();expect(screen.getByRole("button", { name: /connect/i })).toBeDefined();});+ it("discards manual credentials when the server URL changes", async () => {+ const {+ postV2InitiateOauthLoginForAnMcpServer,+ postV2StoreABearerTokenForAnMcpServer,+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");++ vi.mocked(postV2InitiateOauthLoginForAnMcpServer)+ .mockResolvedValueOnce({+ status: 400,+ data: { detail: "OAuth not supported" },+ headers: new Headers(),+ } as never)+ .mockResolvedValueOnce({+ status: 400,+ data: { detail: "OAuth not supported" },+ headers: new Headers(),+ } as never);++ render(<McpConnectPanel onSuccess={() => {}} />);++ const urlInput = screen.getByLabelText(/server url/i);+ fireEvent.change(urlInput, {+ target: { value: "https://server-a.example.com" },+ });+ fireEvent.click(screen.getByRole("button", { name: /connect/i }));++ await waitFor(() => {+ expect(screen.getByLabelText("Authentication type")).toBeDefined();+ });+ fireEvent.change(screen.getByLabelText("Authentication type"), {+ target: { value: "basic" },+ });+ fireEvent.change(screen.getByPlaceholderText(manualTokenPlaceholder), {+ target: { value: "credential-for-server-a" },+ });++ fireEvent.change(urlInput, {+ target: { value: "https://server-b.example.com" },+ });++ expect(screen.queryByLabelText("Authentication type")).toBeNull();+ expect(screen.queryByPlaceholderText(manualTokenPlaceholder)).toBeNull();+ expect(screen.queryByRole("alert")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: /connect/i }));++ await waitFor(() => {+ expect(screen.getByLabelText("Authentication type")).toBeDefined();+ });+ expect(+ (screen.getByLabelText("Authentication type") as HTMLSelectElement).value,+ ).toBe("bearer");+ expect(+ (screen.getByPlaceholderText(manualTokenPlaceholder) as HTMLInputElement)+ .value,+ ).toBe("");+ expect(+ (+ screen.getByRole("button", {+ name: /save token/i,+ }) as HTMLButtonElement+ ).disabled,+ ).toBe(true);+ expect(postV2StoreABearerTokenForAnMcpServer).not.toHaveBeenCalled();+ });+it("surfaces an error when bearer-token submission fails", async () => {const {postV2InitiateOauthLoginForAnMcpServer,@@ -209,14 +555,16 @@ describe("McpConnectPanel", () => {fireEvent.click(screen.getByRole("button", { name: /connect/i }));await waitFor(() => {- expect(screen.getByPlaceholderText(/paste api token/i)).toBeDefined();+ expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();});- vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockRejectedValueOnce(- makeApiError(401, "invalid token"),- );+ vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce({+ status: 401,+ data: { detail: "invalid token" },+ headers: new Headers(),+ } as never);- fireEvent.change(screen.getByPlaceholderText(/paste api token/i), {+ fireEvent.change(screen.getByPlaceholderText(manualTokenPlaceholder), {target: { value: "wrong-token" },});fireEvent.click(screen.getByRole("button", { name: /save token/i }));diff --git a/autogpt_platform/frontend/src/components/contextual/MCPAuthSchemeField/MCPAuthSchemeField.tsx b/autogpt_platform/frontend/src/components/contextual/MCPAuthSchemeField/MCPAuthSchemeField.tsxnew file mode 100644index 0000000000..8c7a9ce933--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/MCPAuthSchemeField/MCPAuthSchemeField.tsx@@ -0,0 +1,51 @@+"use client";++import { useId } from "react";++import type { MCPAuthScheme } from "@/lib/mcp-auth";++interface Props {+ value: MCPAuthScheme;+ onChange: (scheme: MCPAuthScheme) => void;+ disabled?: boolean;+ /** Disambiguates the accessible name when several connectors render at once. */+ nameSuffix?: string;+ className?: string;+ labelClassName?: string;+ selectClassName?: string;+}++/** Bearer/Basic selector shared by every surface that takes a manual MCP credential. */+export function MCPAuthSchemeField({+ value,+ onChange,+ disabled,+ nameSuffix,+ className,+ labelClassName,+ selectClassName,+}: Props) {+ const id = useId();+ const accessibleName = nameSuffix+ ? `Authentication type for ${nameSuffix}`+ : undefined;++ return (+ <div className={className}>+ <label htmlFor={id} className={labelClassName}>+ Authentication type+ </label>+ <select+ id={id}+ aria-label={accessibleName}+ value={value}+ onChange={(e) => onChange(e.target.value as MCPAuthScheme)}+ disabled={disabled}+ className={selectClassName}+ >+ <option value="bearer">API token (Bearer)</option>+ <option value="basic">Basic authentication</option>+ </select>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/components/contextual/MCPAuthSchemeField/helpers.ts b/autogpt_platform/frontend/src/components/contextual/MCPAuthSchemeField/helpers.tsnew file mode 100644index 0000000000..b58d577e9d--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/MCPAuthSchemeField/helpers.ts@@ -0,0 +1,17 @@+import type { MCPAuthScheme } from "@/lib/mcp-auth";++export function mcpAuthTokenLabel(scheme: MCPAuthScheme): string {+ return scheme === "basic" ? "Basic authentication token" : "API token";+}++export function mcpAuthTokenHint(scheme: MCPAuthScheme): string {+ return scheme === "basic"+ ? 'Paste the Base64 of user:password — the value after "Basic" — or the complete Authorization header.'+ : "Paste the token itself. AutoGPT sends it using Bearer authentication.";+}++export function mcpAuthTokenPlaceholder(scheme: MCPAuthScheme): string {+ return scheme === "basic"+ ? "Paste Base64 of user:password"+ : "Paste API token";+}diff --git a/autogpt_platform/frontend/src/components/contextual/MCPAuthSchemeField/useMCPAuthScheme.ts b/autogpt_platform/frontend/src/components/contextual/MCPAuthSchemeField/useMCPAuthScheme.tsnew file mode 100644index 0000000000..1fa05a0a01--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/MCPAuthSchemeField/useMCPAuthScheme.ts@@ -0,0 +1,42 @@+import { useCallback, useEffect, useRef, useState } from "react";++import { detectMCPAuthScheme, type MCPAuthScheme } from "@/lib/mcp-auth";++/**+ * Follows `storedScheme` until the user picks a scheme or types a credential.+ * The callbacks are stable and read `storedScheme` through a ref so memoized+ * callers never pin a stale value.+ */+export function useMCPAuthScheme(+ storedScheme: MCPAuthScheme,+ credential: string,+) {+ const [scheme, setScheme] = useState<MCPAuthScheme>(storedScheme);+ const [locked, setLocked] = useState(false);+ const storedSchemeRef = useRef(storedScheme);+ storedSchemeRef.current = storedScheme;++ useEffect(() => {+ if (!locked && !credential.trim()) setScheme(storedScheme);+ }, [locked, storedScheme, credential]);++ const selectScheme = useCallback((next: MCPAuthScheme) => {+ setScheme(next);+ setLocked(true);+ }, []);++ const detectSchemeFrom = useCallback((value: string) => {+ const detected = detectMCPAuthScheme(value);+ if (detected) {+ setScheme(detected);+ setLocked(true);+ }+ }, []);++ const resetScheme = useCallback(() => {+ setScheme(storedSchemeRef.current);+ setLocked(false);+ }, []);++ return { scheme, selectScheme, detectSchemeFrom, resetScheme };+}diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/CodeGenerationTransport.test.tsx b/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/CodeGenerationTransport.test.tsxindex a16b608a96..256e52aed1 100644--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/CodeGenerationTransport.test.tsx+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/CodeGenerationTransport.test.tsx@@ -125,6 +125,7 @@ function makeProvider(isSystemProvider: false,oAuthCallback: async () => codexCredential,mcpOAuthCallback: async () => codexCredential,+ mcpStoreToken: async () => codexCredential,createAPIKeyCredentials: async () => codexCredential,createUserPasswordCredentials: async () => codexCredential,createHostScopedCredentials: async () => codexCredential,diff --git a/autogpt_platform/frontend/src/hooks/__tests__/useCredentials.test.ts b/autogpt_platform/frontend/src/hooks/__tests__/useCredentials.test.tsindex 0a8181de54..487498848f 100644--- a/autogpt_platform/frontend/src/hooks/__tests__/useCredentials.test.ts+++ b/autogpt_platform/frontend/src/hooks/__tests__/useCredentials.test.ts@@ -112,6 +112,7 @@ describe("useCredentials provider list", () => {isSystemProvider: false,oAuthCallback: vi.fn(),mcpOAuthCallback: vi.fn(),+ mcpStoreToken: vi.fn(),createAPIKeyCredentials: vi.fn(),createUserPasswordCredentials: vi.fn(),createHostScopedCredentials: vi.fn(),@@ -155,6 +156,7 @@ describe("useCredentials provider list", () => {isSystemProvider: false,oAuthCallback: vi.fn(),mcpOAuthCallback: vi.fn(),+ mcpStoreToken: vi.fn(),createAPIKeyCredentials: vi.fn(),createUserPasswordCredentials: vi.fn(),createHostScopedCredentials: vi.fn(),diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.tsindex d2b0389319..457a5cb9b6 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts@@ -622,6 +622,7 @@ export type CredentialsMetaResponse = {scopes?: Array<string>;username?: string;host?: string;+ mcp_auth_scheme?: "basic" | "bearer" | null;is_system?: boolean;is_managed?: boolean;};diff --git a/autogpt_platform/frontend/src/lib/mcp-auth.test.ts b/autogpt_platform/frontend/src/lib/mcp-auth.test.tsnew file mode 100644index 0000000000..b5bc46e58f--- /dev/null+++ b/autogpt_platform/frontend/src/lib/mcp-auth.test.ts@@ -0,0 +1,94 @@+import { readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";++import {+ detectMCPAuthScheme,+ prepareMCPAuthCredential,+ validateMCPAuthCredential,+ type MCPAuthScheme,+} from "./mcp-auth";++interface AuthCase {+ input: string;+ scheme: MCPAuthScheme | null;+ canonical: string;+ headerForm?: boolean;+}++// The backend's copy on purpose: one table keeps the two grammars in step.+const authCases: { accepted: AuthCase[] } = JSON.parse(+ readFileSync(+ resolve(+ dirname(fileURLToPath(import.meta.url)),+ "../../../backend/backend/blocks/mcp/mcp_auth_cases.json",+ ),+ "utf8",+ ),+);++describe("the shared backend/frontend credential grammar", () => {+ it.each(authCases.accepted)(+ "reads $input the way the backend does",+ (authCase) => {+ expect(detectMCPAuthScheme(authCase.input)).toBe(authCase.scheme);+ if (authCase.headerForm) return;+ expect(+ prepareMCPAuthCredential(authCase.input, authCase.scheme ?? "bearer"),+ ).toBe(authCase.canonical);+ },+ );+});++describe("MCP manual authentication helpers", () => {+ it("prefixes a bare Basic credential", () => {+ expect(prepareMCPAuthCredential(" cGstbGYtYWJjZA== ", "basic")).toBe(+ "Basic cGstbGYtYWJjZA==",+ );+ });++ it("keeps a complete Authorization header in header form", () => {+ expect(+ prepareMCPAuthCredential(+ "Authorization: Basic cGstbGYtYWJjZA==",+ "basic",+ ),+ ).toBe("Authorization: Basic cGstbGYtYWJjZA==");+ });++ it("makes the selected scheme authoritative over a pasted prefix", () => {+ expect(prepareMCPAuthCredential("Basic abc", "bearer")).toBe("Bearer abc");+ expect(prepareMCPAuthCredential("Authorization: Bearer abc", "basic")).toBe(+ "Authorization: Basic abc",+ );+ });++ it("preserves unsupported complete Authorization headers for validation", () => {+ expect(+ prepareMCPAuthCredential("Authorization: Digest abc", "bearer"),+ ).toBe("Authorization: Digest abc");+ });++ it("rejects an unencoded user:password under the Basic scheme", () => {+ expect(validateMCPAuthCredential("pk-lf-abc:sk-lf-xyz", "basic")).toMatch(+ /unencoded user:password/,+ );+ expect(+ validateMCPAuthCredential("Basic pk-lf-abc:sk-lf-xyz", "basic"),+ ).toMatch(/unencoded user:password/);+ expect(validateMCPAuthCredential("user:pass", "bearer")).toBeNull();+ });++ it("rejects a Basic credential containing whitespace", () => {+ expect(validateMCPAuthCredential("dXNlcjpwYXNz", "basic")).toBeNull();+ expect(validateMCPAuthCredential("Basic dXNlcjpwYXNz", "basic")).toBeNull();+ expect(validateMCPAuthCredential("Basic auth key", "basic")).toMatch(+ /cannot contain spaces/,+ );+ });++ it("allows whitespace in a Bearer credential", () => {+ expect(validateMCPAuthCredential("orgid api-key", "bearer")).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/lib/mcp-auth.ts b/autogpt_platform/frontend/src/lib/mcp-auth.tsnew file mode 100644index 0000000000..039b1a7908--- /dev/null+++ b/autogpt_platform/frontend/src/lib/mcp-auth.ts@@ -0,0 +1,82 @@+export type MCPAuthScheme = "bearer" | "basic";++const AUTHORIZATION_HEADER_PREFIX = /^authorization\s*:\s*/i;+const SUPPORTED_SCHEME_PREFIX = /^(bearer|basic)\s+(\S[\s\S]*)$/i;++/**+ * Mirrors `normalize_mcp_authorization` in `backend/blocks/mcp/client.py`: the+ * scheme word takes the whole remainder. `mcp_auth_cases.json` pins both sides.+ */+function matchSchemePrefix(+ candidate: string,+): { scheme: MCPAuthScheme; credential: string } | null {+ const match = SUPPORTED_SCHEME_PREFIX.exec(candidate);+ if (!match) return null;+ return {+ scheme: match[1].toLowerCase() as MCPAuthScheme,+ credential: match[2].trim(),+ };+}++/** Detect an explicit Basic/Bearer scheme in a pasted credential. */+export function detectMCPAuthScheme(value: string): MCPAuthScheme | null {+ const candidate = value+ .trim()+ .replace(AUTHORIZATION_HEADER_PREFIX, "")+ .trim();+ return matchSchemePrefix(candidate)?.scheme ?? null;+}++/**+ * Reject a Basic value the server cannot accept: RFC 7617 puts Base64 of+ * `user:password` on the wire, and that alphabet has neither `:` nor spaces.+ * Returns an error message, or null when the value is sendable.+ */+export function validateMCPAuthCredential(+ value: string,+ scheme: MCPAuthScheme,+): string | null {+ if (scheme !== "basic") return null;++ const candidate = value+ .trim()+ .replace(AUTHORIZATION_HEADER_PREFIX, "")+ .trim();+ const credential = matchSchemePrefix(candidate)?.credential ?? candidate;+ if (credential.includes(":")) {+ return "This looks like an unencoded user:password. Basic authentication sends the Base64 of that pair — encode it first, or paste the complete Authorization header.";+ }+ if (/\s/.test(credential)) {+ return "A Basic credential is the Base64 of user:password and cannot contain spaces.";+ }+ return null;+}++/**+ * Bare credentials get the selected scheme as an explicit prefix; the selector+ * is authoritative over any recognized pasted scheme.+ */+export function prepareMCPAuthCredential(+ value: string,+ scheme: MCPAuthScheme,+): string {+ const credential = value.trim();+ if (!credential) return credential;++ const hasAuthorizationHeader = AUTHORIZATION_HEADER_PREFIX.test(credential);+ const candidate = credential.replace(AUTHORIZATION_HEADER_PREFIX, "").trim();+ const recognizedPrefix = matchSchemePrefix(candidate);++ // An unsupported complete header is passed through for the backend to reject.+ if (hasAuthorizationHeader && !recognizedPrefix) return credential;++ const credentialValue = recognizedPrefix+ ? recognizedPrefix.credential+ : candidate;+ const selectedPrefix = scheme === "basic" ? "Basic" : "Bearer";+ const headerPrefix = hasAuthorizationHeader ? "Authorization: " : "";++ return `${headerPrefix}${selectedPrefix}${+ credentialValue ? ` ${credentialValue}` : ""+ }`;+}diff --git a/autogpt_platform/frontend/src/lib/mcp-errors.ts b/autogpt_platform/frontend/src/lib/mcp-errors.tsnew file mode 100644index 0000000000..c80022136f--- /dev/null+++ b/autogpt_platform/frontend/src/lib/mcp-errors.ts@@ -0,0 +1,34 @@+type APIErrorPayload = {+ status?: unknown;+ message?: unknown;+ detail?: unknown;+};++export function getErrorStatus(error: unknown): number | null {+ if (typeof error !== "object" || error === null) return null;+ const status = (error as APIErrorPayload).status;+ return typeof status === "number" ? status : null;+}++export function getErrorMessage(+ error: unknown,+ fallback = "Something went wrong. Please try again.",+): string {+ if (error instanceof Error && error.message) return error.message;+ if (typeof error !== "object" || error === null) return fallback;+ const { message, detail } = error as APIErrorPayload;+ if (typeof detail === "string" && detail) return detail;+ if (typeof message === "string" && message) return message;+ const value = detail ?? message;+ if (value === undefined || value === null) return fallback;+ return JSON.stringify(value) || fallback;+}++export function getAPIResponseError(status: number, data: unknown) {+ if (typeof data !== "object" || data === null) {+ return { status, detail: data };+ }+ const detail = "detail" in data ? data.detail : data;+ const message = "message" in data ? data.message : undefined;+ return { status, detail, message };+}diff --git a/autogpt_platform/frontend/src/lib/mcp-url.ts b/autogpt_platform/frontend/src/lib/mcp-url.tsnew file mode 100644index 0000000000..b0f90f6429--- /dev/null+++ b/autogpt_platform/frontend/src/lib/mcp-url.ts@@ -0,0 +1,17 @@+/** Mirrors the backend `normalize_mcp_url` (`blocks/mcp/helpers.py`). */+export function normalizeMcpUrl(value: string): string {+ return value.trim().replace(/\/+$/, "");+}++/**+ * The origin of a server URL, so editing the path does not count as switching+ * servers. Falls back to the normalized string while the URL is unparseable.+ */+export function mcpServerIdentity(value: string): string {+ const normalized = normalizeMcpUrl(value);+ try {+ return new URL(normalized).origin.toLowerCase();+ } catch {+ return normalized.toLowerCase();+ }+}diff --git a/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider.test.ts b/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider.test.tsindex 7f986789ed..48f4378811 100644--- a/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider.test.ts+++ b/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider.test.ts@@ -35,6 +35,7 @@ function makeProviderMap(isSystemProvider: false,oAuthCallback: async () => makeCred({}),mcpOAuthCallback: async () => makeCred({}),+ mcpStoreToken: async () => makeCred({}),createAPIKeyCredentials: async () => makeCred({}),createUserPasswordCredentials: async () => makeCred({}),createHostScopedCredentials: async () => makeCred({}),diff --git a/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/mcpStoreToken.test.tsx b/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/mcpStoreToken.test.tsxnew file mode 100644index 0000000000..b124f56389--- /dev/null+++ b/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/mcpStoreToken.test.tsx@@ -0,0 +1,146 @@+import type { CredentialsProviderName } from "@/lib/autogpt-server-api";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import * as React from "react";+import { useContext, type ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";++import CredentialsProvider, {+ CredentialsProvidersContext,+} from "../credentials-provider";++const storedCredential = {+ id: "cred-stored",+ provider: "mcp",+ type: "oauth2",+ title: "MCP: mcp.example.com",+ scopes: null,+ username: null,+ host: "https://mcp.example.com/mcp",+ mcp_auth_scheme: "basic",+};++const mocks = vi.hoisted(() => ({+ storeToken: vi.fn(),+ listCredentials: vi.fn(),+}));++vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({ isLoggedIn: true, isUserLoading: false }),+}));++vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({+ postV2StoreABearerTokenForAnMcpServer: mocks.storeToken,+ postV2ExchangeOauthCodeForMcpTokens: vi.fn(),+}));++vi.mock("@/lib/autogpt-server-api/context", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useBackendAPI: () => ({+ listCredentials: mocks.listCredentials,+ listProviders: async () => ["mcp"],+ listSystemProviders: async () => [],+ }),+}));++// Deliberately not `tests/integrations/test-utils`: its wrapper mounts+// `OnboardingProvider`, which reaches for `BackendAPI` methods this file stubs+// out. `CredentialsProvider` itself only needs a query client.+function Wrapper({ children }: { children: ReactNode }) {+ const [queryClient] = React.useState(+ () =>+ new QueryClient({+ defaultOptions: { queries: { retry: false } },+ }),+ );+ return (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+}++function McpConsumer() {+ const providers = useContext(CredentialsProvidersContext);+ const mcp = providers?.["mcp" as CredentialsProviderName];++ if (!mcp) return <span>loading</span>;+ return (+ <div>+ <button+ onClick={() =>+ mcp+ .mcpStoreToken("https://mcp.example.com/mcp", "Basic dXNlcjpwdw==")+ // The refusal case rejects; the assertion is on what the provider+ // map does *not* gain, so swallow it rather than let it surface as+ // an unhandled rejection.+ .catch(() => undefined)+ }+ >+ store credential+ </button>+ <span data-testid="saved-ids">+ {mcp.savedCredentials.map((cred) => cred.id).join(",")}+ </span>+ </div>+ );+}++describe("CredentialsProvider.mcpStoreToken", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.listCredentials.mockResolvedValue([]);+ mocks.storeToken.mockResolvedValue({ status: 200, data: storedCredential });+ });++ // The half this covers that `upsertProviderCredentials` cannot: that+ // `mcpStoreToken` actually feeds the endpoint's result back into the provider+ // map. Binding a node to a credential the map has never seen renders it as+ // "MCP: … was removed" until a full reload, which is the bug this exists to+ // fix — and deleting the `upsertCredentials` call left the suite green.+ it("publishes the stored credential to the provider map", async () => {+ render(+ <CredentialsProvider>+ <McpConsumer />+ </CredentialsProvider>,+ { wrapper: Wrapper },+ );++ await waitFor(() =>+ expect(screen.getByTestId("saved-ids").textContent).toBe(""),+ );++ fireEvent.click(screen.getByRole("button", { name: "store credential" }));++ await waitFor(() =>+ expect(screen.getByTestId("saved-ids").textContent).toBe("cred-stored"),+ );+ expect(mocks.storeToken).toHaveBeenCalledWith({+ server_url: "https://mcp.example.com/mcp",+ token: "Basic dXNlcjpwdw==",+ });+ });++ it("does not publish anything when the endpoint refuses the credential", async () => {+ mocks.storeToken.mockResolvedValue({+ status: 422,+ data: {+ detail: "Basic authentication expects the Base64 of user:password",+ },+ });++ render(+ <CredentialsProvider>+ <McpConsumer />+ </CredentialsProvider>,+ { wrapper: Wrapper },+ );++ await waitFor(() =>+ expect(screen.getByTestId("saved-ids").textContent).toBe(""),+ );++ fireEvent.click(screen.getByRole("button", { name: "store credential" }));++ await waitFor(() => expect(mocks.storeToken).toHaveBeenCalled());+ expect(screen.getByTestId("saved-ids").textContent).toBe("");+ });+});diff --git a/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx b/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsxindex fdd4f3a1fe..4eee51f484 100644--- a/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx+++ b/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx@@ -9,7 +9,10 @@ import {UserPasswordCredentials,} from "@/lib/autogpt-server-api";import { getGetV1ListCredentialsQueryKey } from "@/app/api/__generated__/endpoints/integrations/integrations";-import { postV2ExchangeOauthCodeForMcpTokens } from "@/app/api/__generated__/endpoints/mcp/mcp";+import {+ postV2ExchangeOauthCodeForMcpTokens,+ postV2StoreABearerTokenForAnMcpServer,+} from "@/app/api/__generated__/endpoints/mcp/mcp";import { useBackendAPI } from "@/lib/autogpt-server-api/context";import { useAuth } from "@/lib/auth/hooks/useAuth";import { toDisplayName } from "@/providers/agent-credentials/helper";@@ -46,6 +49,11 @@ export type CredentialsProviderData = {code: string,state_token: string,) => Promise<CredentialsMetaResponse>;+ /** Stores a manually entered MCP credential for a server without OAuth. */+ mcpStoreToken: (+ server_url: string,+ token: string,+ ) => Promise<CredentialsMetaResponse>;createAPIKeyCredentials: (credentials: APIKeyCredentialsCreatable,) => Promise<CredentialsMetaResponse>;@@ -186,6 +194,30 @@ export default function CredentialsProvider({[upsertCredentials, onFailToast],);+ /** Stores a manual MCP credential, and adds the result to the internal credentials store. */+ const mcpStoreToken = useCallback(+ async (+ server_url: string,+ token: string,+ ): Promise<CredentialsMetaResponse> => {+ const response = await postV2StoreABearerTokenForAnMcpServer({+ server_url,+ token,+ });+ if (response.status !== 200) throw response.data;+ const credsMeta: CredentialsMetaResponse = {+ ...response.data,+ title: response.data.title ?? undefined,+ scopes: response.data.scopes ?? undefined,+ username: response.data.username ?? undefined,+ host: response.data.host ?? undefined,+ };+ upsertCredentials("mcp", credsMeta);+ return credsMeta;+ },+ [upsertCredentials],+ );+/** Wraps `BackendAPI.createAPIKeyCredentials`, and adds the result to the internal credentials store. */const createAPIKeyCredentials = useCallback(async (@@ -336,6 +368,7 @@ export default function CredentialsProvider({oAuthCallback: (code: string, state_token: string) =>oAuthCallback(provider, code, state_token),mcpOAuthCallback,+ mcpStoreToken,createAPIKeyCredentials: (credentials: APIKeyCredentialsCreatable,) => createAPIKeyCredentials(provider, credentials),@@ -366,6 +399,7 @@ export default function CredentialsProvider({deleteCredentials,oAuthCallback,mcpOAuthCallback,+ mcpStoreToken,onFailToast,]);