Skip to content

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

Drop clamped log records the logger is not enabled for (#5915)

Asem ahmed48d947f57c8f
diff --git a/fastmcp_slim/fastmcp/utilities/logging.py b/fastmcp_slim/fastmcp/utilities/logging.py
index eebf4eda8..c9e305b11 100644
--- a/fastmcp_slim/fastmcp/utilities/logging.py
+++ b/fastmcp_slim/fastmcp/utilities/logging.py
@@ -188,16 +188,19 @@ _level_to_no: dict[
class _ClampedLogFilter(logging.Filter):
+ logger: logging.Logger
min_level: tuple[int, str] | None
max_level: tuple[int, str] | None
def __init__(
self,
+ logger: logging.Logger,
min_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
| None = None,
max_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
| None = None,
):
+ self.logger = logger
self.min_level = None
self.max_level = None
@@ -216,7 +219,9 @@ class _ClampedLogFilter(logging.Filter):
if record.levelno > max_level_no:
record.levelno = max_level_no
record.levelname = max_level_name
- return True
+ # `Logger.log` checked the original level before filters ran, so
+ # drop the record if the logger isn't enabled for the clamped level.
+ return self.logger.isEnabledFor(max_level_no)
if self.min_level:
min_level_no, min_level_name = self.min_level
@@ -236,7 +241,8 @@ def _clamp_logger(
"""Clamp the logger to a minimum and maximum level.
If min_level is provided, messages logged at a lower level than `min_level` will have their level increased to `min_level`.
- If max_level is provided, messages logged at a higher level than `max_level` will have their level decreased to `max_level`.
+ If max_level is provided, messages logged at a higher level than `max_level` will have their level decreased to `max_level`,
+ and are dropped if the logger is not enabled for `max_level`.
Args:
min_level: The lower bound of the clamp
@@ -244,7 +250,11 @@ def _clamp_logger(
"""
_unclamp_logger(logger=logger)
- logger.addFilter(filter=_ClampedLogFilter(min_level=min_level, max_level=max_level))
+ logger.addFilter(
+ filter=_ClampedLogFilter(
+ logger=logger, min_level=min_level, max_level=max_level
+ )
+ )
def _unclamp_logger(logger: logging.Logger) -> None:
diff --git a/tests/server/test_context.py b/tests/server/test_context.py
index ee37484b6..17c4544a6 100644
--- a/tests/server/test_context.py
+++ b/tests/server/test_context.py
@@ -1,7 +1,10 @@
+import logging
+from collections.abc import Iterator
from unittest.mock import MagicMock
import pytest
+from fastmcp import Client
from fastmcp.server.context import (
Context,
reset_transport,
@@ -550,3 +553,63 @@ class TestContextLogExtra:
assert result.data == "ok"
assert received == [{"msg": "hello", "extra": {"request_id": "r-1"}}]
+
+
+class TestContextToClientLogger:
+ @pytest.fixture
+ def to_client_logger(self) -> Iterator[logging.Logger]:
+ logger = logging.getLogger("fastmcp.server.context.to_client")
+ yield logger
+ logger.setLevel(logging.NOTSET)
+
+ @staticmethod
+ async def call_log_tool(method: str) -> list[str]:
+ """Call a tool that logs "hello" with `ctx.<method>`.
+
+ Returns the levels of the log messages the client received.
+ """
+ mcp = FastMCP("test")
+
+ @mcp.tool
+ async def emit(ctx: Context) -> str:
+ await getattr(ctx, method)("hello")
+ return "ok"
+
+ received: list[str] = []
+
+ async def log_handler(message):
+ received.append(message.level)
+
+ async with Client(mcp, log_handler=log_handler) as client:
+ await client.call_tool("emit", {})
+ return received
+
+ @pytest.mark.parametrize("method", ["debug", "info", "warning", "error"])
+ async def test_server_side_copy_is_not_logged_at_info_level(
+ self,
+ caplog: pytest.LogCaptureFixture,
+ to_client_logger: logging.Logger,
+ method: str,
+ ):
+ to_client_logger.setLevel(logging.INFO)
+
+ assert await self.call_log_tool(method) == [method]
+
+ assert [r for r in caplog.records if r.name == to_client_logger.name] == []
+
+ @pytest.mark.parametrize("method", ["debug", "info", "warning", "error"])
+ async def test_server_side_copy_is_logged_at_debug_level_when_enabled(
+ self,
+ caplog: pytest.LogCaptureFixture,
+ to_client_logger: logging.Logger,
+ method: str,
+ ):
+ to_client_logger.setLevel(logging.DEBUG)
+
+ assert await self.call_log_tool(method) == [method]
+
+ assert [
+ (r.levelno, r.levelname, r.getMessage())
+ for r in caplog.records
+ if r.name == to_client_logger.name
+ ] == [(logging.DEBUG, "DEBUG", f"Sending {method.upper()} to client: hello")]
diff --git a/tests/utilities/test_logging.py b/tests/utilities/test_logging.py
index c74b6c436..0bcf13ff8 100644
--- a/tests/utilities/test_logging.py
+++ b/tests/utilities/test_logging.py
@@ -1,10 +1,17 @@
import logging
+from collections.abc import Iterator
from pathlib import Path
+import pytest
from rich.logging import RichHandler
import fastmcp
-from fastmcp.utilities.logging import configure_logging, get_logger
+from fastmcp.utilities.logging import (
+ _clamp_logger,
+ _unclamp_logger,
+ configure_logging,
+ get_logger,
+)
def test_logging_doesnt_affect_other_loggers(caplog):
@@ -112,3 +119,59 @@ def test_configure_logging_with_rich_enabled():
fastmcp.settings.enable_rich_logging = original_enable_rich
# Reconfigure to restore state
configure_logging()
+
+
+def clamped_logger() -> Iterator[logging.Logger]:
+ logger = logging.getLogger("test_logging.clamped")
+ yield logger
+ _unclamp_logger(logger)
+ logger.setLevel(logging.NOTSET)
+
+
+ "level",
+ [logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL],
+ ids=logging.getLevelName,
+)
+def test_max_clamp_drops_record_the_logger_is_not_enabled_for(
+ caplog: pytest.LogCaptureFixture, clamped_logger: logging.Logger, level: int
+):
+ """A record lowered to DEBUG is dropped when the logger is only enabled for INFO."""
+ clamped_logger.setLevel(logging.INFO)
+ _clamp_logger(clamped_logger, max_level="DEBUG")
+
+ clamped_logger.log(level, "hello")
+
+ assert caplog.records == []
+
+
+ "level",
+ [logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL],
+ ids=logging.getLevelName,
+)
+def test_max_clamp_lowers_record_the_logger_is_enabled_for(
+ caplog: pytest.LogCaptureFixture, clamped_logger: logging.Logger, level: int
+):
+ clamped_logger.setLevel(logging.DEBUG)
+ _clamp_logger(clamped_logger, max_level="DEBUG")
+
+ clamped_logger.log(level, "hello")
+
+ assert [(r.levelno, r.levelname, r.getMessage()) for r in caplog.records] == [
+ (logging.DEBUG, "DEBUG", "hello")
+ ]
+
+
+def test_min_clamp_raises_record_to_min_level(
+ caplog: pytest.LogCaptureFixture, clamped_logger: logging.Logger
+):
+ clamped_logger.setLevel(logging.DEBUG)
+ _clamp_logger(clamped_logger, min_level="WARNING")
+
+ clamped_logger.debug("hello")
+
+ assert [(r.levelno, r.levelname, r.getMessage()) for r in caplog.records] == [
+ (logging.WARNING, "WARNING", "hello")
+ ]