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.

fix(platform/copilot): MCP setup card fires on stale creds, OAuth popup close race, registry-search prompt, Connected/Reconnect UI, integrations page polish (#13207)

Zamil Majdy97a7bc188814
diff --git a/autogpt_platform/backend/backend/api/features/mcp/routes.py b/autogpt_platform/backend/backend/api/features/mcp/routes.py
index 87dbb64b77..4972535886 100644
--- a/autogpt_platform/backend/backend/api/features/mcp/routes.py
+++ b/autogpt_platform/backend/backend/api/features/mcp/routes.py
@@ -476,7 +476,14 @@ async def mcp_store_token(
title=credentials.title,
scopes=credentials.scopes,
username=credentials.username,
- host=hostname,
+ # Use the full ``mcp_server_url`` for parity with the OAuth callback
+ # response and with ``to_meta_response``'s ``get_host`` (which reads
+ # the same metadata key for MCP creds). The list endpoint already
+ # normalizes both flows to full URL via ``get_host``, so the matching
+ # logic in ``MCPSetupCard.liveHasCred`` works either way — but
+ # returning the same shape from POST keeps the contract consistent
+ # for any consumer that uses the immediate POST response.
+ host=credentials.metadata.get("mcp_server_url"),
)
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 9b82eec9c8..3b3665f903 100644
--- a/autogpt_platform/backend/backend/api/features/mcp/test_routes.py
+++ b/autogpt_platform/backend/backend/api/features/mcp/test_routes.py
@@ -476,7 +476,11 @@ class TestStoreToken:
data = response.json()
assert data["provider"] == "mcp"
assert data["type"] == "oauth2"
- assert data["host"] == "mcp.example.com"
+ # ``host`` carries the full normalized ``mcp_server_url`` (not just
+ # the bare hostname) so the response is parity with the OAuth
+ # callback path — ``MCPSetupCard`` matches against this URL to
+ # render the Connected/Reconnect state on chat refresh.
+ assert data["host"] == "https://mcp.example.com/mcp"
mock_cm.create.assert_called_once()
@pytest.mark.asyncio(loop_scope="session")
diff --git a/autogpt_platform/backend/backend/blocks/mcp/client.py b/autogpt_platform/backend/backend/blocks/mcp/client.py
index a0386c3b14..6272c81d83 100644
--- a/autogpt_platform/backend/backend/blocks/mcp/client.py
+++ b/autogpt_platform/backend/backend/blocks/mcp/client.py
@@ -278,6 +278,27 @@ class MCPClient:
return result or {}
+ async def close(self) -> None:
+ """Terminate the MCP session on the server (Streamable HTTP spec).
+
+ The MCP transport spec asks clients to ``DELETE`` the session URL
+ with their ``Mcp-Session-Id`` header so the server can free its
+ session state immediately instead of waiting for a timeout sweep.
+ Best-effort: failures are swallowed so a flaky close can't poison
+ the caller's flow. Resets ``self._session_id`` so a subsequent
+ ``initialize`` starts a fresh session.
+ """
+ if not self._session_id:
+ return
+ try:
+ headers = self._build_headers()
+ requests = Requests(raise_for_status=False, extra_headers=headers)
+ await requests.delete(self.server_url)
+ except Exception:
+ pass
+ finally:
+ self._session_id = None
+
async def list_tools(self) -> list[MCPTool]:
"""
Discover available tools from the MCP server.
diff --git a/autogpt_platform/backend/backend/blocks/mcp/helpers.py b/autogpt_platform/backend/backend/blocks/mcp/helpers.py
index bec173ba8b..863463484f 100644
--- a/autogpt_platform/backend/backend/blocks/mcp/helpers.py
+++ b/autogpt_platform/backend/backend/blocks/mcp/helpers.py
@@ -4,11 +4,12 @@ from __future__ import annotations
import json
import logging
-from typing import TYPE_CHECKING, Any
+from typing import Any
from urllib.parse import urlparse
-if TYPE_CHECKING:
- from backend.data.model import OAuth2Credentials
+from backend.data.model import OAuth2Credentials
+from backend.integrations.creds_manager import IntegrationCredentialsManager
+from backend.integrations.providers import ProviderName
logger = logging.getLogger(__name__)
@@ -71,6 +72,41 @@ def parse_mcp_content(content: list[dict[str, Any]]) -> Any:
return output_parts or None
+async def invalidate_mcp_credential(user_id: str, credential_id: str) -> None:
+ """Delete a stored MCP credential that the server just rejected.
+
+ Called from the copilot's ``run_mcp_tool`` path when an MCP server
+ returns 401/403 with a credential we *do* have on file — meaning the
+ token was revoked or expired server-side without our local
+ ``access_token_expires_at`` knowing. Removing the dead row prevents
+ ``auto_lookup_mcp_credential`` from feeding the same stale token back
+ on the next attempt and lets the user re-auth cleanly via the setup
+ card. Failures are swallowed (best-effort) — the worst case is a
+ second loop through the same code path, which still surfaces the
+ setup card.
+ """
+ try:
+ mgr = IntegrationCredentialsManager()
+ # Go through ``mgr.delete`` (not ``store.delete_creds_by_id``) so the
+ # per-credential lock + ``_invoke_creds_changed_hook`` fire — the hook
+ # evicts any cached provider token for the user.
+ await mgr.delete(user_id, credential_id)
+ logger.info("Invalidated stale MCP credential %s", credential_id)
+ except ValueError:
+ # ``mgr.delete`` raises ``ValueError`` when the credential is
+ # already gone (e.g. the user deleted it manually in Settings
+ # between the ``auto_lookup_mcp_credential`` call and now). Not
+ # a problem — the goal was "this row should not exist" and it
+ # doesn't. Demote to debug so we don't spam warnings on retries.
+ logger.debug("MCP credential %s already gone during invalidate", credential_id)
+ except Exception:
+ logger.warning(
+ "Failed to invalidate stale MCP credential %s",
+ credential_id,
+ exc_info=True,
+ )
+
+
async def auto_lookup_mcp_credential(
user_id: str, server_url: str
) -> OAuth2Credentials | None:
@@ -82,10 +118,6 @@ async def auto_lookup_mcp_credential(
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(
diff --git a/autogpt_platform/backend/backend/copilot/prompting.py b/autogpt_platform/backend/backend/copilot/prompting.py
index 248e0f0361..b72489a334 100644
--- a/autogpt_platform/backend/backend/copilot/prompting.py
+++ b/autogpt_platform/backend/backend/copilot/prompting.py
@@ -147,12 +147,34 @@ Order of fallbacks (only after `find_block` returns nothing usable):
(Google Sheets, Docs, Calendar, Gmail, Slack, GitHub, LinkedIn via Ayrshare,
etc.). Most "obscure" integrations have a block.
-2. **`run_mcp_tool`** — If `find_block` returns no match, check if a hosted MCP
- server is available for the service. Only use known MCP server URLs from
- the registry.
-
-3. **`SendAuthenticatedWebRequestBlock`** — If no block or MCP server exists,
- use `SendAuthenticatedWebRequestBlock` with existing host-scoped
+2. **`run_mcp_tool` — MANDATORY when `find_block` returns nothing.** Don't
+ stop at "no integration exists" after one `find_block` miss. Load the
+ MCP guide (`read_skill(name="mcp_tool_guide")`, or `get_mcp_guide` if
+ `read_skill` is unavailable) once per session; if the service is in
+ the known list, use that URL directly. Otherwise query
+ `https://registry.modelcontextprotocol.io/v0/servers?q=<service>` via
+ the unauthenticated `SendWebRequestBlock` (the registry is public, no
+ creds needed). Many popular services (Sentry, etc.) aren't in the
+ hardcoded list — always check the registry before falling back.
+
+ Before calling `run_mcp_tool` on a registry-returned URL, **verify the
+ server's hostname matches the service** (e.g. `mcp.sentry.dev` for
+ Sentry, `mcp.<service>.com` / `mcp.<service>.dev` / vendor-owned
+ domain). If multiple plausible results exist or the hostname's vendor
+ isn't obvious, surface the candidates to the user and ask which one
+ to use — never auto-pick when the match is ambiguous, since the user
+ is about to hand sign-in credentials to that URL.
+
+ **For "just connect" intent** (user says "connect to X" / "sign in to
+ X" with no action yet), call `run_mcp_tool(server_url,
+ surface_connect_card=true)` — the tool returns only the sign-in card,
+ skipping the network call. The card renders as "Connected to X —
+ Reconnect" when creds already exist, or "Connect X" when not. Use this
+ instead of discovery-only calls so the user always sees visible state.
+
+3. **`SendAuthenticatedWebRequestBlock`** — If no block AND no MCP server
+ exists (after searching both `find_block` AND the MCP registry), use
+ `SendAuthenticatedWebRequestBlock` with existing host-scoped
credentials. Check available credentials via `connect_integration`.
4. **Manual API call** — As a last resort, guide the user to set up
@@ -161,8 +183,9 @@ Order of fallbacks (only after `find_block` returns nothing usable):
### Anti-pattern: refusing without searching (CRITICAL)
-**Never** emit any variant of these without a preceding `find_block` call in
-the current turn:
+**Never** emit any variant of these without **both** a preceding
+`find_block` call AND, if `find_block` returned no usable match, an MCP
+registry lookup in the current turn:
- "We don't have a native X integration yet."
- "X isn't supported on the platform."
@@ -170,20 +193,18 @@ the current turn:
- "There's no block for X."
- Any feature-request flow ("I'll flag this as a requested integration").
-If you have not called `find_block` for the service the user named, you do
-**not yet know** whether it exists. Refusing or pivoting to a workaround
-before searching wastes the user's turn and is a known regression. This rule
-overrides any worked example earlier in this prompt that shows a capability
-gap being declared without a preceding `find_block` call — those examples
-are wrong and should be ignored.
+Without **both** searches you do not yet know whether the service exists.
+Pivoting to a workaround before exhausting both is a known regression that
+overrides any worked example earlier in this prompt.
-Correct flow for *any* integration request, even ones you "know" don't
-exist:
+Correct flow for *any* integration request:
```
1. find_block(query="<service> <action>")
-2. If a matching block exists → use it (or run with validate_only to inspect).
-3. If find_block returns no match → THEN state the gap and offer
+2. Matching block → use it (validate_only to inspect).
+3. No match → load mcp_tool_guide + registry-search; run_mcp_tool if a
+ server is found.
+4. Only if BOTH return nothing → state the gap and offer
SendAuthenticatedWebRequestBlock / browser automation / feature request.
```
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
index 61a64709cc..6420fe1e56 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
@@ -8,6 +8,7 @@ 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,
+ invalidate_mcp_credential,
normalize_mcp_url,
parse_mcp_content,
server_host,
@@ -79,6 +80,16 @@ class RunMCPToolTool(BaseTool):
"type": "object",
"description": "Arguments matching the tool's input schema.",
},
+ "surface_connect_card": {
+ "type": "boolean",
+ "description": (
+ "When true, return only the sign-in card for this "
+ "server (no MCPClient call). Use for 'connect to "
+ "<service>' intent without an action — the card "
+ "indicates connected/not-connected state and offers "
+ "Reconnect."
+ ),
+ },
},
"required": ["server_url"],
}
@@ -94,6 +105,7 @@ class RunMCPToolTool(BaseTool):
server_url: str = "",
tool_name: str = "",
tool_arguments: dict[str, Any] | None = None,
+ surface_connect_card: bool = False,
**kwargs,
) -> ToolResponseBase:
server_url = server_url.strip()
@@ -175,6 +187,67 @@ class RunMCPToolTool(BaseTool):
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
+ # "Just connect" intent: return only the setup card so the user
+ # gets a visible Connect/Reconnect affordance even when there's
+ # nothing else to render (previously: discovery succeeded
+ # silently and nothing rendered, so the model's "click Connect"
+ # promise mismatched the empty UI).
+ #
+ # When stored creds exist we still need to know whether they're
+ # *valid* before promising the user "Connected" — a stale row
+ # left over from a server-side revocation would mislead the UI
+ # into showing the Reconnect pill, then 401 on the next real
+ # tool call (see the John bug this PR also fixes). Cheapest
+ # verification is ``MCPClient.initialize`` (one round-trip, no
+ # tool listing); on 401/403 we treat the cred as stale, drop the
+ # dead row, and surface the not-connected card so the user
+ # re-auths in one step. Other HTTP errors (timeouts, 5xx) are
+ # treated as "unknown, optimistically connected" — the next
+ # real tool call will self-correct via the same invalidate path.
+ if surface_connect_card:
+ connected = creds is not None
+ if creds is not None:
+ probe_client = MCPClient(server_url, auth_token=auth_token)
+ try:
+ try:
+ await probe_client.initialize()
+ except HTTPClientError as probe_err:
+ if probe_err.status_code in _AUTH_STATUS_CODES:
+ await invalidate_mcp_credential(user_id, creds.id)
+ connected = False
+ # Other HTTP statuses (5xx, redirects, etc.) →
+ # leave the cred in place and report
+ # "optimistically connected" — the user can
+ # still try; the real tool call will surface
+ # the actual error if it persists.
+ except Exception:
+ # Any non-HTTP failure (asyncio.TimeoutError,
+ # network errors, MCPClientError, etc.) — also
+ # treat as "unknown, optimistically connected".
+ # Important: we MUST NOT let a transient server
+ # outage delete the user's still-valid cred.
+ # Catching ``Exception`` broadly here keeps the
+ # surface_connect_card fast-path resilient
+ # instead of propagating an uncaught exception
+ # out of ``_execute``.
+ logger.debug(
+ "MCP probe for surface_connect_card failed for %s — "
+ "reporting optimistically connected",
+ server_host(server_url),
+ exc_info=True,
+ )
+ finally:
+ # Terminate the probe session on the MCP server.
+ # Without DELETE, every surface_connect_card call
+ # leaks a session row server-side; under load this
+ # accumulates (sentry MEDIUM bug-prediction).
+ # ``close`` is best-effort and swallows its own
+ # errors.
+ await probe_client.close()
+ return self._build_setup_requirements(
+ server_url, session_id, connected=connected
+ )
+
client = MCPClient(server_url, auth_token=auth_token)
try:
@@ -190,8 +263,17 @@ class RunMCPToolTool(BaseTool):
)
except HTTPClientError as e:
- if e.status_code in _AUTH_STATUS_CODES and not creds:
- # Server requires auth and user has no stored credentials
+ if e.status_code in _AUTH_STATUS_CODES:
+ # 401/403 → user needs to (re)authenticate. Fire the setup
+ # card whether or not we have a stored credential row: when
+ # `creds` is None the user has never connected, and when it
+ # is non-None the stored token has been revoked / expired
+ # server-side without us knowing (refresh_if_needed only
+ # refreshes when local `access_token_expires_at` says so).
+ # If we have a stale row, delete it so the next attempt
+ # doesn't loop on the same dead token.
+ if creds is not None:
+ await invalidate_mcp_credential(user_id, creds.id)
return self._build_setup_requirements(server_url, session_id)
host = server_host(server_url)
logger.warning("MCP HTTP error for %s: status=%s", host, e.status_code)
@@ -296,8 +378,16 @@ class RunMCPToolTool(BaseTool):
self,
server_url: str,
session_id: str,
+ connected: bool = False,
) -> SetupRequirementsResponse | ErrorResponse:
- """Build a SetupRequirementsResponse for a missing MCP server credential."""
+ """Build a SetupRequirementsResponse for an MCP server credential.
+
+ ``connected=True`` flips the response into the "already signed in"
+ shape — frontend renders "Connected to <service> — Reconnect"
+ instead of the bare Connect button. Used by the
+ ``surface_connect_card`` path so the user always gets visible
+ feedback even when stored creds are still valid.
+ """
mcp_block = MCPToolBlock()
credentials_fields_info = mcp_block.input_schema.get_credentials_fields_info()
@@ -329,19 +419,27 @@ class RunMCPToolTool(BaseTool):
host = server_host(server_url)
service = _service_name(host)
+ message = (
+ f"You're connected to {service}. Use Reconnect to swap accounts."
+ if connected
+ else f"To continue, sign in to {service} and approve access."
+ )
return SetupRequirementsResponse(
- message=(f"To continue, sign in to {service} and approve access."),
+ message=message,
session_id=session_id,
setup_info=SetupInfo(
agent_id=server_url,
agent_name=service,
user_readiness=UserReadiness(
- has_all_credentials=False,
- missing_credentials=missing_creds_dict,
- ready_to_run=False,
+ has_all_credentials=connected,
+ missing_credentials={} if connected else missing_creds_dict,
+ ready_to_run=connected,
),
requirements={
- "credentials": missing_creds_list,
+ # Keep `requirements.credentials` in sync with
+ # `user_readiness.missing_credentials` — when connected,
+ # neither field should advertise a credential need.
+ "credentials": [] if connected else missing_creds_list,
"inputs": [],
"execution_modes": ["immediate"],
},
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
index e831772b64..84ebc550ce 100644
--- a/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py
+++ b/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py
@@ -544,8 +544,64 @@ async def test_auth_required_without_creds_returns_setup_requirements():
@pytest.mark.asyncio(loop_scope="session")
-async def test_auth_error_with_existing_creds_returns_error():
- """HTTP 403 when creds ARE present → generic ErrorResponse (not setup card)."""
+async def test_surface_connect_card_connected_when_creds_exist_and_probe_ok():
+ """surface_connect_card + valid creds + probe initialize() OK → connected.
+
+ The probe is a one-round-trip ``MCPClient.initialize`` — no tool
+ listing. When it succeeds the cred is fresh, ``has_all_credentials``
+ reports True, and the UI renders Connected/Reconnect.
+ """
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ mock_creds = MagicMock()
+ mock_creds.access_token = SecretStr("fresh-token")
+ mock_creds.id = "fresh-cred-id"
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url_host", 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(return_value=None)
+ mock_client.close = AsyncMock(return_value=None)
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ) as mock_client_cls:
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ surface_connect_card=True,
+ )
+ # Probe ran exactly once — no follow-up tool listing.
+ mock_client_cls.assert_called_once()
+ mock_client.initialize.assert_awaited_once()
+ # Session terminated via DELETE so we don't leak a row
+ # server-side on every "just connect" intent.
+ mock_client.close.assert_awaited_once()
+
+ assert isinstance(response, SetupRequirementsResponse)
+ assert response.setup_info.user_readiness.has_all_credentials is True
+ assert response.setup_info.user_readiness.ready_to_run is True
+ assert response.setup_info.user_readiness.missing_credentials == {}
+
+
[email protected](loop_scope="session")
+async def test_surface_connect_card_stale_creds_invalidated_returns_not_connected():
+ """surface_connect_card + stale creds + probe 401 → cred deleted, not-connected card.
+
+ Prevents the John bug from re-surfacing through the ``surface_connect_card``
+ fast-path: when the cred is revoked server-side, the probe surfaces it
+ immediately and we invalidate the row + return a not-connected card so
+ the user re-auths in one step instead of seeing a misleading "Connected"
+ pill that 401s on the next tool call.
+ """
from backend.util.request import HTTPClientError
tool = RunMCPToolTool()
@@ -553,6 +609,7 @@ async def test_auth_error_with_existing_creds_returns_error():
mock_creds = MagicMock()
mock_creds.access_token = SecretStr("stale-token")
+ mock_creds.id = "stale-cred-id"
with patch(
"backend.copilot.tools.run_mcp_tool.validate_url_host", new_callable=AsyncMock
@@ -564,20 +621,222 @@ async def test_auth_error_with_existing_creds_returns_error():
):
mock_client = AsyncMock()
mock_client.initialize = AsyncMock(
- side_effect=HTTPClientError("Forbidden", status_code=403)
+ side_effect=HTTPClientError("Unauthorized", status_code=401)
)
+ mock_client.close = AsyncMock(return_value=None)
with patch(
"backend.copilot.tools.run_mcp_tool.MCPClient",
return_value=mock_client,
):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.invalidate_mcp_credential",
+ new_callable=AsyncMock,
+ ) as mock_invalidate:
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ surface_connect_card=True,
+ )
+ mock_invalidate.assert_awaited_once_with(_USER_ID, "stale-cred-id")
+ # close() runs in ``finally`` even when initialize raised.
+ mock_client.close.assert_awaited_once()
+
+ assert isinstance(response, SetupRequirementsResponse)
+ assert response.setup_info.user_readiness.has_all_credentials is False
+ assert response.setup_info.user_readiness.ready_to_run is False
+
+
[email protected](loop_scope="session")
+async def test_surface_connect_card_disconnected_when_no_creds():
+ """surface_connect_card=True + no creds → SetupReq has_all_credentials=False.
+
+ Renders as the standard "Connect <service>" card; no network call made.
+ """
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url_host", new_callable=AsyncMock
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=None,
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient"
+ ) as mock_client_cls:
response = await tool._execute(
user_id=_USER_ID,
session=session,
server_url=_SERVER_URL,
+ surface_connect_card=True,
)
+ mock_client_cls.assert_not_called()
- assert isinstance(response, ErrorResponse)
- assert "403" in response.message
+ assert isinstance(response, SetupRequirementsResponse)
+ assert response.setup_info.user_readiness.has_all_credentials is False
+ assert response.setup_info.user_readiness.ready_to_run is False
+
+
[email protected](loop_scope="session")
+async def test_surface_connect_card_probe_5xx_reports_optimistically_connected():
+ """surface_connect_card + valid creds + probe 500 → connected, cred kept.
+
+ The probe is best-effort: transient server errors (5xx, redirects)
+ must NOT delete an otherwise-valid cred. We report
+ ``has_all_credentials=True`` and let the next real tool call surface
+ the actual error if it persists.
+ """
+ from backend.util.request import HTTPClientError
+
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ mock_creds = MagicMock()
+ mock_creds.access_token = SecretStr("valid-token")
+ mock_creds.id = "valid-cred-id"
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url_host", 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("Internal Server Error", status_code=500)
+ )
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.invalidate_mcp_credential",
+ new_callable=AsyncMock,
+ ) as mock_invalidate:
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ surface_connect_card=True,
+ )
+ mock_invalidate.assert_not_awaited()
+
+ assert isinstance(response, SetupRequirementsResponse)
+ assert response.setup_info.user_readiness.has_all_credentials is True
+ assert response.setup_info.user_readiness.ready_to_run is True
+
+
[email protected](loop_scope="session")
+async def test_surface_connect_card_probe_timeout_reports_optimistically_connected():
+ """surface_connect_card + valid creds + probe TimeoutError → connected, cred kept.
+
+ Non-HTTP failures (asyncio.TimeoutError, OSError, MCPClientError) hit
+ the broad ``except Exception`` branch — same "optimistically connected"
+ semantics as the 5xx path.
+ """
+ import asyncio
+
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ mock_creds = MagicMock()
+ mock_creds.access_token = SecretStr("valid-token")
+ mock_creds.id = "valid-cred-id"
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url_host", 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=asyncio.TimeoutError("probe took too long")
+ )
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.MCPClient",
+ return_value=mock_client,
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.invalidate_mcp_credential",
+ new_callable=AsyncMock,
+ ) as mock_invalidate:
+ response = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ server_url=_SERVER_URL,
+ surface_connect_card=True,
+ )
+ mock_invalidate.assert_not_awaited()
+
+ assert isinstance(response, SetupRequirementsResponse)
+ assert response.setup_info.user_readiness.has_all_credentials is True
+ assert response.setup_info.user_readiness.ready_to_run is True
+
+
[email protected](loop_scope="session")
+async def test_auth_error_with_stale_creds_fires_setup_and_invalidates():
+ """HTTP 403 when creds ARE present → still fire setup card, drop the stale row.
+
+ Stored creds whose ``access_token_expires_at`` is in the future locally
+ but which the server has revoked/expired don't get refreshed by
+ ``auto_lookup_mcp_credential`` — they come back live, the request 401s,
+ and the user is stuck. The fix: on any 401/403, surface the setup card
+ so the user can re-auth, and delete the stale row so the next attempt
+ doesn't loop on the same dead token.
+ """
+ from backend.util.request import HTTPClientError
+
+ tool = RunMCPToolTool()
+ session = make_session(_USER_ID)
+
+ mock_creds = MagicMock()
+ mock_creds.access_token = SecretStr("stale-token")
+ mock_creds.id = "stale-cred-id"
+
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url_host", 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,
+ ):
+ with patch(
+ "backend.copilot.tools.run_mcp_tool.invalidate_mcp_credential",
+ new_callable=AsyncMock,
+ ) as mock_invalidate:
+ 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()
+ mock_invalidate.assert_awaited_once_with(
+ _USER_ID, "stale-cred-id"
+ )
+
+ assert response is mock_build.return_value
@pytest.mark.asyncio(loop_scope="session")
diff --git a/autogpt_platform/frontend/public/integrations/mcp.png b/autogpt_platform/frontend/public/integrations/mcp.png
new file mode 100644
index 0000000000..f9d56203fc
Binary files /dev/null and b/autogpt_platform/frontend/public/integrations/mcp.png differ
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
index de3758d645..888eb7de52 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useGetV1ListCredentials } from "@/app/api/__generated__/endpoints/integrations/integrations";
import {
postV2ExchangeOauthCodeForMcpTokens,
postV2InitiateOauthLoginForAnMcpServer,
@@ -12,6 +13,13 @@ import { CredentialsProvidersContext } from "@/providers/agent-credentials/crede
import { useContext, useEffect, useRef, useState } from "react";
import { useCopilotChatActions } from "../../../../components/CopilotChatActionsProvider/useCopilotChatActions";
import { ContentMessage } from "../../../../components/ToolAccordion/AccordionContent";
+
+function normalizeMcpUrl(url: string): string {
+ // Mirrors backend ``normalize_mcp_url`` (helpers.py) so a stored cred
+ // for ``https://mcp.sentry.dev/mcp`` matches a card emitted with the
+ // same URL whether or not the trailing slash is present.
+ return url.trim().replace(/\/+$/, "");
+}
interface Props {
output: SetupRequirementsResponse;
/**
@@ -39,18 +47,102 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {
// agent_name is computed by the backend as the display name for the service
const service = output.setup_info.agent_name;
+ // Initial connection state comes from the backend. When the model
+ // calls `run_mcp_tool` with `surface_connect_card=true`, the response's
+ // `has_all_credentials` reflects whether the user already has a stored
+ // credential for this server — so we render "Connected — Reconnect"
+ // straight away instead of a bare Connect button.
+ const initiallyConnected = Boolean(
+ output.setup_info?.user_readiness?.has_all_credentials,
+ );
+
+ // The persisted backend state above is a snapshot from the moment the
+ // card was emitted. On chat refresh that snapshot is stale — the user
+ // may have completed sign-in in a prior session. Re-fetch the live
+ // cred list and OR it into ``connected`` so a previously-connected
+ // server still renders the "Connected — Reconnect" pill after a
+ // page reload. We OR rather than override: once the user clicks
+ // Connect successfully in this component, ``localConnected`` stays
+ // true even if the live-cred query is briefly stale.
+ const normalizedServer = normalizeMcpUrl(serverUrl);
+ const { data: liveCredsRes } = useGetV1ListCredentials({
+ query: {
+ select: (res) => (res.status === 200 ? res.data : null),
+ // No staleTime — when this card mounts (e.g. immediately after the
+ // backend's ``invalidate_mcp_credential`` deleted a stale row),
+ // we want a fresh fetch. A non-zero staleTime would let the
+ // previously-cached "cred exists" override the post-invalidation
+ // truth, briefly rendering "Connected" on a card whose
+ // ``has_all_credentials=false`` snapshot is the authoritative
+ // post-invalidation state.
+ refetchOnMount: "always",
+ },
+ });
+ // Tri-state: ``true``/``false`` when the live API responded, ``"unknown"``
+ // while loading or after a network/auth failure (``select`` returned
+ // ``null``). Treating an unknown live state as ``false`` would override
+ // a still-valid persisted snapshot — see review for the
+ // initiallyConnected=false + 5xx race that surfaces a bare Connect
+ // button despite an existing cred.
+ const liveHasCred: boolean | "unknown" = !Array.isArray(liveCredsRes)
+ ? "unknown"
+ : liveCredsRes.some(
+ (c) =>
+ c.provider === "mcp" &&
+ typeof c.host === "string" &&
+ normalizeMcpUrl(c.host) === normalizedServer,
+ );
+
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);
+ // ``localConnected`` is set ONLY when the user successfully completes
+ // OAuth / manual-token in this component instance. It is NOT seeded
+ // from ``initiallyConnected`` — that path is handled via ``liveSays``
+ // below. Seeding from the persisted snapshot would shadow a later
+ // ``liveHasCred=false`` (e.g. cred revoked) and keep the Connected
+ // pill stuck.
+ const [localConnected, setLocalConnected] = useState(false);
+ // When Reconnect fails (or any in-card flow errors out), force the
+ // not-connected branch even though the live cred row still exists —
+ // otherwise ``liveHasCred=true`` would keep the pill rendered and the
+ // user couldn't see the error banner or the manual-token input. Reset
+ // on the next attempt so the user can retry.
+ const [forceDisconnected, setForceDisconnected] = useState(false);
const oauthAbortRef = useRef<(() => void) | null>(null);
+ // Combined view:
+ // 1. ``forceDisconnected`` (set by the catch block) wins.
+ // 2. ``localConnected`` (just completed sign-in in this component) wins.
+ // 3. Live API truth wins over the persisted snapshot — a true tells
+ // us the cred is there, a false tells us it isn't.
+ // 4. When live state is unknown (loading/network/auth error), fall
+ // back to the persisted ``initiallyConnected`` snapshot rather
+ // than defaulting to disconnected.
+ const liveSays = liveHasCred === "unknown" ? initiallyConnected : liveHasCred;
+ const connected = !forceDisconnected && (localConnected || liveSays);
+ // Setter compatible with the existing call-sites — they only ever set
+ // ``true`` after a successful flow or ``false`` to drop the pill.
+ const setConnected = setLocalConnected;
+
// Abort any in-progress OAuth popup when the component unmounts.
useEffect(() => () => oauthAbortRef.current?.(), []);
async function handleConnect() {
+ // Re-entrancy guard: a rapid double-click would otherwise race the
+ // two in-flight ``handleConnect`` invocations — the second one aborts
+ // the first's popup (``oauthAbortRef.current?.()``) but the first's
+ // ``await promise`` then rejects with ``OAUTH_ERROR_FLOW_CANCELED``,
+ // which flips ``forceDisconnected=true`` even though the second
+ // attempt is still alive. Bail out cheaply when a flow is already
+ // running. Button is also ``disabled={loading}`` but disabled
+ // <button> elements still fire ``click`` in some browsers.
+ if (loading) return;
setError(null);
+ // Reset showManualToken so a prior 400 doesn't keep the input visible
+ // when a later attempt fails with a non-400 (e.g. network) error.
+ setShowManualToken(false);
setLoading(true);
oauthAbortRef.current?.();
@@ -93,10 +185,24 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {
}
}
+ // Only clear the force-disconnect override AFTER the OAuth dance
+ // completes successfully. Clearing it earlier would let
+ // ``liveHasCred=true`` (Reconnect path) render the Connected pill
+ // mid-flight, briefly contradicting the in-progress "Reconnecting…"
+ // affordance.
+ setForceDisconnected(false);
setConnected(true);
onSend(retryInstruction ?? "I've connected. Please retry.");
} catch (e: unknown) {
const err = e as Record<string, unknown>;
+ // Reconnect failures must drop the Connected view so the user sees
+ // the error / manual-token input rendered by the not-connected
+ // branch. Setting ``localConnected=false`` alone isn't enough when
+ // a stored cred still exists (``liveHasCred=true``) — flip
+ // ``forceDisconnected`` so the not-connected branch wins until the
+ // user retries.
+ setConnected(false);
+ setForceDisconnected(true);
if (err?.status === 400) {
setShowManualToken(true);
setError(
@@ -121,6 +227,10 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {
}
async function handleManualToken() {
+ // Re-entrancy guard first — mirrors ``handleConnect`` so both flows
+ // present the same shape to readers. See the comment on
+ // ``handleConnect``'s guard for the double-click race this prevents.
+ if (loading) return;
const token = manualToken.trim();
if (!token) return;
setLoading(true);
@@ -132,9 +242,20 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {
});
if (!(res.status >= 200 && res.status < 300))
throw new Error("Failed to store token");
+ // Only clear the force-disconnect override AFTER the API confirms
+ // the token was stored. Clearing it before the await would let
+ // ``liveHasCred=true`` (from an existing stale cred) re-render the
+ // Connected pill while the request is still in flight, briefly
+ // showing a false "Connected" state to the user.
+ setForceDisconnected(false);
setConnected(true);
onSend(retryInstruction ?? "I've connected. Please retry.");
} catch (e: unknown) {
+ // Keep the force-disconnect override on so the not-connected
+ // branch (error banner + manual-token input) stays visible — an
+ // existing ``liveHasCred=true`` would otherwise re-render the
+ // Connected pill.
+ setForceDisconnected(true);
const err = e as Record<string, unknown>;
setError(
(typeof err?.message === "string" ? err.message : null) ||
@@ -145,10 +266,29 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {
}
}
+ // Already-connected state. Shown when the backend reports
+ // ``has_all_credentials=true`` (model called with
+ // ``surface_connect_card=true`` and creds already exist), or after the
+ // user just completed a Connect flow in this component instance. Always
+ // expose Reconnect so the user can swap accounts.
if (connected) {
+ // No error banner here — any caught error flips ``forceDisconnected``
+ // to true which forces ``connected=false``, so an error inside the
+ // connected branch is unreachable. The not-connected branch below
+ // owns the error display.
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 {service}!
+ <div className="mt-2 grid gap-2">
+ <div className="rounded-lg border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700">
+ Connected to {service}.{" "}
+ <button
+ type="button"
+ onClick={handleConnect}
+ disabled={loading}
+ className="ml-1 underline underline-offset-2 hover:no-underline disabled:opacity-60"
+ >
+ {loading ? "Reconnecting…" : "Reconnect"}
+ </button>
+ </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
index 37e053f34f..841ed964a2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/__tests__/MCPSetupCard.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/__tests__/MCPSetupCard.test.tsx
@@ -29,7 +29,28 @@ vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({
postV2StoreABearerTokenForAnMcpServer: vi.fn(),
}));
-function makeSetupOutput(serverUrl = "https://mcp.example.com/mcp") {
+// Mock the credentials list hook used for the on-mount live-cred re-sync.
+// Default: no stored creds → ``liveHasCred=false`` matches the persisted
+// ``has_all_credentials=false`` snapshot so the existing tests don't have
+// to thread a connected state through MSW. ``setMockLiveCreds`` lets
+// individual tests override the live state to verify the refresh path.
+let mockLiveCreds: Array<{ provider: string; host?: string | null }> = [];
+function setMockLiveCreds(
+ next: Array<{ provider: string; host?: string | null }>,
+) {
+ mockLiveCreds = next;
+}
+vi.mock("@/app/api/__generated__/endpoints/integrations/integrations", () => ({
+ useGetV1ListCredentials: () => ({
+ data: mockLiveCreds,
+ isLoading: false,
+ }),
+}));
+
+function makeSetupOutput(
+ serverUrl = "https://mcp.example.com/mcp",
+ hasAllCredentials = false,
+) {
return {
type: "setup_requirements" as const,
message: "To continue, sign in to example.com and approve access.",
@@ -38,9 +59,9 @@ function makeSetupOutput(serverUrl = "https://mcp.example.com/mcp") {
agent_id: serverUrl,
agent_name: "example.com",
user_readiness: {
- has_all_credentials: false,
+ has_all_credentials: hasAllCredentials,
missing_credentials: {},
- ready_to_run: false,
+ ready_to_run: hasAllCredentials,
},
requirements: {
credentials: [],
@@ -54,7 +75,10 @@ function makeSetupOutput(serverUrl = "https://mcp.example.com/mcp") {
}
describe("MCPSetupCard", () => {
- afterEach(() => cleanup());
+ afterEach(() => {
+ cleanup();
+ setMockLiveCreds([]);
+ });
it("renders setup message and connect button", () => {
render(<MCPSetupCard output={makeSetupOutput()} />);
@@ -64,6 +88,55 @@ describe("MCPSetupCard", () => {
).toBeDefined();
});
+ it("renders Connected/Reconnect when live creds say the server is connected even if the persisted snapshot was disconnected", () => {
+ // Persisted card snapshot was emitted while the cred was missing (e.g.
+ // John's stale-cred 401 path), but on chat refresh the cred now exists.
+ // Card should render the connected pill, not the bare Connect button.
+ setMockLiveCreds([
+ { provider: "mcp", host: "https://mcp.example.com/mcp" },
+ ]);
+ render(<MCPSetupCard output={makeSetupOutput()} />);
+ expect(screen.getByText(/connected to example\.com/i)).toBeDefined();
+ expect(screen.getByRole("button", { name: /reconnect/i })).toBeDefined();
+ });
+
+ it("matches live creds across a trailing slash on the server URL", () => {
+ // Card was emitted with no trailing slash; stored cred has one.
+ // The frontend ``normalizeMcpUrl`` mirrors the backend so they match.
+ setMockLiveCreds([
+ { provider: "mcp", host: "https://mcp.example.com/mcp/" },
+ ]);
+ render(
+ <MCPSetupCard output={makeSetupOutput("https://mcp.example.com/mcp")} />,
+ );
+ expect(screen.getByText(/connected to example\.com/i)).toBeDefined();
+ });
+
+ it("drops Connected state when live API confirms the cred is gone, even if persisted snapshot said connected", () => {
+ // Sentry-flagged sticky-localConnected regression: the card was
+ // emitted with ``has_all_credentials=true`` (persisted snapshot)
+ // but the cred was deleted server-side before the card re-mounted
+ // on chat refresh. Live API returns ``liveHasCred=false`` (cred
+ // gone). The pill must flip to "Connect", not stay on "Reconnect".
+ setMockLiveCreds([]); // live truth: no cred
+ render(<MCPSetupCard output={makeSetupOutput(undefined, true)} />);
+ expect(
+ screen.getByRole("button", { name: /connect example\.com/i }),
+ ).toBeDefined();
+ expect(screen.queryByText(/connected to example\.com/i)).toBeNull();
+ });
+
+ it("falls back to persisted snapshot when the live cred API fails", () => {
+ // ``useGetV1ListCredentials`` returns ``null`` via ``select`` on a
+ // 401/5xx response. Treating that as "no creds" would override a
+ // still-valid persisted snapshot; the card must keep the
+ // ``initiallyConnected`` truth instead.
+ setMockLiveCreds(null as unknown as Array<{ provider: string }>);
+ render(<MCPSetupCard output={makeSetupOutput(undefined, true)} />);
+ expect(screen.getByText(/connected to example\.com/i)).toBeDefined();
+ expect(screen.getByRole("button", { name: /reconnect/i })).toBeDefined();
+ });
+
it("shows manual token input after OAuth 400", async () => {
const { postV2InitiateOauthLoginForAnMcpServer } = await import(
"@/app/api/__generated__/endpoints/mcp/mcp"
@@ -130,4 +203,247 @@ describe("MCPSetupCard", () => {
expect(screen.getByText(/connected to example\.com/i)).toBeDefined();
});
});
+
+ it("drops Connected state and surfaces manual token input when Reconnect hits HTTP 400", async () => {
+ // Live creds must report the server connected so the card starts in
+ // Connected/Reconnect — ``localConnected`` is no longer seeded from
+ // the persisted snapshot (sentry bug: live false would have been
+ // shadowed by a sticky ``localConnected=true`` from initialization).
+ setMockLiveCreds([
+ { provider: "mcp", host: "https://mcp.example.com/mcp" },
+ ]);
+ 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(undefined, true)} />);
+
+ // Starts in Connected state with Reconnect button visible.
+ const reconnectBtn = screen.getByRole("button", { name: /reconnect/i });
+ fireEvent.click(reconnectBtn);
+
+ // After 400, the not-connected branch must render: error banner + manual
+ // token input. The Connected/Reconnect banner must be gone.
+ await waitFor(() => {
+ expect(screen.getByPlaceholderText("Paste API token")).toBeDefined();
+ });
+ expect(screen.getByText(/does not support OAuth/)).toBeDefined();
+ expect(screen.queryByText(/connected to example\.com/i)).toBeNull();
+ });
+
+ it("drops Connected state on Reconnect failure even when live creds still report the server as connected", async () => {
+ // Sentry-flagged bug: when a stored cred exists (``liveHasCred=true``)
+ // and the user clicks Reconnect → OAuth 400, the previous
+ // ``connected = localConnected || liveHasCred`` logic would keep the
+ // Connected pill rendered because liveHasCred was still true. The
+ // user couldn't see the error or the manual-token input. Fix:
+ // ``forceDisconnected`` overrides both states on any catch.
+ setMockLiveCreds([
+ { provider: "mcp", host: "https://mcp.example.com/mcp" },
+ ]);
+ 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()} />);
+ // Live creds say connected → starts in Connected state.
+ const reconnectBtn = screen.getByRole("button", { name: /reconnect/i });
+ fireEvent.click(reconnectBtn);
+
+ await waitFor(() => {
+ expect(screen.getByPlaceholderText("Paste API token")).toBeDefined();
+ });
+ expect(screen.queryByText(/connected to example\.com/i)).toBeNull();
+ });
+
+ it("re-entrancy guard prevents handleConnect from firing twice on rapid double-click", async () => {
+ // Without ``if (loading) return;`` the second click would race the
+ // first's in-flight popup — abort it and reject the first's await
+ // with OAUTH_ERROR_FLOW_CANCELED, even though the second attempt is
+ // still alive. The guard keeps the second click a no-op so the
+ // first attempt runs to completion.
+ const { postV2InitiateOauthLoginForAnMcpServer } = await import(
+ "@/app/api/__generated__/endpoints/mcp/mcp"
+ );
+ // Reset call counter — prior tests in this file also invoke the same mock.
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockClear();
+ let resolveLogin: ((value: unknown) => void) | undefined;
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockReturnValueOnce(
+ new Promise((res) => {
+ resolveLogin = res;
+ }) as never,
+ );
+
+ render(<MCPSetupCard output={makeSetupOutput()} />);
+ const btn = screen.getByRole("button", { name: /connect example\.com/i });
+ // Rapid double-click before the first call resolves.
+ fireEvent.click(btn);
+ fireEvent.click(btn);
+
+ // Only one network call despite two clicks.
+ expect(
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mock.calls.length,
+ ).toBe(1);
+
+ // Drain the in-flight promise so React doesn't warn on unmount.
+ resolveLogin?.({
+ status: 400,
+ data: { detail: "No OAuth" },
+ headers: new Headers(),
+ });
+ await waitFor(() => {
+ expect(screen.getByPlaceholderText("Paste API token")).toBeDefined();
+ });
+ });
+
+ it("shows timeout-specific error message when OAuth popup times out", async () => {
+ const { postV2InitiateOauthLoginForAnMcpServer } = await import(
+ "@/app/api/__generated__/endpoints/mcp/mcp"
+ );
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
+ status: 200,
+ data: { login_url: "https://example.com/oauth", state_token: "s1" },
+ headers: new Headers(),
+ } as never);
+
+ const { openOAuthPopup } = await import("@/lib/oauth-popup");
+ vi.mocked(openOAuthPopup).mockReturnValueOnce({
+ promise: Promise.reject(new Error("OAuth flow timed out")),
+ cleanup: { abort: vi.fn(), signal: new AbortController().signal },
+ popupBlocked: false,
+ });
+
+ render(<MCPSetupCard output={makeSetupOutput()} />);
+ fireEvent.click(
+ screen.getByRole("button", { name: /connect example\.com/i }),
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText(/oauth sign-in timed out/i)).toBeDefined();
+ });
+ });
+
+ it("shows generic error message when OAuth callback fails with a non-400 status", async () => {
+ const { postV2InitiateOauthLoginForAnMcpServer } = await import(
+ "@/app/api/__generated__/endpoints/mcp/mcp"
+ );
+ // Login itself returns 500 (not 400, not timeout) → catch hits the
+ // "generic error" branch with the server's ``detail``.
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
+ status: 500,
+ data: { detail: "Upstream OAuth registration failed" },
+ headers: new Headers(),
+ } as never);
+
+ render(<MCPSetupCard output={makeSetupOutput()} />);
+ fireEvent.click(
+ screen.getByRole("button", { name: /connect example\.com/i }),
+ );
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(/upstream oauth registration failed/i),
+ ).toBeDefined();
+ });
+ // Manual-token input must NOT appear — that's the 400-only branch.
+ expect(screen.queryByPlaceholderText("Paste API token")).toBeNull();
+ });
+
+ it("submits manual token via Enter key", async () => {
+ // The token input has an onKeyDown that fires handleManualToken on
+ // Enter — covers the keyboard path that's an alternative to the Use
+ // Token button click.
+ const {
+ postV2InitiateOauthLoginForAnMcpServer,
+ postV2StoreABearerTokenForAnMcpServer,
+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
+ status: 400,
+ data: { detail: "No OAuth" },
+ headers: new Headers(),
+ } as never);
+
+ render(<MCPSetupCard output={makeSetupOutput()} />);
+ fireEvent.click(
+ screen.getByRole("button", { name: /connect example\.com/i }),
+ );
+ await waitFor(() => {
+ expect(screen.getByPlaceholderText("Paste API token")).toBeDefined();
+ });
+
+ vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce({
+ status: 200,
+ data: {
+ id: "cred-enter",
+ provider: "mcp",
+ type: "oauth2",
+ title: "MCP: mcp.example.com",
+ scopes: [],
+ },
+ headers: new Headers(),
+ } as never);
+
+ const input = screen.getByPlaceholderText("Paste API token");
+ fireEvent.change(input, { target: { value: "my-token" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+
+ await waitFor(() => {
+ expect(screen.getByText(/connected to example\.com/i)).toBeDefined();
+ });
+ });
+
+ it("re-renders not-connected branch when manual token POST fails (forceDisconnected flips on)", async () => {
+ // ``handleManualToken`` catch must flip ``forceDisconnected=true`` —
+ // otherwise an existing live cred would re-show the Connected pill
+ // even though the just-attempted manual-token store failed.
+ setMockLiveCreds([
+ { provider: "mcp", host: "https://mcp.example.com/mcp" },
+ ]);
+ const {
+ postV2InitiateOauthLoginForAnMcpServer,
+ postV2StoreABearerTokenForAnMcpServer,
+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
+ status: 400,
+ data: { detail: "No OAuth" },
+ headers: new Headers(),
+ } as never);
+
+ render(<MCPSetupCard output={makeSetupOutput(undefined, true)} />);
+ fireEvent.click(screen.getByRole("button", { name: /reconnect/i }));
+ await waitFor(() => {
+ expect(screen.getByPlaceholderText("Paste API token")).toBeDefined();
+ });
+
+ // Token endpoint rejects with non-2xx → catch fires → forceDisconnected stays on.
+ vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce({
+ status: 422,
+ data: { detail: "Invalid token format" },
+ headers: new Headers(),
+ } as never);
+
+ fireEvent.change(screen.getByPlaceholderText("Paste API token"), {
+ target: { value: "bad-token" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: /use token/i }));
+
+ await waitFor(() => {
+ // ``handleManualToken`` throws ``new Error("Failed to store token")``
+ // on non-2xx, which becomes the displayed error message.
+ expect(screen.getByText(/failed to store token/i)).toBeDefined();
+ });
+ // Crucial: live creds say "connected" but the failed token attempt
+ // must keep the not-connected branch rendered so the user can retry.
+ expect(screen.queryByText(/connected to example\.com/i)).toBeNull();
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/integrations/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/__tests__/helpers.test.ts
index ce1f1b6546..8f57f62629 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/integrations/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/__tests__/helpers.test.ts
@@ -45,6 +45,9 @@ describe("formatProviderName", () => {
expect(formatProviderName("github")).toBe("GitHub");
expect(formatProviderName("d_id")).toBe("D-ID");
expect(formatProviderName("twitter")).toBe("X");
+ // "MCP" is an acronym — without an override the title-caser would
+ // emit the awkward "Mcp" we shipped before; keep the override.
+ expect(formatProviderName("mcp")).toBe("MCP");
});
test("title-cases unknown snake_case slugs", () => {
@@ -103,6 +106,39 @@ describe("groupCredentialsByProvider", () => {
]);
expect(groups[0].credentials[0].title).toBe("GitHub");
});
+
+ test("strips redundant '<ProviderName>: ' prefix from per-credential titles", () => {
+ // The row already lives under the provider group, so a title like
+ // ``"MCP: <hostname>"`` or ``"GitHub: octocat"`` duplicates the
+ // group label. Strip generically using the formatted provider name.
+ const groups = groupCredentialsByProvider([
+ makeCred({
+ id: "1",
+ provider: "mcp",
+ title: "MCP: mcp.sentry.dev",
+ }),
+ makeCred({
+ id: "2",
+ provider: "github",
+ title: "GitHub: octocat",
+ }),
+ makeCred({
+ id: "3",
+ provider: "github",
+ title: "Personal",
+ }),
+ ]);
+ const mcp = groups.find((g) => g.id === "mcp");
+ const github = groups.find((g) => g.id === "github");
+ expect(mcp?.credentials[0].title).toBe("mcp.sentry.dev");
+ expect(github?.credentials.find((c) => c.id === "2")?.title).toBe(
+ "octocat",
+ );
+ // Title without the prefix is left alone.
+ expect(github?.credentials.find((c) => c.id === "3")?.title).toBe(
+ "Personal",
+ );
+ });
});
describe("filterProviders", () => {
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/integrations/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/helpers.ts
index c1e2518ae6..22c068c612 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/integrations/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/helpers.ts
@@ -43,6 +43,7 @@ const PROVIDER_DISPLAY_NAME_OVERRIDES: Record<string, string> = {
d_id: "D-ID",
ideogram: "Ideogram",
jina: "Jina",
+ mcp: "MCP",
twitter: "X",
zerobounce: "ZeroBounce",
};
@@ -68,12 +69,26 @@ export function formatMaskedValue(credential: CredentialView): string {
return "Configured";
}
+function stripProviderPrefix(title: string, provider: string): string {
+ // The row already lives under the provider group, so any leading
+ // ``<ProviderName>: `` in the per-credential title doubles up. Strip
+ // it generically (case-insensitive) so e.g. ``"MCP: mcp.sentry.dev"``
+ // collapses to ``"mcp.sentry.dev"`` without a per-provider branch.
+ const displayName = formatProviderName(provider);
+ if (!displayName) return title;
+ const prefix = `${displayName}: `;
+ return title.toLowerCase().startsWith(prefix.toLowerCase())
+ ? title.slice(prefix.length)
+ : title;
+}
+
function toCredentialView(cred: CredentialsMetaResponse): CredentialView {
+ const rawTitle = cred.title ?? formatProviderName(cred.provider);
return {
id: cred.id,
provider: cred.provider,
type: cred.type,
- title: cred.title ?? formatProviderName(cred.provider),
+ title: stripProviderPrefix(rawTitle, cred.provider),
username: cred.username ?? null,
host: cred.host ?? null,
isManaged: cred.is_managed ?? false,
diff --git a/autogpt_platform/frontend/src/lib/oauth-popup.test.ts b/autogpt_platform/frontend/src/lib/oauth-popup.test.ts
new file mode 100644
index 0000000000..4202c0e715
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/oauth-popup.test.ts
@@ -0,0 +1,245 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ OAUTH_ERROR_FLOW_CANCELED,
+ OAUTH_ERROR_WINDOW_CLOSED,
+ openOAuthPopup,
+} from "./oauth-popup";
+
+// Minimal popup stub — window.open returns this. `closed` flips when the
+// "user" closes the popup so the close-detect interval can observe it.
+function makePopupStub() {
+ return {
+ closed: false,
+ location: { href: "" },
+ close: vi.fn(),
+ };
+}
+
+function setupPopup(stub: ReturnType<typeof makePopupStub> | null) {
+ return vi
+ .spyOn(window, "open")
+ .mockImplementation(() => stub as unknown as Window);
+}
+
+describe("openOAuthPopup popup-close grace window", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ localStorage.clear();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ test("rejects with WINDOW_CLOSED after grace if no result arrives", async () => {
+ const popup = makePopupStub();
+ setupPopup(popup);
+
+ const { promise } = openOAuthPopup("https://example.com/oauth", {
+ stateToken: "tok-1",
+ useCrossOriginListeners: true,
+ });
+ const onReject = vi.fn();
+ promise.catch(onReject);
+
+ // User closes the popup.
+ popup.closed = true;
+
+ // First closed-poll tick (500ms) observes closed and starts the 3s grace.
+ await vi.advanceTimersByTimeAsync(500);
+ expect(onReject).not.toHaveBeenCalled();
+
+ // Mid-grace: still pending.
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(onReject).not.toHaveBeenCalled();
+
+ // Grace expires (total +3000ms after close-detect) → reject fires.
+ await vi.advanceTimersByTimeAsync(1600);
+ expect(onReject).toHaveBeenCalledTimes(1);
+ expect(onReject.mock.calls[0][0]).toBeInstanceOf(Error);
+ expect((onReject.mock.calls[0][0] as Error).message).toBe(
+ OAUTH_ERROR_WINDOW_CLOSED,
+ );
+ });
+
+ test("final localStorage sweep resolves when result lands after close", async () => {
+ const popup = makePopupStub();
+ setupPopup(popup);
+
+ const { promise } = openOAuthPopup("https://example.com/oauth", {
+ stateToken: "tok-2",
+ useCrossOriginListeners: true,
+ });
+ const onResolve = vi.fn();
+ const onReject = vi.fn();
+ promise.then(onResolve, onReject);
+
+ // Result lands in scoped localStorage just before the user closes the
+ // popup — the BroadcastChannel listener never fired (storage partitioning)
+ // and the periodic poll hasn't ticked yet.
+ localStorage.setItem(
+ "oauth_popup_result_tok-2",
+ JSON.stringify({
+ message_type: "mcp_oauth_result",
+ success: true,
+ code: "auth-code-xyz",
+ state: "tok-2",
+ }),
+ );
+ popup.closed = true;
+
+ // First closed-poll tick runs the synchronous final-storage check,
+ // which resolves the promise before the grace timer even arms.
+ await vi.advanceTimersByTimeAsync(500);
+
+ expect(onReject).not.toHaveBeenCalled();
+ expect(onResolve).toHaveBeenCalledWith({
+ code: "auth-code-xyz",
+ state: "tok-2",
+ });
+ // Storage entry consumed.
+ expect(localStorage.getItem("oauth_popup_result_tok-2")).toBeNull();
+ });
+
+ test("result arriving during grace window cancels the WINDOW_CLOSED reject", async () => {
+ const popup = makePopupStub();
+ setupPopup(popup);
+
+ const { promise } = openOAuthPopup("https://example.com/oauth", {
+ stateToken: "tok-3",
+ useCrossOriginListeners: true,
+ });
+ const onResolve = vi.fn();
+ const onReject = vi.fn();
+ promise.then(onResolve, onReject);
+
+ // User closes popup before the result lands.
+ popup.closed = true;
+ await vi.advanceTimersByTimeAsync(500); // close-detect fires, grace armed
+
+ // Result lands ~1s into the grace via localStorage (polled every 500ms).
+ localStorage.setItem(
+ "oauth_popup_result_tok-3",
+ JSON.stringify({
+ message_type: "mcp_oauth_result",
+ success: true,
+ code: "late-code",
+ state: "tok-3",
+ }),
+ );
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(onResolve).toHaveBeenCalledWith({
+ code: "late-code",
+ state: "tok-3",
+ });
+
+ // Run out the rest of the grace window — must NOT reject after the fact.
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(onReject).not.toHaveBeenCalled();
+ });
+
+ test("abort during grace window tears down the grace timer", async () => {
+ const popup = makePopupStub();
+ setupPopup(popup);
+
+ const { promise, cleanup } = openOAuthPopup("https://example.com/oauth", {
+ stateToken: "tok-4",
+ useCrossOriginListeners: true,
+ });
+ const onReject = vi.fn();
+ promise.catch(onReject);
+
+ popup.closed = true;
+ await vi.advanceTimersByTimeAsync(500); // grace armed
+
+ // Caller aborts (e.g. component unmount) before grace expires.
+ cleanup.abort();
+ await vi.advanceTimersByTimeAsync(10);
+
+ // Abort wins → CANCELED, not WINDOW_CLOSED.
+ expect(onReject).toHaveBeenCalledTimes(1);
+ expect((onReject.mock.calls[0][0] as Error).message).toBe(
+ OAUTH_ERROR_FLOW_CANCELED,
+ );
+
+ // Advancing past the original grace deadline must not produce a second
+ // reject — the grace setTimeout was cleared by the abort listener.
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(onReject).toHaveBeenCalledTimes(1);
+ });
+
+ test("same-origin flow rejects immediately on popup close (no grace)", async () => {
+ const popup = makePopupStub();
+ setupPopup(popup);
+
+ const { promise } = openOAuthPopup("https://example.com/oauth", {
+ stateToken: "tok-so",
+ useCrossOriginListeners: false, // same-origin → no grace
+ });
+ const onReject = vi.fn();
+ promise.catch(onReject);
+
+ popup.closed = true;
+ // One close-poll tick (500ms) is enough — there's no 3s grace
+ // because synchronous opener.postMessage would have already fired.
+ await vi.advanceTimersByTimeAsync(500);
+
+ expect(onReject).toHaveBeenCalledTimes(1);
+ expect((onReject.mock.calls[0][0] as Error).message).toBe(
+ OAUTH_ERROR_WINDOW_CLOSED,
+ );
+ });
+
+ test("overall timeout rejects with FLOW_TIMED_OUT if popup never closes", async () => {
+ const popup = makePopupStub();
+ setupPopup(popup);
+
+ const { promise } = openOAuthPopup("https://example.com/oauth", {
+ stateToken: "tok-timeout",
+ useCrossOriginListeners: true,
+ timeout: 1000, // tight outer timeout for the test
+ });
+ const onReject = vi.fn();
+ promise.catch(onReject);
+
+ // Popup never closes → close-poll never observes ``closed`` → only
+ // the outer timeout can reject.
+ await vi.advanceTimersByTimeAsync(1100);
+
+ expect(onReject).toHaveBeenCalledTimes(1);
+ expect((onReject.mock.calls[0][0] as Error).message).toMatch(/timed out/i);
+ });
+
+ test("state-mismatch message is ignored and does not resolve the promise", async () => {
+ const popup = makePopupStub();
+ setupPopup(popup);
+
+ const { promise, cleanup } = openOAuthPopup("https://example.com/oauth", {
+ stateToken: "expected-state",
+ useCrossOriginListeners: false,
+ });
+ const onResolve = vi.fn();
+ const onReject = vi.fn();
+ promise.then(onResolve, onReject);
+
+ // Dispatch a postMessage with a different state token — must be ignored.
+ window.dispatchEvent(
+ new MessageEvent("message", {
+ data: {
+ message_type: "oauth_popup_result",
+ success: true,
+ code: "wrong-code",
+ state: "OTHER-state",
+ },
+ }),
+ );
+
+ await vi.advanceTimersByTimeAsync(10);
+ expect(onResolve).not.toHaveBeenCalled();
+ expect(onReject).not.toHaveBeenCalled();
+
+ cleanup.abort();
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/oauth-popup.ts b/autogpt_platform/frontend/src/lib/oauth-popup.ts
index 178ea32f85..9e17f1e3d9 100644
--- a/autogpt_platform/frontend/src/lib/oauth-popup.ts
+++ b/autogpt_platform/frontend/src/lib/oauth-popup.ts
@@ -181,14 +181,93 @@ export function openOAuthPopup(
);
}
- // Detect popup closed by user (without completing sign-in)
- if (popup) {
+ // Detect popup closed without completing sign-in.
+ //
+ // Three timeouts apply to the OAuth flow, only the outermost bounds
+ // user time:
+ // 1. ``timeout`` (default 5 min) — overall deadline; rejects with
+ // OAUTH_ERROR_FLOW_TIMED_OUT if the user never finishes signing
+ // in. This is the only timeout that limits how long the user
+ // has to log in.
+ // 2. 500 ms polling on ``popup.closed`` — only fires after the
+ // popup window actually goes away (user closed it OR callback
+ // page self-closed). Doesn't run while the popup is open.
+ // 3. POPUP_CLOSE_GRACE_MS (3000 ms) — only starts after step 2
+ // observes a closed popup; gives in-flight result messages a
+ // chance to land before we declare failure.
+ //
+ // Why the grace at all? The callback page (see
+ // ``frontend/src/app/(platform)/auth/integrations/mcp_callback/route.ts``)
+ // does:
+ // bc.postMessage(...); localStorage.setItem(...); setTimeout(close, 1500)
+ // BroadcastChannel delivery is async across-origin; the parent's
+ // localStorage poll fires every 500 ms. Without a grace window the
+ // ``popup.closed`` rejection can win the race against a successful
+ // result that's a few hundred ms behind, surfacing the bogus
+ // "Sign-in window was closed" error John screenshotted.
+ //
+ // On detected close we ALSO do one synchronous final localStorage
+ // read — covers the case where the BroadcastChannel listener never
+ // fired (storage-partitioning / BCG isolation) and the poll tick
+ // hasn't run yet. The grace then handles any remaining
+ // post-message latency.
+ //
+ // The setTimeout lives in a plain JS closure, not React state — it
+ // does NOT stack across re-renders, and the AbortController cleanup
+ // tears it down if the caller aborts before grace expires.
+ // Skip the close-poll entirely when the popup was blocked. The
+ // ``window.open("about:blank", ...)`` reference can be non-null but
+ // already-closed in that branch (we fell back to a separate new-tab
+ // ``window.open(loginUrl, "_blank")`` whose handle we deliberately
+ // don't keep — the new tab is the user's primary surface and
+ // pre-emptively rejecting on its ``closed`` state would short-circuit
+ // a successful sign-in arriving via BroadcastChannel/localStorage.
+ if (popup && !popupBlocked) {
+ // Grace window only applies to cross-origin flows. Same-origin
+ // OAuth resolves via ``window.opener.postMessage`` which the
+ // parent receives synchronously on the same event-loop tick the
+ // popup posts it — there's no async delivery race to wait for,
+ // and adding 3 s of fake spinner after a manual close hurts UX.
+ const POPUP_CLOSE_GRACE_MS = useCrossOriginListeners ? 3000 : 0;
+ const finalLocalStorageCheck = () => {
+ if (!useCrossOriginListeners || handled) return;
+ try {
+ const stored = localStorage.getItem(scopedLocalStorageKey);
+ if (stored) {
+ const data = JSON.parse(stored);
+ localStorage.removeItem(scopedLocalStorageKey);
+ handleResult(data);
+ }
+ } catch {}
+ };
+
const closedPollInterval = setInterval(() => {
if (popup.closed && !handled) {
clearInterval(closedPollInterval);
- handled = true;
- reject(new Error(OAUTH_ERROR_WINDOW_CLOSED));
- controller.abort("popup_closed");
+ finalLocalStorageCheck();
+ if (handled) return;
+ if (POPUP_CLOSE_GRACE_MS === 0) {
+ // Same-origin path: the ``window.addEventListener("message", …)``
+ // at line 149 fires synchronously when the popup posts before
+ // closing, so any successful result has already been handled
+ // by the time ``popup.closed`` flips. Reject immediately —
+ // no async-delivery race to wait for.
+ handled = true;
+ reject(new Error(OAUTH_ERROR_WINDOW_CLOSED));
+ controller.abort("popup_closed");
+ return;
+ }
+ const graceTimeout = setTimeout(() => {
+ if (handled) return;
+ finalLocalStorageCheck();
+ if (handled) return;
+ handled = true;
+ reject(new Error(OAUTH_ERROR_WINDOW_CLOSED));
+ controller.abort("popup_closed");
+ }, POPUP_CLOSE_GRACE_MS);
+ controller.signal.addEventListener("abort", () =>
+ clearTimeout(graceTimeout),
+ );
}
}, 500);
controller.signal.addEventListener("abort", () =>
diff --git a/docs/integrations/block-integrations/misc.md b/docs/integrations/block-integrations/misc.md
index 64035959dc..6a7d9f7671 100644
--- a/docs/integrations/block-integrations/misc.md
+++ b/docs/integrations/block-integrations/misc.md
@@ -58,7 +58,7 @@ Tool and block identifiers provided in `tools` and `blocks` are validated at run
| system_context | Optional additional context prepended to the prompt. Use this to constrain autopilot behavior, provide domain context, or set output format requirements. | str | No |
| session_id | Session ID to continue an existing autopilot conversation. Leave empty to start a new session. Use the session_id output from a previous run to continue. | str | No |
| max_recursion_depth | Maximum nesting depth when the autopilot calls this block recursively (sub-agent pattern). Prevents infinite loops. | int | No |
-| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "connect_integration" \| "continue_run_block" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "delete_folder" \| "delete_schedule" \| "delete_workspace_file" \| "edit_agent" \| "find_agent" \| "find_block" \| "find_library_agent" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_mcp_guide" \| "get_platform_info" \| "get_sub_session_result" \| "list_agent_triggers" \| "list_folders" \| "list_schedules" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "move_agents_to_folder" \| "move_folder" \| "read_workspace_file" \| "run_agent" \| "run_block" \| "run_mcp_tool" \| "run_sub_session" \| "search_docs" \| "search_feature_requests" \| "update_folder" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No |
+| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "connect_integration" \| "continue_run_block" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "delete_folder" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "edit_agent" \| "find_agent" \| "find_block" \| "find_library_agent" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_mcp_guide" \| "get_platform_info" \| "get_sub_session_result" \| "list_agent_triggers" \| "list_folders" \| "list_schedules" \| "list_skills" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "move_agents_to_folder" \| "move_folder" \| "read_skill" \| "read_workspace_file" \| "run_agent" \| "run_block" \| "run_mcp_tool" \| "run_sub_session" \| "schedule_followup" \| "search_docs" \| "search_feature_requests" \| "store_skill" \| "update_folder" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No |
| tools_exclude | Controls how the 'tools' list is interpreted. True (default): 'tools' is a deny-list — listed tools are blocked, all others are allowed. An empty 'tools' list means allow everything. False: 'tools' is an allow-list — only listed tools are permitted. | bool | No |
| blocks | Block identifiers to filter when the copilot uses run_block. Each entry can be: a block name (e.g. 'HTTP Request'), a full block UUID, or the first 8 hex characters of the UUID (e.g. 'c069dc6b'). Works with blocks_exclude. Leave empty to apply no block filter. | List[str] | No |
| blocks_exclude | Controls how the 'blocks' list is interpreted. True (default): 'blocks' is a deny-list — listed blocks are blocked, all others are allowed. An empty 'blocks' list means allow everything. False: 'blocks' is an allow-list — only listed blocks are permitted. | bool | No |