π The fast, Pythonic way to build MCP servers and clients.
Apply logging/setLevel to mounted servers over HTTP sessions (#6421)
nate nowackc4a1bcb67303
diff --git a/fastmcp_slim/fastmcp/server/context.py b/fastmcp_slim/fastmcp/server/context.pyindex 86d202c22..5e27912a7 100644--- a/fastmcp_slim/fastmcp/server/context.py+++ b/fastmcp_slim/fastmcp/server/context.py@@ -644,7 +644,7 @@ class Context:# falling back to the server's configured default.min_level = self.fastmcp.client_log_levelsession = self.session- session_min = _get_client_log_level(self.fastmcp, session)+ session_min = _get_client_log_level(session)if session_min is not None:min_level = session_min@@ -1346,28 +1346,23 @@ def _detached_request_context(context: Context) -> ServerRequestContext:)-# `Connection.state` key holding the level a client set with logging/setLevel-# on a connection that has no session id.+# `Connection.state` key holding the level a client set with logging/setLevel._CONNECTION_LOG_LEVEL_KEY = "_fastmcp_client_log_level"-def _get_client_log_level(- server: FastMCP, session: ServerSession-) -> LoggingLevel | None:+def _get_client_log_level(session: ServerSession) -> LoggingLevel | None:"""Return the minimum log level the client set with logging/setLevel, if any.v2 constructs sessions per-request, so the stable identity is the- connection. A handshake-era HTTP session is keyed by its session id on the- server. Any other connection (stdio, in-memory, stateless HTTP, 2026-07-28)- has no session id, so its level lives in the connection's own state, where- no other client can see it and which ends with the connection.+ connection. The level lives in the connection's own state, where no other+ client can see it and which ends with the connection. Every server that+ handles the connection's requests, mounted servers included, reads the same+ value."""connection = getattr(session, "_connection", None)if connection is None:return None- if connection.session_id is None:- return connection.state.get(_CONNECTION_LOG_LEVEL_KEY)- return server._client_log_levels.get(connection.session_id)+ return connection.state.get(_CONNECTION_LOG_LEVEL_KEY)async def _log_to_server_and_client(diff --git a/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py b/fastmcp_slim/fastmcp/server/mixins/mcp_operations.pyindex b74dec535..d64b3868a 100644--- a/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py+++ b/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py@@ -494,9 +494,8 @@ class MCPOperationsMixin:Stores the requested minimum log level so that subsequent log messagesbelow this level are suppressed. v2 sessions are per-request, so the- level lives on the FastMCP server keyed by session id, or on the- connection itself when it has no session id (stdio, in-memory,- stateless HTTP).+ level lives on the client's connection, where mounted servers handling+ the same connection also see it."""from fastmcp.server.context import _CONNECTION_LOG_LEVEL_KEY@@ -504,18 +503,7 @@ class MCPOperationsMixin:logger.debug(f"[{self.name}] Handler called: set_logging_level %s", params.level)- connection = rc.session._connection- session_id = connection.session_id- if session_id is None:- connection.state[_CONNECTION_LOG_LEVEL_KEY] = params.level- return EmptyResult()- self._client_log_levels[session_id] = params.level- cleanup_key = "_fastmcp_log_level_cleanup_registered"- if not connection.state.get(cleanup_key):- connection.exit_stack.callback(- self._client_log_levels.pop, session_id, None- )- connection.state[cleanup_key] = True+ rc.session._connection.state[_CONNECTION_LOG_LEVEL_KEY] = params.levelreturn EmptyResult()async def _on_complete(diff --git a/fastmcp_slim/fastmcp/server/server.py b/fastmcp_slim/fastmcp/server/server.pyindex 6272be09d..cda46c54e 100644--- a/fastmcp_slim/fastmcp/server/server.py+++ b/fastmcp_slim/fastmcp/server/server.py@@ -611,12 +611,6 @@ class FastMCP(else fastmcp.settings.client_log_level)- # Per-session minimum log level requested by clients via logging/setLevel,- # keyed by session id. Connections without one (stdio, in-memory,- # stateless HTTP) keep theirs in `Connection.state`. v2 sessions are- # per-request so this state lives on the server, not the session object.- self._client_log_levels: dict[str, mcp_types.LoggingLevel] = {}-self.experimental_capabilities: dict[str, dict[str, Any]] = (experimental_capabilities or {})diff --git a/tests/client/test_logs.py b/tests/client/test_logs.pyindex 0e35da0e5..f31806a39 100644--- a/tests/client/test_logs.py+++ b/tests/client/test_logs.py@@ -7,7 +7,7 @@ from mcp_types import LoggingMessageNotificationParamsfrom fastmcp import Client, Context, FastMCPfrom fastmcp.client.logging import LogMessage, create_log_callback-from fastmcp.utilities.tests import asgi_server+from fastmcp.utilities.tests import asgi_client, asgi_serverclass LogHandler:@@ -235,6 +235,28 @@ class TestSetLoggingLevel:assert [log.data["msg"] for log in log_handler.logs] == ["info msg"]+ @pytest.mark.parametrize("transport", ["memory", "http"])+ async def test_level_applies_to_mounted_server_tools(+ self, fastmcp_server: FastMCP, transport: Literal["memory", "http"]+ ):+ """setLevel sent to a parent filters logs from its mounted servers' tools."""+ parent = FastMCP("parent")+ parent.mount(fastmcp_server)+ log_handler = LogHandler()+ connect = (+ asgi_client(parent, mode="legacy", log_handler=log_handler.handle_log)+ if transport == "http"+ else Client(parent, mode="legacy", log_handler=log_handler.handle_log)+ )+ async with connect as client:+ await client.set_logging_level("warning")+ await client.call_tool("echo_log", {"message": "info msg", "level": "info"})+ await client.call_tool(+ "echo_log", {"message": "error msg", "level": "error"}+ )++ assert [log.data["msg"] for log in log_handler.logs] == ["error msg"]+@pytest.mark.parametrize("other_mode", ["legacy", "auto"])async def test_stateless_http_level_does_not_reach_other_clients(self, fastmcp_server: FastMCP, other_mode: Literal["legacy", "auto"]diff --git a/tests/server/http/test_session_idle_timeout.py b/tests/server/http/test_session_idle_timeout.pyindex 01ba8c32f..3199e0254 100644--- a/tests/server/http/test_session_idle_timeout.py+++ b/tests/server/http/test_session_idle_timeout.py@@ -204,42 +204,3 @@ def test_idle_session_is_terminated_after_timeout(use_http_app: bool):json={"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}},)assert response.status_code == 404---def test_idle_session_cleanup_removes_legacy_log_level():- """A legacy session's logging preference is released when it expires."""- server = FastMCP(name="IdleLogLevelServer")- with temporary_settings(http_session_idle_timeout=1.0):- app = server.http_app(path="/mcp")-- with TestClient(app, base_url="http://127.0.0.1") as client:- response = client.post("/mcp", headers=MCP_HEADERS, json=INITIALIZE_REQUEST)- assert response.status_code == 200- session_id = response.headers["mcp-session-id"]-- session_headers = {- **MCP_HEADERS,- "mcp-session-id": session_id,- "mcp-protocol-version": "2024-11-05",- }- response = client.post(- "/mcp",- headers=session_headers,- json={- "jsonrpc": "2.0",- "id": 2,- "method": "logging/setLevel",- "params": {"level": "warning"},- },- )- assert response.status_code == 200- assert server._client_log_levels[session_id] == "warning"-- sm = _find_session_manager(app)- assert sm is not None- deadline = time.monotonic() + 4.0- while session_id in sm._server_instances and time.monotonic() < deadline:- time.sleep(0.02)-- assert session_id not in sm._server_instances- assert session_id not in server._client_log_levelsdiff --git a/tests/tasks/server/test_context_background_task.py b/tests/tasks/server/test_context_background_task.pyindex 85257a9f4..64972ad6a 100644--- a/tests/tasks/server/test_context_background_task.py+++ b/tests/tasks/server/test_context_background_task.py@@ -36,7 +36,7 @@ from mcp_types import (from fastmcp import FastMCPfrom fastmcp.exceptions import ToolErrorfrom fastmcp.server.auth import AccessToken-from fastmcp.server.context import Context+from fastmcp.server.context import _CONNECTION_LOG_LEVEL_KEY, Contextfrom fastmcp.server.dependencies import get_access_tokenfrom fastmcp_tasks import TasksExtensionfrom tests.tasks.task_helpers import (@@ -192,6 +192,7 @@ class TestContextBackgroundTaskLogging:class MockConnection:def __init__(self, session_id: str) -> None:self.session_id = session_id+ self.state: dict[str, Any] = {}class MockSession:def __init__(self, session_id: str) -> None:@@ -211,9 +212,9 @@ class TestContextBackgroundTaskLogging:its logs, so sub-threshold messages are not sent to the client."""mcp = FastMCP("test")session_id = "session-abc"- mcp._client_log_levels[session_id] = "error"ctx, send_log_message = self._make_task_context(mcp, session_id)+ ctx.session._connection.state[_CONNECTION_LOG_LEVEL_KEY] = "error"assert ctx.is_background_task is Trueassert ctx.request_context is None