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): tell AutoPilot and the user when a stored credential is rejected, not "not connected" (#14390)

Reinier van der Leer4cffe3d20583
diff --git a/autogpt_platform/backend/backend/copilot/prompting.py b/autogpt_platform/backend/backend/copilot/prompting.py
index abf24b9626..b8e81737e6 100644
--- a/autogpt_platform/backend/backend/copilot/prompting.py
+++ b/autogpt_platform/backend/backend/copilot/prompting.py
@@ -361,7 +361,7 @@ modify its fields.
When the user asks to run something that needs credentials (a block, an
agent, an MCP server, or an authenticated web request) and the user may
-not have them yet, three rules apply:
+not have them yet, these rules apply:
**1. Surface the sign-in card EAGERLY — in the same turn, before
collecting other inputs.** Call `connect_integration(provider=...)`
@@ -397,6 +397,11 @@ if you do not have a value, ask the user for it via `ask_question`, then
call the tool with it once they connect. Do not tell the user to fill
anything in on the card.
+**6. `rejection` on a `setup_requirements` response means the provider
+refused a credential the user already has.** Name it only if
+`credential_title` is set; do not re-run until they reconnect or pick a
+different credential.
+
### Grounded claims — CRITICAL
Every factual claim in your reply must be backed by a tool result from this
diff --git a/autogpt_platform/backend/backend/copilot/prompting_test.py b/autogpt_platform/backend/backend/copilot/prompting_test.py
index 65fb76de34..d05b708d84 100644
--- a/autogpt_platform/backend/backend/copilot/prompting_test.py
+++ b/autogpt_platform/backend/backend/copilot/prompting_test.py
@@ -52,6 +52,14 @@ class TestCredentialsSurfacingGuardrails:
assert "NEVER claim a card has appeared" in result
assert "call the tool first" in result
+ def test_prompt_contains_rejection_rule(self):
+ """This section collects rules from several PRs at once, so a merge
+ that takes one side drops a rule silently."""
+ result = prompting.get_sdk_supplement(use_e2b=False)
+ assert "refused a credential the user already has" in result
+ assert "Connecting is not running" in result
+ assert "The card asks for credentials, not inputs" in result
+
class TestToolDiscoveryPriorityAntiPattern:
"""The Tool Discovery Priority section must forbid claiming a capability
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.py
index ec714bfc5a..5f57bfb406 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py
@@ -44,6 +44,7 @@ from backend.util.type import coerce_inputs_to_schema
from .models import (
BlockOutputResponse,
+ CredentialRejection,
ErrorResponse,
InputValidationErrorResponse,
ReviewRequiredResponse,
@@ -54,7 +55,9 @@ from .models import (
)
from .utils import (
build_missing_credentials_from_field_info,
+ credential_rejection_status,
match_credentials_to_requirements,
+ sanitize_provider_message,
)
logger = logging.getLogger(__name__)
@@ -574,6 +577,21 @@ async def execute_block(
)
except BlockError as e:
+ status_code = credential_rejection_status(e)
+ if status_code is not None and matched_credentials:
+ logger.warning(
+ f"Provider rejected a stored credential for block {block.name} "
+ f"with HTTP {status_code}"
+ )
+ return _build_credential_rejected_card(
+ block=block,
+ block_id=block_id,
+ input_data=input_data,
+ matched_credentials=matched_credentials,
+ session_id=session_id,
+ status_code=status_code,
+ exc=e,
+ )
logger.warning("Block execution failed: %s", e)
return ErrorResponse(
message=f"Block execution failed: {e}",
@@ -589,6 +607,67 @@ async def execute_block(
)
+def _build_credential_rejected_card(
+ *,
+ block: AnyBlockSchema,
+ block_id: str,
+ input_data: dict[str, Any],
+ matched_credentials: dict[str, CredentialsMetaInput],
+ session_id: str,
+ status_code: int,
+ exc: BlockError,
+) -> SetupRequirementsResponse:
+ """Setup card for a credential the provider refused mid-execution.
+
+ The rejected row is kept — a 401 is not proof the secret is wrong — so
+ the ``rejection`` field is what stops the card re-offering it as ready.
+ """
+ missing_creds_dict = build_missing_credentials_from_field_info(
+ _resolve_discriminated_credentials(block, input_data), matched_keys=set()
+ )
+ rejected = (
+ next(iter(matched_credentials.values()))
+ if len(matched_credentials) == 1
+ else None
+ )
+ provider = (
+ # ProviderName is a str-Enum: str() would render "ProviderName.X".
+ str(getattr(rejected.provider, "value", rejected.provider))
+ if rejected
+ else get_block_provider(block) or ""
+ )
+ provider_name = provider.replace("_", " ").title() or "The provider"
+ named = f" '{rejected.title}'" if rejected and rejected.title else ""
+ return SetupRequirementsResponse(
+ message=(
+ f"{provider_name} rejected the saved credential{named} "
+ f"(HTTP {status_code}). Connect or pick a different one, then re-run."
+ ),
+ session_id=session_id,
+ setup_info=SetupInfo(
+ agent_id=block_id,
+ agent_name=block.name,
+ user_readiness=UserReadiness(
+ has_all_credentials=False,
+ missing_credentials=missing_creds_dict,
+ ready_to_run=False,
+ ),
+ requirements={
+ "credentials": list(missing_creds_dict.values()),
+ "inputs": [],
+ "execution_modes": ["immediate"],
+ },
+ ),
+ rejection=CredentialRejection(
+ provider=provider or "unknown",
+ detail=sanitize_provider_message(str(exc)),
+ status_code=status_code,
+ credential_id=rejected.id if rejected else None,
+ credential_title=rejected.title if rejected else None,
+ ),
+ )
+
+
async def _collect_block_outputs(
block: AnyBlockSchema,
input_data: dict[str, Any],
diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.py
index 3812b8f6ab..d34a892c44 100644
--- a/autogpt_platform/backend/backend/copilot/tools/models.py
+++ b/autogpt_platform/backend/backend/copilot/tools/models.py
@@ -290,6 +290,16 @@ class SetupInfo(BaseModel):
user_readiness: UserReadiness = Field(default_factory=UserReadiness)
+class CredentialRejection(BaseModel):
+ """A stored credential that the provider refused at use time."""
+
+ provider: str
+ detail: str = Field(description="Sanitised reason; never carries a secret.")
+ status_code: int | None = None
+ credential_id: str | None = None
+ credential_title: str | None = None
+
+
class SetupRequirementsResponse(ToolResponseBase):
"""Response for validate action."""
@@ -297,6 +307,9 @@ class SetupRequirementsResponse(ToolResponseBase):
setup_info: SetupInfo
graph_id: str | None = None
graph_version: int | None = None
+ # Set only when a credential we had was rejected; its absence is what
+ # "never connected" looks like, so the two cases stay distinguishable.
+ rejection: CredentialRejection | None = None
# Execution models
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
index 837e272766..e5773b9833 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
@@ -1359,6 +1359,123 @@ class TestExecuteBlockUserTimezoneAccessor:
assert ctx.user_timezone == "America/New_York" # type: ignore[attr-defined]
+class TestExecuteBlockCredentialRejection:
+ """A provider that refuses a stored credential mid-run must produce the
+ reconnect card, not a bare "Block execution failed"."""
+
+ @staticmethod
+ def _block(exc: Exception):
+ from backend.data.model import CredentialsFieldInfo
+
+ block = MagicMock()
+ block.name = "AyrsharePostBlock"
+ block.id = "ayrshare-block-id"
+ block.input_schema = MagicMock()
+ block.input_schema.jsonschema.return_value = {"properties": {}, "required": []}
+ block.input_schema.get_credentials_fields.return_value = {"credentials": object}
+ block.input_schema.get_credentials_fields_info.return_value = {
+ "credentials": CredentialsFieldInfo.model_validate(
+ {
+ "credentials_provider": ["ayrshare"],
+ "credentials_types": ["api_key"],
+ "is_auto_credential": False,
+ },
+ by_alias=True,
+ )
+ }
+ block.input_schema.get_required_fields.return_value = {"credentials"}
+
+ async def _fail(_input, **_kwargs):
+ raise exc
+ yield # pragma: no cover -- keeps this an async generator
+
+ block.execute = _fail
+ return block
+
+ @staticmethod
+ async def _run(exc: Exception):
+ from backend.copilot.tools.helpers import execute_block
+ from backend.data.model import CredentialsMetaInput
+
+ cred_meta = CredentialsMetaInput(
+ id="cred-1",
+ title="Work Ayrshare key",
+ provider="ayrshare", # type: ignore[arg-type]
+ type="api_key",
+ )
+ stored = MagicMock()
+ stored.provider = "ayrshare"
+ stored.type = "api_key"
+
+ creds_manager = MagicMock()
+ creds_manager.get = AsyncMock(return_value=stored)
+
+ workspace = MagicMock()
+ workspace.get_or_create_workspace = AsyncMock(return_value=MagicMock(id="ws-1"))
+
+ with (
+ patch("backend.copilot.tools.helpers.workspace_db", return_value=workspace),
+ patch(
+ "backend.copilot.tools.helpers.IntegrationCredentialsManager",
+ return_value=creds_manager,
+ ),
+ patch(
+ "backend.copilot.tools.helpers.acquire_auto_credentials",
+ new_callable=AsyncMock,
+ return_value=({}, []),
+ ),
+ patch(
+ "backend.copilot.tools.helpers.block_usage_cost", return_value=(0, {})
+ ),
+ ):
+ return await execute_block(
+ block=TestExecuteBlockCredentialRejection._block(exc),
+ block_id="ayrshare-block-id",
+ input_data={},
+ user_id="u-1",
+ session_id="s-1",
+ node_exec_id="n-1",
+ matched_credentials={"credentials": cred_meta},
+ dry_run=False,
+ )
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_provider_401_returns_a_card_naming_the_credential(self):
+ from backend.util.exceptions import BlockUnknownError
+ from backend.util.request import HTTPClientError
+
+ from .models import SetupRequirementsResponse
+
+ try:
+ raise HTTPClientError("HTTP 401 Error: token=sk-live-abc", 401)
+ except HTTPClientError as inner:
+ wrapped = BlockUnknownError("failed", "AyrsharePostBlock", "block-id")
+ wrapped.__cause__ = inner
+
+ response = await self._run(wrapped)
+
+ assert isinstance(response, SetupRequirementsResponse)
+ assert response.rejection is not None
+ assert response.rejection.provider == "ayrshare"
+ assert response.rejection.status_code == 401
+ assert response.rejection.credential_id == "cred-1"
+ assert "sk-live-abc" not in response.rejection.detail
+ assert "Work Ayrshare key" in response.message
+ # The picker must be offered again, or there is no way back.
+ assert "credentials" in response.setup_info.user_readiness.missing_credentials
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_non_auth_block_failure_still_returns_an_error(self):
+ from backend.util.exceptions import BlockExecutionError
+
+ response = await self._run(
+ BlockExecutionError("bad input", "AyrsharePostBlock", "block-id")
+ )
+
+ assert isinstance(response, ErrorResponse)
+ assert "Block execution failed" in response.message
+
+
class TestExecuteBlockExpertAttribution:
"""A block run from an expert chat must carry the expert on its execution
context, so ``workspace://`` inputs resolve inside that expert's scope."""
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 88931bb5ec..1ffbfc6fe4 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
@@ -21,7 +21,12 @@ from backend.copilot.sdk.file_ref import (
FileRefExpansionError,
expand_file_refs_in_args,
)
-from backend.copilot.tools.utils import build_missing_credentials_from_field_info
+from backend.copilot.tools.utils import (
+ build_missing_credentials_from_field_info,
+ sanitize_provider_message,
+)
+from backend.data.model import OAuth2Credentials
+from backend.integrations.providers import ProviderName
from backend.util.request import (
AUTH_STATUS_CODES,
CREDENTIAL_REJECTED_STATUS_CODES,
@@ -31,6 +36,7 @@ from backend.util.request import (
from .base import BaseTool
from .models import (
+ CredentialRejection,
ErrorResponse,
MCPToolInfo,
MCPToolOutputResponse,
@@ -243,6 +249,7 @@ class RunMCPToolTool(BaseTool):
# real tool call will self-correct via the same invalidate path.
if surface_connect_card:
connected = creds is not None
+ rejection: CredentialRejection | None = None
if client is not None and creds is not None:
probe_client = client
try:
@@ -255,6 +262,7 @@ class RunMCPToolTool(BaseTool):
probe_err.status_code
in CREDENTIAL_REJECTED_STATUS_CODES
):
+ rejection = _rejection(creds, probe_err)
await invalidate_mcp_credential(user_id, creds.id)
# Other HTTP statuses (5xx, redirects, etc.) →
# leave the cred in place and report
@@ -286,7 +294,7 @@ class RunMCPToolTool(BaseTool):
# errors.
await probe_client.close()
return self._build_setup_requirements(
- server_url, session_id, connected=connected
+ server_url, session_id, connected=connected, rejection=rejection
)
if client is None:
@@ -314,6 +322,11 @@ class RunMCPToolTool(BaseTool):
if e.status_code in AUTH_STATUS_CODES:
credential_rejected = e.status_code in CREDENTIAL_REJECTED_STATUS_CODES
# Fire the setup card whether or not a credential row exists.
+ rejected = (
+ _rejection(creds, e)
+ if creds is not None and credential_rejected
+ else None
+ )
if creds is not None and credential_rejected:
await invalidate_mcp_credential(user_id, creds.id)
# A 403 over a credential we deliberately kept means "this
@@ -327,6 +340,7 @@ class RunMCPToolTool(BaseTool):
server_url,
session_id,
connected=creds is not None and not credential_rejected,
+ rejection=rejected,
)
host = server_host(server_url)
logger.warning("MCP HTTP error for %s: status=%s", host, e.status_code)
@@ -539,6 +553,7 @@ class RunMCPToolTool(BaseTool):
server_url: str,
session_id: str,
connected: bool = False,
+ rejection: CredentialRejection | None = None,
) -> SetupRequirementsResponse | ErrorResponse:
"""Build a SetupRequirementsResponse for an MCP server credential.
@@ -579,11 +594,16 @@ 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."
- )
+ if rejection:
+ status = f" (HTTP {rejection.status_code})" if rejection.status_code else ""
+ message = (
+ f"{service} rejected the saved credential{status}. "
+ "Sign in again to continue."
+ )
+ elif connected:
+ message = f"You're connected to {service}. Use Reconnect to swap accounts."
+ else:
+ message = f"To continue, sign in to {service} and approve access."
return SetupRequirementsResponse(
message=message,
session_id=session_id,
@@ -606,9 +626,20 @@ class RunMCPToolTool(BaseTool):
),
graph_id=None,
graph_version=None,
+ rejection=rejection,
)
+def _rejection(creds: OAuth2Credentials, error: HTTPClientError) -> CredentialRejection:
+ return CredentialRejection(
+ provider=ProviderName.MCP.value,
+ detail=sanitize_provider_message(str(error)),
+ status_code=error.status_code,
+ credential_id=creds.id,
+ credential_title=creds.title,
+ )
+
+
def _summarize_params(schema: dict | None) -> str | None:
"""Compact one-line argument summary for a tool's input schema.
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 ed7c33d007..29c48ce870 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
@@ -747,6 +747,7 @@ async def test_surface_connect_card_stale_creds_invalidated_returns_not_connecte
mock_creds = MagicMock()
mock_creds.access_token = SecretStr("stale-token")
mock_creds.id = "stale-cred-id"
+ mock_creds.title = "Stale token"
with patch(
"backend.copilot.tools.run_mcp_tool.validate_url_host", new_callable=AsyncMock
@@ -949,6 +950,7 @@ async def test_auth_error_with_stale_creds_fires_setup_and_invalidates(
mock_creds = MagicMock()
mock_creds.access_token = SecretStr("stale-token")
mock_creds.id = "stale-cred-id"
+ mock_creds.title = "Stale token"
with patch(
"backend.copilot.tools.run_mcp_tool.validate_url_host", new_callable=AsyncMock
@@ -1373,3 +1375,90 @@ async def test_lookup_tool_schema_returns_none_on_any_failure():
schema = await tool._lookup_tool_schema(mock_client, "notion-update-page")
assert schema is None
+
+
+# ---------------------------------------------------------------------------
+# Rejected credentials (T123.2)
+# ---------------------------------------------------------------------------
+
+
+async def _run_with_auth_failure(creds: Any, session: Any) -> SetupRequirementsResponse:
+ """Drive ``_execute`` into the 401 path with *creds* on file (or ``None``)."""
+ from backend.util.request import HTTPClientError
+
+ tool = RunMCPToolTool()
+
+ with (
+ patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url_host",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ new_callable=AsyncMock,
+ return_value=creds,
+ ),
+ patch(
+ "backend.copilot.tools.run_mcp_tool.invalidate_mcp_credential",
+ new_callable=AsyncMock,
+ ),
+ ):
+ mock_client = AsyncMock()
+ mock_client.initialize = AsyncMock(
+ side_effect=HTTPClientError(
+ "HTTP 401 Error: Unauthorized, Body: token=sk-live-abc", 401
+ )
+ )
+ 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, SetupRequirementsResponse)
+ return response
+
+
+def _rejected_creds() -> MagicMock:
+ creds = MagicMock()
+ creds.access_token = SecretStr("stale-token")
+ creds.id = "stale-cred-id"
+ creds.title = "My Sentry token"
+ return creds
+
+
[email protected](loop_scope="session")
+async def test_rejected_token_card_names_the_credential_and_the_status():
+ rejected = await _run_with_auth_failure(_rejected_creds(), make_session(_USER_ID))
+
+ assert rejected.rejection is not None
+ assert rejected.rejection.provider == "mcp"
+ assert rejected.rejection.status_code == 401
+ assert rejected.rejection.credential_id == "stale-cred-id"
+ assert rejected.rejection.credential_title == "My Sentry token"
+ assert "sk-live-abc" not in rejected.rejection.detail
+ assert "rejected the saved credential (HTTP 401)" in rejected.message
+
+
[email protected](loop_scope="session")
+async def test_rejected_card_differs_from_never_connected_by_the_rejection():
+ """The whole point: the two states must not be byte-identical any more.
+
+ Everything else about the payload is deliberately unchanged, so the model
+ and the card can tell "wrong credential" from "no credential" and nothing
+ downstream has to learn a new shape.
+ """
+ session = make_session(_USER_ID)
+ rejected = await _run_with_auth_failure(_rejected_creds(), session)
+ never_connected = await _run_with_auth_failure(None, session)
+
+ assert rejected.rejection is not None
+ assert never_connected.rejection is None
+ assert "sign in" in never_connected.message.lower()
+
+ ignored = {"rejection", "message"}
+ assert {k: v for k, v in rejected.model_dump().items() if k not in ignored} == {
+ k: v for k, v in never_connected.model_dump().items() if k not in ignored
+ }
diff --git a/autogpt_platform/backend/backend/copilot/tools/utils.py b/autogpt_platform/backend/backend/copilot/tools/utils.py
index 6021ced003..bbbc1f183e 100644
--- a/autogpt_platform/backend/backend/copilot/tools/utils.py
+++ b/autogpt_platform/backend/backend/copilot/tools/utils.py
@@ -17,6 +17,7 @@ from backend.data.model import (
from backend.integrations.creds_manager import IntegrationCredentialsManager
from backend.integrations.providers import ProviderName
from backend.util.exceptions import NotFoundError
+from backend.util.request import CREDENTIAL_REJECTED_STATUS_CODES
logger = logging.getLogger(__name__)
@@ -561,3 +562,64 @@ async def check_user_has_required_credentials(
missing.append(required)
return missing
+
+
+def credential_rejection_status(exc: BaseException) -> int | None:
+ """Rejection status from *exc* or anything it was raised from, else ``None``.
+
+ Blocks bubble the provider's failure through ``BlockError`` with the
+ original exception on ``__cause__``, so the status only survives one
+ level down.
+ """
+ seen: set[int] = set()
+ current: BaseException | None = exc
+ while current is not None and id(current) not in seen:
+ seen.add(id(current))
+ status = _status_code_of(current)
+ if status in CREDENTIAL_REJECTED_STATUS_CODES:
+ return status
+ current = current.__cause__ or current.__context__
+ return None
+
+
+def sanitize_provider_message(message: str, max_chars: int = 200) -> str:
+ """Bounded one-line copy of a provider error, with secrets removed.
+
+ The input is an upstream body we do not control and may quote the request
+ it rejected, so anything that can carry a token is dropped before the text
+ reaches the chat.
+ """
+ text = " ".join(str(message).split())
+ text = _BEARER_TOKEN_RE.sub("[redacted]", text)
+ text = _URL_QUERY_RE.sub(r"\1", text)
+ text = _AUTH_HEADER_RE.sub("[redacted]", text)
+ text = _SECRET_PARAM_RE.sub("[redacted]", text)
+ if len(text) > max_chars:
+ text = text[:max_chars].rstrip() + "…"
+ return text
+
+
+def _status_code_of(exc: BaseException) -> int | None:
+ for value in (
+ getattr(exc, "status_code", None), # HTTPClientError, openai, httpx wrappers
+ getattr(exc, "status", None), # aiohttp.ClientResponseError
+ getattr(getattr(exc, "response", None), "status_code", None), # requests
+ ):
+ if isinstance(value, int):
+ return value
+ return None
+
+
+_BEARER_TOKEN_RE = re.compile(r"(?i)\bbearer\s+\S+")
+_URL_QUERY_RE = re.compile(r"(https?://[^\s\"'?]+)\?\S*")
+# An Authorization value is a scheme plus its token, so a bare \S+ would eat
+# only the scheme and leave the credential sitting behind "[redacted]".
+_AUTH_HEADER_RE = re.compile(
+ r"(?i)['\"]?\bauthorization\b['\"]?\s*[=:]\s*['\"]?(?:\w[\w-]*\s+)?\S+"
+)
+# Optional quotes around the key and value cover the JSON and dict shapes a
+# provider echoes back; without them the quote before the colon defeats the match.
+_SECRET_PARAM_RE = re.compile(
+ r"(?i)['\"]?\b(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token"
+ r"|secret|password)\b['\"]?\s*[=:]\s*(?:\"[^\"]*\"|'[^']*'|\S+)"
+)
diff --git a/autogpt_platform/backend/backend/copilot/tools/utils_test.py b/autogpt_platform/backend/backend/copilot/tools/utils_test.py
index 971b3da973..b49bb71234 100644
--- a/autogpt_platform/backend/backend/copilot/tools/utils_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/utils_test.py
@@ -74,3 +74,99 @@ async def test_match_user_credentials_excludes_auto_creds():
assert len(matched) == 0
assert len(missing) == 1
assert "github_api_key" in missing[0]
+
+
+_SECRET = "sk-live-SHOULD-NOT-APPEAR"
+
+
+ "raw, expected",
+ [
+ (
+ "GET https://api.example.com/me?api_key=sk-live-abc failed",
+ "GET https://api.example.com/me failed",
+ ),
+ ("Authorization: Bearer sk-live-abc rejected", "[redacted] rejected"),
+ ("bad token=sk-live-abc", "bad [redacted]"),
+ ("password: hunter2", "[redacted]"),
+ ("HTTP 401 Error:\n Unauthorized", "HTTP 401 Error: Unauthorized"),
+ # The rejection reason is the point of the card, so prose that merely
+ # mentions a secret-ish word must survive intact.
+ ("Invalid API key provided.", "Invalid API key provided."),
+ ("The token has expired; reconnect.", "The token has expired; reconnect."),
+ ("Your basic plan does not allow this", "Your basic plan does not allow this"),
+ ],
+)
+def test_sanitize_provider_message_drops_secrets(raw: str, expected: str):
+ from backend.copilot.tools.utils import sanitize_provider_message
+
+ assert sanitize_provider_message(raw) == expected
+
+
+ "raw",
+ [
+ f"api_key={_SECRET}",
+ f'{{"api_key": "{_SECRET}"}}',
+ f'{{"api_key":"{_SECRET}"}}',
+ f'{{"access_token": "{_SECRET}"}}',
+ f"{{'refresh_token': '{_SECRET}'}}",
+ f'headers={{"X-Api-Key": "{_SECRET}"}}',
+ f"Authorization: Bearer {_SECRET}",
+ f"Authorization: Basic {_SECRET}",
+ f"Authorization: Token {_SECRET}",
+ f'{{"authorization": "Bearer {_SECRET}"}}',
+ ],
+)
+def test_sanitize_provider_message_leaves_no_secret(raw: str):
+ """Asserts on the secret, not on "[redacted]" — the Authorization shapes
+ substituted the scheme and left the token standing next to the marker."""
+ from backend.copilot.tools.utils import sanitize_provider_message
+
+ assert _SECRET not in sanitize_provider_message(raw)
+
+
+def test_sanitize_provider_message_is_bounded():
+ from backend.copilot.tools.utils import sanitize_provider_message
+
+ out = sanitize_provider_message("x" * 500, max_chars=50)
+ assert out == "x" * 50 + "…"
+
+
+def test_credential_rejection_status_reads_through_the_cause_chain():
+ """Blocks wrap the provider's error, so only ``__cause__`` still has it."""
+ from backend.copilot.tools.utils import credential_rejection_status
+ from backend.util.exceptions import BlockUnknownError
+ from backend.util.request import HTTPClientError
+
+ try:
+ try:
+ raise HTTPClientError("Unauthorized", 401)
+ except HTTPClientError as inner:
+ raise BlockUnknownError("failed", "Block", "block-id") from inner
+ except BlockUnknownError as wrapped:
+ assert credential_rejection_status(wrapped) == 401
+
+
+ "exc, expected",
+ [
+ (type("Aiohttp", (Exception,), {"status": 401})(), 401),
+ # A 403 is a scope decision or a WAF, not a rejected credential.
+ (type("Forbidden", (Exception,), {"status_code": 403})(), None),
+ (
+ type(
+ "Requests",
+ (Exception,),
+ {"response": type("R", (), {"status_code": 401})()},
+ )(),
+ 401,
+ ),
+ (type("ServerErr", (Exception,), {"status_code": 500})(), None),
+ (ValueError("no status anywhere"), None),
+ ],
+)
+def test_credential_rejection_status_only_matches_rejections(exc, expected):
+ from backend.copilot.tools.utils import credential_rejection_status
+
+ assert credential_rejection_status(exc) == expected
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CredentialRejectionNotice/CredentialRejectionNotice.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CredentialRejectionNotice/CredentialRejectionNotice.tsx
new file mode 100644
index 0000000000..21ac069146
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CredentialRejectionNotice/CredentialRejectionNotice.tsx
@@ -0,0 +1,20 @@
+import type { CredentialRejection } from "@/app/api/__generated__/models/credentialRejection";
+
+interface Props {
+ rejection: CredentialRejection;
+}
+
+export function CredentialRejectionNotice({ rejection }: Props) {
+ return (
+ <div
+ role="alert"
+ className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700"
+ >
+ {rejection.credential_title
+ ? `"${rejection.credential_title}" was refused`
+ : "The saved credential was refused"}
+ {rejection.status_code ? ` — HTTP ${rejection.status_code}` : ""}
+ <p className="mt-1 break-words opacity-80">{rejection.detail}</p>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx
index e71bc2302d..2c7d55bc3f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx
@@ -32,8 +32,10 @@ import {
coerceExpectedInputs,
extractInitialValues,
getRequestedProviders,
+ isRejectedCredentialSelected,
mergeInputValues,
} from "./helpers";
+import { CredentialRejectionNotice } from "../CredentialRejectionNotice/CredentialRejectionNotice";
/**
* Single credential/setup card rendered inline in copilot chats.
@@ -81,6 +83,8 @@ export function SetupRequirementsCard({
output.setup_info.user_readiness?.missing_credentials,
);
+ const rejection = output.rejection ?? null;
+
const expectedInputs = coerceExpectedInputs(
(output.setup_info.requirements as Record<string, unknown>)?.inputs,
);
@@ -154,11 +158,15 @@ export function SetupRequirementsCard({
// inputs reports ready on the first typed character, so sending on readiness
// would fire mid-word with a half-typed value.
const needsManualPick = isTriggerMode;
+ // A rejection must never self-dismiss: the provider refused a credential the
+ // session store still counts as connected, so dismissing would re-send the
+ // "I've configured the credentials" turn into the same failure, forever.
const canAutoDismiss =
needsCredentials &&
alreadyConnected &&
!hasUserActionableInputs &&
- !needsManualPick;
+ !needsManualPick &&
+ !rejection;
// Inside a chain this card renders no Proceed of its own — the chain only
// renders one for inputs/questions — so a completed sign-in is the sole "go"
// signal; without this the chain stalls after the user connects. It must be
@@ -194,11 +202,9 @@ export function SetupRequirementsCard({
// eslint-disable-next-line react-hooks/exhaustive-deps -- handleRun captures latest state; claim guards re-entry
}, [chainActions, canAutoDismiss, hasSent]);
- const canRun = checkCanRun(
- needsCredentials,
- isAllCredsComplete,
- isAllInputsDone,
- );
+ const canRun =
+ checkCanRun(needsCredentials, isAllCredsComplete, isAllInputsDone) &&
+ !isRejectedCredentialSelected(rejection, inputCredentials);
// Inside a tool chain the card's own Proceed is replaced by the chain's
// single Proceed step — register readiness + message with the chain.
@@ -290,6 +296,8 @@ export function SetupRequirementsCard({
<div className="grid gap-2">
<ContentMessage>{output.message}</ContentMessage>
+ {rejection && <CredentialRejectionNotice rejection={rejection} />}
+
{/* Inside a chain the connectors are lifted out and rendered as a card
below it; standalone the card keeps the full credentials picker. */}
{needsCredentials && !chainActions && (
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/SetupRequirementsCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/SetupRequirementsCard.test.tsx
index 2b601217e3..998a221daf 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/SetupRequirementsCard.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/SetupRequirementsCard.test.tsx
@@ -9,6 +9,7 @@ import { StrictMode } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { SetupRequirementsCard } from "../SetupRequirementsCard";
import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";
+import type { CredentialRejection } from "@/app/api/__generated__/models/credentialRejection";
import { useConnectedProvidersStore } from "../../../connectedProvidersStore";
const mockOnSend = vi.fn();
@@ -74,12 +75,14 @@ function makeOutput(
message?: string;
missingCredentials?: Record<string, unknown>;
inputs?: unknown[];
+ rejection?: CredentialRejection;
} = {},
): SetupRequirementsResponse {
const {
message = "Please configure credentials",
missingCredentials,
inputs,
+ rejection,
} = overrides;
return {
type: "setup_requirements",
@@ -101,6 +104,7 @@ function makeOutput(
},
graph_id: null,
graph_version: null,
+ rejection: rejection ?? null,
} as SetupRequirementsResponse;
}
@@ -653,3 +657,75 @@ describe("SetupRequirementsCard (trigger mode)", () => {
);
});
});
+
+describe("SetupRequirementsCard (rejected credential)", () => {
+ const rejection: CredentialRejection = {
+ provider: "openai",
+ detail: "HTTP 401 Error: invalid_api_key",
+ status_code: 401,
+ credential_id: "cred-api_key",
+ credential_title: "Work key",
+ };
+
+ function renderRejected(overrides: Partial<CredentialRejection> = {}) {
+ render(
+ <SetupRequirementsCard
+ output={makeOutput({
+ missingCredentials: {
+ api_key: { provider: "openai", types: ["api_key"] },
+ },
+ rejection: { ...rejection, ...overrides },
+ })}
+ />,
+ );
+ }
+
+ it("shows the provider's reason and the status code", () => {
+ renderRejected();
+
+ expect(screen.getByRole("alert").textContent).toContain(
+ "HTTP 401 Error: invalid_api_key",
+ );
+ expect(screen.getByRole("alert").textContent).toContain("Work key");
+ });
+
+ it("never auto-dismisses, even when the provider is already connected here", async () => {
+ useConnectedProvidersStore
+ .getState()
+ .markConnected({ sessionID: "sess-1", providers: ["openai"] });
+
+ renderRejected();
+
+ expect(screen.queryByText(/Connected. Continuing/)).toBeNull();
+ expect(screen.getByText("Proceed")).toBeDefined();
+ await waitFor(() => expect(mockOnSend).not.toHaveBeenCalled());
+ });
+
+ it("keeps Proceed disabled while the refused credential is the selected one", () => {
+ renderRejected();
+
+ fireEvent.click(screen.getByTestId("select-credential"));
+ expect(screen.getByText("Proceed").closest("button")?.disabled).toBe(true);
+ });
+
+ it("enables Proceed once a different credential is selected", () => {
+ renderRejected({ credential_id: "cred-that-was-replaced" });
+
+ fireEvent.click(screen.getByTestId("select-credential"));
+ expect(screen.getByText("Proceed").closest("button")?.disabled).toBe(false);
+ });
+
+ it("renders no rejection notice when the field is absent", () => {
+ render(
+ <SetupRequirementsCard
+ output={makeOutput({
+ missingCredentials: {
+ api_key: { provider: "openai", types: ["api_key"] },
+ },
+ })}
+ />,
+ );
+
+ expect(screen.queryByRole("alert")).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts
index 928e204e03..bc0a353a8d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts
@@ -1,4 +1,5 @@
import type { CredentialField } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/helpers";
+import type { CredentialRejection } from "@/app/api/__generated__/models/credentialRejection";
import type { RJSFSchema } from "@rjsf/utils";
const VALID_CREDENTIAL_TYPES = new Set([
@@ -300,6 +301,23 @@ export function checkAllInputsComplete(
});
}
+/**
+ * True while a credential the provider just refused is still the one selected.
+ *
+ * The row is kept on file, so the picker re-selects it on mount; without this
+ * the card would report ready and the chat would re-run into the same 401.
+ */
+export function isRejectedCredentialSelected(
+ rejection: CredentialRejection | null | undefined,
+ inputCredentials: Record<string, { id?: string } | undefined>,
+): boolean {
+ const rejectedId = rejection?.credential_id;
+ if (!rejectedId) return false;
+ return Object.values(inputCredentials).some(
+ (credential) => credential?.id === rejectedId,
+ );
+}
+
export function checkCanRun(
needsCredentials: boolean,
isAllCredentialsComplete: boolean,
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 3270fc878b..aa6b7f0d4a 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
@@ -31,6 +31,7 @@ import { useContext, useEffect, useId, useRef, useState } from "react";
import { useCopilotChatActions } from "../../../../components/CopilotChatActionsProvider/useCopilotChatActions";
import { ContentMessage } from "../../../../components/ToolAccordion/AccordionContent";
import { ChainActionsContext } from "../../../../components/ToolChain/chainActions";
+import { CredentialRejectionNotice } from "../../../../components/CredentialRejectionNotice/CredentialRejectionNotice";
interface Props {
output: SetupRequirementsResponse;
@@ -62,6 +63,7 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {
const serverUrl = output.setup_info.agent_id;
// agent_name is computed by the backend as the display name for the service
const service = output.setup_info.agent_name;
+ const rejection = output.rejection ?? null;
// Initial connection state comes from the backend. When the model
// calls `run_mcp_tool` with `surface_connect_card=true`, the response's
@@ -156,7 +158,10 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {
// back to the persisted ``initiallyConnected`` snapshot rather
// than defaulting to disconnected.
const liveSays = liveHasCred === "unknown" ? initiallyConnected : liveHasCred;
- const connected = !forceDisconnected && (localConnected || liveSays);
+ // A rejected credential never counts as connected, whatever a stale cred
+ // list says — only a sign-in completed in this card does.
+ const connected =
+ !forceDisconnected && (localConnected || (!rejection && 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;
@@ -434,6 +439,8 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {
<div className="mt-2 grid gap-2">
<ContentMessage>{output.message}</ContentMessage>
+ {rejection && <CredentialRejectionNotice rejection={rejection} />}
+
<div className="rounded-2xl border bg-background p-4">
<Button
variant="primary"
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 f698cf2d55..4045b24bcc 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
@@ -733,6 +733,56 @@ describe("MCPSetupCard", () => {
});
});
+ it("shows why a stored token was refused instead of the never-connected card", () => {
+ render(
+ <MCPSetupCard
+ output={{
+ ...makeSetupOutput(),
+ message: "example.com rejected the saved credential (HTTP 401).",
+ rejection: {
+ provider: "mcp",
+ detail: "HTTP 401 Error: Unauthorized",
+ status_code: 401,
+ credential_id: "cred-1",
+ credential_title: "Sentry token",
+ },
+ }}
+ />,
+ );
+
+ expect(screen.getByRole("alert").textContent).toContain(
+ "HTTP 401 Error: Unauthorized",
+ );
+ expect(
+ screen.getByRole("button", { name: /connect example\.com/i }),
+ ).toBeDefined();
+ });
+
+ it("keeps the Connect affordance when a stale cred list still lists the refused token", () => {
+ setMockLiveCreds([
+ { provider: "mcp", host: "https://mcp.example.com/mcp" },
+ ]);
+ render(
+ <MCPSetupCard
+ output={{
+ ...makeSetupOutput(),
+ rejection: {
+ provider: "mcp",
+ detail: "HTTP 401 Error: Unauthorized",
+ status_code: 401,
+ credential_id: "cred-1",
+ credential_title: null,
+ },
+ }}
+ />,
+ );
+
+ expect(screen.queryByText(/connected to example\.com/i)).toBeNull();
+ expect(
+ screen.getByRole("button", { name: /connect example\.com/i }),
+ ).toBeDefined();
+ });
+
it("does not report Connected for a credential the server rejects", async () => {
// A 2xx from ``/mcp/token`` only says the row was written. Without a probe
// the card claims Connected, the very next copilot call 401s, and the card,
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 42a9bcc8e8..6a03e2f206 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -18805,6 +18805,32 @@
"required": ["creators", "pagination"],
"title": "CreatorsResponse"
},
+ "CredentialRejection": {
+ "properties": {
+ "provider": { "type": "string", "title": "Provider" },
+ "detail": {
+ "type": "string",
+ "title": "Detail",
+ "description": "Sanitised reason; never carries a secret."
+ },
+ "status_code": {
+ "anyOf": [{ "type": "integer" }, { "type": "null" }],
+ "title": "Status Code"
+ },
+ "credential_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Credential Id"
+ },
+ "credential_title": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Credential Title"
+ }
+ },
+ "type": "object",
+ "required": ["provider", "detail"],
+ "title": "CredentialRejection",
+ "description": "A stored credential that the provider refused at use time."
+ },
"CredentialsDeletionNeedsConfirmationResponse": {
"properties": {
"deleted": {
@@ -26760,6 +26786,12 @@
"graph_version": {
"anyOf": [{ "type": "integer" }, { "type": "null" }],
"title": "Graph Version"
+ },
+ "rejection": {
+ "anyOf": [
+ { "$ref": "#/components/schemas/CredentialRejection" },
+ { "type": "null" }
+ ]
}
},
"type": "object",