Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions src/mcp/server/mcpserver/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@
)
from mcp.server.mcpserver.tools import Tool, ToolManager
from mcp.server.mcpserver.utilities.context_injection import find_context_parameter
from mcp.server.mcpserver.utilities.logging import configure_logging, get_logger
from mcp.server.mcpserver.utilities.logging import configure_logging as _configure_logging
from mcp.server.mcpserver.utilities.logging import get_logger
from mcp.server.request_state import RequestStateBoundary, RequestStateSecurity
from mcp.server.sse import SseServerTransport
from mcp.server.stdio import stdio_server
Expand Down Expand Up @@ -174,6 +175,7 @@ def __init__(
extensions: Sequence[Extension] | None = None,
debug: bool = False,
log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO",
configure_logging: bool = True,
warn_on_duplicate_resources: bool = True,
warn_on_duplicate_tools: bool = True,
warn_on_duplicate_prompts: bool = True,
Expand Down Expand Up @@ -256,8 +258,10 @@ def __init__(
self._token_verifier = ProviderTokenVerifier(auth_server_provider)
self._custom_starlette_routes: list[Route] = []

# Configure logging
configure_logging(self.settings.log_level)
# Configure logging (opt-out via configure_logging=False for applications
# that embed MCPServer and manage their own logging setup; see #1656)
if configure_logging:
_configure_logging(self.settings.log_level)

self._extensions: list[Extension] = []
for extension in extensions or ():
Expand Down
62 changes: 62 additions & 0 deletions tests/server/mcpserver/test_configure_logging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import logging

import pytest

from mcp.server.mcpserver import MCPServer


@pytest.fixture
def clean_root_logger():
"""Save and restore the root logger's handlers/level around each test.

`MCPServer` can mutate the root logger via `logging.basicConfig()`, so
tests that exercise this behavior must not leak handlers into other
tests (or into pytest's own log capturing, which itself attaches a
handler to the root logger -- hence comparing against a baseline
snapshot below, rather than assuming an empty handler list).
"""
root = logging.getLogger()
original_handlers = list(root.handlers)
original_level = root.level
yield root
root.handlers.clear()
root.handlers.extend(original_handlers)
root.setLevel(original_level)


class TestConfigureLogging:
def test_default_does_not_override_existing_handlers(self, clean_root_logger):
"""If an application has already configured the root logger before
creating an `MCPServer`, the default behavior must not replace it.

This matches the standard library's own `logging.basicConfig()`
contract: it is a no-op if the root logger already has handlers.
"""
baseline = list(clean_root_logger.handlers)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The new opt-out test can pass even if configure_logging=False is ignored when pytest has already attached root handlers. Because logging.basicConfig() is a no-op with existing handlers, constructing MCPServer against the baseline handler list does not exercise the race this option fixes; clearing the root handlers before constructing the server (or spying on _configure_logging) would make the regression test cover the intended no-handlers case.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At tests/server/mcpserver/test_configure_logging.py, line 35:

<comment>The new opt-out test can pass even if `configure_logging=False` is ignored when pytest has already attached root handlers. Because `logging.basicConfig()` is a no-op with existing handlers, constructing `MCPServer` against the `baseline` handler list does not exercise the race this option fixes; clearing the root handlers before constructing the server (or spying on `_configure_logging`) would make the regression test cover the intended no-handlers case.</comment>

<file context>
@@ -0,0 +1,62 @@
+        This matches the standard library's own `logging.basicConfig()`
+        contract: it is a no-op if the root logger already has handlers.
+        """
+        baseline = list(clean_root_logger.handlers)
+        app_handler = logging.StreamHandler()
+        clean_root_logger.addHandler(app_handler)
</file context>

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks — you're right that comparing root logger state was
fragile since pytest's own log capture handler masks the exact race
this fixes. Pushed a fix that spies on _configure_logging directly
instead, and verified it actually fails if the configure_logging flag
is ignored (I temporarily reverted the fix locally to confirm).

app_handler = logging.StreamHandler()
clean_root_logger.addHandler(app_handler)

MCPServer("test-server")

assert clean_root_logger.handlers == [*baseline, app_handler]

def test_configure_logging_false_leaves_root_logger_untouched(self, clean_root_logger):
"""`configure_logging=False` opts a server out of touching the root
logger entirely, so an application can safely configure its own
logging before or after constructing the server.

See: https://github.com/modelcontextprotocol/python-sdk/issues/1656
"""
baseline = list(clean_root_logger.handlers)

MCPServer("test-server", configure_logging=False)
assert clean_root_logger.handlers == baseline

# The application's own logging setup, performed afterwards, must
# take effect (i.e. must not have been pre-empted by the server).
# Clear first so `basicConfig` (a no-op if handlers already exist)
# is guaranteed to actually apply the new format.
clean_root_logger.handlers.clear()
logging.basicConfig(format="MYAPP: %(message)s")
assert len(clean_root_logger.handlers) == 1
assert clean_root_logger.handlers[0].formatter._fmt == "MYAPP: %(message)s"
Loading