π The fast, Pythonic way to build MCP servers and clients.
fix(middleware): treat an empty methods allowlist as "log nothing" (#5727)
δΈηδΈη92789979a62b
diff --git a/fastmcp_slim/fastmcp/server/middleware/logging.py b/fastmcp_slim/fastmcp/server/middleware/logging.pyindex b2d62507e..fe77a4d03 100644--- a/fastmcp_slim/fastmcp/server/middleware/logging.py+++ b/fastmcp_slim/fastmcp/server/middleware/logging.py@@ -126,7 +126,7 @@ class BaseLoggingMiddleware(Middleware):) -> Any:"""Log messages for configured methods."""- if self.methods and context.method not in self.methods:+ if self.methods is not None and context.method not in self.methods:return await call_next(context)self._log_message(self._create_before_message(context))diff --git a/tests/server/middleware/test_logging_methods_filter.py b/tests/server/middleware/test_logging_methods_filter.pynew file mode 100644index 000000000..b596c9f5d--- /dev/null+++ b/tests/server/middleware/test_logging_methods_filter.py@@ -0,0 +1,75 @@+"""`methods` is an allowlist, including when it is empty.++`LoggingMiddleware(methods=[])` asks for no method to be logged, and both+constructors document `methods` as "List of methods to log. If None, logs all+methods." The filter tested truthiness, so an empty list was indistinguishable+from `None` and every message was logged instead.+"""++from __future__ import annotations++import io+import logging++from fastmcp import Client, FastMCP+from fastmcp.server.middleware import Middleware+from fastmcp.server.middleware.logging import (+ LoggingMiddleware,+ StructuredLoggingMiddleware,+)+++def _capture() -> tuple[io.StringIO, logging.Logger]:+ stream = io.StringIO()+ logger = logging.getLogger("test.logging.methods")+ logger.handlers = [logging.StreamHandler(stream)]+ logger.setLevel(logging.DEBUG)+ logger.propagate = False+ return stream, logger+++def _server(middleware: Middleware) -> FastMCP:+ mcp = FastMCP("methods-filter", middleware=[middleware])++ @mcp.tool+ def ping() -> str:+ return "pong"++ return mcp+++async def _call(mcp: FastMCP) -> None:+ async with Client(mcp) as client:+ await client.call_tool("ping", {})+++async def test_empty_methods_logs_nothing() -> None:+ stream, logger = _capture()++ await _call(_server(LoggingMiddleware(methods=[], logger=logger)))++ assert stream.getvalue() == ""+++async def test_none_methods_logs_everything() -> None:+ stream, logger = _capture()++ await _call(_server(LoggingMiddleware(methods=None, logger=logger)))++ assert "tools/call" in stream.getvalue()+++async def test_allowlist_restricts_to_listed_methods() -> None:+ stream, logger = _capture()++ await _call(_server(LoggingMiddleware(methods=["tools/list"], logger=logger)))++ assert "tools/call" not in stream.getvalue()+++async def test_structured_middleware_shares_the_filter() -> None:+ stream, logger = _capture()++ await _call(_server(StructuredLoggingMiddleware(methods=[], logger=logger)))++ assert stream.getvalue() == ""