Skip to content

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(copilot): run_mcp_tool — MCP server discovery and execution in Otto (#12213)

Zamil Majdy7fd26d35540f
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index de4226d2d0..4564e73234 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -42,6 +42,8 @@ from backend.copilot.tools.models import (
ErrorResponse,
ExecutionStartedResponse,
InputValidationErrorResponse,
+ MCPToolOutputResponse,
+ MCPToolsDiscoveredResponse,
NeedLoginResponse,
NoResultsResponse,
SetupRequirementsResponse,
@@ -854,6 +856,8 @@ ToolResponseUnion = (
| BlockOutputResponse
| DocSearchResultsResponse
| DocPageResponse
+ | MCPToolsDiscoveredResponse
+ | MCPToolOutputResponse
)
diff --git a/autogpt_platform/backend/backend/api/features/mcp/routes.py b/autogpt_platform/backend/backend/api/features/mcp/routes.py
index f8d311f372..cdf827feed 100644
--- a/autogpt_platform/backend/backend/api/features/mcp/routes.py
+++ b/autogpt_platform/backend/backend/api/features/mcp/routes.py
@@ -7,20 +7,24 @@ frontend can list available tools on an MCP server before placing a block.
import logging
from typing import Annotated, Any
-from urllib.parse import urlparse
import fastapi
from autogpt_libs.auth import get_user_id
from fastapi import Security
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, SecretStr
from backend.api.features.integrations.router import CredentialsMetaResponse
from backend.blocks.mcp.client import MCPClient, MCPClientError
+from backend.blocks.mcp.helpers import (
+ auto_lookup_mcp_credential,
+ normalize_mcp_url,
+ server_host,
+)
from backend.blocks.mcp.oauth import MCPOAuthHandler
from backend.data.model import OAuth2Credentials
from backend.integrations.creds_manager import IntegrationCredentialsManager
from backend.integrations.providers import ProviderName
-from backend.util.request import HTTPClientError, Requests
+from backend.util.request import HTTPClientError, Requests, validate_url
from backend.util.settings import Settings
logger = logging.getLogger(__name__)
@@ -74,32 +78,20 @@ async def discover_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.
"""
+ # Validate URL to prevent SSRF — blocks loopback and private IP ranges.
+ try:
+ await validate_url(request.server_url, trusted_origins=[])
+ 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:
- mcp_creds = await creds_manager.store.get_creds_by_provider(
- user_id, ProviderName.MCP.value
+ best_cred = await auto_lookup_mcp_credential(
+ user_id, normalize_mcp_url(request.server_url)
)
- # Find the freshest credential for this server URL
- best_cred: OAuth2Credentials | None = None
- for cred in mcp_creds:
- if (
- isinstance(cred, OAuth2Credentials)
- and (cred.metadata or {}).get("mcp_server_url") == request.server_url
- ):
- if best_cred is None or (
- (cred.access_token_expires_at or 0)
- > (best_cred.access_token_expires_at or 0)
- ):
- best_cred = cred
if best_cred:
- # Refresh the token if expired before using it
- best_cred = await creds_manager.refresh_if_needed(user_id, best_cred)
- logger.info(
- f"Using MCP credential {best_cred.id} for {request.server_url}, "
- f"expires_at={best_cred.access_token_expires_at}"
- )
auth_token = best_cred.access_token.get_secret_value()
client = MCPClient(request.server_url, auth_token=auth_token)
@@ -134,7 +126,7 @@ async def discover_tools(
],
server_name=(
init_result.get("serverInfo", {}).get("name")
- or urlparse(request.server_url).hostname
+ or server_host(request.server_url)
or "MCP"
),
protocol_version=init_result.get("protocolVersion"),
@@ -173,7 +165,16 @@ async def mcp_oauth_login(
3. Performs Dynamic Client Registration (RFC 7591) if available
4. Returns the authorization URL for the frontend to open in a popup
"""
- client = MCPClient(request.server_url)
+ # Validate URL to prevent SSRF — blocks loopback and private IP ranges.
+ try:
+ await validate_url(request.server_url, trusted_origins=[])
+ except ValueError as e:
+ raise fastapi.HTTPException(status_code=400, detail=f"Invalid server URL: {e}")
+
+ # Normalize the URL so that credentials stored here are matched consistently
+ # by auto_lookup_mcp_credential (which also uses normalized URLs).
+ server_url = normalize_mcp_url(request.server_url)
+ client = MCPClient(server_url)
# Step 1: Discover protected-resource metadata (RFC 9728)
protected_resource = await client.discover_auth()
@@ -182,7 +183,16 @@ async def mcp_oauth_login(
if protected_resource and protected_resource.get("authorization_servers"):
auth_server_url = protected_resource["authorization_servers"][0]
- resource_url = protected_resource.get("resource", request.server_url)
+ resource_url = protected_resource.get("resource", server_url)
+
+ # Validate the auth server URL from metadata to prevent SSRF.
+ try:
+ await validate_url(auth_server_url, trusted_origins=[])
+ except ValueError as e:
+ raise fastapi.HTTPException(
+ status_code=400,
+ detail=f"Invalid authorization server URL in metadata: {e}",
+ )
# Step 2a: Discover auth-server metadata (RFC 8414)
metadata = await client.discover_auth_server_metadata(auth_server_url)
@@ -192,7 +202,7 @@ async def mcp_oauth_login(
# Don't assume a resource_url — omitting it lets the auth server choose
# the correct audience for the token (RFC 8707 resource is optional).
resource_url = None
- metadata = await client.discover_auth_server_metadata(request.server_url)
+ metadata = await client.discover_auth_server_metadata(server_url)
if (
not metadata
@@ -222,12 +232,18 @@ async def mcp_oauth_login(
client_id = ""
client_secret = ""
if registration_endpoint:
- reg_result = await _register_mcp_client(
- registration_endpoint, redirect_uri, request.server_url
- )
- if reg_result:
- client_id = reg_result.get("client_id", "")
- client_secret = reg_result.get("client_secret", "")
+ # Validate the registration endpoint to prevent SSRF via metadata.
+ try:
+ await validate_url(registration_endpoint, trusted_origins=[])
+ except ValueError:
+ pass # Skip registration, fall back to default client_id
+ else:
+ reg_result = await _register_mcp_client(
+ registration_endpoint, redirect_uri, server_url
+ )
+ if reg_result:
+ client_id = reg_result.get("client_id", "")
+ client_secret = reg_result.get("client_secret", "")
if not client_id:
client_id = "autogpt-platform"
@@ -245,7 +261,7 @@ async def mcp_oauth_login(
"token_url": token_url,
"revoke_url": revoke_url,
"resource_url": resource_url,
- "server_url": request.server_url,
+ "server_url": server_url,
"client_id": client_id,
"client_secret": client_secret,
},
@@ -342,7 +358,7 @@ async def mcp_oauth_callback(
credentials.metadata["mcp_token_url"] = meta["token_url"]
credentials.metadata["mcp_resource_url"] = meta.get("resource_url", "")
- hostname = urlparse(meta["server_url"]).hostname or meta["server_url"]
+ hostname = server_host(meta["server_url"])
credentials.title = f"MCP: {hostname}"
# Remove old MCP credentials for the same server to prevent stale token buildup.
@@ -357,7 +373,9 @@ async def mcp_oauth_callback(
):
await creds_manager.store.delete_creds_by_id(user_id, old.id)
logger.info(
- f"Removed old MCP credential {old.id} for {meta['server_url']}"
+ "Removed old MCP credential %s for %s",
+ old.id,
+ server_host(meta["server_url"]),
)
except Exception:
logger.debug("Could not clean up old MCP credentials", exc_info=True)
@@ -375,6 +393,93 @@ async def mcp_oauth_callback(
)
+# ======================== Bearer Token ======================== #
+
+
+class MCPStoreTokenRequest(BaseModel):
+ """Request to store a bearer token for an MCP server that doesn't support OAuth."""
+
+ server_url: str = Field(
+ description="MCP server URL the token authenticates against"
+ )
+ token: SecretStr = Field(
+ min_length=1, description="Bearer token / API key for the MCP server"
+ )
+
+
+ "/token",
+ summary="Store a bearer token for an MCP server",
+)
+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.
+
+ Used by the Copilot MCPSetupCard when the server doesn't support the MCP
+ OAuth discovery flow (returns 400 from /oauth/login). Subsequent
+ ``run_mcp_tool`` calls will automatically pick up the token 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.")
+
+ # Validate URL to prevent SSRF — blocks loopback and private IP ranges.
+ try:
+ await validate_url(request.server_url, trusted_origins=[])
+ except ValueError as e:
+ raise fastapi.HTTPException(status_code=400, detail=f"Invalid server URL: {e}")
+
+ # Normalize URL so trailing-slash variants match existing credentials.
+ 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] = []
+ 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)
+
+ # Only delete old credentials after the new one is safely stored.
+ for old_id in old_cred_ids:
+ try:
+ await creds_manager.store.delete_creds_by_id(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,
+ host=hostname,
+ )
+
+
# ======================== Helpers ======================== #
@@ -400,5 +505,7 @@ async def _register_mcp_client(
return data
return None
except Exception as e:
- logger.warning(f"Dynamic client registration failed for {server_url}: {e}")
+ logger.warning(
+ "Dynamic client registration failed for %s: %s", server_host(server_url), e
+ )
return None
diff --git a/autogpt_platform/backend/backend/api/features/mcp/test_routes.py b/autogpt_platform/backend/backend/api/features/mcp/test_routes.py
index e86b9f4865..db23c40dbd 100644
--- a/autogpt_platform/backend/backend/api/features/mcp/test_routes.py
+++ b/autogpt_platform/backend/backend/api/features/mcp/test_routes.py
@@ -11,9 +11,11 @@ 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.client import MCPClientError, MCPTool
+from backend.data.model import OAuth2Credentials
from backend.util.request import HTTPClientError
app = fastapi.FastAPI()
@@ -28,6 +30,16 @@ async def client():
yield c
[email protected](autouse=True)
+def _bypass_ssrf_validation():
+ """Bypass validate_url in all route tests (test URLs don't resolve)."""
+ with patch(
+ "backend.api.features.mcp.routes.validate_url",
+ new_callable=AsyncMock,
+ ):
+ yield
+
+
class TestDiscoverTools:
@pytest.mark.asyncio(loop_scope="session")
async def test_discover_tools_success(self, client):
@@ -56,9 +68,12 @@ class TestDiscoverTools:
with (
patch("backend.api.features.mcp.routes.MCPClient") as MockClient,
- patch("backend.api.features.mcp.routes.creds_manager") as mock_cm,
+ patch(
+ "backend.api.features.mcp.routes.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ),
):
- mock_cm.store.get_creds_by_provider = AsyncMock(return_value=[])
instance = MockClient.return_value
instance.initialize = AsyncMock(
return_value={
@@ -107,10 +122,6 @@ class TestDiscoverTools:
@pytest.mark.asyncio(loop_scope="session")
async def test_discover_tools_auto_uses_stored_credential(self, client):
"""When no explicit token is given, stored MCP credentials are used."""
- from pydantic import SecretStr
-
- from backend.data.model import OAuth2Credentials
-
stored_cred = OAuth2Credentials(
provider="mcp",
title="MCP: example.com",
@@ -124,10 +135,12 @@ class TestDiscoverTools:
with (
patch("backend.api.features.mcp.routes.MCPClient") as MockClient,
- patch("backend.api.features.mcp.routes.creds_manager") as mock_cm,
+ patch(
+ "backend.api.features.mcp.routes.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=stored_cred,
+ ),
):
- mock_cm.store.get_creds_by_provider = AsyncMock(return_value=[stored_cred])
- mock_cm.refresh_if_needed = AsyncMock(return_value=stored_cred)
instance = MockClient.return_value
instance.initialize = AsyncMock(
return_value={"serverInfo": {}, "protocolVersion": "2025-03-26"}
@@ -149,9 +162,12 @@ class TestDiscoverTools:
async def test_discover_tools_mcp_error(self, client):
with (
patch("backend.api.features.mcp.routes.MCPClient") as MockClient,
- patch("backend.api.features.mcp.routes.creds_manager") as mock_cm,
+ patch(
+ "backend.api.features.mcp.routes.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ),
):
- mock_cm.store.get_creds_by_provider = AsyncMock(return_value=[])
instance = MockClient.return_value
instance.initialize = AsyncMock(
side_effect=MCPClientError("Connection refused")
@@ -169,9 +185,12 @@ class TestDiscoverTools:
async def test_discover_tools_generic_error(self, client):
with (
patch("backend.api.features.mcp.routes.MCPClient") as MockClient,
- patch("backend.api.features.mcp.routes.creds_manager") as mock_cm,
+ patch(
+ "backend.api.features.mcp.routes.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ),
):
- mock_cm.store.get_creds_by_provider = AsyncMock(return_value=[])
instance = MockClient.return_value
instance.initialize = AsyncMock(side_effect=Exception("Network timeout"))
@@ -187,9 +206,12 @@ class TestDiscoverTools:
async def test_discover_tools_auth_required(self, client):
with (
patch("backend.api.features.mcp.routes.MCPClient") as MockClient,
- patch("backend.api.features.mcp.routes.creds_manager") as mock_cm,
+ patch(
+ "backend.api.features.mcp.routes.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ),
):
- mock_cm.store.get_creds_by_provider = AsyncMock(return_value=[])
instance = MockClient.return_value
instance.initialize = AsyncMock(
side_effect=HTTPClientError("HTTP 401 Error: Unauthorized", 401)
@@ -207,9 +229,12 @@ class TestDiscoverTools:
async def test_discover_tools_forbidden(self, client):
with (
patch("backend.api.features.mcp.routes.MCPClient") as MockClient,
- patch("backend.api.features.mcp.routes.creds_manager") as mock_cm,
+ patch(
+ "backend.api.features.mcp.routes.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ),
):
- mock_cm.store.get_creds_by_provider = AsyncMock(return_value=[])
instance = MockClient.return_value
instance.initialize = AsyncMock(
side_effect=HTTPClientError("HTTP 403 Error: Forbidden", 403)
@@ -331,10 +356,6 @@ class TestOAuthLogin:
class TestOAuthCallback:
@pytest.mark.asyncio(loop_scope="session")
async def test_oauth_callback_success(self, client):
- from pydantic import SecretStr
-
- from backend.data.model import OAuth2Credentials
-
mock_creds = OAuth2Credentials(
provider="mcp",
title=None,
@@ -434,3 +455,118 @@ class TestOAuthCallback:
assert response.status_code == 400
assert "token exchange failed" in response.json()["detail"].lower()
+
+
+class TestStoreToken:
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_store_token_success(self, client):
+ 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()
+
+ response = await client.post(
+ "/token",
+ json={
+ "server_url": "https://mcp.example.com/mcp",
+ "token": "my-api-key-123",
+ },
+ )
+
+ assert response.status_code == 200
+ data = response.json()
+ assert data["provider"] == "mcp"
+ assert data["type"] == "oauth2"
+ assert data["host"] == "mcp.example.com"
+ mock_cm.create.assert_called_once()
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_store_token_blank_rejected(self, client):
+ """Blank token string (after stripping) should return 422."""
+ response = await client.post(
+ "/token",
+ json={
+ "server_url": "https://mcp.example.com/mcp",
+ "token": " ",
+ },
+ )
+ # Pydantic min_length=1 catches the whitespace-only token
+ assert response.status_code == 422
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_store_token_replaces_old_credential(self, client):
+ old_cred = OAuth2Credentials(
+ provider="mcp",
+ title="MCP: mcp.example.com",
+ access_token=SecretStr("old-token"),
+ 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.store.delete_creds_by_id = AsyncMock()
+
+ response = await client.post(
+ "/token",
+ json={
+ "server_url": "https://mcp.example.com/mcp",
+ "token": "new-token",
+ },
+ )
+
+ assert response.status_code == 200
+ mock_cm.store.delete_creds_by_id.assert_called_once_with(
+ "test-user-id", old_cred.id
+ )
+
+
+class TestSSRFValidation:
+ """Verify that validate_url is enforced on all endpoints."""
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_discover_tools_ssrf_blocked(self, client):
+ with patch(
+ "backend.api.features.mcp.routes.validate_url",
+ new_callable=AsyncMock,
+ side_effect=ValueError("blocked loopback"),
+ ):
+ response = await client.post(
+ "/discover-tools",
+ json={"server_url": "http://localhost/mcp"},
+ )
+
+ assert response.status_code == 400
+ assert "blocked loopback" in response.json()["detail"].lower()
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_oauth_login_ssrf_blocked(self, client):
+ with patch(
+ "backend.api.features.mcp.routes.validate_url",
+ new_callable=AsyncMock,
+ side_effect=ValueError("blocked private IP"),
+ ):
+ response = await client.post(
+ "/oauth/login",
+ json={"server_url": "http://10.0.0.1/mcp"},
+ )
+
+ assert response.status_code == 400
+ assert "blocked private ip" in response.json()["detail"].lower()
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_store_token_ssrf_blocked(self, client):
+ with patch(
+ "backend.api.features.mcp.routes.validate_url",
+ new_callable=AsyncMock,
+ side_effect=ValueError("blocked loopback"),
+ ):
+ response = await client.post(
+ "/token",
+ json={
+ "server_url": "http://127.0.0.1/mcp",
+ "token": "some-token",
+ },
+ )
+
+ assert response.status_code == 400
+ assert "blocked loopback" in response.json()["detail"].lower()
diff --git a/autogpt_platform/backend/backend/blocks/mcp/block.py b/autogpt_platform/backend/backend/blocks/mcp/block.py
index 9e3056d928..bf16e25595 100644
--- a/autogpt_platform/backend/backend/blocks/mcp/block.py
+++ b/autogpt_platform/backend/backend/blocks/mcp/block.py
@@ -6,7 +6,6 @@ and execute them. Works like AgentExecutorBlock — the user selects a tool from
dropdown and the input/output schema adapts dynamically.
"""
-import json
import logging
from typing import Any, Literal
@@ -20,6 +19,11 @@ from backend.blocks._base import (
BlockType,
)
from backend.blocks.mcp.client import MCPClient, MCPClientError
+from backend.blocks.mcp.helpers import (
+ auto_lookup_mcp_credential,
+ normalize_mcp_url,
+ parse_mcp_content,
+)
from backend.data.block import BlockInput, BlockOutput
from backend.data.model import (
CredentialsField,
@@ -179,31 +183,7 @@ class MCPToolBlock(Block):
f"{error_text or 'Unknown error'}"
)
- # Extract text content from the result
- output_parts = []
- for item in result.content:
- if item.get("type") == "text":
- text = item.get("text", "")
- # Try to parse as JSON for structured output
- try:
- output_parts.append(json.loads(text))
- except (json.JSONDecodeError, ValueError):
- output_parts.append(text)
- elif item.get("type") == "image":
- output_parts.append(
- {
- "type": "image",
- "data": item.get("data"),
- "mimeType": item.get("mimeType"),
- }
- )
- elif item.get("type") == "resource":
- output_parts.append(item.get("resource", {}))
-
- # If single result, unwrap
- if len(output_parts) == 1:
- return output_parts[0]
- return output_parts if output_parts else None
+ return parse_mcp_content(result.content)
@staticmethod
async def _auto_lookup_credential(
@@ -211,37 +191,10 @@ class MCPToolBlock(Block):
) -> "OAuth2Credentials | None":
"""Auto-lookup stored MCP credential for a server URL.
- This is a fallback for nodes that don't have ``credentials`` explicitly
- set (e.g. nodes created before the credential field was wired up).
+ Delegates to :func:`~backend.blocks.mcp.helpers.auto_lookup_mcp_credential`.
+ The caller should pass a normalized URL.
"""
- from backend.integrations.creds_manager import IntegrationCredentialsManager
- from backend.integrations.providers import ProviderName
-
- try:
- mgr = IntegrationCredentialsManager()
- mcp_creds = await mgr.store.get_creds_by_provider(
- user_id, ProviderName.MCP.value
- )
- best: OAuth2Credentials | None = None
- for 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)
- ):
- best = cred
- if best:
- best = await mgr.refresh_if_needed(user_id, best)
- logger.info(
- "Auto-resolved MCP credential %s for %s", best.id, server_url
- )
- return best
- except Exception:
- logger.warning("Auto-lookup MCP credential failed", exc_info=True)
- return None
+ return await auto_lookup_mcp_credential(user_id, server_url)
async def run(
self,
@@ -278,7 +231,7 @@ class MCPToolBlock(Block):
# the stored MCP credential for this server URL.
if credentials is None:
credentials = await self._auto_lookup_credential(
- user_id, input_data.server_url
+ user_id, normalize_mcp_url(input_data.server_url)
)
auth_token = (
diff --git a/autogpt_platform/backend/backend/blocks/mcp/client.py b/autogpt_platform/backend/backend/blocks/mcp/client.py
index 050349dbcc..a0386c3b14 100644
--- a/autogpt_platform/backend/backend/blocks/mcp/client.py
+++ b/autogpt_platform/backend/backend/blocks/mcp/client.py
@@ -55,7 +55,9 @@ class MCPClient:
server_url: str,
auth_token: str | None = None,
):
- self.server_url = server_url.rstrip("/")
+ from backend.blocks.mcp.helpers import normalize_mcp_url
+
+ self.server_url = normalize_mcp_url(server_url)
self.auth_token = auth_token
self._request_id = 0
self._session_id: str | None = None
diff --git a/autogpt_platform/backend/backend/blocks/mcp/helpers.py b/autogpt_platform/backend/backend/blocks/mcp/helpers.py
new file mode 100644
index 0000000000..bec173ba8b
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/mcp/helpers.py
@@ -0,0 +1,117 @@
+"""Shared MCP helpers used by blocks, copilot tools, and API routes."""
+
+from __future__ import annotations
+
+import json
+import logging
+from typing import TYPE_CHECKING, Any
+from urllib.parse import urlparse
+
+if TYPE_CHECKING:
+ from backend.data.model import OAuth2Credentials
+
+logger = logging.getLogger(__name__)
+
+
+def normalize_mcp_url(url: str) -> str:
+ """Normalize an MCP server URL for consistent credential matching.
+
+ Strips leading/trailing whitespace and a single trailing slash so that
+ ``https://mcp.example.com/`` and ``https://mcp.example.com`` resolve to
+ the same stored credential.
+ """
+ return url.strip().rstrip("/")
+
+
+def server_host(server_url: str) -> str:
+ """Extract the hostname from a server URL for display purposes.
+
+ Uses ``parsed.hostname`` (never ``netloc``) to strip any embedded
+ username/password before surfacing the value in UI messages.
+ """
+ try:
+ parsed = urlparse(server_url)
+ return parsed.hostname or server_url
+ except Exception:
+ return server_url
+
+
+def parse_mcp_content(content: list[dict[str, Any]]) -> Any:
+ """Parse MCP tool response content into a plain Python value.
+
+ - text items: parsed as JSON when possible, kept as str otherwise
+ - image items: kept as ``{type, data, mimeType}`` dict for frontend rendering
+ - resource items: unwrapped to their resource payload dict
+
+ Single-item responses are unwrapped from the list; multiple items are
+ returned as a list; empty content returns ``None``.
+ """
+ output_parts: list[Any] = []
+ for item in content:
+ item_type = item.get("type")
+ if item_type == "text":
+ text = item.get("text", "")
+ try:
+ output_parts.append(json.loads(text))
+ except (json.JSONDecodeError, ValueError):
+ output_parts.append(text)
+ elif item_type == "image":
+ output_parts.append(
+ {
+ "type": "image",
+ "data": item.get("data"),
+ "mimeType": item.get("mimeType"),
+ }
+ )
+ elif item_type == "resource":
+ output_parts.append(item.get("resource", {}))
+
+ if len(output_parts) == 1:
+ return output_parts[0]
+ return output_parts or None
+
+
+async def auto_lookup_mcp_credential(
+ user_id: str, server_url: str
+) -> OAuth2Credentials | None:
+ """Look up the best stored MCP credential for *server_url*.
+
+ The caller should pass a **normalized** URL (via :func:`normalize_mcp_url`)
+ 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.
+ """
+ from backend.data.model import OAuth2Credentials
+ from backend.integrations.creds_manager import IntegrationCredentialsManager
+ from backend.integrations.providers import ProviderName
+
+ 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: OAuth2Credentials | None = None
+ for 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)
+ ):
+ best = cred
+ if best:
+ best = await mgr.refresh_if_needed(user_id, best)
+ logger.info("Auto-resolved MCP credential %s for %s", best.id, server_url)
+ return best
+ except Exception:
+ logger.warning("Auto-lookup MCP credential failed", exc_info=True)
+ return None
diff --git a/autogpt_platform/backend/backend/blocks/mcp/test_helpers.py b/autogpt_platform/backend/backend/blocks/mcp/test_helpers.py
new file mode 100644
index 0000000000..f04f8b5a53
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/mcp/test_helpers.py
@@ -0,0 +1,98 @@
+"""Unit tests for the shared MCP helpers."""
+
+from backend.blocks.mcp.helpers import normalize_mcp_url, parse_mcp_content, server_host
+
+# ---------------------------------------------------------------------------
+# normalize_mcp_url
+# ---------------------------------------------------------------------------
+
+
+def test_normalize_trailing_slash():
+ assert normalize_mcp_url("https://mcp.example.com/") == "https://mcp.example.com"
+
+
+def test_normalize_whitespace():
+ assert normalize_mcp_url(" https://mcp.example.com ") == "https://mcp.example.com"
+
+
+def test_normalize_both():
+ assert (
+ normalize_mcp_url(" https://mcp.example.com/ ") == "https://mcp.example.com"
+ )
+
+
+def test_normalize_noop():
+ assert normalize_mcp_url("https://mcp.example.com") == "https://mcp.example.com"
+
+
+def test_normalize_path_with_trailing_slash():
+ assert (
+ normalize_mcp_url("https://mcp.example.com/path/")
+ == "https://mcp.example.com/path"
+ )
+
+
+# ---------------------------------------------------------------------------
+# server_host
+# ---------------------------------------------------------------------------
+
+
+def test_server_host_standard_url():
+ assert server_host("https://mcp.example.com/mcp") == "mcp.example.com"
+
+
+def test_server_host_strips_credentials():
+ """hostname must not expose user:pass."""
+ assert server_host("https://user:[email protected]/mcp") == "mcp.example.com"
+
+
+def test_server_host_with_port():
+ """Port should not appear in hostname (hostname strips it)."""
+ assert server_host("https://mcp.example.com:8080/mcp") == "mcp.example.com"
+
+
+def test_server_host_fallback():
+ """Falls back to the raw string for un-parseable URLs."""
+ assert server_host("not-a-url") == "not-a-url"
+
+
+# ---------------------------------------------------------------------------
+# parse_mcp_content
+# ---------------------------------------------------------------------------
+
+
+def test_parse_text_plain():
+ assert parse_mcp_content([{"type": "text", "text": "hello world"}]) == "hello world"
+
+
+def test_parse_text_json():
+ content = [{"type": "text", "text": '{"status": "ok", "count": 42}'}]
+ assert parse_mcp_content(content) == {"status": "ok", "count": 42}
+
+
+def test_parse_image():
+ content = [{"type": "image", "data": "abc123==", "mimeType": "image/png"}]
+ assert parse_mcp_content(content) == {
+ "type": "image",
+ "data": "abc123==",
+ "mimeType": "image/png",
+ }
+
+
+def test_parse_resource():
+ content = [
+ {"type": "resource", "resource": {"uri": "file:///tmp/out.txt", "text": "hi"}}
+ ]
+ assert parse_mcp_content(content) == {"uri": "file:///tmp/out.txt", "text": "hi"}
+
+
+def test_parse_multi_item():
+ content = [
+ {"type": "text", "text": "first"},
+ {"type": "text", "text": "second"},
+ ]
+ assert parse_mcp_content(content) == ["first", "second"]
+
+
+def test_parse_empty():
+ assert parse_mcp_content([]) is None
diff --git a/autogpt_platform/backend/backend/copilot/service.py b/autogpt_platform/backend/backend/copilot/service.py
index 52033ed130..181d119587 100644
--- a/autogpt_platform/backend/backend/copilot/service.py
+++ b/autogpt_platform/backend/backend/copilot/service.py
@@ -107,6 +107,7 @@ Adapt flexibly to the conversation context. Not every interaction requires all s
- **Always check the user's library first** with `find_library_agent` (these may be customized to their needs)
- Search the marketplace with `find_agent` for pre-built automations
- Find reusable components with `find_block`
+ - **For live integrations** (read a GitHub repo, query a database, post to Slack, etc.) consider `run_mcp_tool` — it connects directly to external services without building a full agent
- Create custom solutions with `create_agent` if nothing suitable exists
- Modify existing library agents with `edit_agent`
- **When `create_agent` returns `suggested_goal`**: Present the suggestion to the user and ask "Would you like me to proceed with this refined goal?" If they accept, call `create_agent` again with the suggested goal.
@@ -137,6 +138,31 @@ Adapt flexibly to the conversation context. Not every interaction requires all s
- `run_block`: Test or run a specific block independently
- `agent_output`: View results from previous agent runs
+**MCP (Model Context Protocol) Servers:**
+- `run_mcp_tool`: Connect to any MCP server to discover and run its tools
+
+ **Two-step flow:**
+ 1. `run_mcp_tool(server_url)` → returns a list of available tools. Each tool has `name`, `description`, and `input_schema` (JSON Schema). Read `input_schema.properties` to understand what arguments are needed.
+ 2. `run_mcp_tool(server_url, tool_name, tool_arguments)` → executes the tool. Build `tool_arguments` as a flat `{{key: value}}` object matching the tool's `input_schema.properties`.
+
+ **Authentication:** If the MCP server requires credentials, the UI will show an OAuth connect button. Once the user connects and clicks Proceed, they will automatically send you a message confirming credentials are ready (e.g. "I've connected the MCP server credentials. Please retry run_mcp_tool..."). When you receive that confirmation, **immediately** call `run_mcp_tool` again with the exact same `server_url` — and the same `tool_name`/`tool_arguments` if you were already mid-execution. Do not ask the user what to do next; just retry.
+
+ **Finding server URLs (fastest → slowest):**
+ 1. **Known hosted servers** — use directly, no lookup:
+ - Notion: `https://mcp.notion.com/mcp`
+ - Linear: `https://mcp.linear.app/mcp`
+ - Stripe: `https://mcp.stripe.com`
+ - Intercom: `https://mcp.intercom.com/mcp`
+ - Cloudflare: `https://mcp.cloudflare.com/mcp`
+ - Atlassian (Jira/Confluence): `https://mcp.atlassian.com/mcp`
+ 2. **`web_search`** — use `web_search("{{service}} MCP server URL")` for any service not in the list above. This is the fastest way to find unlisted servers.
+ 3. **Registry API** — `web_fetch("https://registry.modelcontextprotocol.io/v0.1/servers?search={{query}}&limit=10")` to browse what's available. Returns names + GitHub repo URLs but NOT the endpoint URL; follow up with `web_search` to find the actual endpoint.
+ - **Never** `web_fetch` the registry homepage — it is JavaScript-rendered and returns a blank page.
+
+ **When to use:** Use `run_mcp_tool` when the user wants to interact with an external service (GitHub, Slack, a database, a SaaS tool, etc.) via its MCP integration. Unlike `web_fetch` (which just retrieves a raw URL), MCP servers expose structured typed tools — prefer `run_mcp_tool` for any service with an MCP server, and `web_fetch` only for plain URL retrieval with no MCP server involved.
+
+ **CRITICAL**: `run_mcp_tool` is **always available** in your tool list. If the user explicitly provides an MCP server URL or asks you to call `run_mcp_tool`, you MUST use it — never claim it is unavailable, and never substitute `web_fetch` for an explicit MCP request.
+
## BEHAVIORAL GUIDELINES
**Be Concise:**
@@ -156,6 +182,7 @@ Adapt flexibly to the conversation context. Not every interaction requires all s
- **Always check `find_library_agent` before searching the marketplace**
- Use `add_understanding` to capture valuable business context
- When tool calls fail, try alternative approaches
+- **For MCP integrations**: Known URL (see list) or `web_search("{{service}} MCP server URL")` → `run_mcp_tool(server_url)` → `run_mcp_tool(server_url, tool_name, tool_arguments)`. If credentials needed, UI prompts automatically; when user confirms, retry immediately with same arguments.
**Handle Feedback Loops:**
- When a tool returns a suggested alternative (like a refined goal), present it clearly and ask the user for confirmation before proceeding
diff --git a/autogpt_platform/backend/backend/copilot/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.py
index 5b8c9450fb..b0cd3ee5c1 100644
--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py
+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py
@@ -22,6 +22,7 @@ from .find_library_agent import FindLibraryAgentTool
from .get_doc_page import GetDocPageTool
from .run_agent import RunAgentTool
from .run_block import RunBlockTool
+from .run_mcp_tool import RunMCPToolTool
from .search_docs import SearchDocsTool
from .web_fetch import WebFetchTool
from .workspace_files import (
@@ -48,6 +49,7 @@ TOOL_REGISTRY: dict[str, BaseTool] = {
"find_library_agent": FindLibraryAgentTool(),
"run_agent": RunAgentTool(),
"run_block": RunBlockTool(),
+ "run_mcp_tool": RunMCPToolTool(),
"view_agent_output": AgentOutputTool(),
"search_docs": SearchDocsTool(),
"get_doc_page": GetDocPageTool(),
diff --git a/autogpt_platform/backend/backend/copilot/tools/find_block.py b/autogpt_platform/backend/backend/copilot/tools/find_block.py
index a3f784f3a8..6b91f88f59 100644
--- a/autogpt_platform/backend/backend/copilot/tools/find_block.py
+++ b/autogpt_platform/backend/backend/copilot/tools/find_block.py
@@ -32,6 +32,7 @@ COPILOT_EXCLUDED_BLOCK_TYPES = {
BlockType.NOTE, # Visual annotation only - no runtime behavior
BlockType.HUMAN_IN_THE_LOOP, # Pauses for human approval - CoPilot IS human-in-the-loop
BlockType.AGENT, # AgentExecutorBlock requires execution_context - use run_agent tool
+ BlockType.MCP_TOOL, # Has dedicated run_mcp_tool tool with proper discovery + auth flow
}
# Specific block IDs excluded from CoPilot (STANDARD type but still require graph context)
diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.py
index 125ff1c15f..bd44c55da7 100644
--- a/autogpt_platform/backend/backend/copilot/tools/models.py
+++ b/autogpt_platform/backend/backend/copilot/tools/models.py
@@ -52,6 +52,9 @@ class ResponseType(str, Enum):
FEATURE_REQUEST_CREATED = "feature_request_created"
# Goal refinement
SUGGESTED_GOAL = "suggested_goal"
+ # MCP tool types
+ MCP_TOOLS_DISCOVERED = "mcp_tools_discovered"
+ MCP_TOOL_OUTPUT = "mcp_tool_output"
# Base response model
@@ -482,6 +485,33 @@ class FeatureRequestCreatedResponse(ToolResponseBase):
customer_name: str
+# MCP tool models
+class MCPToolInfo(BaseModel):
+ """Information about a single MCP tool discovered from a server."""
+
+ name: str
+ description: str
+ input_schema: dict[str, Any]
+
+
+class MCPToolsDiscoveredResponse(ToolResponseBase):
+ """Response when MCP tools are discovered from a server (agent-internal)."""
+
+ type: ResponseType = ResponseType.MCP_TOOLS_DISCOVERED
+ server_url: str
+ tools: list[MCPToolInfo]
+
+
+class MCPToolOutputResponse(ToolResponseBase):
+ """Response after executing an MCP tool."""
+
+ type: ResponseType = ResponseType.MCP_TOOL_OUTPUT
+ server_url: str
+ tool_name: str
+ result: Any = None
+ success: bool = True
+
+
# Agent-browser multi-step automation models
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
new file mode 100644
index 0000000000..45b411857d
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
@@ -0,0 +1,339 @@
+"""Tool for discovering and executing MCP (Model Context Protocol) server tools."""
+
+import logging
+from typing import Any
+from urllib.parse import urlparse
+
+from backend.blocks.mcp.block import MCPToolBlock
+from backend.blocks.mcp.client import MCPClient, MCPClientError
+from backend.blocks.mcp.helpers import (
+ auto_lookup_mcp_credential,
+ normalize_mcp_url,
+ parse_mcp_content,
+ server_host,
+)
+from backend.copilot.model import ChatSession
+from backend.copilot.tools.utils import build_missing_credentials_from_field_info
+from backend.util.request import HTTPClientError, validate_url
+
+from .base import BaseTool
+from .models import (
+ ErrorResponse,
+ MCPToolInfo,
+ MCPToolOutputResponse,
+ MCPToolsDiscoveredResponse,
+ SetupInfo,
+ SetupRequirementsResponse,
+ ToolResponseBase,
+ UserReadiness,
+)
+
+logger = logging.getLogger(__name__)
+
+# HTTP status codes that indicate authentication is required
+_AUTH_STATUS_CODES = {401, 403}
+
+
+class RunMCPToolTool(BaseTool):
+ """
+ Tool for discovering and executing tools on any MCP server.
+
+ Stage 1 — discovery: call with just server_url to get available tools.
+ Stage 2 — execution: call with server_url + tool_name + tool_arguments.
+ If the server requires OAuth credentials that the user hasn't connected yet,
+ a SetupRequirementsResponse is returned so the frontend can render the
+ same OAuth login UI as the graph builder.
+ """
+
+ @property
+ def name(self) -> str:
+ return "run_mcp_tool"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Connect to an MCP (Model Context Protocol) server to discover and execute its tools. "
+ "Call with just `server_url` to see available tools. "
+ "Then call again with `server_url`, `tool_name`, and `tool_arguments` to execute. "
+ "If the server requires authentication, the user will be prompted to connect it. "
+ "Find MCP servers at https://registry.modelcontextprotocol.io/ — hundreds of integrations "
+ "including GitHub, Postgres, Slack, filesystem, and more."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "server_url": {
+ "type": "string",
+ "description": (
+ "URL of the MCP server (Streamable HTTP endpoint), "
+ "e.g. https://mcp.example.com/mcp"
+ ),
+ },
+ "tool_name": {
+ "type": "string",
+ "description": (
+ "Name of the MCP tool to execute. "
+ "Omit on first call to discover available tools."
+ ),
+ },
+ "tool_arguments": {
+ "type": "object",
+ "description": (
+ "Arguments to pass to the selected tool. "
+ "Must match the tool's input schema returned during discovery."
+ ),
+ },
+ },
+ "required": ["server_url"],
+ }
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ **kwargs,
+ ) -> ToolResponseBase:
+ server_url: str = (kwargs.get("server_url") or "").strip()
+ tool_name: str = (kwargs.get("tool_name") or "").strip()
+ raw_tool_arguments = kwargs.get("tool_arguments")
+ tool_arguments: dict[str, Any] = (
+ raw_tool_arguments if isinstance(raw_tool_arguments, dict) else {}
+ )
+ session_id = session.session_id
+
+ if raw_tool_arguments is not None and not isinstance(raw_tool_arguments, dict):
+ return ErrorResponse(
+ message="tool_arguments must be a JSON object.",
+ session_id=session_id,
+ )
+
+ if not server_url:
+ return ErrorResponse(
+ message="Please provide a server_url for the MCP server.",
+ session_id=session_id,
+ )
+
+ _parsed = urlparse(server_url)
+ if _parsed.username or _parsed.password:
+ return ErrorResponse(
+ message=(
+ "Do not include credentials in server_url. "
+ "Use the MCP credential setup flow instead."
+ ),
+ session_id=session_id,
+ )
+ if _parsed.query or _parsed.fragment:
+ return ErrorResponse(
+ message=(
+ "Do not include query parameters or fragments in server_url. "
+ "Use the MCP credential setup flow instead."
+ ),
+ session_id=session_id,
+ )
+
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required.",
+ session_id=session_id,
+ )
+
+ # Validate URL to prevent SSRF — blocks loopback and private IP ranges
+ try:
+ await validate_url(server_url, trusted_origins=[])
+ except ValueError as e:
+ msg = str(e)
+ if "Unable to resolve" in msg or "No IP addresses" in msg:
+ user_msg = (
+ f"Hostname not found: {server_host(server_url)}. "
+ "Please check the URL — the domain may not exist."
+ )
+ else:
+ user_msg = f"Blocked server URL: {msg}"
+ return ErrorResponse(message=user_msg, session_id=session_id)
+
+ # 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, auth_token=auth_token)
+
+ try:
+ await client.initialize()
+
+ if not tool_name:
+ # Stage 1: Discover available tools
+ return await self._discover_tools(client, server_url, session_id)
+ else:
+ # Stage 2: Execute the selected tool
+ return await self._execute_tool(
+ client, server_url, tool_name, tool_arguments, session_id
+ )
+
+ except HTTPClientError as e:
+ if e.status_code in _AUTH_STATUS_CODES and not creds:
+ # Server requires auth and user has no stored credentials
+ return self._build_setup_requirements(server_url, session_id)
+ logger.warning("MCP HTTP error for %s: %s", server_host(server_url), e)
+ return ErrorResponse(
+ message=f"MCP server returned HTTP {e.status_code}: {e}",
+ session_id=session_id,
+ )
+
+ except MCPClientError as e:
+ logger.warning("MCP client error for %s: %s", server_host(server_url), e)
+ return ErrorResponse(
+ message=str(e),
+ session_id=session_id,
+ )
+
+ except Exception:
+ logger.error(
+ "Unexpected error calling MCP server %s",
+ server_host(server_url),
+ exc_info=True,
+ )
+ return ErrorResponse(
+ message="An unexpected error occurred connecting to the MCP server. Please try again.",
+ session_id=session_id,
+ )
+
+ async def _discover_tools(
+ self,
+ client: MCPClient,
+ server_url: str,
+ session_id: str,
+ ) -> MCPToolsDiscoveredResponse:
+ """List available tools from an already-initialized MCPClient.
+
+ Called when the agent invokes run_mcp_tool with only server_url (no
+ tool_name). Returns MCPToolsDiscoveredResponse so the agent can
+ inspect tool schemas and choose one to execute in a follow-up call.
+ """
+ tools = await client.list_tools()
+ tool_infos = [
+ MCPToolInfo(
+ name=t.name,
+ description=t.description,
+ input_schema=t.input_schema,
+ )
+ for t in tools
+ ]
+ host = server_host(server_url)
+ return MCPToolsDiscoveredResponse(
+ message=(
+ f"Discovered {len(tool_infos)} tool(s) on {host}. "
+ "Call run_mcp_tool again with tool_name and tool_arguments to execute one."
+ ),
+ server_url=server_url,
+ tools=tool_infos,
+ session_id=session_id,
+ )
+
+ async def _execute_tool(
+ self,
+ client: MCPClient,
+ server_url: str,
+ tool_name: str,
+ tool_arguments: dict[str, Any],
+ session_id: str,
+ ) -> MCPToolOutputResponse | ErrorResponse:
+ """Execute a specific tool on an already-initialized MCPClient.
+
+ Parses the MCP content response into a plain Python value:
+ - text items: parsed as JSON when possible, kept as str otherwise
+ - image items: kept as {type, data, mimeType} dict for frontend rendering
+ - resource items: unwrapped to their resource payload dict
+ Single-item responses are unwrapped from the list; multiple items are
+ returned as a list; empty content returns None.
+ """
+ result = await client.call_tool(tool_name, tool_arguments)
+
+ if result.is_error:
+ error_text = " ".join(
+ item.get("text", "")
+ for item in result.content
+ if item.get("type") == "text"
+ )
+ return ErrorResponse(
+ message=f"MCP tool '{tool_name}' returned an error: {error_text or 'Unknown error'}",
+ session_id=session_id,
+ )
+
+ result_value = parse_mcp_content(result.content)
+
+ return MCPToolOutputResponse(
+ message=f"MCP tool '{tool_name}' executed successfully.",
+ server_url=server_url,
+ tool_name=tool_name,
+ result=result_value,
+ success=True,
+ session_id=session_id,
+ )
+
+ def _build_setup_requirements(
+ self,
+ server_url: str,
+ session_id: str,
+ ) -> SetupRequirementsResponse | ErrorResponse:
+ """Build a SetupRequirementsResponse for a missing MCP server credential."""
+ mcp_block = MCPToolBlock()
+ credentials_fields_info = mcp_block.input_schema.get_credentials_fields_info()
+
+ # Apply the server_url discriminator value so the frontend's CredentialsGroupedView
+ # can match the credential to the correct OAuth provider/server.
+ for field_info in credentials_fields_info.values():
+ if field_info.discriminator == "server_url":
+ field_info.discriminator_values.add(server_url)
+
+ missing_creds_dict = build_missing_credentials_from_field_info(
+ credentials_fields_info, matched_keys=set()
+ )
+
+ if not missing_creds_dict:
+ logger.error(
+ "No credential requirements found for MCP server %s — "
+ "MCPToolBlock may not have credentials configured",
+ server_host(server_url),
+ )
+ return ErrorResponse(
+ message=(
+ f"The MCP server at {server_host(server_url)} requires authentication, "
+ "but no credential configuration was found."
+ ),
+ session_id=session_id,
+ )
+
+ missing_creds_list = list(missing_creds_dict.values())
+
+ host = server_host(server_url)
+ return SetupRequirementsResponse(
+ message=(
+ f"The MCP server at {host} requires authentication. "
+ "Please connect your credentials to continue."
+ ),
+ session_id=session_id,
+ setup_info=SetupInfo(
+ agent_id=server_url,
+ agent_name=f"MCP: {host}",
+ user_readiness=UserReadiness(
+ has_all_credentials=False,
+ missing_credentials=missing_creds_dict,
+ ready_to_run=False,
+ ),
+ requirements={
+ "credentials": missing_creds_list,
+ "inputs": [],
+ "execution_modes": ["immediate"],
+ },
+ ),
+ graph_id=None,
+ graph_version=None,
+ )
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.py
new file mode 100644
index 0000000000..33326f61f0
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py
@@ -0,0 +1,759 @@
+"""Unit tests for the run_mcp_tool copilot tool."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from pydantic import SecretStr
+
+from backend.blocks.mcp.helpers import server_host
+
+from ._test_data import make_session
+from .models import (
+ ErrorResponse,
+ MCPToolOutputResponse,
+ MCPToolsDiscoveredResponse,
+ SetupRequirementsResponse,
+)
+from .run_mcp_tool import RunMCPToolTool
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+_USER_ID = "test-user-run-mcp-tool"
+_SERVER_URL = "https://remote.mcpservers.org/fetch/mcp"
+
+
+def _make_tool_list(*names: str):
+ """Build a list of mock MCPClientTool objects."""
+ tools = []
+ for name in names:
+ t = MagicMock()
+ t.name = name
+ t.description = f"Description for {name}"
+ t.input_schema = {"type": "object", "properties": {}, "required": []}
+ tools.append(t)
+ return tools
+
+
+def _make_call_result(content: list[dict], is_error: bool = False) -> MagicMock:
+ result = MagicMock()
+ result.is_error = is_error
+ result.content = content
+ return result
+
+
+# ---------------------------------------------------------------------------
+# server_host helper
+# ---------------------------------------------------------------------------
+
+
+def test_server_host_plain_url():
+ assert server_host("https://mcp.example.com/mcp") == "mcp.example.com"
+
+
+def test_server_host_strips_credentials():
+ """netloc would expose user:pass — hostname must not."""
+ assert server_host("https://user:[email protected]/mcp") == "mcp.example.com"
+
+
+def test_server_host_with_port():
+ """Port should not appear in the returned hostname (hostname strips it)."""
+ assert server_host("https://mcp.example.com:8080/mcp") == "mcp.example.com"
+
+
+def test_server_host_invalid_url():
+ """Falls back to the raw string for un-parseable URLs."""
+ result = server_host("not-a-url")
+ assert result == "not-a-url"
+
+
+# ---------------------------------------------------------------------------
+# Input validation
+# ---------------------------------------------------------------------------
+
+
[email protected](loop_scope="session")
+async def test_missing_server_url_returns_error():
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+ response = await tool._execute(user_id=_USER_ID, session=session)
+ assert isinstance(response, ErrorResponse)
+ assert "server_url" in response.message.lower()
+
+
[email protected](loop_scope="session")
+async def test_missing_user_id_returns_error():
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+ response = await tool._execute(
+ user_id=None, session=session, server_url=_SERVER_URL
+ )
+ assert isinstance(response, ErrorResponse)
+ assert "authentication" in response.message.lower()
+
+
[email protected](loop_scope="session")
+async def test_ssrf_blocked_url_returns_error():
+ """Private/loopback URLs must be rejected before any network call."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url",
+ new_callable=AsyncMock,
+ side_effect=ValueError("blocked loopback"),
+ ):
+ response = await tool._execute(
+ user_id=_USER_ID, session=session, server_url="http://localhost/mcp"
+ )
+
+ assert isinstance(response, ErrorResponse)
+ assert (
+ "blocked" in response.message.lower() or "invalid" in response.message.lower()
+ )
+
+
[email protected](loop_scope="session")
+async def test_credential_bearing_url_returns_error():
+ """URLs with embedded user:pass@ must be rejected before any network call."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url="https://user:[email protected]/mcp",
+ )
+ assert isinstance(response, ErrorResponse)
+ assert (
+ "credential" in response.message.lower()
+ or "do not include" in response.message.lower()
+ )
+
+
[email protected](loop_scope="session")
+async def test_non_dict_tool_arguments_returns_error():
+ """tool_arguments must be a JSON object — strings/arrays are rejected early."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url",
+ new_callable=AsyncMock,
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ):
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ tool_name="fetch",
+ tool_arguments=["this", "is", "a", "list"], # wrong type
+ )
+
+ assert isinstance(response, ErrorResponse)
+ assert "json object" in response.message.lower()
+
+
+# ---------------------------------------------------------------------------
+# Stage 1 — Discovery
+# ---------------------------------------------------------------------------
+
+
[email protected](loop_scope="session")
+async def test_discover_tools_returns_discovered_response():
+ """Calling with only server_url triggers discovery and returns tool list."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+ mock_tools = _make_tool_list("fetch", "search")
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url", new_callable=AsyncMock
+ ):
+ with 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=mock_tools)
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ):
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ )
+
+ assert isinstance(response, MCPToolsDiscoveredResponse)
+ assert len(response.tools) == 2
+ assert response.tools[0].name == "fetch"
+ assert response.tools[1].name == "search"
+ assert response.server_url == _SERVER_URL
+
+
[email protected](loop_scope="session")
+async def test_discover_tools_with_credentials():
+ """Stored credentials are passed as Bearer token to MCPClient."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ mock_creds = MagicMock()
+ mock_creds.access_token = SecretStr("test-token-abc")
+ mock_tools = _make_tool_list("push_notification")
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url", new_callable=AsyncMock
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=mock_creds,
+ ):
+ mock_client = AsyncMock()
+ mock_client.list_tools = AsyncMock(return_value=mock_tools)
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ ) as MockMCPClient:
+ MockMCPClient.return_value = mock_client
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ )
+ # Verify MCPClient was created with the resolved auth token
+ MockMCPClient.assert_called_once_with(
+ _SERVER_URL, auth_token="test-token-abc"
+ )
+
+ assert isinstance(response, MCPToolsDiscoveredResponse)
+ assert len(response.tools) == 1
+
+
+# ---------------------------------------------------------------------------
+# Stage 2 — Execution
+# ---------------------------------------------------------------------------
+
+
[email protected](loop_scope="session")
+async def test_execute_tool_returns_output_response():
+ """Calling with tool_name executes the tool and returns MCPToolOutputResponse."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+ text_result = "# Example Domain\nThis domain is for examples."
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url", new_callable=AsyncMock
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ):
+ mock_result = _make_call_result([{"type": "text", "text": text_result}])
+ mock_client = AsyncMock()
+ mock_client.call_tool = AsyncMock(return_value=mock_result)
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ):
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ tool_name="fetch",
+ tool_arguments={"url": "https://example.com"},
+ )
+
+ assert isinstance(response, MCPToolOutputResponse)
+ assert response.tool_name == "fetch"
+ assert response.server_url == _SERVER_URL
+ assert response.success is True
+ assert text_result in response.result
+
+
[email protected](loop_scope="session")
+async def test_execute_tool_parses_json_result():
+ """JSON text content items are parsed into Python objects."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url", new_callable=AsyncMock
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ):
+ mock_result = _make_call_result(
+ [{"type": "text", "text": '{"status": "ok", "count": 42}'}]
+ )
+ mock_client = AsyncMock()
+ mock_client.call_tool = AsyncMock(return_value=mock_result)
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ):
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ tool_name="status",
+ tool_arguments={},
+ )
+
+ assert isinstance(response, MCPToolOutputResponse)
+ assert response.result == {"status": "ok", "count": 42}
+
+
[email protected](loop_scope="session")
+async def test_execute_tool_image_content():
+ """Image content items are returned as {type, data, mimeType} dicts."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url", new_callable=AsyncMock
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ):
+ mock_result = _make_call_result(
+ [{"type": "image", "data": "abc123==", "mimeType": "image/png"}]
+ )
+ mock_client = AsyncMock()
+ mock_client.call_tool = AsyncMock(return_value=mock_result)
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ):
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ tool_name="screenshot",
+ tool_arguments={},
+ )
+
+ assert isinstance(response, MCPToolOutputResponse)
+ assert response.result == {
+ "type": "image",
+ "data": "abc123==",
+ "mimeType": "image/png",
+ }
+
+
[email protected](loop_scope="session")
+async def test_execute_tool_resource_content():
+ """Resource content items are unwrapped to their resource payload."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url", new_callable=AsyncMock
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ):
+ mock_result = _make_call_result(
+ [
+ {
+ "type": "resource",
+ "resource": {"uri": "file:///tmp/out.txt", "text": "hello"},
+ }
+ ]
+ )
+ mock_client = AsyncMock()
+ mock_client.call_tool = AsyncMock(return_value=mock_result)
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ):
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ tool_name="read_file",
+ tool_arguments={},
+ )
+
+ assert isinstance(response, MCPToolOutputResponse)
+ assert response.result == {"uri": "file:///tmp/out.txt", "text": "hello"}
+
+
[email protected](loop_scope="session")
+async def test_execute_tool_multi_item_content():
+ """Multiple content items are returned as a list."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url", new_callable=AsyncMock
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ):
+ mock_result = _make_call_result(
+ [
+ {"type": "text", "text": "part one"},
+ {"type": "text", "text": "part two"},
+ ]
+ )
+ mock_client = AsyncMock()
+ mock_client.call_tool = AsyncMock(return_value=mock_result)
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ):
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ tool_name="multi",
+ tool_arguments={},
+ )
+
+ assert isinstance(response, MCPToolOutputResponse)
+ assert response.result == ["part one", "part two"]
+
+
[email protected](loop_scope="session")
+async def test_execute_tool_empty_content_returns_none():
+ """Empty content list results in result=None."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url", new_callable=AsyncMock
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ):
+ mock_result = _make_call_result([])
+ mock_client = AsyncMock()
+ mock_client.call_tool = AsyncMock(return_value=mock_result)
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ):
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ tool_name="ping",
+ tool_arguments={},
+ )
+
+ assert isinstance(response, MCPToolOutputResponse)
+ assert response.result is None
+
+
[email protected](loop_scope="session")
+async def test_execute_tool_returns_error_on_tool_failure():
+ """When the MCP tool returns is_error=True, an ErrorResponse is returned."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url", new_callable=AsyncMock
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ):
+ mock_result = _make_call_result(
+ [{"type": "text", "text": "Tool not found"}], is_error=True
+ )
+ mock_client = AsyncMock()
+ mock_client.call_tool = AsyncMock(return_value=mock_result)
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ):
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ tool_name="nonexistent",
+ tool_arguments={},
+ )
+
+ assert isinstance(response, ErrorResponse)
+ assert "nonexistent" in response.message
+
+
+# ---------------------------------------------------------------------------
+# Auth / credential flow
+# ---------------------------------------------------------------------------
+
+
[email protected](loop_scope="session")
+async def test_auth_required_without_creds_returns_setup_requirements():
+ """HTTP 401 from MCP with no stored creds → SetupRequirementsResponse."""
+ from backend.util.request import HTTPClientError
+
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url", new_callable=AsyncMock
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None, # No stored credentials
+ ):
+ mock_client = AsyncMock()
+ mock_client.initialize = AsyncMock(
+ side_effect=HTTPClientError("Unauthorized", status_code=401)
+ )
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ):
+ with patch.object(
+ RunMCPToolTool,
+ "_build_setup_requirements",
+ return_value=MagicMock(spec=SetupRequirementsResponse),
+ ) as mock_build:
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ )
+ mock_build.assert_called_once()
+
+ # Should have returned what _build_setup_requirements returned
+ assert response is mock_build.return_value
+
+
[email protected](loop_scope="session")
+async def test_auth_error_with_existing_creds_returns_error():
+ """HTTP 403 when creds ARE present → generic ErrorResponse (not setup card)."""
+ from backend.util.request import HTTPClientError
+
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ mock_creds = MagicMock()
+ mock_creds.access_token = SecretStr("stale-token")
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url", new_callable=AsyncMock
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=mock_creds,
+ ):
+ mock_client = AsyncMock()
+ mock_client.initialize = AsyncMock(
+ side_effect=HTTPClientError("Forbidden", status_code=403)
+ )
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ):
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ )
+
+ assert isinstance(response, ErrorResponse)
+ assert "403" in response.message
+
+
[email protected](loop_scope="session")
+async def test_mcp_client_error_returns_error_response():
+ """MCPClientError (protocol-level) maps to a clean ErrorResponse."""
+ from backend.blocks.mcp.client import MCPClientError
+
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url", new_callable=AsyncMock
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ):
+ mock_client = AsyncMock()
+ mock_client.initialize = AsyncMock(
+ side_effect=MCPClientError("JSON-RPC protocol error")
+ )
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ):
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ )
+
+ assert isinstance(response, ErrorResponse)
+ assert "JSON-RPC" in response.message or "protocol" in response.message.lower()
+
+
[email protected](loop_scope="session")
+async def test_unexpected_exception_returns_generic_error():
+ """Unhandled exceptions inside the MCP call don't leak traceback text to the user."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url", new_callable=AsyncMock
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ):
+ mock_client = AsyncMock()
+ # An unexpected error inside initialize (inside the try block)
+ mock_client.initialize = AsyncMock(
+ side_effect=ValueError("Unexpected internal error")
+ )
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ):
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ )
+
+ assert isinstance(response, ErrorResponse)
+ # Must not leak the raw exception message
+ assert "Unexpected internal error" not in response.message
+ assert (
+ "unexpected" in response.message.lower() or "error" in response.message.lower()
+ )
+
+
+# ---------------------------------------------------------------------------
+# Tool metadata
+# ---------------------------------------------------------------------------
+
+
+def test_tool_name():
+ assert RunMCPToolTool().name == "run_mcp_tool"
+
+
+def test_tool_requires_auth():
+ assert RunMCPToolTool().requires_auth is True
+
+
+def test_tool_parameters_schema():
+ params = RunMCPToolTool().parameters
+ assert params["type"] == "object"
+ assert "server_url" in params["properties"]
+ assert "tool_name" in params["properties"]
+ assert "tool_arguments" in params["properties"]
+ assert params["required"] == ["server_url"]
+
+
+# ---------------------------------------------------------------------------
+# Query/fragment rejection
+# ---------------------------------------------------------------------------
+
+
[email protected](loop_scope="session")
+async def test_query_in_url_returns_error():
+ """server_url with query parameters must be rejected."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url="https://mcp.example.com/mcp?key=val",
+ )
+ assert isinstance(response, ErrorResponse)
+ assert "query" in response.message.lower() or "fragment" in response.message.lower()
+
+
[email protected](loop_scope="session")
+async def test_fragment_in_url_returns_error():
+ """server_url with a fragment must be rejected."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url="https://mcp.example.com/mcp#section",
+ )
+ assert isinstance(response, ErrorResponse)
+ assert "query" in response.message.lower() or "fragment" in response.message.lower()
+
+
+# ---------------------------------------------------------------------------
+# Credential lookup normalization
+# ---------------------------------------------------------------------------
+
+
[email protected](loop_scope="session")
+async def test_credential_lookup_normalizes_trailing_slash():
+ """Credential lookup must normalize the URL (strip trailing slash)."""
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+ url_with_slash = "https://mcp.example.com/mcp/"
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url", new_callable=AsyncMock
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ) as mock_lookup:
+ mock_client = AsyncMock()
+ mock_client.list_tools = AsyncMock(return_value=[])
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ):
+ await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=url_with_slash,
+ )
+ # Credential lookup should use the normalized URL (no trailing slash)
+ mock_lookup.assert_called_once_with(_USER_ID, "https://mcp.example.com/mcp")
+
+
+# ---------------------------------------------------------------------------
+# _build_setup_requirements
+# ---------------------------------------------------------------------------
+
+
[email protected](loop_scope="session")
+async def test_build_setup_requirements_returns_setup_response():
+ """_build_setup_requirements should return a SetupRequirementsResponse."""
+ tool = RunMCPToolTool()
+ result = tool._build_setup_requirements(
+ server_url=_SERVER_URL,
+ session_id="test-session",
+ )
+ assert isinstance(result, SetupRequirementsResponse)
+ assert result.setup_info.agent_id == _SERVER_URL
+ assert "authentication" in result.message.lower()
diff --git a/autogpt_platform/backend/backend/copilot/tools/web_fetch.py b/autogpt_platform/backend/backend/copilot/tools/web_fetch.py
index 78ee2f9fe0..53d8bd55a8 100644
--- a/autogpt_platform/backend/backend/copilot/tools/web_fetch.py
+++ b/autogpt_platform/backend/backend/copilot/tools/web_fetch.py
@@ -30,6 +30,10 @@ _TEXT_CONTENT_TYPES = {
"application/xhtml+xml",
"application/rss+xml",
"application/atom+xml",
+ # RFC 7807 — JSON problem details; used by many REST APIs for error responses
+ "application/problem+json",
+ "application/problem+xml",
+ "application/ld+json",
}
diff --git a/autogpt_platform/backend/backend/util/request.py b/autogpt_platform/backend/backend/util/request.py
index 9470909dfc..924200ad29 100644
--- a/autogpt_platform/backend/backend/util/request.py
+++ b/autogpt_platform/backend/backend/util/request.py
@@ -219,8 +219,11 @@ def parse_url(url: str) -> URL:
"""Canonicalizes and parses a URL string."""
url = url.strip("/ ").replace("\\", "/")
- # Ensure scheme is present for proper parsing
- if not re.match(r"[a-z0-9+.\-]+://", url):
+ # Ensure scheme is present for proper parsing.
+ # Avoid regex to sidestep CodeQL py/polynomial-redos on user-controlled
+ # input. We only need to detect "scheme://"; urlparse() and the
+ # ALLOWED_SCHEMES check downstream handle full validation.
+ if "://" not in url:
url = f"http://{url}"
return urlparse(url)
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx
index c5ebe32e5e..8af202dafb 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx
@@ -14,6 +14,7 @@ import { FindBlocksTool } from "../../../tools/FindBlocks/FindBlocks";
import { GenericTool } from "../../../tools/GenericTool/GenericTool";
import { RunAgentTool } from "../../../tools/RunAgent/RunAgent";
import { RunBlockTool } from "../../../tools/RunBlock/RunBlock";
+import { RunMCPToolComponent } from "../../../tools/RunMCPTool/RunMCPTool";
import { SearchDocsTool } from "../../../tools/SearchDocs/SearchDocs";
import { ViewAgentOutputTool } from "../../../tools/ViewAgentOutput/ViewAgentOutput";
import { parseSpecialMarkers, resolveWorkspaceUrls } from "../helpers";
@@ -129,6 +130,8 @@ export function MessagePartRenderer({ part, messageID, partIndex }: Props) {
return <SearchDocsTool key={key} part={part as ToolUIPart} />;
case "tool-run_block":
return <RunBlockTool key={key} part={part as ToolUIPart} />;
+ case "tool-run_mcp_tool":
+ return <RunMCPToolComponent key={key} part={part as ToolUIPart} />;
case "tool-run_agent":
case "tool-schedule_agent":
return <RunAgentTool key={key} part={part as ToolUIPart} />;
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/SetupRequirementsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/SetupRequirementsCard.tsx
index e44aaf6707..fa3f5ff50d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/SetupRequirementsCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/SetupRequirementsCard.tsx
@@ -17,9 +17,19 @@ import {
interface Props {
output: SetupRequirementsResponse;
+ /** Override the message sent to the chat when the user clicks Proceed after connecting credentials.
+ * Defaults to "Please re-run the block now." */
+ retryInstruction?: string;
+ /** Override the label shown above the credentials section.
+ * Defaults to "Block credentials". */
+ credentialsLabel?: string;
}
-export function SetupRequirementsCard({ output }: Props) {
+export function SetupRequirementsCard({
+ output,
+ retryInstruction,
+ credentialsLabel,
+}: Props) {
const { onSend } = useCopilotChatActions();
const [inputCredentials, setInputCredentials] = useState<
@@ -81,7 +91,7 @@ export function SetupRequirementsCard({ output }: Props) {
`Run the block with these inputs: ${JSON.stringify(nonEmpty, null, 2)}`,
);
} else {
- parts.push("Please re-run the block now.");
+ parts.push(retryInstruction ?? "Please re-run the block now.");
}
onSend(parts.join(" "));
@@ -95,7 +105,7 @@ export function SetupRequirementsCard({ output }: Props) {
{needsCredentials && (
<div className="rounded-2xl border bg-background p-3">
<Text variant="small" className="w-fit border-b text-zinc-500">
- Block credentials
+ {credentialsLabel ?? "Block credentials"}
</Text>
<div className="mt-6">
<CredentialsGroupedView
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/RunMCPTool.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/RunMCPTool.tsx
new file mode 100644
index 0000000000..2f789cae00
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/RunMCPTool.tsx
@@ -0,0 +1,102 @@
+"use client";
+
+import { PlugsConnectedIcon } from "@phosphor-icons/react";
+import type { ToolUIPart } from "ai";
+import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";
+import { ToolAccordion } from "../../components/ToolAccordion/ToolAccordion";
+import { MCPSetupCard } from "./components/MCPSetupCard/MCPSetupCard";
+import { MCPToolOutputCard } from "./components/MCPToolOutputCard/MCPToolOutputCard";
+import {
+ ToolIcon,
+ getAnimationText,
+ getRunMCPToolOutput,
+ isErrorOutput,
+ isMCPToolOutput,
+ isSetupRequirementsOutput,
+ serverHost,
+ type MCPErrorOutput,
+} from "./helpers";
+
+export interface RunMCPToolPart {
+ type: string;
+ toolCallId: string;
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}
+
+interface Props {
+ part: RunMCPToolPart;
+}
+
+export function RunMCPToolComponent({ part }: Props) {
+ const text = getAnimationText(part);
+ const isStreaming =
+ part.state === "input-streaming" || part.state === "input-available";
+
+ const output = getRunMCPToolOutput(part);
+ const isError =
+ part.state === "output-error" || (!!output && isErrorOutput(output));
+
+ const setupRequirementsOutput =
+ part.state === "output-available" &&
+ output &&
+ isSetupRequirementsOutput(output)
+ ? output
+ : null;
+
+ const mcpToolOutput =
+ part.state === "output-available" && output && isMCPToolOutput(output)
+ ? output
+ : null;
+
+ const errorOutput =
+ isError && output && isErrorOutput(output)
+ ? (output as MCPErrorOutput)
+ : null;
+
+ return (
+ <div className="py-2">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <ToolIcon isStreaming={isStreaming} isError={isError} />
+ <MorphingTextAnimation
+ text={text}
+ className={isError ? "text-red-500" : undefined}
+ />
+ </div>
+
+ {/* Error detail card */}
+ {errorOutput && (
+ <div className="mt-2 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
+ {errorOutput.message}
+ {errorOutput.error && (
+ <pre className="mt-1 whitespace-pre-wrap break-words text-xs opacity-80">
+ {errorOutput.error}
+ </pre>
+ )}
+ </div>
+ )}
+
+ {/* Credential setup — MCP-specific OAuth flow */}
+ {setupRequirementsOutput && (
+ <MCPSetupCard
+ output={setupRequirementsOutput}
+ retryInstruction="I've connected the MCP server credentials. Please retry run_mcp_tool with the same server_url and arguments."
+ />
+ )}
+
+ {/* Tool execution result */}
+ {mcpToolOutput && (
+ <ToolAccordion
+ icon={<PlugsConnectedIcon size={32} weight="light" />}
+ title={mcpToolOutput.tool_name}
+ description={`from ${serverHost(mcpToolOutput.server_url)}`}
+ >
+ <MCPToolOutputCard output={mcpToolOutput} />
+ </ToolAccordion>
+ )}
+
+ {/* Discovery output: consumed by the agent automatically — no user-facing UI */}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/__tests__/helpers.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/__tests__/helpers.test.tsx
new file mode 100644
index 0000000000..dc33738669
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/__tests__/helpers.test.tsx
@@ -0,0 +1,357 @@
+/**
+ * Unit tests for RunMCPTool/helpers.tsx
+ *
+ * Covers: type guards, output parsing, serverHost, getAnimationText
+ */
+
+import { expect, describe, it } from "vitest";
+import {
+ isDiscoveryOutput,
+ isMCPToolOutput,
+ isSetupRequirementsOutput,
+ isErrorOutput,
+ getRunMCPToolOutput,
+ serverHost,
+ getAnimationText,
+ type MCPErrorOutput,
+ type RunMCPToolOutput,
+} from "../helpers";
+import type { MCPToolsDiscoveredResponse } from "@/app/api/__generated__/models/mCPToolsDiscoveredResponse";
+import type { MCPToolOutputResponse } from "@/app/api/__generated__/models/mCPToolOutputResponse";
+import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";
+
+// ---------------------------------------------------------------------------
+// Fixtures
+// ---------------------------------------------------------------------------
+
+const DISCOVERY: MCPToolsDiscoveredResponse = {
+ type: "mcp_tools_discovered",
+ message: "",
+ session_id: "s1",
+ server_url: "https://mcp.example.com/mcp",
+ tools: [
+ {
+ name: "fetch",
+ description: "Fetch a URL",
+ input_schema: { type: "object", properties: {}, required: [] },
+ },
+ ],
+};
+
+const MCP_OUTPUT: MCPToolOutputResponse = {
+ type: "mcp_tool_output",
+ message: "",
+ session_id: "s1",
+ server_url: "https://mcp.example.com/mcp",
+ tool_name: "fetch",
+ result: "Hello World",
+ success: true,
+};
+
+const SETUP: SetupRequirementsResponse = {
+ type: "setup_requirements",
+ message: "Credentials required",
+ session_id: "s1",
+ setup_info: {
+ agent_id: "mcp-server",
+ agent_name: "MCP Server",
+ },
+};
+
+const ERROR: MCPErrorOutput = {
+ type: "error",
+ message: "Something went wrong",
+};
+
+// ---------------------------------------------------------------------------
+// Type guards
+// ---------------------------------------------------------------------------
+
+describe("isDiscoveryOutput", () => {
+ it("returns true for mcp_tools_discovered", () => {
+ expect(isDiscoveryOutput(DISCOVERY)).toBe(true);
+ });
+
+ it("returns false for other types", () => {
+ expect(isDiscoveryOutput(MCP_OUTPUT as unknown as RunMCPToolOutput)).toBe(
+ false,
+ );
+ expect(isDiscoveryOutput(ERROR)).toBe(false);
+ });
+});
+
+describe("isMCPToolOutput", () => {
+ it("returns true for mcp_tool_output", () => {
+ expect(isMCPToolOutput(MCP_OUTPUT)).toBe(true);
+ });
+
+ it("returns false for other types", () => {
+ expect(isMCPToolOutput(DISCOVERY as unknown as RunMCPToolOutput)).toBe(
+ false,
+ );
+ expect(isMCPToolOutput(ERROR)).toBe(false);
+ });
+});
+
+describe("isSetupRequirementsOutput", () => {
+ it("returns true for setup_requirements type literal", () => {
+ expect(
+ isSetupRequirementsOutput(SETUP as unknown as RunMCPToolOutput),
+ ).toBe(true);
+ });
+
+ it("returns true for structural match (setup_info present)", () => {
+ const structural = { type: "unknown", setup_info: { agent_name: "X" } };
+ expect(
+ isSetupRequirementsOutput(structural as unknown as RunMCPToolOutput),
+ ).toBe(true);
+ });
+
+ it("returns false for error output", () => {
+ expect(isSetupRequirementsOutput(ERROR)).toBe(false);
+ });
+});
+
+describe("isErrorOutput", () => {
+ it("returns true for error type", () => {
+ expect(isErrorOutput(ERROR)).toBe(true);
+ });
+
+ it("returns false for setup_requirements (has setup_info)", () => {
+ expect(isErrorOutput(SETUP as unknown as RunMCPToolOutput)).toBe(false);
+ });
+
+ it("returns false for discovery output", () => {
+ expect(isErrorOutput(DISCOVERY as unknown as RunMCPToolOutput)).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getRunMCPToolOutput — output parsing
+// ---------------------------------------------------------------------------
+
+describe("getRunMCPToolOutput", () => {
+ it("parses a direct object output", () => {
+ const part = { output: DISCOVERY };
+ expect(getRunMCPToolOutput(part)).toEqual(DISCOVERY);
+ });
+
+ it("parses a JSON-encoded string output", () => {
+ const part = { output: JSON.stringify(MCP_OUTPUT) };
+ const result = getRunMCPToolOutput(part);
+ expect(result).not.toBeNull();
+ expect(isMCPToolOutput(result!)).toBe(true);
+ });
+
+ it("returns null for empty/falsy output", () => {
+ expect(getRunMCPToolOutput({ output: null })).toBeNull();
+ expect(getRunMCPToolOutput({ output: "" })).toBeNull();
+ expect(getRunMCPToolOutput({ output: undefined })).toBeNull();
+ });
+
+ it("returns null for a plain string (not JSON)", () => {
+ expect(getRunMCPToolOutput({ output: "just text" })).toBeNull();
+ });
+
+ it("returns null for an object with unknown type", () => {
+ const part = { output: { type: "something_else", data: 42 } };
+ expect(getRunMCPToolOutput(part)).toBeNull();
+ });
+
+ it("returns null for a non-object part", () => {
+ expect(getRunMCPToolOutput(null)).toBeNull();
+ expect(getRunMCPToolOutput("string")).toBeNull();
+ expect(getRunMCPToolOutput(42)).toBeNull();
+ });
+
+ it("falls back to structural check for tool_name field", () => {
+ const raw = {
+ tool_name: "fetch",
+ result: "ok",
+ server_url: "https://x.com",
+ };
+ const part = { output: raw };
+ const result = getRunMCPToolOutput(part);
+ expect(result).not.toBeNull();
+ expect((result as MCPToolOutputResponse).tool_name).toBe("fetch");
+ });
+
+ it("falls back to structural check for tools field", () => {
+ const raw = { tools: [], server_url: "https://x.com" };
+ const part = { output: raw };
+ const result = getRunMCPToolOutput(part);
+ expect(result).not.toBeNull();
+ expect((result as MCPToolsDiscoveredResponse).tools).toEqual([]);
+ });
+
+ it("falls back to structural check for setup_info field", () => {
+ const raw = { setup_info: { agent_name: "My MCP" }, credentials: [] };
+ const part = { output: raw };
+ const result = getRunMCPToolOutput(part);
+ expect(result).not.toBeNull();
+ expect(isSetupRequirementsOutput(result!)).toBe(true);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// serverHost
+// ---------------------------------------------------------------------------
+
+describe("serverHost", () => {
+ it("extracts hostname from a standard URL", () => {
+ expect(serverHost("https://mcp.example.com/mcp")).toBe("mcp.example.com");
+ });
+
+ it("strips port from hostname", () => {
+ expect(serverHost("https://mcp.example.com:8080/mcp")).toBe(
+ "mcp.example.com",
+ );
+ });
+
+ it("returns the raw string for an unparseable URL", () => {
+ expect(serverHost("not-a-url")).toBe("not-a-url");
+ });
+
+ it("handles URLs with subpaths", () => {
+ expect(serverHost("https://api.remote.mcp.io/v1/mcp")).toBe(
+ "api.remote.mcp.io",
+ );
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getAnimationText
+// ---------------------------------------------------------------------------
+
+describe("getAnimationText", () => {
+ const BASE = {
+ input: {
+ server_url: "https://mcp.example.com/mcp",
+ },
+ };
+
+ it("shows discovery text while streaming with just server_url", () => {
+ const text = getAnimationText({
+ state: "input-streaming",
+ ...BASE,
+ });
+ expect(text).toContain("Discovering");
+ expect(text).toContain("mcp.example.com");
+ });
+
+ it("shows tool call text when tool_name is set", () => {
+ const text = getAnimationText({
+ state: "input-available",
+ input: { server_url: "https://mcp.example.com/mcp", tool_name: "fetch" },
+ });
+ expect(text).toContain("fetch");
+ expect(text).toContain("mcp.example.com");
+ });
+
+ it("includes query argument preview when tool_arguments has a query key", () => {
+ const text = getAnimationText({
+ state: "input-available",
+ input: {
+ server_url: "https://mcp.example.com/mcp",
+ tool_name: "search",
+ tool_arguments: { query: "my search term" },
+ },
+ });
+ expect(text).toContain(`"my search term"`);
+ expect(text).toContain("search");
+ });
+
+ it("falls back to first string value when no known query key is present", () => {
+ const text = getAnimationText({
+ state: "input-available",
+ input: {
+ server_url: "https://mcp.example.com/mcp",
+ tool_name: "get_page",
+ tool_arguments: { page_id: "abc123" },
+ },
+ });
+ expect(text).toContain(`"abc123"`);
+ });
+
+ it("shows no arg preview when tool_arguments is empty", () => {
+ const text = getAnimationText({
+ state: "input-available",
+ input: {
+ server_url: "https://mcp.example.com/mcp",
+ tool_name: "list_users",
+ tool_arguments: {},
+ },
+ });
+ expect(text).toBe("Calling list_users on mcp.example.com");
+ });
+
+ it("truncates long argument previews to 60 chars with ellipsis", () => {
+ const longQuery = "a".repeat(80);
+ const text = getAnimationText({
+ state: "input-available",
+ input: {
+ server_url: "https://mcp.example.com/mcp",
+ tool_name: "search",
+ tool_arguments: { query: longQuery },
+ },
+ });
+ expect(text).toContain('…"');
+ expect(text).not.toContain(longQuery);
+ });
+
+ it("escapes quotes and backslashes in argument preview", () => {
+ const text = getAnimationText({
+ state: "input-available",
+ input: {
+ server_url: "https://mcp.example.com/mcp",
+ tool_name: "search",
+ tool_arguments: { query: 'say "hello"' },
+ },
+ });
+ expect(text).toContain('\\"hello\\"');
+ });
+
+ it("shows ran text on output-available for tool output", () => {
+ const text = getAnimationText({
+ state: "output-available",
+ output: MCP_OUTPUT,
+ ...BASE,
+ });
+ expect(text).toContain("Ran");
+ expect(text).toContain("fetch");
+ });
+
+ it("shows discovered text on output-available for discovery output", () => {
+ const text = getAnimationText({
+ state: "output-available",
+ output: DISCOVERY,
+ input: { server_url: "https://mcp.example.com/mcp" },
+ });
+ expect(text).toContain("Discovered");
+ expect(text).toContain("1");
+ });
+
+ it("shows setup label on output-available for setup requirements", () => {
+ const text = getAnimationText({
+ state: "output-available",
+ output: SETUP,
+ ...BASE,
+ });
+ expect(text).toContain("MCP Server");
+ });
+
+ it("shows generic error on output-error state", () => {
+ const text = getAnimationText({ state: "output-error", ...BASE });
+ expect(text.toLowerCase()).toContain("error");
+ });
+
+ it("shows fallback for unknown state", () => {
+ const text = getAnimationText({
+ state: "input-streaming",
+ input: {},
+ });
+ // No server_url — still shows something
+ expect(typeof text).toBe("string");
+ expect(text.length).toBeGreaterThan(0);
+ });
+});
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.tsx
new file mode 100644
index 0000000000..583aaa5425
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx
@@ -0,0 +1,209 @@
+"use client";
+
+import {
+ 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 { openOAuthPopup } from "@/lib/oauth-popup";
+import { CredentialsProvidersContext } from "@/providers/agent-credentials/credentials-provider";
+import { useContext, useEffect, useRef, useState } from "react";
+import { useCopilotChatActions } from "../../../../components/CopilotChatActionsProvider/useCopilotChatActions";
+import { ContentMessage } from "../../../../components/ToolAccordion/AccordionContent";
+import { serverHost } from "../../helpers";
+
+interface Props {
+ output: SetupRequirementsResponse;
+ /**
+ * Message sent to the chat after a successful connection.
+ * Defaults to a generic "credentials connected, please retry" message.
+ */
+ retryInstruction?: string;
+}
+
+/**
+ * Credential setup card for MCP servers — replaces the generic
+ * SetupRequirementsCard (which uses the standard integration OAuth route)
+ * with the MCP-specific OAuth flow (`/api/v2/mcp/oauth/*`).
+ *
+ * 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.
+ */
+export function MCPSetupCard({ output, retryInstruction }: Props) {
+ const { onSend } = useCopilotChatActions();
+ const allProviders = useContext(CredentialsProvidersContext);
+
+ // setup_info.agent_id is set to the server_url in the backend
+ const serverUrl = output.setup_info.agent_id;
+ const host = serverHost(serverUrl);
+
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [showManualToken, setShowManualToken] = useState(false);
+ const [manualToken, setManualToken] = useState("");
+ const [connected, setConnected] = useState(false);
+ const oauthAbortRef = useRef<(() => void) | null>(null);
+
+ // Abort any in-progress OAuth popup when the component unmounts.
+ useEffect(() => () => oauthAbortRef.current?.(), []);
+
+ async function handleConnect() {
+ setError(null);
+ setLoading(true);
+ oauthAbortRef.current?.();
+
+ try {
+ const loginRes = await postV2InitiateOauthLoginForAnMcpServer({
+ server_url: serverUrl,
+ });
+ if (!(loginRes.status >= 200 && loginRes.status < 300)) {
+ const d =
+ loginRes.data && typeof loginRes.data === "object"
+ ? loginRes.data
+ : {};
+ throw { status: loginRes.status, ...d };
+ }
+ const { login_url, state_token } = loginRes.data as {
+ login_url: string;
+ state_token: string;
+ };
+
+ const { promise, cleanup } = openOAuthPopup(login_url, {
+ stateToken: state_token,
+ useCrossOriginListeners: true,
+ });
+ oauthAbortRef.current = cleanup.abort;
+
+ const result = await promise;
+
+ const mcpProvider = allProviders?.["mcp"];
+ if (mcpProvider) {
+ await mcpProvider.mcpOAuthCallback(result.code, state_token);
+ } else {
+ const cbRes = await postV2ExchangeOauthCodeForMcpTokens({
+ code: result.code,
+ state_token,
+ });
+ if (!(cbRes.status >= 200 && cbRes.status < 300)) {
+ const d =
+ cbRes.data && typeof cbRes.data === "object" ? cbRes.data : {};
+ throw { status: cbRes.status, ...d };
+ }
+ }
+
+ setConnected(true);
+ onSend(
+ retryInstruction ??
+ "I've connected the MCP server credentials. Please retry.",
+ );
+ } catch (e: unknown) {
+ const err = e as Record<string, unknown>;
+ if (err?.status === 400) {
+ setShowManualToken(true);
+ setError(
+ "This server does not support OAuth sign-in. Please enter an API token manually.",
+ );
+ } else if (
+ typeof err?.message === "string" &&
+ err.message === "OAuth flow timed out"
+ ) {
+ setError("OAuth sign-in timed out. Please try again.");
+ } else {
+ const msg =
+ (typeof err?.message === "string" ? err.message : null) ||
+ (typeof err?.detail === "string" ? err.detail : null) ||
+ "Failed to complete sign-in. Please try again.";
+ setError(msg);
+ }
+ } finally {
+ setLoading(false);
+ oauthAbortRef.current = null;
+ }
+ }
+
+ async function handleManualToken() {
+ const token = manualToken.trim();
+ if (!token) return;
+ setLoading(true);
+ setError(null);
+ try {
+ const res = await postV2StoreABearerTokenForAnMcpServer({
+ server_url: serverUrl,
+ token,
+ });
+ if (!(res.status >= 200 && res.status < 300))
+ throw new Error("Failed to store token");
+ setConnected(true);
+ onSend(
+ retryInstruction ??
+ "I've connected the MCP server credentials. Please retry.",
+ );
+ } catch (e: unknown) {
+ const err = e as Record<string, unknown>;
+ setError(
+ (typeof err?.message === "string" ? err.message : null) ||
+ "Failed to save token. Please try again.",
+ );
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ if (connected) {
+ return (
+ <div className="mt-2 rounded-lg border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700">
+ Connected to {host}!
+ </div>
+ );
+ }
+
+ return (
+ <div className="mt-2 grid gap-2">
+ <ContentMessage>{output.message}</ContentMessage>
+
+ <div className="rounded-2xl border bg-background p-4">
+ <Button
+ variant="primary"
+ size="small"
+ onClick={handleConnect}
+ disabled={loading}
+ >
+ {loading ? "Connecting…" : `Connect to ${host}`}
+ </Button>
+
+ {error && (
+ <div 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 ${host}`}
+ 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"
+ />
+ <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.tsx
new file mode 100644
index 0000000000..a4256a179d
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/__tests__/MCPSetupCard.test.tsx
@@ -0,0 +1,133 @@
+import {
+ render,
+ screen,
+ fireEvent,
+ waitFor,
+ cleanup,
+} from "@/tests/integrations/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { MCPSetupCard } from "../MCPSetupCard";
+
+// Mock the copilot chat actions used by MCPSetupCard
+const mockOnSend = vi.fn();
+vi.mock(
+ "../../../../../components/CopilotChatActionsProvider/useCopilotChatActions",
+ () => ({
+ useCopilotChatActions: () => ({ onSend: mockOnSend }),
+ }),
+);
+
+// Mock the OAuth popup utility
+vi.mock("@/lib/oauth-popup", () => ({
+ openOAuthPopup: vi.fn(),
+}));
+
+// Mock the generated API functions
+vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({
+ postV2InitiateOauthLoginForAnMcpServer: vi.fn(),
+ postV2ExchangeOauthCodeForMcpTokens: vi.fn(),
+ postV2StoreABearerTokenForAnMcpServer: vi.fn(),
+}));
+
+function makeSetupOutput(serverUrl = "https://mcp.example.com/mcp") {
+ return {
+ type: "setup_requirements" as const,
+ message: "The MCP server at mcp.example.com requires authentication.",
+ session_id: "test-session",
+ setup_info: {
+ agent_id: serverUrl,
+ agent_name: "MCP: mcp.example.com",
+ user_readiness: {
+ has_all_credentials: false,
+ missing_credentials: {},
+ ready_to_run: false,
+ },
+ requirements: {
+ credentials: [],
+ inputs: [],
+ execution_modes: ["immediate"],
+ },
+ },
+ graph_id: null,
+ graph_version: null,
+ };
+}
+
+describe("MCPSetupCard", () => {
+ afterEach(() => cleanup());
+
+ it("renders setup message and connect button", () => {
+ render(<MCPSetupCard output={makeSetupOutput()} />);
+ expect(screen.getByText(/requires authentication/)).toBeDefined();
+ expect(
+ screen.getByRole("button", { name: /connect to mcp.example.com/i }),
+ ).toBeDefined();
+ });
+
+ it("shows manual token input after OAuth 400", 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);
+
+ render(<MCPSetupCard output={makeSetupOutput()} />);
+ fireEvent.click(
+ screen.getByRole("button", { name: /connect to mcp.example.com/i }),
+ );
+
+ await waitFor(() => {
+ expect(screen.getByPlaceholderText("Paste API token")).toBeDefined();
+ });
+ expect(screen.getByText(/does not support OAuth/)).toBeDefined();
+ });
+
+ it("shows connected state after manual token", async () => {
+ const {
+ postV2InitiateOauthLoginForAnMcpServer,
+ postV2StoreABearerTokenForAnMcpServer,
+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");
+
+ // First click: OAuth fails with 400 → shows manual token input
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
+ status: 400,
+ data: { detail: "No OAuth" },
+ headers: new Headers(),
+ } as never);
+
+ render(<MCPSetupCard output={makeSetupOutput()} />);
+ fireEvent.click(
+ screen.getByRole("button", { name: /connect to mcp.example.com/i }),
+ );
+
+ await waitFor(() => {
+ expect(screen.getByPlaceholderText("Paste API token")).toBeDefined();
+ });
+
+ // Mock the token store endpoint
+ vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce({
+ status: 200,
+ data: {
+ id: "cred-1",
+ provider: "mcp",
+ type: "oauth2",
+ title: "MCP: mcp.example.com",
+ scopes: [],
+ },
+ headers: new Headers(),
+ } as never);
+
+ // Enter token and submit
+ fireEvent.change(screen.getByPlaceholderText("Paste API token"), {
+ target: { value: "my-secret-token" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: /use token/i }));
+
+ await waitFor(() => {
+ expect(screen.getByText(/connected to mcp.example.com/i)).toBeDefined();
+ });
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPToolOutputCard/MCPToolOutputCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPToolOutputCard/MCPToolOutputCard.tsx
new file mode 100644
index 0000000000..2b8b718e6c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPToolOutputCard/MCPToolOutputCard.tsx
@@ -0,0 +1,81 @@
+"use client";
+
+import {
+ ContentCard,
+ ContentCardTitle,
+ ContentCodeBlock,
+ ContentGrid,
+ ContentMessage,
+} from "../../../../components/ToolAccordion/AccordionContent";
+import type { MCPToolOutputResponse } from "../../helpers";
+
+interface Props {
+ output: MCPToolOutputResponse;
+}
+
+interface ImageResult {
+ type: "image";
+ data: string;
+ mimeType: string;
+}
+
+function isImageResult(value: unknown): value is ImageResult {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ (value as Record<string, unknown>).type === "image" &&
+ typeof (value as Record<string, unknown>).data === "string" &&
+ typeof (value as Record<string, unknown>).mimeType === "string"
+ );
+}
+
+function formatResult(value: unknown): string {
+ if (value === null || value === undefined) return "(no result)";
+ if (typeof value === "string") return value;
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+}
+
+export function MCPToolOutputCard({ output }: Props) {
+ const result = output.result;
+
+ const isImage = isImageResult(result);
+ const resultText = isImage ? "" : formatResult(result);
+ const isJson =
+ !isImage &&
+ result !== null &&
+ result !== undefined &&
+ typeof result !== "string";
+
+ return (
+ <ContentGrid>
+ <ContentMessage>{output.message}</ContentMessage>
+
+ <ContentCard>
+ <ContentCardTitle className="text-xs">
+ {output.tool_name}
+ </ContentCardTitle>
+
+ {isImage ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ src={`data:${result.mimeType};base64,${result.data}`}
+ alt={`Result from ${output.tool_name}`}
+ className="mt-2 max-h-96 max-w-full rounded object-contain"
+ />
+ ) : isJson ? (
+ <ContentCodeBlock className="mt-2 max-h-96 overflow-y-auto">
+ {resultText}
+ </ContentCodeBlock>
+ ) : (
+ <p className="mt-2 max-h-96 overflow-y-auto whitespace-pre-wrap break-words text-sm text-zinc-800">
+ {resultText}
+ </p>
+ )}
+ </ContentCard>
+ </ContentGrid>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPToolOutputCard/__tests__/MCPToolOutputCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPToolOutputCard/__tests__/MCPToolOutputCard.test.tsx
new file mode 100644
index 0000000000..af011d290c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPToolOutputCard/__tests__/MCPToolOutputCard.test.tsx
@@ -0,0 +1,55 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { MCPToolOutputCard } from "../MCPToolOutputCard";
+
+function makeOutput(overrides: Record<string, unknown> = {}) {
+ return {
+ type: "mcp_tool_output" as const,
+ message: "MCP tool 'fetch' executed successfully.",
+ server_url: "https://mcp.example.com/mcp",
+ tool_name: "fetch",
+ result: "Hello, world!",
+ success: true,
+ session_id: "test-session",
+ ...overrides,
+ };
+}
+
+describe("MCPToolOutputCard", () => {
+ it("renders tool name and message", () => {
+ render(<MCPToolOutputCard output={makeOutput()} />);
+ expect(screen.getByText("fetch")).toBeDefined();
+ expect(
+ screen.getByText("MCP tool 'fetch' executed successfully."),
+ ).toBeDefined();
+ });
+
+ it("renders plain text result", () => {
+ render(<MCPToolOutputCard output={makeOutput({ result: "plain text" })} />);
+ expect(screen.getByText("plain text")).toBeDefined();
+ });
+
+ it("renders JSON result in code block", () => {
+ const json = { status: "ok", count: 42 };
+ render(<MCPToolOutputCard output={makeOutput({ result: json })} />);
+ // JSON may be split across text nodes by ContentCodeBlock, so match a key substring.
+ expect(screen.getByText(/"status": "ok"/)).toBeDefined();
+ });
+
+ it("renders null as '(no result)'", () => {
+ render(<MCPToolOutputCard output={makeOutput({ result: null })} />);
+ expect(screen.getByText("(no result)")).toBeDefined();
+ });
+
+ it("renders image result as img element", () => {
+ const imageResult = {
+ type: "image",
+ data: "abc123==",
+ mimeType: "image/png",
+ };
+ render(<MCPToolOutputCard output={makeOutput({ result: imageResult })} />);
+ const img = screen.getByRole("img");
+ expect(img.getAttribute("src")).toBe("data:image/png;base64,abc123==");
+ expect(img.getAttribute("alt")).toBe("Result from fetch");
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/helpers.tsx
new file mode 100644
index 0000000000..416c18bd3f
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/helpers.tsx
@@ -0,0 +1,224 @@
+"use client";
+
+import type { MCPToolOutputResponse } from "@/app/api/__generated__/models/mCPToolOutputResponse";
+import type { MCPToolsDiscoveredResponse } from "@/app/api/__generated__/models/mCPToolsDiscoveredResponse";
+import { ResponseType } from "@/app/api/__generated__/models/responseType";
+import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";
+import { WarningDiamondIcon, PlugsConnectedIcon } from "@phosphor-icons/react";
+import type { ToolUIPart } from "ai";
+import { OrbitLoader } from "../../components/OrbitLoader/OrbitLoader";
+
+// ------------------------------------------------------------------ //
+// Re-export generated types for use by RunMCPTool components
+// ------------------------------------------------------------------ //
+
+export type { MCPToolsDiscoveredResponse, MCPToolOutputResponse };
+
+export interface MCPErrorOutput {
+ type: typeof ResponseType.error;
+ message: string;
+ error?: string | null;
+ session_id?: string | null;
+}
+
+export type RunMCPToolOutput =
+ | MCPToolsDiscoveredResponse
+ | MCPToolOutputResponse
+ | SetupRequirementsResponse
+ | MCPErrorOutput;
+
+// ------------------------------------------------------------------ //
+// Type guards
+// ------------------------------------------------------------------ //
+
+export function isDiscoveryOutput(
+ output: RunMCPToolOutput,
+): output is MCPToolsDiscoveredResponse {
+ return output.type === ResponseType.mcp_tools_discovered;
+}
+
+export function isMCPToolOutput(
+ output: RunMCPToolOutput,
+): output is MCPToolOutputResponse {
+ return output.type === ResponseType.mcp_tool_output;
+}
+
+export function isSetupRequirementsOutput(
+ output: RunMCPToolOutput,
+): output is SetupRequirementsResponse {
+ return (
+ output.type === ResponseType.setup_requirements ||
+ ("setup_info" in output &&
+ output.setup_info !== null &&
+ typeof output.setup_info === "object")
+ );
+}
+
+/** Returns true only when the response type is explicitly "error". */
+export function isErrorOutput(
+ output: RunMCPToolOutput,
+): output is MCPErrorOutput {
+ return output.type === ResponseType.error;
+}
+
+// ------------------------------------------------------------------ //
+// Output parsing
+// ------------------------------------------------------------------ //
+
+/**
+ * Parse a raw server payload into a typed RunMCPToolOutput.
+ * Accepts both objects (already parsed) and JSON strings.
+ * Returns null for anything that doesn't look like a known response shape.
+ */
+function parseOutput(raw: unknown): RunMCPToolOutput | null {
+ if (!raw) return null;
+ if (typeof raw === "string") {
+ const trimmed = raw.trim();
+ if (!trimmed) return null;
+ try {
+ return parseOutput(JSON.parse(trimmed) as unknown);
+ } catch {
+ return null;
+ }
+ }
+ if (raw !== null && typeof raw === "object") {
+ const type = (raw as { type?: unknown }).type;
+ if (
+ typeof type === "string" &&
+ (Object.values(ResponseType) as string[]).includes(type)
+ ) {
+ return raw as RunMCPToolOutput;
+ }
+ // Fallback structural checks for legacy / no-type payloads
+ if ("setup_info" in (raw as object))
+ return raw as SetupRequirementsResponse;
+ if ("tool_name" in (raw as object)) return raw as MCPToolOutputResponse;
+ if ("tools" in (raw as object)) return raw as MCPToolsDiscoveredResponse;
+ }
+ return null;
+}
+
+/**
+ * Extract and parse the `output` field from a tool UI part.
+ * Returns null when the output is absent or unrecognised.
+ */
+export function getRunMCPToolOutput(part: unknown): RunMCPToolOutput | null {
+ if (!part || typeof part !== "object") return null;
+ return parseOutput((part as { output?: unknown }).output);
+}
+
+// ------------------------------------------------------------------ //
+// UI helpers
+// ------------------------------------------------------------------ //
+
+export interface RunMCPToolInput {
+ server_url?: string;
+ tool_name?: string;
+ tool_arguments?: Record<string, unknown>;
+}
+
+export function serverHost(url: string): string {
+ try {
+ return new URL(url).hostname || url;
+ } catch {
+ return url;
+ }
+}
+
+/**
+ * Return a short preview of the most meaningful argument value, e.g. `"my query"`.
+ * Checks common "query" key names first, then falls back to the first string value.
+ * Returns an empty string when no suitable argument is found.
+ */
+const ARG_PREVIEW_MAX = 60;
+
+function truncateArgPreview(value: string): string {
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
+ if (escaped.length <= ARG_PREVIEW_MAX) return `"${escaped}"`;
+ return `"${escaped.slice(0, ARG_PREVIEW_MAX)}…"`;
+}
+
+function getArgPreview(args: Record<string, unknown> | undefined): string {
+ if (!args) return "";
+ const queryKeys = [
+ "query",
+ "q",
+ "search",
+ "text",
+ "content",
+ "message",
+ "input",
+ "prompt",
+ ];
+ for (const key of queryKeys) {
+ if (typeof args[key] === "string" && (args[key] as string).length > 0)
+ return truncateArgPreview(args[key] as string);
+ }
+ for (const val of Object.values(args)) {
+ if (typeof val === "string" && val.length > 0)
+ return truncateArgPreview(val);
+ }
+ return "";
+}
+
+/**
+ * Return the human-readable status line shown next to the MCP tool spinner.
+ * Transitions through: connecting → discovering / calling → result summary.
+ */
+export function getAnimationText(part: {
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}): string {
+ const input = part.input as RunMCPToolInput | undefined;
+ const host = input?.server_url ? serverHost(input.server_url) : "";
+ const toolName = input?.tool_name?.trim();
+
+ switch (part.state) {
+ case "input-streaming":
+ case "input-available": {
+ if (!toolName) return `Discovering MCP tools${host ? ` on ${host}` : ""}`;
+ const argPreview = getArgPreview(input?.tool_arguments);
+ return `Calling ${toolName}${argPreview ? `(${argPreview})` : ""}${host ? ` on ${host}` : ""}`;
+ }
+ case "output-available": {
+ const output = getRunMCPToolOutput(part);
+ if (!output) return "Connecting to MCP server";
+ if (isSetupRequirementsOutput(output))
+ return `Connect to ${output.setup_info.agent_name}`;
+ if (isMCPToolOutput(output))
+ return `Ran ${output.tool_name}${host ? ` on ${host}` : ""}`;
+ if (isDiscoveryOutput(output))
+ return `Discovered ${output.tools.length} tool(s) on ${serverHost(output.server_url)}`;
+ return "MCP error";
+ }
+ case "output-error":
+ return "MCP error";
+ default:
+ return "Connecting to MCP server";
+ }
+}
+
+export function ToolIcon({
+ isStreaming,
+ isError,
+}: {
+ isStreaming?: boolean;
+ isError?: boolean;
+}) {
+ if (isError) {
+ return (
+ <WarningDiamondIcon size={14} weight="regular" className="text-red-500" />
+ );
+ }
+ if (isStreaming) {
+ return <OrbitLoader size={24} />;
+ }
+ return (
+ <PlugsConnectedIcon
+ size={14}
+ weight="regular"
+ className="text-neutral-400"
+ />
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index d2f1b8413d..b14e627845 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -986,7 +986,11 @@
{ "$ref": "#/components/schemas/BlockDetailsResponse" },
{ "$ref": "#/components/schemas/BlockOutputResponse" },
{ "$ref": "#/components/schemas/DocSearchResultsResponse" },
- { "$ref": "#/components/schemas/DocPageResponse" }
+ { "$ref": "#/components/schemas/DocPageResponse" },
+ {
+ "$ref": "#/components/schemas/MCPToolsDiscoveredResponse"
+ },
+ { "$ref": "#/components/schemas/MCPToolOutputResponse" }
],
"title": "Response Getv2[Dummy] Tool Response Type Export For Codegen"
}
@@ -4655,6 +4659,46 @@
"security": [{ "HTTPBearerJWT": [] }]
}
},
+ "/api/mcp/token": {
+ "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``.",
+ "operationId": "postV2Store a bearer token for an mcp server",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/MCPStoreTokenRequest" }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CredentialsMetaResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ },
+ "security": [{ "HTTPBearerJWT": [] }]
+ }
+ },
"/api/oauth/app/{client_id}": {
"get": {
"tags": ["oauth"],
@@ -10063,6 +10107,63 @@
"title": "MCPOAuthLoginResponse",
"description": "Response with the OAuth login URL for the user to authenticate."
},
+ "MCPStoreTokenRequest": {
+ "properties": {
+ "server_url": {
+ "type": "string",
+ "title": "Server Url",
+ "description": "MCP server URL the token authenticates against"
+ },
+ "token": {
+ "type": "string",
+ "minLength": 1,
+ "format": "password",
+ "title": "Token",
+ "description": "Bearer token / API key for the MCP server",
+ "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."
+ },
+ "MCPToolInfo": {
+ "properties": {
+ "name": { "type": "string", "title": "Name" },
+ "description": { "type": "string", "title": "Description" },
+ "input_schema": {
+ "additionalProperties": true,
+ "type": "object",
+ "title": "Input Schema"
+ }
+ },
+ "type": "object",
+ "required": ["name", "description", "input_schema"],
+ "title": "MCPToolInfo",
+ "description": "Information about a single MCP tool discovered from a server."
+ },
+ "MCPToolOutputResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "mcp_tool_output"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "server_url": { "type": "string", "title": "Server Url" },
+ "tool_name": { "type": "string", "title": "Tool Name" },
+ "result": { "title": "Result" },
+ "success": { "type": "boolean", "title": "Success", "default": true }
+ },
+ "type": "object",
+ "required": ["message", "server_url", "tool_name"],
+ "title": "MCPToolOutputResponse",
+ "description": "Response after executing an MCP tool."
+ },
"MCPToolResponse": {
"properties": {
"name": { "type": "string", "title": "Name" },
@@ -10078,6 +10179,29 @@
"title": "MCPToolResponse",
"description": "A single MCP tool returned by discovery."
},
+ "MCPToolsDiscoveredResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "mcp_tools_discovered"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "server_url": { "type": "string", "title": "Server Url" },
+ "tools": {
+ "items": { "$ref": "#/components/schemas/MCPToolInfo" },
+ "type": "array",
+ "title": "Tools"
+ }
+ },
+ "type": "object",
+ "required": ["message", "server_url", "tools"],
+ "title": "MCPToolsDiscoveredResponse",
+ "description": "Response when MCP tools are discovered from a server (agent-internal)."
+ },
"MarketplaceListing": {
"properties": {
"id": { "type": "string", "title": "Id" },
@@ -11260,7 +11384,9 @@
"bash_exec",
"feature_request_search",
"feature_request_created",
- "suggested_goal"
+ "suggested_goal",
+ "mcp_tools_discovered",
+ "mcp_tool_output"
],
"title": "ResponseType",
"description": "Types of tool responses."