Skip to content

Commit 57d739c

Browse files
fix(mcp): guard against division by zero in size calculations
Add zero-division guards in middleware and token_utils when token_limit or estimated_tokens could be zero.
1 parent 40ff227 commit 57d739c

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

superset/mcp_service/middleware.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -834,7 +834,7 @@ async def on_call_tool(
834834
"Response size warning for %s: ~%d tokens (%.0f%% of %d limit)",
835835
tool_name,
836836
estimated_tokens,
837-
(estimated_tokens / self.token_limit) * 100,
837+
(estimated_tokens / self.token_limit * 100) if self.token_limit else 0,
838838
self.token_limit,
839839
)
840840

superset/mcp_service/utils/token_utils.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -184,14 +184,19 @@ def generate_size_reduction_suggestions(
184184
suggestions = []
185185
query_params = extract_query_params(params)
186186
reduction_needed = estimated_tokens - token_limit
187-
reduction_pct = int((reduction_needed / estimated_tokens) * 100)
187+
reduction_pct = (
188+
int((reduction_needed / estimated_tokens) * 100) if estimated_tokens else 0
189+
)
188190

189191
# Suggestion 1: Reduce page_size or limit
190192
current_page_size = query_params.get("page_size") or query_params.get("limit")
191193
if current_page_size:
192194
# Calculate suggested new limit based on reduction needed
193195
suggested_limit = max(
194-
1, int(current_page_size * (token_limit / estimated_tokens))
196+
1,
197+
int(current_page_size * (token_limit / estimated_tokens))
198+
if estimated_tokens
199+
else 1,
195200
)
196201
suggestions.append(
197202
f"Reduce page_size/limit from {current_page_size} to {suggested_limit} "
@@ -392,7 +397,11 @@ def format_size_limit_error(
392397
for i, suggestion in enumerate(suggestions[:5], 1): # Limit to top 5 suggestions
393398
error_lines.append(f"{i}. {suggestion}")
394399

395-
reduction_pct = (estimated_tokens - token_limit) / estimated_tokens * 100
400+
reduction_pct = (
401+
(estimated_tokens - token_limit) / estimated_tokens * 100
402+
if estimated_tokens
403+
else 0
404+
)
396405
error_lines.extend(
397406
[
398407
"",

0 commit comments

Comments
 (0)