Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Bound error-stat cardinality in ErrorHandlingMiddleware (#5537)

mika089ff09a3f33
diff --git a/fastmcp_slim/fastmcp/server/middleware/error_handling.py b/fastmcp_slim/fastmcp/server/middleware/error_handling.py
index e0727c3de..29f8bc0f1 100644
--- a/fastmcp_slim/fastmcp/server/middleware/error_handling.py
+++ b/fastmcp_slim/fastmcp/server/middleware/error_handling.py
@@ -13,6 +13,9 @@ from fastmcp.exceptions import NotFoundError, ValidationError
from .middleware import CallNext, Middleware, MiddlewareContext
+_MAX_ERROR_STATS = 1000
+_OTHER_ERROR_STATS_KEY = "<other>"
+
class ErrorHandlingMiddleware(Middleware):
"""Middleware that provides consistent error handling and logging.
@@ -61,7 +64,16 @@ class ErrorHandlingMiddleware(Middleware):
# Track error counts
error_key = f"{error_type}:{method}"
- self.error_counts[error_key] = self.error_counts.get(error_key, 0) + 1
+ if error_key in self.error_counts:
+ self.error_counts[error_key] += 1
+ elif len(self.error_counts) < _MAX_ERROR_STATS - 1:
+ self.error_counts[error_key] = 1
+ else:
+ # Method names come from incoming requests. Keep the statistics map
+ # bounded even when callers send a new unsupported method each time.
+ self.error_counts[_OTHER_ERROR_STATS_KEY] = (
+ self.error_counts.get(_OTHER_ERROR_STATS_KEY, 0) + 1
+ )
base_message = f"Error in {method}: {error_type}: {error!s}"
@@ -122,7 +134,11 @@ class ErrorHandlingMiddleware(Middleware):
raise transformed_error from error
def get_error_stats(self) -> dict[str, int]:
- """Get error statistics for monitoring."""
+ """Get error statistics for monitoring.
+
+ The map is capped at 1000 entries. Errors that would exceed the cap are
+ counted together under ``<other>``.
+ """
return self.error_counts.copy()
diff --git a/tests/server/middleware/test_error_handling.py b/tests/server/middleware/test_error_handling.py
index a3b0b8d93..a6b8bf4be 100644
--- a/tests/server/middleware/test_error_handling.py
+++ b/tests/server/middleware/test_error_handling.py
@@ -308,6 +308,19 @@ class TestErrorHandlingMiddleware:
assert stats["ValueError:test_method"] == 2
assert stats["RuntimeError:test_method"] == 1
+ def test_get_error_stats_bounds_distinct_methods(self, mock_context):
+ """Distinct request methods beyond the stats limit share one bucket."""
+ middleware = ErrorHandlingMiddleware(logger=MagicMock())
+
+ for index in range(1005):
+ mock_context.method = f"unsupported/{index}"
+ middleware._log_error(ValueError("failure"), mock_context)
+
+ stats = middleware.get_error_stats()
+ assert len(stats) == 1000
+ assert stats["ValueError:unsupported/0"] == 1
+ assert stats["<other>"] == 6
+
class TestRetryMiddleware:
"""Test retry middleware functionality."""