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.

feat: give MCP agent control over sub-research iterations and search engine (#3067)

LearningCircuit86898fb071d1
diff --git a/docs/mcp-server.md b/docs/mcp-server.md
index e7d9681893..c66c4ea735 100644
--- a/docs/mcp-server.md
+++ b/docs/mcp-server.md
@@ -379,9 +379,7 @@ The ReAct loop follows this pattern:
- `web_search` — Quick web search using the default engine
**Deep research (sub-strategies, bounded by `max_depth=2`):**
-- `focused_research` — Iterative deep analysis from multiple angles
-- `source_research` — Prioritizes authoritative sources
-- `quick_research` — Fast multi-iteration search
+- `focused_research` — Iterative deep analysis from multiple angles. Supports optional `iterations` (1-25) and `search_engine` override parameters.
**Specialized search engines:**
- `search_{engine}` — Specialized engine search (e.g., `search_arxiv`, `search_wikipedia`, `search_pubmed`, `search_github`)
diff --git a/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py b/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py
index a25a470827..0fababeeb1 100644
--- a/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py
@@ -27,87 +27,65 @@ from .base_strategy import BaseSearchStrategy
# ReAct prompt template - simplified for better model compatibility
# Note: {current_date} placeholder is replaced at runtime
-REACT_SYSTEM_PROMPT = """You are a research assistant. You MUST search for information before answering.
+REACT_SYSTEM_PROMPT = """You are a research assistant. Today's date: {current_date}
-Today's date: {current_date}
+You MUST search before answering. Do NOT answer from memory. Do NOT ask clarifying questions.
-CRITICAL: You MUST call at least one search tool BEFORE giving any ANSWER.
-- Do NOT answer from memory or prior knowledge
-- Do NOT ask clarifying questions - just search for the topic
-- If the query seems vague, search for it anyway and provide what you find
+## Tool Selection — pick the right tool for the domain:
-## Available Tools:
+| Domain | First step (quick) | Deep dive |
+|--------|-------------------|-----------|
+| Medical/biomedical | **search_pubmed** | focused_research with search_engine="pubmed" |
+| Scientific papers (physics, math, CS) | **search_arxiv** | focused_research with search_engine="arxiv" |
+| Academic papers (all fields) | **search_semantic_scholar** or **search_openalex** | focused_research with search_engine="semantic_scholar" |
+| Background knowledge | **search_wikipedia** | — |
+| Current news | **search_wikinews** or **web_search** | — |
+| General/mixed topics | **web_search** | focused_research |
-### General Search:
-- **web_search** - Quick web search using the default engine
+**Strategy**: Start with a quick direct search (web_search or search_[engine]) to learn about the topic. Only use focused_research after initial exploration — it runs many search rounds and is slow.
-### Deep Research (delegate to sub-strategies):
-- **focused_research** - Iterative deep analysis from multiple angles
-- **source_research** - Prioritizes authoritative sources
-- **quick_research** - Fast multi-iteration search
+## Tools:
-### Specialized Search Engines (examples — actual availability depends on configuration):
-- **search_arxiv** - Academic papers (physics, math, CS)
-- **search_wikipedia** - Encyclopedia/background info
-- **search_pubmed** - Medical/biomedical papers
-- **search_semantic_scholar** - Academic papers, citations
-- **search_github** - Code repositories and projects
-- And more based on your configuration...
+- **web_search** — General web search. You control the query — use exact phrases, date ranges, site filters.
+- **search_[engine]** — Single query against a specialized database (arxiv, pubmed, wikipedia, etc.). Fast and targeted.
+- **focused_research** — Deep iterative research with multiple automatic search rounds. Optional parameters:
+ - **iterations** (1-25): Search rounds. Default 8. Use 15-20+ for exhaustive research. More iterations = deeper.
+ - **search_engine**: Override which engine to use (e.g. "pubmed", "arxiv"). Powerful for domain-specific deep dives.
+- **download_content** — Fetch full text from a URL (papers, articles, web pages).
-### Content Download:
-- **download_content** - Get full text from a URL (papers, articles, web pages)
+## Response format:
-## How to respond:
+THOUGHT: [your reasoning]
+ACTION: [tool_name]
+ARGUMENTS: {{"query": "search terms"}}
-To SEARCH (do this first):
-THOUGHT: I need to search for [topic]
-ACTION: web_search
-ARGUMENTS: {{"query": "your search terms here"}}
-
-To do DEEP RESEARCH on a subtopic:
-THOUGHT: This aspect needs deeper investigation
-ACTION: focused_research
-ARGUMENTS: {{"query": "specific question to investigate"}}
-
-To DOWNLOAD full content from a URL:
-THOUGHT: I need to read the full paper/article at this URL
-ACTION: download_content
-ARGUMENTS: {{"url": "https://arxiv.org/abs/2301.12345"}}
-
-To give FINAL ANSWER (only after searching):
-THOUGHT: Based on my searches, I found [summary]
-ANSWER: [Your answer here with citations like [1], [2], etc.]
-
-## Citations:
-- Search results are numbered [1], [2], [3], etc.
-- In your ANSWER, cite sources: "According to [1], solar power is..."
-- Reference multiple sources: "Research shows [1][3] that..."
+After searching, give your final answer:
+THOUGHT: [summary of what you found]
+ANSWER: [comprehensive answer citing sources as [1], [2], etc.]
## Example:
-User: What is the population of France?
-THOUGHT: I need to search for current population data for France.
-ACTION: web_search
-ARGUMENTS: {{"query": "France population 2024"}}
+THOUGHT: I need to find recent papers on protein folding.
+ACTION: search_arxiv
+ARGUMENTS: {{"query": "protein structure prediction diffusion models 2024"}}
+
+[Results: [1] AlphaFold3 paper, [2] RFdiffusion...]
-[After receiving results like [1] Wikipedia - France, [2] WorldBank...]
+THOUGHT: I found key papers. Let me search deeper on PubMed for clinical applications.
+ACTION: search_pubmed
+ARGUMENTS: {{"query": "protein structure prediction clinical applications"}}
-THOUGHT: I found population data from multiple sources.
-ANSWER: France has a population of approximately 68 million people [1]. According to recent census data [2], this makes it one of the most populous countries in Europe.
+[More results...]
-## When to use research tools:
-- **web_search**: Quick facts, simple queries, current events
-- **focused_research**: Complex topics needing iterative deep analysis
-- **source_research**: When source authority/credibility is important
-- **quick_research**: When you need a fast multi-iteration search across sources
-- **download_content**: When you need the full text of a paper/article, not just the snippet
+THOUGHT: I have enough information from both sources.
+ANSWER: Recent breakthroughs in protein structure prediction include... [1][2]. Clinical applications show... [3][4].
## Rules:
1. ALWAYS search before answering
2. Use THOUGHT: then ACTION: then ARGUMENTS: format
-3. Only give ANSWER: after you have search results
-4. ALWAYS cite sources using [1], [2], etc. in your answer
-5. Use focused/source/quick_research for complex subtopics
+3. Cite sources as [1], [2], etc. in your ANSWER
+4. Start with quick searches, escalate to focused_research only if needed
+5. Match the search engine to the domain (arxiv for science, pubmed for medical, etc.)
"""
@@ -140,10 +118,16 @@ class MCPSearchStrategy(BaseSearchStrategy):
"""
# -- Content limits --
- OBSERVATION_MAX_LENGTH = 5000
+ # NOTE: The MCP/agentic strategy is designed for large-context LLMs (32k+).
+ # These high limits ensure the agent sees full sub-research output for better
+ # synthesis. For small-context models (4k-8k), use focused-iteration or
+ # source-based strategies instead — they don't accumulate history this way.
+ OBSERVATION_MAX_LENGTH = 50000 # Max chars kept from a single tool result
MAX_ARG_LENGTH = 10000
DOWNLOAD_DEFAULT_MAX_LENGTH = 10000
- HISTORY_OBSERVATION_MAX_LENGTH = 1000
+ HISTORY_OBSERVATION_MAX_LENGTH = (
+ 10000 # Max chars per observation in LLM prompt history
+ )
DIRECT_ANSWER_MIN_LENGTH = 300
# -- Display limits --
@@ -585,60 +569,36 @@ class MCPSearchStrategy(BaseSearchStrategy):
f"Sub-research check: enabled={self.include_sub_research}, depth={self.depth}, max_depth={self.max_depth}"
)
if self.include_sub_research and self.depth < self.max_depth:
- # Focused iteration - good for complex queries needing multiple angles
+ _sub_research_params = {
+ "query": {
+ "type": "string",
+ "description": "The specific research question to investigate",
+ "required": True,
+ },
+ "iterations": {
+ "type": "integer",
+ "description": "Number of search iterations (1-25). More iterations = deeper research. Use 3-5 for quick checks, 10-15 for thorough, 20+ for exhaustive. Prefer more iterations over broader queries.",
+ "required": False,
+ },
+ "search_engine": {
+ "type": "string",
+ "description": "Override the search engine for this research (e.g. 'arxiv', 'pubmed', 'wikipedia', 'searxng'). By default uses the main configured engine.",
+ "required": False,
+ },
+ }
+
+ # Focused iteration - deep iterative research
tools.append(
{
"name": "focused_research",
- "description": "Deep focused research using iterative refinement. Best for complex topics that need multiple search angles and thorough analysis. Takes longer but provides comprehensive results with proper citations.",
- "parameters": {
- "query": {
- "type": "string",
- "description": "The specific research question to investigate",
- "required": True,
- }
- },
+ "description": "Deep iterative research that runs multiple search rounds automatically. Best for complex topics needing thorough investigation. Use 'search_engine' to target specific databases (e.g. 'pubmed' for medical, 'arxiv' for scientific). Use 'iterations' to control depth — default 8, but 15-20+ is better for exhaustive research.",
+ "parameters": _sub_research_params,
"executor": lambda args: self._execute_strategy_research(
args, "focused-iteration"
),
}
)
- # Source-based - good for finding authoritative sources
- tools.append(
- {
- "name": "source_research",
- "description": "Source-focused research that prioritizes finding and extracting from authoritative sources. Best for factual queries where source credibility matters.",
- "parameters": {
- "query": {
- "type": "string",
- "description": "The specific research question to investigate",
- "required": True,
- }
- },
- "executor": lambda args: self._execute_strategy_research(
- args, "source-based"
- ),
- }
- )
-
- # Standard iteration - quick multi-iteration search
- tools.append(
- {
- "name": "quick_research",
- "description": "Quick iterative research with multiple search rounds. Faster than focused_research but still thorough.",
- "parameters": {
- "query": {
- "type": "string",
- "description": "The specific research question to investigate",
- "required": True,
- }
- },
- "executor": lambda args: self._execute_strategy_research(
- args, "standard"
- ),
- }
- )
-
# Add specialized search engine tools dynamically from available engines
available_engines = self._get_available_search_engines()
for engine_name, engine_config in available_engines.items():
@@ -1250,6 +1210,10 @@ class MCPSearchStrategy(BaseSearchStrategy):
This delegates to other research strategies (focused-iteration,
source-based, comprehensive) for deeper investigation.
+
+ The agent can control sub-research via optional arguments:
+ - iterations: number of search rounds (1-25)
+ - search_engine: override the search engine (e.g. "pubmed", "arxiv")
"""
sub_query = arguments.get("query", "")
if not sub_query:
@@ -1262,13 +1226,69 @@ class MCPSearchStrategy(BaseSearchStrategy):
"content": f"Maximum research depth ({self.max_depth}) reached",
}
+ # Extract optional parameters from agent arguments
+ iterations = arguments.get("iterations")
+ search_engine_name = arguments.get("search_engine")
+
+ # Clamp iterations to safe range
+ if iterations is not None:
+ try:
+ iterations = max(1, min(25, int(iterations)))
+ except (ValueError, TypeError):
+ iterations = None
+
try:
- logger.info(
- f"Delegating to {strategy_name} strategy: {sub_query[:100]}"
+ # Import factory to create strategy
+ from local_deep_research.search_system_factory import (
+ create_strategy,
)
+ # Resolve the search engine override if requested
+ search_instance = self.search
+ actual_engine_name = None
+ if search_engine_name:
+ try:
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ override_engine = create_search_engine(
+ engine_name=search_engine_name,
+ llm=self.model,
+ settings_snapshot=self.settings_snapshot,
+ )
+ if override_engine:
+ search_instance = override_engine
+ actual_engine_name = search_engine_name
+ logger.info(
+ f"Sub-research using overridden engine: {search_engine_name}"
+ )
+ else:
+ logger.warning(
+ f"Could not create engine '{search_engine_name}', "
+ f"falling back to default"
+ )
+ except Exception as e:
+ logger.warning(
+ f"Failed to create engine '{search_engine_name}': {e}, "
+ f"falling back to default"
+ )
+
+ # Log and emit progress after engine resolution so we report the actual engine
+ info_parts = [
+ f"Delegating to {strategy_name} strategy: {sub_query[:100]}"
+ ]
+ if iterations:
+ info_parts.append(f"iterations={iterations}")
+ if actual_engine_name:
+ info_parts.append(f"engine={actual_engine_name}")
+ logger.info(", ".join(info_parts))
+
+ progress_msg = f"DELEGATING to {strategy_name}: {sub_query[:80]}..."
+ if actual_engine_name:
+ progress_msg += f" (using {actual_engine_name})"
self._update_progress(
- f"DELEGATING to {strategy_name}: {sub_query[:80]}...",
+ progress_msg,
50,
{
"phase": "sub_research",
@@ -1278,20 +1298,22 @@ class MCPSearchStrategy(BaseSearchStrategy):
},
)
- # Import factory to create strategy
- from local_deep_research.search_system_factory import (
- create_strategy,
- )
+ # Build kwargs for the strategy factory
+ strategy_kwargs: Dict[str, Any] = {
+ "depth": self.depth + 1,
+ "max_depth": self.max_depth,
+ }
+ if iterations is not None:
+ strategy_kwargs["max_iterations"] = iterations
# Create the delegated strategy with incremented depth
child_strategy = create_strategy(
strategy_name=strategy_name,
model=self.model,
- search=self.search,
+ search=search_instance,
all_links_of_system=self.all_links_of_system,
settings_snapshot=self.settings_snapshot,
- depth=self.depth + 1,
- max_depth=self.max_depth,
+ **strategy_kwargs,
)
# Run the research
@@ -1360,6 +1382,23 @@ class MCPSearchStrategy(BaseSearchStrategy):
"status": "error",
"content": f"{strategy_name} research failed: {e}",
}
+ finally:
+ # Close the overridden engine if we created one
+ if search_engine_name and search_instance is not self.search:
+ try:
+ from local_deep_research.utilities.resource_utils import (
+ safe_close,
+ )
+
+ safe_close(
+ search_instance,
+ f"sub-research engine ({search_engine_name})",
+ )
+ except Exception:
+ logger.debug(
+ f"Failed to close sub-research engine {search_engine_name}",
+ exc_info=True,
+ )
def _get_available_search_engines(self) -> Dict[str, Any]:
"""Get search engines that are actually usable (enabled for auto-search
diff --git a/src/local_deep_research/defaults/settings_openalex.json b/src/local_deep_research/defaults/settings_openalex.json
index 2045f88076..15ac154622 100644
--- a/src/local_deep_research/defaults/settings_openalex.json
+++ b/src/local_deep_research/defaults/settings_openalex.json
@@ -227,5 +227,19 @@
"real-time information"
],
"visible": true
+ },
+ "search.engine.web.openalex.use_in_auto_search": {
+ "category": "openalex",
+ "description": "Include OpenAlex in auto search mode",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Include in Auto Search",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
}
}
diff --git a/src/local_deep_research/defaults/settings_semantic_scholar.json b/src/local_deep_research/defaults/settings_semantic_scholar.json
index 1f827dfd3a..63d21b9bdc 100644
--- a/src/local_deep_research/defaults/settings_semantic_scholar.json
+++ b/src/local_deep_research/defaults/settings_semantic_scholar.json
@@ -241,5 +241,19 @@
"newer papers may be missing"
],
"visible": true
+ },
+ "search.engine.web.semantic_scholar.use_in_auto_search": {
+ "category": "semantic_scholar",
+ "description": "Include Semantic Scholar in auto search mode",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Include in Auto Search",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
}
}
diff --git a/tests/mcp/test_mcp_strategy.py b/tests/mcp/test_mcp_strategy.py
index c3daed52b5..23616af20d 100644
--- a/tests/mcp/test_mcp_strategy.py
+++ b/tests/mcp/test_mcp_strategy.py
@@ -506,14 +506,10 @@ ANSWER: The answer based on research."""
# Strategy still has research tools available (sub-research and download_content)
# When include_sub_research=True (default) and depth < max_depth:
- # - focused_research, source_research, quick_research, download_content
+ # - focused_research, download_content
tools = strategy._build_tool_descriptions()
- assert (
- len(tools) >= 4
- ) # focused_research, source_research, quick_research, download_content
+ assert len(tools) >= 2 # focused_research, download_content
assert any(t["name"] == "focused_research" for t in tools)
- assert any(t["name"] == "source_research" for t in tools)
- assert any(t["name"] == "quick_research" for t in tools)
assert any(t["name"] == "download_content" for t in tools)
def test_analyze_topic_llm_error_recovery(self):
@@ -911,6 +907,246 @@ ANSWER: The answer is here."""
assert result["current_knowledge"] # Should not be empty
+class TestSubResearchParameters:
+ """Tests for iterations and search_engine parameters in _execute_strategy_research."""
+
+ def _make_strategy(self, **kwargs):
+ from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
+ MCPSearchStrategy,
+ )
+
+ return MCPSearchStrategy(
+ model=MagicMock(),
+ search=MagicMock(),
+ include_sub_research=True,
+ **kwargs,
+ )
+
+ def _mock_child_result(self):
+ return {
+ "findings": [],
+ "sources": [],
+ "formatted_findings": "test result",
+ "current_knowledge": "test",
+ }
+
+ def test_iterations_forwarded_to_create_strategy(self):
+ """iterations parameter is passed as max_iterations to create_strategy."""
+ strategy = self._make_strategy()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_child = MagicMock()
+ mock_child.analyze_topic.return_value = self._mock_child_result()
+ mock_create.return_value = mock_child
+
+ strategy._execute_strategy_research(
+ {"query": "test", "iterations": 12}, "focused-iteration"
+ )
+
+ call_kwargs = mock_create.call_args[1]
+ assert call_kwargs["max_iterations"] == 12
+
+ def test_iterations_not_passed_when_absent(self):
+ """When iterations is not provided, max_iterations is not passed."""
+ strategy = self._make_strategy()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_child = MagicMock()
+ mock_child.analyze_topic.return_value = self._mock_child_result()
+ mock_create.return_value = mock_child
+
+ strategy._execute_strategy_research(
+ {"query": "test"}, "focused-iteration"
+ )
+
+ call_kwargs = mock_create.call_args[1]
+ assert "max_iterations" not in call_kwargs
+
+ def test_iterations_clamped_to_min_1(self):
+ """iterations=0 and negative values are clamped to 1."""
+ strategy = self._make_strategy()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_child = MagicMock()
+ mock_child.analyze_topic.return_value = self._mock_child_result()
+ mock_create.return_value = mock_child
+
+ strategy._execute_strategy_research(
+ {"query": "test", "iterations": -5}, "focused-iteration"
+ )
+ assert mock_create.call_args[1]["max_iterations"] == 1
+
+ def test_iterations_clamped_to_max_25(self):
+ """iterations above 25 are clamped to 25."""
+ strategy = self._make_strategy()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_child = MagicMock()
+ mock_child.analyze_topic.return_value = self._mock_child_result()
+ mock_create.return_value = mock_child
+
+ strategy._execute_strategy_research(
+ {"query": "test", "iterations": 100}, "focused-iteration"
+ )
+ assert mock_create.call_args[1]["max_iterations"] == 25
+
+ def test_iterations_invalid_string_ignored(self):
+ """Non-numeric iterations string falls back to default (not passed)."""
+ strategy = self._make_strategy()
+
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create:
+ mock_child = MagicMock()
+ mock_child.analyze_topic.return_value = self._mock_child_result()
+ mock_create.return_value = mock_child
+
+ strategy._execute_strategy_research(
+ {"query": "test", "iterations": "abc"}, "focused-iteration"
+ )
+ assert "max_iterations" not in mock_create.call_args[1]
+
+ def test_search_engine_override_passed_to_child(self):
+ """search_engine parameter creates override engine for the child strategy."""
+ strategy = self._make_strategy()
+
+ mock_override = MagicMock()
+ with (
+ patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine",
+ return_value=mock_override,
+ ),
+ ):
+ mock_child = MagicMock()
+ mock_child.analyze_topic.return_value = self._mock_child_result()
+ mock_create.return_value = mock_child
+
+ strategy._execute_strategy_research(
+ {"query": "test", "search_engine": "pubmed"},
+ "focused-iteration",
+ )
+
+ # Child strategy should get the override engine, not self.search
+ assert mock_create.call_args[1]["search"] is mock_override
+
+ def test_search_engine_invalid_falls_back_to_default(self):
+ """Invalid search_engine falls back to default engine."""
+ strategy = self._make_strategy()
+
+ with (
+ patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine",
+ return_value=None,
+ ),
+ ):
+ mock_child = MagicMock()
+ mock_child.analyze_topic.return_value = self._mock_child_result()
+ mock_create.return_value = mock_child
+
+ strategy._execute_strategy_research(
+ {"query": "test", "search_engine": "nonexistent"},
+ "focused-iteration",
+ )
+
+ # Should fall back to self.search
+ assert mock_create.call_args[1]["search"] is strategy.search
+
+ def test_search_engine_cleanup_on_success(self):
+ """Override engine is closed after successful sub-research."""
+ strategy = self._make_strategy()
+
+ mock_override = MagicMock()
+ with (
+ patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine",
+ return_value=mock_override,
+ ),
+ patch(
+ "local_deep_research.utilities.resource_utils.safe_close"
+ ) as mock_close,
+ ):
+ mock_child = MagicMock()
+ mock_child.analyze_topic.return_value = self._mock_child_result()
+ mock_create.return_value = mock_child
+
+ strategy._execute_strategy_research(
+ {"query": "test", "search_engine": "pubmed"},
+ "focused-iteration",
+ )
+
+ mock_close.assert_called_once_with(
+ mock_override, "sub-research engine (pubmed)"
+ )
+
+ def test_search_engine_cleanup_on_error(self):
+ """Override engine is closed even when sub-research raises."""
+ strategy = self._make_strategy()
+
+ mock_override = MagicMock()
+ with (
+ patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine",
+ return_value=mock_override,
+ ),
+ patch(
+ "local_deep_research.utilities.resource_utils.safe_close"
+ ) as mock_close,
+ ):
+ mock_create.side_effect = RuntimeError("strategy creation failed")
+
+ strategy._execute_strategy_research(
+ {"query": "test", "search_engine": "pubmed"},
+ "focused-iteration",
+ )
+
+ # Engine should still be cleaned up despite the error
+ mock_close.assert_called_once_with(
+ mock_override, "sub-research engine (pubmed)"
+ )
+
+ def test_no_cleanup_when_no_override(self):
+ """No cleanup when search_engine was not requested."""
+ strategy = self._make_strategy()
+
+ with (
+ patch(
+ "local_deep_research.search_system_factory.create_strategy"
+ ) as mock_create,
+ patch(
+ "local_deep_research.utilities.resource_utils.safe_close"
+ ) as mock_close,
+ ):
+ mock_child = MagicMock()
+ mock_child.analyze_topic.return_value = self._mock_child_result()
+ mock_create.return_value = mock_child
+
+ strategy._execute_strategy_research(
+ {"query": "test"}, "focused-iteration"
+ )
+
+ mock_close.assert_not_called()
+
+
class TestHighPriorityBugFixes:
"""Tests for high-priority bug fixes."""
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 7514214a68..0a15b60ce2 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -4069,6 +4069,20 @@
],
"visible": true
},
+ "search.engine.web.openalex.use_in_auto_search": {
+ "category": "openalex",
+ "description": "Include OpenAlex in auto search mode",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Include in Auto Search",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
"search.engine.web.openalex.weaknesses": {
"category": "openalex",
"description": "List of content types where OpenAlex has limited coverage",
@@ -5808,6 +5822,20 @@
],
"visible": true
},
+ "search.engine.web.semantic_scholar.use_in_auto_search": {
+ "category": "semantic_scholar",
+ "description": "Include Semantic Scholar in auto search mode",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Include in Auto Search",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
"search.engine.web.semantic_scholar.weaknesses": {
"category": "semantic_scholar",
"description": "Weaknesses of this search engine",