Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(mcp): stop returning opaque 500s from MCP connect/auth (#42177)

Charles Yao96c8cc43838a
diff --git a/api/core/mcp/auth/auth_flow.py b/api/core/mcp/auth/auth_flow.py
index 1d8356acf67..9f18bd3e7ad 100644
--- a/api/core/mcp/auth/auth_flow.py
+++ b/api/core/mcp/auth/auth_flow.py
@@ -531,7 +531,9 @@ def register_client(
headers={"Content-Type": "application/json"},
)
if not response.is_success:
- response.raise_for_status()
+ # Callers only translate RequestError/ValueError into a user-facing error,
+ # so a raise_for_status() here would escape as an opaque 500.
+ raise ValueError(f"Client registration failed: HTTP {response.status_code}, Response: {response.text}")
return OAuthClientInformationFull.model_validate(response.json())
diff --git a/api/core/mcp/client/sse_client.py b/api/core/mcp/client/sse_client.py
index 28ecf290c32..533ff256558 100644
--- a/api/core/mcp/client/sse_client.py
+++ b/api/core/mcp/client/sse_client.py
@@ -297,6 +297,13 @@ def sse_client(
if exc.response.status_code == 401:
raise MCPAuthError(response=exc.response)
raise MCPConnectionError()
+ except httpx.RequestError as exc:
+ # Transport-level failures (refused connection, DNS, protocol errors, timeouts)
+ # must keep the MCP error contract: MCPClient only falls back to streamable
+ # HTTP on MCPConnectionError, and the console API only turns MCP errors into
+ # a 4xx. A raw httpx error skips both and surfaces as an opaque 500.
+ logger.exception("Error connecting to SSE endpoint")
+ raise MCPConnectionError(f"Failed to connect to SSE endpoint: {exc}") from exc
except Exception:
logger.exception("Error connecting to SSE endpoint")
raise
diff --git a/api/tests/unit_tests/core/mcp/auth/test_auth_flow.py b/api/tests/unit_tests/core/mcp/auth/test_auth_flow.py
index 1f5fdd2657f..32a48500fe9 100644
--- a/api/tests/unit_tests/core/mcp/auth/test_auth_flow.py
+++ b/api/tests/unit_tests/core/mcp/auth/test_auth_flow.py
@@ -500,6 +500,38 @@ class TestAuthorizationFlow:
headers={"Content-Type": "application/json"},
)
+ @patch("core.helper.ssrf_proxy.post")
+ def test_register_client_rejected_by_server(self, mock_post):
+ """A rejected dynamic registration must raise ValueError, not httpx.HTTPStatusError.
+
+ `auth()` lets anything that is not a RequestError propagate, and the
+ console MCP auth endpoint only turns MCPError/ValueError into a 4xx, so
+ a raw HTTPStatusError here surfaces as an opaque 500.
+ """
+ mock_response = Mock()
+ mock_response.is_success = False
+ mock_response.status_code = 400
+ mock_response.text = '{"error":"invalid_redirect_uri"}'
+ mock_response.raise_for_status.side_effect = httpx.HTTPStatusError(
+ "Bad Request", request=Mock(), response=mock_response
+ )
+ mock_post.return_value = mock_response
+
+ metadata = OAuthMetadata(
+ authorization_endpoint="https://auth.example.com/authorize",
+ token_endpoint="https://auth.example.com/token",
+ registration_endpoint="https://auth.example.com/register",
+ response_types_supported=["code"],
+ )
+ client_metadata = OAuthClientMetadata(client_name="Dify", redirect_uris=["https://redirect.example.com"])
+
+ with pytest.raises(ValueError) as exc_info:
+ register_client("https://api.example.com", metadata, client_metadata)
+
+ message = str(exc_info.value)
+ assert "400" in message
+ assert "invalid_redirect_uri" in message
+
def test_register_client_no_endpoint(self):
"""Test client registration when no endpoint available."""
metadata = OAuthMetadata(
@@ -1244,13 +1276,13 @@ class TestAuthOrchestration:
with pytest.raises(ValueError, match="does not support dynamic client registration"):
register_client("https://api", metadata, client_metadata)
- # Failure: HTTP
+ # Failure: HTTP. A rejected registration must be reported as a ValueError so
+ # callers can turn it into a user-facing error instead of a bare 500.
res.is_success = False
- res.raise_for_status = Mock()
res.status_code = 400
- # If is_success is false, it should call raise_for_status
- register_client("https://api", None, client_metadata)
- res.raise_for_status.assert_called_once()
+ res.text = '{"error":"invalid_redirect_uri"}'
+ with pytest.raises(ValueError, match="Client registration failed: HTTP 400"):
+ register_client("https://api", None, client_metadata)
@patch("core.mcp.auth.auth_flow.discover_oauth_metadata")
def test_auth_orchestration_failures(self, mock_discover):
diff --git a/api/tests/unit_tests/core/mcp/client/test_sse.py b/api/tests/unit_tests/core/mcp/client/test_sse.py
index ea0ff7395df..1c9a6a30eac 100644
--- a/api/tests/unit_tests/core/mcp/client/test_sse.py
+++ b/api/tests/unit_tests/core/mcp/client/test_sse.py
@@ -173,6 +173,38 @@ def test_sse_client_error_handling():
pass
+ "transport_error",
+ [
+ httpx.ConnectError("[Errno 111] Connection refused"),
+ httpx.RemoteProtocolError("Server disconnected without sending a response."),
+ httpx.ReadTimeout("timed out"),
+ ],
+ ids=["connect_error", "remote_protocol_error", "read_timeout"],
+)
+def test_sse_client_wraps_transport_errors(transport_error: httpx.RequestError):
+ """Transport failures must surface as MCPConnectionError, not raw httpx errors.
+
+ Callers rely on the MCP error contract: MCPClient only falls back to
+ streamable HTTP on MCPConnectionError/ValueError, and the console API maps
+ those to a 4xx with a readable message instead of a bare 500.
+ """
+ test_url = "http://test.example/sse"
+
+ with (
+ patch("core.mcp.client.sse_client.create_ssrf_proxy_mcp_http_client"),
+ patch("core.mcp.client.sse_client.ssrf_proxy_sse_connect") as mock_sse_connect,
+ ):
+ mock_sse_connect.side_effect = transport_error
+
+ with pytest.raises(MCPConnectionError) as exc_info:
+ with sse_client(test_url):
+ pass
+
+ # The underlying reason must survive so the user can act on it.
+ assert str(transport_error) in str(exc_info.value)
+
+
def test_sse_client_timeout_configuration():
"""Test SSE client timeout configuration."""
test_url = "http://test.example/sse"
diff --git a/api/tests/unit_tests/core/mcp/test_mcp_client.py b/api/tests/unit_tests/core/mcp/test_mcp_client.py
index 62baee83ce3..4f9c9291d00 100644
--- a/api/tests/unit_tests/core/mcp/test_mcp_client.py
+++ b/api/tests/unit_tests/core/mcp/test_mcp_client.py
@@ -4,6 +4,7 @@ from contextlib import ExitStack
from types import TracebackType
from unittest.mock import MagicMock, Mock, patch
+import httpx
import pytest
from sqlalchemy.orm import Session
@@ -211,6 +212,56 @@ class TestMCPClient:
# Verify session was created with MCP
assert client._session == mock_session
+ @patch("core.mcp.client.sse_client.ssrf_proxy_sse_connect")
+ @patch("core.mcp.client.sse_client.create_ssrf_proxy_mcp_http_client")
+ @patch("core.mcp.mcp_client.streamablehttp_client")
+ @patch("core.mcp.mcp_client.ClientSession")
+ def test_initialize_fallback_from_sse_transport_error_to_mcp(
+ self, mock_client_session, mock_streamable_client, mock_http_client, mock_sse_connect
+ ):
+ """A transport failure on the SSE probe must still fall back to streamable HTTP.
+
+ Uses the real sse_client so the exception translation between the two
+ layers is exercised: an httpx error leaking out of sse_client skips the
+ fallback entirely and reaches the console API as an opaque 500.
+ """
+ mock_sse_connect.side_effect = httpx.ConnectError("[Errno 111] Connection refused")
+
+ mock_read_stream = Mock()
+ mock_write_stream = Mock()
+ mock_client_context = Mock()
+ mock_streamable_client.return_value.__enter__.return_value = (
+ mock_read_stream,
+ mock_write_stream,
+ mock_client_context,
+ )
+
+ mock_session = Mock()
+ mock_client_session.return_value.__enter__.return_value = mock_session
+
+ client = MCPClient(server_url="http://test.example.com/unknown")
+ client._initialize()
+
+ mock_streamable_client.assert_called_once()
+ assert client._session == mock_session
+
+ @patch("core.mcp.client.sse_client.ssrf_proxy_sse_connect")
+ @patch("core.mcp.client.sse_client.create_ssrf_proxy_mcp_http_client")
+ def test_initialize_sse_transport_error_raises_mcp_error(self, mock_http_client, mock_sse_connect):
+ """When both transports fail the caller gets an MCPError, never a raw httpx error.
+
+ The console MCP endpoints only translate MCPError/ValueError into a 4xx;
+ anything else becomes `{"code": "unknown", "status": 500}`.
+ """
+ mock_sse_connect.side_effect = httpx.ConnectError("[Errno 111] Connection refused")
+
+ client = MCPClient(server_url="http://test.example.com/sse")
+
+ with pytest.raises(MCPConnectionError) as exc_info:
+ client._initialize()
+
+ assert "Connection refused" in str(exc_info.value)
+
@patch("core.mcp.mcp_client.streamablehttp_client")
@patch("core.mcp.mcp_client.ClientSession")
def test_connect_server_mcp(self, mock_client_session, mock_streamable_client):