wenjin272 commented on code in PR #1474:
URL: https://github.com/apache/flink-agents/pull/1474#discussion_r4739241912


##########
python/flink_agents/integrations/mcp/mcp.py:
##########
@@ -48,6 +54,76 @@
 )
 from flink_agents.integrations.mcp.utils import extract_mcp_content_item
 
+logger = logging.getLogger(__name__)
+
+_T = TypeVar("_T")
+
+DEFAULT_MAX_RETRIES = 3
+DEFAULT_INITIAL_BACKOFF = timedelta(milliseconds=100)
+DEFAULT_MAX_BACKOFF = timedelta(seconds=10)
+
+_RETRYABLE_HTTP_STATUS_CODES = frozenset({429, 503})
+_RETRYABLE_MESSAGE_FRAGMENTS = (
+    "HTTP 503",
+    "HTTP 429",
+    "Connection reset",
+    "Connection refused",
+    "Connection timed out",
+)
+_BASE_EXCEPTION_GROUP = getattr(builtins, "BaseExceptionGroup", None)

Review Comment:
   Could we also support `BaseExceptionGroup` from the `exceptiongroup` 
backport on Python 3.10? I reproduced this with a real HTTP endpoint returning 
503: the MCP SDK wraps `HTTPStatusError` in `exceptiongroup.ExceptionGroup`, 
but this check misses it, so no retry occurs. The corresponding test also 
assumes the built-in `ExceptionGroup` exists and fails on Python 3.10; it 
should exercise the backport there.



##########
python/flink_agents/integrations/mcp/mcp.py:
##########
@@ -169,6 +245,9 @@ class MCPServer(Resource, ABC):
     timeout: timedelta = timedelta(seconds=30)
     sse_read_timeout: timedelta = timedelta(minutes=5)
     auth: httpx.Auth | None = None
+    max_retries: int = DEFAULT_MAX_RETRIES
+    initial_backoff: timedelta = DEFAULT_INITIAL_BACKOFF
+    max_backoff: timedelta = DEFAULT_MAX_BACKOFF

Review Comment:
   When Java delegates MCP execution to Python, the resource arguments retain 
camelCase names such as `maxRetries`, `initialBackoff`, and `maxBackoff`. These 
snake_case fields do not accept those names, so the settings are ignored—for 
example, `maxRetries=0` still uses the Python default of three retries. Could 
we map these names or accept aliases, with coverage through the Java-to-Python 
configuration path?



##########
python/flink_agents/integrations/mcp/mcp.py:
##########
@@ -48,6 +54,76 @@
 )
 from flink_agents.integrations.mcp.utils import extract_mcp_content_item
 
+logger = logging.getLogger(__name__)
+
+_T = TypeVar("_T")
+
+DEFAULT_MAX_RETRIES = 3
+DEFAULT_INITIAL_BACKOFF = timedelta(milliseconds=100)
+DEFAULT_MAX_BACKOFF = timedelta(seconds=10)
+
+_RETRYABLE_HTTP_STATUS_CODES = frozenset({429, 503})
+_RETRYABLE_MESSAGE_FRAGMENTS = (
+    "HTTP 503",
+    "HTTP 429",
+    "Connection reset",
+    "Connection refused",
+    "Connection timed out",
+)
+_BASE_EXCEPTION_GROUP = getattr(builtins, "BaseExceptionGroup", None)
+
+
+def _is_retryable_mcp_exception(
+    exc: BaseException,
+    _visited: set[int] | None = None,
+) -> bool:
+    """Return whether an MCP call exception represents a transient failure."""
+    if _visited is None:
+        _visited = set()
+    exc_id = id(exc)
+    if exc_id in _visited:
+        return False
+    _visited.add(exc_id)
+
+    if _BASE_EXCEPTION_GROUP is not None and isinstance(exc, 
_BASE_EXCEPTION_GROUP):
+        sub_exceptions = exc.exceptions
+        return bool(sub_exceptions) and all(
+            _is_retryable_mcp_exception(sub, _visited) for sub in 
sub_exceptions
+        )
+
+    if isinstance(
+        exc,
+        (
+            TimeoutError,
+            ConnectionError,
+            httpx.TimeoutException,
+            httpx.NetworkError,
+            httpx.RemoteProtocolError,
+        ),
+    ):
+        return True
+
+    if isinstance(exc, httpx.HTTPStatusError):
+        return (
+            exc.response is not None
+            and exc.response.status_code in _RETRYABLE_HTTP_STATUS_CODES
+        )
+
+    if isinstance(exc, McpError):
+        message = str(exc)
+        if "Timed out" in message:
+            return True
+
+    message = str(exc)
+    if any(fragment in message for fragment in _RETRYABLE_MESSAGE_FRAGMENTS):
+        return True

Review Comment:
   Could we check `McpError.error.code == 408` for request timeouts and remove 
the message-string matching below? The SDK exposes this timeout code, while 
HTTP status and network errors are already covered by the existing checks. This 
would simplify the classifier without depending on error wording. The 
exception-group and exception-chain handling can stay.



##########
python/flink_agents/integrations/mcp/mcp.py:
##########
@@ -183,6 +262,35 @@ def validate_timeout(cls, value: Any) -> timedelta:
             raise ValueError(msg)
         return duration
 
+    @field_validator("max_retries", mode="before")
+    @classmethod
+    def validate_max_retries(cls, value: Any) -> int:
+        """Validate that max_retries is a non-negative integer."""
+        if isinstance(value, bool) or not isinstance(value, int) or value < 0:
+            msg = f"max_retries must be a non-negative integer, but was 
{value!r}."
+            raise ValueError(msg)
+        return value

Review Comment:
   Could we use `Field(ge=0, strict=True)` for `max_retries` and 
`Field(ge=timedelta(0))` for the backoff fields? This would replace 
`validate_max_retries` and let `validate_backoff` focus on the existing 
`parse_duration()` conversion, which is still needed for inputs such as `"100 
ms"`. The model validator can retain the `max_backoff >= initial_backoff` check.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to