~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): arm egress audit net for direct MCP searches; fix library engine settings reads (#4517)
LearningCircuitd02cd3917f6c
diff --git a/src/local_deep_research/mcp/server.py b/src/local_deep_research/mcp/server.pyindex 8fdf4345ab..4b209e70ac 100644--- a/src/local_deep_research/mcp/server.py+++ b/src/local_deep_research/mcp/server.py@@ -685,6 +685,53 @@ def search(}+def _egress_audit_net(settings: Dict[str, Any]):+ """Best-effort context manager that arms the egress audit-hook net for+ a direct MCP search.++ Direct MCP searches call ``engine.run()`` without going through+ ``AdvancedSearchSystem`` (which arms the net itself), so under+ PRIVATE_ONLY/STRICT the socket-level backstop would otherwise stay+ inactive for this path. Returns a nullcontext when the policy cannot+ be built or a context is already armed — the factory PEP remains the+ primary enforcement, and an unevaluable policy must not break MCP.+ """+ from contextlib import nullcontext++ try:+ from local_deep_research.security.egress.audit_hook import (+ active_egress_context,+ get_active_context,+ )+ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ context_from_snapshot,+ )+ except Exception:+ return nullcontext()++ if not settings or get_active_context() is not None:+ return nullcontext()+ try:+ primary = settings.get("search.tool", "auto")+ if isinstance(primary, dict) and "value" in primary:+ primary = primary["value"]+ ctx = context_from_snapshot(+ settings,+ primary or "auto",+ username=settings.get("_username"),+ )+ except (PolicyDeniedError, ValueError):+ logger.bind(policy_audit=True).debug(+ "egress audit net not armed for MCP search: policy unevaluable",+ exc_info=True,+ )+ return nullcontext()+ except Exception:+ return nullcontext()+ return active_egress_context(ctx)++def _execute_search(query: str, engine: str, max_results: int, settings: Dict[str, Any]) -> Dict[str, Any]:@@ -712,8 +759,10 @@ def _execute_search(}try:- # Execute search- results = search_engine.run(query)+ # Execute search with the egress audit-hook net armed (no-op+ # under scopes that don't arm it or when policy is unavailable).+ with _egress_audit_net(settings):+ results = search_engine.run(query)# Normalize results: ensure consistent 'snippet' keyfor result in results:diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_library.py b/src/local_deep_research/web_search_engines/engines/search_engine_library.pyindex 3c3fafce6d..69b553fc45 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_library.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_library.py@@ -62,22 +62,31 @@ class LibraryRAGSearchEngine(BaseSearchEngine):"Library RAG search engine initialized without username")- # Get RAG configuration from settings+ # Get RAG configuration from settings. NB: keyword arguments — the+ # signature is (key, default, username, settings_snapshot); these+ # calls used to pass (key, settings_snapshot, default) positionally,+ # so the snapshot was never consulted and, outside a thread settings+ # context, each setting silently resolved to the snapshot DICT+ # itself (the misplaced "default").self.embedding_model = get_setting_from_snapshot("local_search_embedding_model",- settings_snapshot,- "all-MiniLM-L6-v2",+ default="all-MiniLM-L6-v2",+ settings_snapshot=settings_snapshot,)self.embedding_provider = get_setting_from_snapshot("local_search_embedding_provider",- settings_snapshot,- "sentence_transformers",+ default="sentence_transformers",+ settings_snapshot=settings_snapshot,)self.chunk_size = get_setting_from_snapshot(- "local_search_chunk_size", settings_snapshot, 1000+ "local_search_chunk_size",+ default=1000,+ settings_snapshot=settings_snapshot,)self.chunk_overlap = get_setting_from_snapshot(- "local_search_chunk_overlap", settings_snapshot, 200+ "local_search_chunk_overlap",+ default=200,+ settings_snapshot=settings_snapshot,)# Extract server URL from settings snapshot for link generation@@ -270,8 +279,8 @@ class LibraryRAGSearchEngine(BaseSearchEngine):library_root = get_setting_from_snapshot("research_library.storage_path",- self.settings_snapshot,- str(get_library_directory()),+ default=str(get_library_directory()),+ settings_snapshot=self.settings_snapshot,)library_root = (Path(os.path.expandvars(library_root))diff --git a/tests/mcp/test_egress_audit_net.py b/tests/mcp/test_egress_audit_net.pynew file mode 100644index 0000000000..39af26b40c--- /dev/null+++ b/tests/mcp/test_egress_audit_net.py@@ -0,0 +1,75 @@+"""Tests for the MCP direct-search egress audit net.++Direct MCP searches call ``engine.run()`` without going through+``AdvancedSearchSystem`` (which arms the audit-hook net itself), so+``_execute_search`` arms the net via ``_egress_audit_net``.+"""++import pytest++from local_deep_research.security.egress.audit_hook import (+ active_egress_context,+ get_active_context,+)+from local_deep_research.security.egress.policy import (+ EgressScope,+ context_from_snapshot,+)++try:+ import mcp # noqa: F401++ MCP_AVAILABLE = True+except ImportError:+ MCP_AVAILABLE = False++pytestmark = pytest.mark.skipif(+ not MCP_AVAILABLE, reason="MCP package not installed"+)++if MCP_AVAILABLE:+ from local_deep_research.mcp.server import _egress_audit_net+++def test_arms_context_for_private_only():+ settings = {+ "policy.egress_scope": {"value": "private_only"},+ "search.tool": {"value": "library"},+ "_username": "tester",+ }+ assert get_active_context() is None+ with _egress_audit_net(settings):+ ctx = get_active_context()+ assert ctx is not None+ assert ctx.scope == EgressScope.PRIVATE_ONLY+ assert ctx.username == "tester"+ assert get_active_context() is None+++def test_empty_settings_is_noop():+ with _egress_audit_net({}):+ assert get_active_context() is None+++def test_already_armed_context_is_kept():+ """When a caller already armed a context (web research worker), the+ MCP net must not replace it."""+ outer = context_from_snapshot(+ {"policy.egress_scope": {"value": "both"}}, "auto"+ )+ with active_egress_context(outer):+ with _egress_audit_net(+ {+ "policy.egress_scope": {"value": "private_only"},+ "search.tool": {"value": "library"},+ }+ ):+ assert get_active_context() is outer+++def test_unevaluable_policy_is_noop():+ """A corrupted scope must not break MCP search — the net simply stays+ unarmed (the factory PEP remains the primary enforcement)."""+ settings = {"policy.egress_scope": {"value": "garbage_scope"}}+ with _egress_audit_net(settings):+ assert get_active_context() is Nonediff --git a/tests/web_search_engines/engines/test_local_search_coverage.py b/tests/web_search_engines/engines/test_local_search_coverage.pyindex 3a425f30ee..16c1e91210 100644--- a/tests/web_search_engines/engines/test_local_search_coverage.py+++ b/tests/web_search_engines/engines/test_local_search_coverage.py@@ -90,7 +90,7 @@ class TestInitConfiguration:LibraryRAGSearchEngine,)- def side_effect(key, snapshot, default):+ def side_effect(key, default=None, **kwargs):mapping = {"local_search_embedding_model": "custom-model","local_search_embedding_provider": "openai",diff --git a/tests/web_search_engines/engines/test_search_engine_library.py b/tests/web_search_engines/engines/test_search_engine_library.pyindex eaf6c8ee9a..b07f106dab 100644--- a/tests/web_search_engines/engines/test_search_engine_library.py+++ b/tests/web_search_engines/engines/test_search_engine_library.py@@ -45,7 +45,7 @@ class TestLibraryRAGSearchEngineInit:with patch("local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot") as mock_get_setting:- mock_get_setting.side_effect = lambda key, snapshot, default: {+ mock_get_setting.side_effect = lambda key, default=None, **kwargs: {"local_search_embedding_model": "all-MiniLM-L6-v2","local_search_embedding_provider": "sentence_transformers","local_search_chunk_size": 1000,diff --git a/tests/web_search_engines/test_search_engine_library_settings.py b/tests/web_search_engines/test_search_engine_library_settings.pynew file mode 100644index 0000000000..17ed1d9a12--- /dev/null+++ b/tests/web_search_engines/test_search_engine_library_settings.py@@ -0,0 +1,36 @@+"""Regression tests: LibraryRAGSearchEngine must read its RAG settings+from the provided ``settings_snapshot``.++The constructor used to pass ``(key, settings_snapshot, default)``+positionally into ``get_setting_from_snapshot(key, default, username,+settings_snapshot)``, so the snapshot landed in the ``default`` slot and+was never consulted: outside a thread settings context each setting+silently resolved to the snapshot DICT itself.+"""++from local_deep_research.web_search_engines.engines.search_engine_library import (+ LibraryRAGSearchEngine,+)+++def test_snapshot_values_are_honored():+ snap = {+ "_username": "tester",+ "local_search_embedding_model": "custom-model",+ "local_search_embedding_provider": "ollama",+ "local_search_chunk_size": 512,+ "local_search_chunk_overlap": 64,+ }+ eng = LibraryRAGSearchEngine(settings_snapshot=snap)+ assert eng.embedding_model == "custom-model"+ assert eng.embedding_provider == "ollama"+ assert eng.chunk_size == 512+ assert eng.chunk_overlap == 64+++def test_defaults_used_when_keys_missing():+ eng = LibraryRAGSearchEngine(settings_snapshot={"_username": "tester"})+ assert eng.embedding_model == "all-MiniLM-L6-v2"+ assert eng.embedding_provider == "sentence_transformers"+ assert eng.chunk_size == 1000+ assert eng.chunk_overlap == 200