From 38efe9872010ab96add30d64fcca7891a5d89384 Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Thu, 9 Jul 2026 23:06:47 -0700 Subject: [PATCH] refactor(mcp): make context window detection iterative for the recursion gate The code-quality recursive_detector CI step bans recursive functions under litellm/; walk the exception cause chain with a bounded loop instead --- .../mcp_server/semantic_tool_filter.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py b/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py index 0a73420e9d2..e12c6cdbd56 100644 --- a/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py +++ b/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py @@ -33,15 +33,18 @@ class SemanticToolFilterContextWindowError(Exception): ) -def _is_context_window_error(error: Optional[BaseException], depth: int = 5) -> bool: +def _is_context_window_error(error: Optional[BaseException], max_depth: int = 5) -> bool: """Detect a context-window overflow anywhere in an exception's cause chain.""" - if error is None or depth == 0: - return False - if isinstance(error, ContextWindowExceededError): - return True - if ExceptionCheckers.is_error_str_context_window_exceeded(str(error)): - return True - return _is_context_window_error(error.__cause__ or error.__context__, depth - 1) + current = error + for _ in range(max_depth): + if current is None: + return False + if isinstance(current, ContextWindowExceededError): + return True + if ExceptionCheckers.is_error_str_context_window_exceeded(str(current)): + return True + current = current.__cause__ or current.__context__ + return False class SemanticMCPToolFilter: