Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(mcp): strip control characters from the MCP stderr sink (#6081)

Ehsan4fc0acd5bedc
diff --git a/changelog.d/6035.bugfix.md b/changelog.d/6035.bugfix.md
new file mode 100644
index 0000000000..e779179018
--- /dev/null
+++ b/changelog.d/6035.bugfix.md
@@ -0,0 +1 @@
+The MCP server now emits the log records the rest of the package writes, and strips control characters from them. The package disables its own loguru namespace on import and only the web path re-enabled it, so the MCP subprocess logged nothing of its own; and without the sanitizer a research query containing a newline could forge a second stderr log record.
diff --git a/src/local_deep_research/mcp/server.py b/src/local_deep_research/mcp/server.py
index 37d893138c..70c6fd9060 100644
--- a/src/local_deep_research/mcp/server.py
+++ b/src/local_deep_research/mcp/server.py
@@ -1020,12 +1020,27 @@ def get_configuration() -> Dict[str, Any]:
# =============================================================================
-def run_server():
- """Run the MCP server using STDIO transport."""
- # MCP uses stdout for JSON-RPC, so redirect all logging to stderr.
- # This runs in a separate subprocess (ldr-mcp) — logger.remove() only
- # affects this MCP process, not the main LDR application.
+def configure_mcp_logging(sink=None):
+ """Send this process's logs to stderr, with control characters stripped.
+
+ MCP uses stdout for JSON-RPC, so logging goes to stderr. This runs in a
+ separate subprocess (ldr-mcp), so logger.remove() only affects this MCP
+ process, not the main LDR application.
+ """
+ from ..security.log_sanitizer import sanitize_log_record
+
logger.remove()
+ # local_deep_research/__init__.py disables the package's own namespace, so
+ # without this nothing logged from inside the package reaches the sink and
+ # only third-party records get here. config_logger does the same on the
+ # web path.
+ logger.enable("local_deep_research")
+ # The same patcher config_logger installs. Without it a query containing a
+ # newline splits one WARNING into two stderr lines, and queries reach the
+ # log verbatim (query[:80] in the citation-handler warnings). loguru holds
+ # one patcher per process, so this has to be set here rather than
+ # inherited.
+ logger.configure(patcher=sanitize_log_record)
# diagnose=False: loguru's default is True, which renders repr() of every
# local in every traceback frame on exception. The many logger.exception()
# call sites in this file run with frame locals that hold credentials
@@ -1034,11 +1049,16 @@ def run_server():
# failure. Companion to #4185 / config_logger's LDR_LOGURU_DIAGNOSE gate;
# the MCP subprocess has no debug mode, so the gate is unconditionally off.
logger.add(
- sys.stderr,
+ sink if sink is not None else sys.stderr,
level="INFO",
format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} | {message}",
diagnose=False,
)
+
+
+def run_server():
+ """Run the MCP server using STDIO transport."""
+ configure_mcp_logging()
logger.info("Starting Local Deep Research MCP server...")
# Phase-1 of the RAG plaintext-at-rest migration must run here too, not only
diff --git a/src/local_deep_research/security/log_sanitizer.py b/src/local_deep_research/security/log_sanitizer.py
index 0857ae35cf..182fd42d35 100644
--- a/src/local_deep_research/security/log_sanitizer.py
+++ b/src/local_deep_research/security/log_sanitizer.py
@@ -54,6 +54,17 @@ def strip_control_chars(value: str) -> str:
return _UNSAFE_CHAR_RE.sub("", value)
+def sanitize_log_record(record) -> None:
+ """loguru patcher stripping control characters from a record's message.
+
+ loguru holds one patcher per process, so every process that builds its own
+ sink installs this itself. Shared from here rather than from ``log_utils``
+ because that module imports the web stack at module scope, and the MCP
+ subprocess does not.
+ """
+ record["message"] = strip_control_chars(record["message"])
+
+
def sanitize_for_log(value: str, max_length: int = 50) -> str:
"""Return a log-safe version of *value*.
diff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.py
index 3f6421e37e..d9438ef1ce 100644
--- a/src/local_deep_research/utilities/log_utils.py
+++ b/src/local_deep_research/utilities/log_utils.py
@@ -795,12 +795,9 @@ def config_logger(name: str, debug: bool = False) -> None:
debug: Whether to enable unsafe debug logging.
"""
- from ..security.log_sanitizer import strip_control_chars
+ from ..security.log_sanitizer import sanitize_log_record
- def _sanitize_record(record):
- record["message"] = strip_control_chars(record["message"])
-
- logger.configure(patcher=_sanitize_record)
+ logger.configure(patcher=sanitize_log_record)
logger.enable("local_deep_research")
logger.remove()
diff --git a/tests/mcp/test_stderr_control_chars.py b/tests/mcp/test_stderr_control_chars.py
new file mode 100644
index 0000000000..100f05281f
--- /dev/null
+++ b/tests/mcp/test_stderr_control_chars.py
@@ -0,0 +1,102 @@
+"""The MCP stderr sink emits package logs, with control characters stripped.
+
+A research query reaches the MCP log verbatim (query[:80] in the
+citation-handler warnings), so a query containing a newline used to split one
+WARNING into two stderr lines. The web path has stripped control characters
+since config_logger grew its patcher; the MCP subprocess builds its own sink
+and did not.
+
+``local_deep_research/__init__.py`` disables the package's own loguru
+namespace, and only ``config_logger`` re-enabled it, so the MCP sink also has
+to enable it or it sees nothing the package logs.
+"""
+
+import io
+import sys
+from contextlib import contextmanager
+
+import pytest
+from loguru import logger
+
+from local_deep_research.mcp.server import configure_mcp_logging
+from local_deep_research.utilities.url_utils import (
+ is_safe_custom_llm_endpoint,
+)
+
+
+@contextmanager
+def _restored_logger():
+ """Undo what ``configure_mcp_logging`` does to the process-wide logger.
+
+ ``logger.configure(patcher=None)`` does not clear a patcher: None means
+ "leave unchanged", so the patcher would leak into the rest of the pytest
+ worker. The namespace activation and the handlers are process-wide for the
+ same reason, so all three are snapshotted off ``logger._core`` and put back.
+ """
+ core = logger._core
+ saved = (
+ core.patcher,
+ core.enabled.copy(),
+ list(core.activation_list),
+ core.activation_none,
+ )
+ try:
+ yield
+ finally:
+ logger.remove()
+ (
+ core.patcher,
+ core.enabled,
+ core.activation_list,
+ core.activation_none,
+ ) = saved
+ # configure_mcp_logging removed loguru's default stderr handler.
+ logger.add(sys.stderr)
+
+
+def emit():
+ """Emit through a real MCP sink and return what it wrote."""
+ with _restored_logger():
+ sink = io.StringIO()
+ configure_mcp_logging(sink=sink)
+
+ def _emit(call):
+ call()
+ return sink.getvalue()
+
+ yield _emit
+
+
+def test_a_newline_in_the_message_does_not_start_a_second_line(emit):
+ out = emit(
+ lambda: logger.warning(
+ "Citation handler failed (query 'a\nWARNING | forged')"
+ )
+ )
+ assert out.count("\n") == 1, out
+ assert "forged" in out
+
+
+def test_carriage_return_and_escape_are_stripped(emit):
+ out = emit(lambda: logger.warning("query 'a\rb\x1b[31mRED'"))
+ assert "\r" not in out
+ assert "\x1b" not in out
+ assert "RED" in out
+
+
+def test_an_ordinary_message_is_unchanged(emit):
+ out = emit(
+ lambda: logger.warning("Starting Local Deep Research MCP server...")
+ )
+ assert "Starting Local Deep Research MCP server..." in out
+
+
+def test_a_log_call_inside_the_package_reaches_the_sink(emit):
+ """The tests above log from the test module, which the package's own
+ ``logger.disable`` does not cover. Everything the MCP server actually
+ logs comes from inside ``local_deep_research``."""
+ out = emit(lambda: is_safe_custom_llm_endpoint(123))
+
+ assert "rejected non-string custom_endpoint" in out
+ assert "local_deep_research.utilities.url_utils" in out