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!: remove the MCP (ReAct) search strategy (#4548) (#4567)

LearningCircuitf7af7afb33c5
diff --git a/.github/workflows/mcp-tests.yml b/.github/workflows/mcp-tests.yml
index 3537480c4f..6b25755d9f 100644
--- a/.github/workflows/mcp-tests.yml
+++ b/.github/workflows/mcp-tests.yml
@@ -5,7 +5,6 @@ on:
branches: [ main, dev ]
paths:
- 'src/local_deep_research/mcp/**'
- - 'src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py'
- 'tests/mcp/**'
- 'scripts/mcp_smoke_test.sh'
- '.github/workflows/mcp-tests.yml'
@@ -13,7 +12,6 @@ on:
branches: [ main, dev ]
paths:
- 'src/local_deep_research/mcp/**'
- - 'src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py'
- 'tests/mcp/**'
- 'scripts/mcp_smoke_test.sh'
- '.github/workflows/mcp-tests.yml'
@@ -74,15 +72,7 @@ jobs:
- name: Run MCP unit tests
if: steps.check-mcp.outputs.mcp_exists == 'true'
run: |
- pdm run pytest tests/mcp/ -v --tb=short -n auto \
- --ignore=tests/mcp/test_mcp_strategy.py
- env:
- LDR_TESTING_WITH_MOCKS: "true"
-
- - name: Run MCP strategy tests
- if: steps.check-mcp.outputs.mcp_exists == 'true'
- run: |
- pdm run pytest tests/mcp/test_mcp_strategy.py -v --tb=short -n auto
+ pdm run pytest tests/mcp/ -v --tb=short -n auto
env:
LDR_TESTING_WITH_MOCKS: "true"
@@ -109,7 +99,6 @@ jobs:
echo "- 🔌 MCP server module loading"
echo "- 🔧 Discovery tools (list_strategies, list_search_engines, get_configuration)"
echo "- 🧪 Unit tests for all MCP tools"
- echo "- 🤖 MCP strategy (ReAct pattern) tests"
echo "- 🚀 Server startup verification"
echo ""
echo "### MCP Tools Tested:"
diff --git a/changelog.d/4548.breaking.md b/changelog.d/4548.breaking.md
new file mode 100644
index 0000000000..a3f63dc933
--- /dev/null
+++ b/changelog.d/4548.breaking.md
@@ -0,0 +1 @@
+Removed the `mcp` / `agentic` (ReAct) search strategy. Existing selections are automatically migrated to `langgraph-agent` (a near functional superset); connecting to external MCP servers as research tool sources is no longer supported. (LDR still ships its own MCP **server** for exposing research to assistants like Claude — that is unaffected.)
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index e12694e852..fec18ff016 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -160,7 +160,6 @@ They are not available in the Web UI because they are needed to start the applic
| `local_search_normalize_vectors` | `LDR_LOCAL_SEARCH_NORMALIZE_VECTORS` | `true` | L2-normalize embedding vectors after generation. Recommended: ensures fair similarity comparison regardless of source document length. Some embedding models already produce normalized output; in that case this is a no-op. | APP |
| `local_search_splitter_type` | `LDR_LOCAL_SEARCH_SPLITTER_TYPE` | `recursive` | How to divide documents into chunks. Recursive uses natural breaks (paragraphs, sentences). Token-based respects model context limits. Sentence-based produces clean sentence boundaries. Semantic uses an embedding model to group related content (smarter but slower). | APP |
| `local_search_text_separators` | `LDR_LOCAL_SEARCH_TEXT_SEPARATORS` | ``["\n\n", "\n", ". ", " ", ""]`` | JSON array of separator strings tried in order by the recursive splitter. The default works for general prose. For code, add language-specific separators like "\nclass", "\ndef". | APP |
-| `mcp.servers` | `LDR_MCP_SERVERS` | ``[]`` | List of external MCP servers to connect to. Each entry should have 'command' (required), and optionally 'name', 'args', and 'env'. Allowed commands: node, npx, python, python3, uv, uvx, docker. See <a href="https://github.com/LearningCircuit/local-deep-research/blob/main/docs/mcp-server.md#mcp-client-connecting-external-mcp-servers" target="_blank">MCP Client documentation</a> for details. | APP |
| `news.display.default_headline_max_length` | `LDR_NEWS_DISPLAY_DEFAULT_HEADLINE_MAX_LENGTH` | `100` | Default maximum headline length | APP |
| `news.display.max_query_length` | `LDR_NEWS_DISPLAY_MAX_QUERY_LENGTH` | `50` | Maximum query display length in UI | APP |
| `news.feed.default_limit` | `LDR_NEWS_FEED_DEFAULT_LIMIT` | `20` | Default number of news items returned per feed page. Applied when user does not specify a limit in the request. Also used as the default limit for subscription history. | APP |
@@ -553,7 +552,7 @@ They are not available in the Web UI because they are needed to start the applic
| `search.region` | `LDR_SEARCH_REGION` | `us` | Geographic region for search results localization. Affects which results are prioritized based on regional relevance. | SEARCH |
| `search.safe_search` | `LDR_SEARCH_SAFE_SEARCH` | `true` | Filter out adult and inappropriate content from search results. Passed to search engines that support content filtering. | SEARCH |
| `search.search_language` | `LDR_SEARCH_SEARCH_LANGUAGE` | `English` | Preferred language for search results. Search engines will attempt to return and prioritize results in this language when available. | SEARCH |
-| `search.search_strategy` | `LDR_SEARCH_SEARCH_STRATEGY` | `langgraph-agent` | Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'topic-organization': Organizes research around discovered topic clusters. 'mcp': Agentic ReAct-pattern research using MCP tools. 'langgraph-agent': Autonomous agentic research where the LLM decides what to search and when to synthesize. | SEARCH |
+| `search.search_strategy` | `LDR_SEARCH_SEARCH_STRATEGY` | `langgraph-agent` | Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'topic-organization': Organizes research around discovered topic clusters. 'langgraph-agent': Autonomous agentic research where the LLM decides what to search and when to synthesize. | SEARCH |
| `search.searches_per_section` | `LDR_SEARCH_SEARCHES_PER_SECTION` | `2` | Number of independent searches per report section when generating structured reports. Increases coverage but also increases API usage. | SEARCH |
| `search.skip_relevance_filter` | `LDR_SEARCH_SKIP_RELEVANCE_FILTER` | `true` | When checked, LLM-based relevance filtering is suppressed for general-purpose search engines that do not require it. Keyword-based engines (arXiv, PubMed, Wikipedia, GitHub, etc.) always run the filter regardless of this checkbox; per-engine settings override both. | SEARCH |
| `search.snippets_only` | `LDR_SEARCH_SNIPPETS_ONLY` | `true` | Only retrieve search snippets instead of full webpage content. Reduces API usage and processing time, but provides less context for analysis. | SEARCH |
diff --git a/docs/features.md b/docs/features.md
index 969c6c53ff..62fd93aaea 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -226,7 +226,7 @@ Use LDR as a research tool directly from Claude Desktop or other MCP-compatible
- 8 tools (5 research, 3 discovery) accessible via Model Context Protocol
- STDIO transport for secure local operation
- Per-call settings overrides
-- ReAct (agentic) strategy with dynamic tool selection
+- Autonomous agentic research (langgraph-agent strategy) with dynamic tool selection
- Document analysis with RAG pipeline
See [MCP Server Guide](mcp-server.md) for setup and usage.
diff --git a/docs/mcp-server.md b/docs/mcp-server.md
index 7fd7abb19e..1f741a6060 100644
--- a/docs/mcp-server.md
+++ b/docs/mcp-server.md
@@ -355,108 +355,10 @@ LDR supports the following research strategies via MCP:
| `focused-iteration` | Medium | Highest (~95%) | Complex factual / technical topics |
| `focused-iteration-standard` | Medium | High | Comprehensive long-form answers with citations |
| `topic-organization` | Medium | High | Structured output clustered by theme |
-| `mcp` (ReAct) | Varies | High | Multi-step reasoning, when AI decides approach |
| `langgraph-agent` | Varies | High | Autonomous agentic research across engines |
Use `list_strategies()` to see all available strategies and their descriptions.
-## ReAct (Agentic) Strategy
-
-The `mcp` strategy (also called "agentic") uses the ReAct pattern (Reasoning + Acting). Unlike fixed-pipeline strategies, the LLM decides what to do at each step.
-
-### How It Works
-
-The ReAct loop follows this pattern:
-
-1. **THOUGHT** — The LLM reasons about what it knows and what it needs
-2. **ACTION** — It selects a tool to call (e.g., `web_search`, `focused_research`)
-3. **OBSERVATION** — It receives the tool results (truncated to 5,000 chars)
-4. **Repeat** — Until the LLM has enough information to answer
-
-### Available Tools in the ReAct Agent
-
-**General search:**
-- `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. 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`)
-
-**Content fetching:**
-- `download_content` — Fetch full text from a URL (max 10,000 chars)
-
-**External MCP server tools:**
-- `{server_name}.{tool_name}` — Tools from connected external MCP servers (if configured)
-
-### Constants
-
-| Constant | Value |
-|----------|-------|
-| Max iterations | 10 |
-| Observation truncation | 5,000 chars |
-| Max argument length | 10,000 chars |
-| Download max length | 10,000 chars |
-| Recursion depth limit | 2 |
-| MCP discovery timeout | 30s |
-| MCP tool call timeout | 60s |
-
-### When to Use
-
-- Multi-step reasoning where different tools are needed at different stages
-- Queries that need a mix of web search, specialized engines, and deep research
-- Complex topics where the AI should dynamically decide the research approach
-
-## MCP Client (Connecting External MCP Servers)
-
-LDR can also act as an MCP **client**, connecting to external MCP servers and making their tools available to the ReAct strategy.
-
-### Configuration
-
-Configure external MCP servers via the `mcp.servers` setting. Each server needs:
-
-```json
-{
- "name": "my-server",
- "command": "node",
- "args": ["path/to/server.js"],
- "env": {
- "API_KEY": "..."
- }
-}
-```
-
-**Config schema:**
-
-| Field | Type | Required | Description |
-|-------|------|----------|-------------|
-| `name` | string | No | Server name for logging (default: "unnamed") |
-| `command` | string | Yes | Executable to run |
-| `args` | list[string] | No | Command arguments |
-| `env` | dict[string, string] | No | Environment variables |
-
-### Command Whitelist
-
-For security, only these commands are allowed:
-
-```
-node, npx, python, python3, uv, uvx, docker
-```
-
-Any other command will be rejected with an error.
-
-### Connection Details
-
-- **Transport:** STDIO (same as the LDR MCP server itself)
-- **Retry logic:** 5 attempts with exponential backoff (base 0.1s, max 2.0s, factor 2.0x)
-- **Graceful degradation:** Failed servers are skipped; tools from working servers remain available
-- **Timeouts:** 30s for tool discovery, 60s for tool calls
-
-### Tool Naming
-
-External MCP tools appear in the ReAct agent as `{server_name}.{tool_name}`. For example, a tool called `search` on a server named `my-server` becomes `my-server.search`.
-
## Error Handling
All tool calls return structured error responses when something goes wrong. Errors are classified into these categories:
diff --git a/docs/strategies/deleted/pr-remove-mcp-strategy.md b/docs/strategies/deleted/pr-remove-mcp-strategy.md
new file mode 100644
index 0000000000..8e49e89f87
--- /dev/null
+++ b/docs/strategies/deleted/pr-remove-mcp-strategy.md
@@ -0,0 +1,59 @@
+# PR — remove the MCP (ReAct) search strategy
+
+Component deleted in this PR (see the PR diff / `git show <sha>:<path>` for the
+full pre-deletion code — this file only summarises what was novel). Tracked by
+issue #4548.
+
+## Component: `MCPSearchStrategy`
+
+- Files deleted:
+ - `src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py`
+ (1876 LOC) — the strategy itself.
+ - `src/local_deep_research/mcp/client.py` (486 LOC) — the MCP **client**
+ (`MCPClient` / `MCPClientManager` / `run_async`), whose only consumer was
+ `MCPSearchStrategy`. `src/local_deep_research/mcp/server.py` (LDR-as-an-MCP-
+ **provider**, FastMCP) is unrelated and **survives**.
+- Reachability: factory keys `mcp` / `agentic` (`agentic` was a pure alias),
+ the `search.search_strategy` dropdown, and its own tests. Never the default
+ (the default is `langgraph-agent`). `mcp.servers` (default `[]`) was its only
+ setting.
+- Closest reachable successor: `LangGraphAgentStrategy`
+ (`advanced_search_system/strategies/langgraph_agent_strategy.py`, factory key
+ `langgraph-agent`). The factory now routes the `mcp` / `agentic` aliases to it
+ with a deprecation warning, and migration `0014` rewrites persisted
+ references.
+
+### Useful ideas from the pre-deletion version
+
+- **ReAct tool-calling loop over external MCP servers** — connected to
+ user-configured stdio MCP servers (`mcp.servers`), discovered their tools at
+ runtime, and let the LLM call them in a Reason+Act loop. This external-MCP-
+ server tool integration is the **genuinely unique capability**;
+ `langgraph-agent` only exposes LDR's own search engines as tools, not
+ arbitrary MCP servers. It is the one capability removal actually loses —
+ tracked as a follow-up to re-home it on `langgraph-agent` if demand appears.
+- **`focused_research`-as-a-tool** — exposed LDR's focused-iteration research as
+ a callable tool inside the agent loop. Not lost: `langgraph-agent`'s
+ `research_subtopic` tool already provides recursive sub-research (via parallel
+ subagents).
+- **`_mcp_scope_blocked` egress gating** — a fail-closed scope check that
+ blocked MCP tool discovery *and* execution under `STRICT` / `PRIVATE_ONLY`,
+ because MCP tools run in stdio subprocesses whose egress the PEP audit hook
+ cannot inspect. The same fail-closed pattern survives in
+ `notifications.manager` and `journal_reputation_filter`.
+
+### Why deletion was safe
+
+`langgraph-agent` (the default) is a near functional superset for agentic
+research over LDR's own engines — same specialized search tools, content fetch,
+parallel subagents, and egress filtering. The only capability genuinely lost is
+connecting to arbitrary external MCP servers as tool sources, which had an empty
+default (`mcp.servers = []`) and no benchmark/test fixtures exercising it. All
+scope-gating patterns survive in sibling modules.
+
+### Recovery path
+
+Do not restore the files. If external-MCP-server tool support is revived, add it
+as a tool-source adapter on `LangGraphAgentStrategy` (a dynamic MCP→LangChain
+tool adapter plus a port of the fail-closed `_mcp_scope_blocked` egress gate)
+rather than a parallel strategy + client.
diff --git a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
index e04bb87773..805e923675 100644
--- a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
+++ b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
@@ -360,9 +360,9 @@ class JournalReputationFilter(BaseFilter):
except PolicyDeniedError:
# Corrupt/unknown scope value — we cannot certify that a public
# journal fetch is permitted, so SKIP the fetch (fail closed).
- # This matches the hardened siblings mcp_strategy._mcp_scope_blocked
- # and notifications.manager._filter_urls_by_egress_policy, which
- # also refuse rather than proceed when the policy is unevaluable.
+ # This matches the hardened sibling
+ # notifications.manager._filter_urls_by_egress_policy, which also
+ # refuses rather than proceeds when the policy is unevaluable.
logger.bind(policy_audit=True).warning(
"journal fetch skipped: egress policy unevaluable "
"(corrupt scope) — failing closed"
diff --git a/src/local_deep_research/advanced_search_system/strategies/__init__.py b/src/local_deep_research/advanced_search_system/strategies/__init__.py
index 2dc3714f17..8485b50443 100644
--- a/src/local_deep_research/advanced_search_system/strategies/__init__.py
+++ b/src/local_deep_research/advanced_search_system/strategies/__init__.py
@@ -2,12 +2,10 @@
from .base_strategy import BaseSearchStrategy
from .focused_iteration_strategy import FocusedIterationStrategy
-from .mcp_strategy import MCPSearchStrategy
from .source_based_strategy import SourceBasedSearchStrategy
__all__ = [
"BaseSearchStrategy",
"FocusedIterationStrategy",
- "MCPSearchStrategy",
"SourceBasedSearchStrategy",
]
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
deleted file mode 100644
index 2493eac6be..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py
+++ /dev/null
@@ -1,1837 +0,0 @@
-"""
-MCP Strategy using ReAct pattern (Reasoning + Acting).
-
-This strategy makes LDR behave more like Claude - thinking about requests,
-calling tools (MCP and web search), analyzing results, and iterating
-until the query is properly answered.
-
-Unlike traditional strategies with fixed pipelines, the LLM decides
-what to do at each step based on what it has learned.
-"""
-
-import json
-import re
-from datetime import UTC, datetime
-from typing import Any, Dict, List, Optional
-
-from langchain_core.language_models import BaseChatModel
-from loguru import logger
-
-from ...utilities.type_utils import unwrap_setting
-from ...citation_handler import CitationHandler
-from ...utilities.json_utils import extract_json
-from .base_strategy import BaseSearchStrategy
-from ...constants import DEFAULT_SEARCH_TOOL
-
-# ReAct prompt template - simplified for better model compatibility
-# Note: {current_date} placeholder is replaced at runtime
-REACT_SYSTEM_PROMPT = """You are a research assistant. Today's date: {current_date}
-
-You MUST search before answering. Do NOT answer from memory. Do NOT ask clarifying questions.
-
-## Tool Selection — pick the right tool for the domain:
-
-| 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 |
-
-**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.
-
-## Tools:
-
-- **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).
-
-## Response format:
-
-THOUGHT: [your reasoning]
-ACTION: [tool_name]
-ARGUMENTS: {{"query": "search terms"}}
-
-After searching, give your final answer:
-THOUGHT: [summary of what you found]
-ANSWER: [comprehensive answer citing sources as [1], [2], etc.]
-
-## Example:
-
-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...]
-
-THOUGHT: I found key papers. Let me search deeper on PubMed for clinical applications.
-ACTION: search_pubmed
-ARGUMENTS: {{"query": "protein structure prediction clinical applications"}}
-
-[More results...]
-
-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. 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.)
-"""
-
-
-def _to_bool(value) -> bool:
- """Convert a value to bool, handling string 'false'/'0' from settings."""
- if isinstance(value, str):
- return value.strip().lower() not in ("false", "0", "no", "")
- return bool(value)
-
-
-REACT_USER_PROMPT = """## Query
-{query}
-
-## Available Tools
-{tool_descriptions}
-
-## Research History
-{history}
-
-## Your Turn
-Think about what you know and what you still need. Then either call a tool or provide your final answer."""
-
-
-class MCPSearchStrategy(BaseSearchStrategy):
- """
- Agentic research strategy using the ReAct pattern.
-
- The LLM thinks step-by-step, decides which tools to call,
- analyzes results, and continues until the query is answered.
- """
-
- # -- Content limits --
- # 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 = (
- 10000 # Max chars per observation in LLM prompt history
- )
- DIRECT_ANSWER_MIN_LENGTH = 300
-
- # -- Display limits --
- THOUGHT_PREVIEW_LENGTH = 200
- OBSERVATION_PREVIEW_LENGTH = 500
- RAW_RESPONSE_PREVIEW_LENGTH = 500
- ENGINE_STRENGTHS_DISPLAY_LIMIT = 2
- SOURCE_REFS_DISPLAY_LIMIT = 5
-
- # -- Timeouts --
- MCP_DISCOVERY_TIMEOUT = 30.0
- CONTENT_FETCHER_TIMEOUT = 30
- MCP_TOOL_CALL_TIMEOUT = 60.0
-
- def __init__(
- self,
- model: BaseChatModel,
- search: Any, # Search engine instance
- citation_handler=None,
- mcp_servers: Optional[List[Dict[str, Any]]] = None,
- max_iterations: int = 10,
- include_web_search: bool = True,
- include_sub_research: bool = True,
- depth: int = 0,
- max_depth: int = 2,
- all_links_of_system: Optional[List] = None,
- settings_snapshot: Optional[Dict] = None,
- **kwargs,
- ):
- """
- Initialize the MCP strategy.
-
- Args:
- model: Language model for reasoning and decisions
- search: Web search engine instance
- citation_handler: Citation handler for formatting sources
- mcp_servers: List of MCP server configurations
- max_iterations: Maximum ReAct iterations (safety limit)
- include_web_search: Whether to include web_search as a tool
- include_sub_research: Whether to include sub_research tool
- depth: Current recursion depth (0 = top level)
- max_depth: Maximum recursion depth for sub-research
- all_links_of_system: Shared links list
- settings_snapshot: Settings configuration
- """
- super().__init__(
- all_links_of_system=all_links_of_system,
- settings_snapshot=settings_snapshot,
- **kwargs,
- )
-
- self.model = model
- self.search = search
- self.mcp_servers = mcp_servers or []
- self.max_iterations = int(
- max_iterations
- ) # Ensure int (settings may pass string)
- self.include_web_search = _to_bool(include_web_search)
- self.include_sub_research = _to_bool(include_sub_research)
- self.depth = int(depth)
- self.max_depth = int(max_depth)
-
- # Citation handler for proper source formatting
- self.citation_handler = citation_handler or CitationHandler(
- self.model,
- handler_type="standard",
- settings_snapshot=settings_snapshot,
- )
-
- # Track reasoning history
- self._history: List[Dict[str, str]] = []
- self._sources: List[str] = []
- self._findings: List[Dict[str, Any]] = []
-
- # Track all search results for citation handling
- self.all_search_results: List[Dict[str, Any]] = []
-
- # Cache for MCP tools (avoid rediscovery on every call)
- self._mcp_tools_cache: Optional[List[Dict[str, Any]]] = None
-
- def analyze_topic(self, query: str) -> Dict:
- """
- Analyze a topic using the ReAct pattern.
-
- The LLM reasons about what to do, calls tools, observes results,
- and continues until it has enough information to answer.
-
- Args:
- query: The research query
-
- Returns:
- Dict with findings, sources, iterations, etc.
- """
- logger.info(f"Starting MCP ReAct research for: {query[:100]}...")
- self._update_progress(
- f'STARTING ReAct agent for: "{query[:80]}..."',
- 5,
- {"phase": "init", "type": "milestone", "query": query[:100]},
- )
-
- # Reset state
- self._history = []
- self._sources = []
- self._findings = []
- self.all_search_results = []
-
- # Build tool descriptions
- tools = self._build_tool_descriptions()
-
- if not tools:
- return self._create_error_response(
- "No tools available for research"
- )
-
- tool_descriptions = self._format_tool_descriptions(tools)
-
- # ReAct loop
- iteration = 0
- final_answer = None
-
- while iteration < self.max_iterations:
- iteration += 1
- progress = 10 + int((iteration / self.max_iterations) * 80)
-
- self._update_progress(
- f"CYCLE {iteration}/{self.max_iterations}: Agent is reasoning about what to do next...",
- progress,
- {
- "phase": "react",
- "iteration": iteration,
- "max": self.max_iterations,
- },
- )
-
- # Get LLM response
- try:
- response = self._get_llm_response(
- query, tool_descriptions, tools
- )
- except Exception as e:
- logger.exception("LLM call failed")
- return self._create_error_response(f"LLM error: {e}")
-
- # Parse the response
- parsed = self._parse_response(response)
-
- if parsed["type"] == "answer":
- # LLM decided it has enough information
- final_answer = parsed["content"]
- self._history.append(
- {
- "role": "assistant",
- "thought": parsed.get("thought", ""),
- "answer": final_answer,
- }
- )
- logger.info(
- f"ReAct completed with answer after {iteration} iterations"
- )
- break
-
- if parsed["type"] == "action":
- # LLM wants to call a tool
- tool_name = parsed.get("tool")
- arguments = parsed.get("arguments", {})
- thought = parsed.get("thought", "")
-
- # Validate required action fields
- if not tool_name:
- logger.warning(
- "Action missing 'tool' field, treating as error"
- )
- self._history.append(
- {
- "role": "system",
- "error": "Invalid action: missing tool name. Please specify which tool to use.",
- }
- )
- continue
-
- # Show detailed progress with thought and action
- thought_preview = (
- thought[: self.THOUGHT_PREVIEW_LENGTH]
- if thought
- else "Analyzing..."
- )
- search_query = arguments.get("query", str(arguments))
-
- self._update_progress(
- f"THINKING: {thought_preview}",
- progress,
- {"phase": "thought", "thought": thought},
- )
- display_name = self._display_tool_name(tool_name)
- self._update_progress(
- f'ACTION: Using {display_name} - "{search_query}"',
- progress + 2,
- {
- "phase": "tool_call",
- "tool": display_name,
- "arguments": arguments,
- },
- )
-
- # Execute the tool
- try:
- result = self._execute_tool(tool_name, arguments, tools)
- if not isinstance(result, dict):
- result = (
- {"content": str(result)}
- if result
- else {"content": "No result returned"}
- )
- observation = result.get("content", str(result))
-
- # Truncate very long observations
- if len(observation) > self.OBSERVATION_MAX_LENGTH:
- observation = (
- observation[: self.OBSERVATION_MAX_LENGTH]
- + "\n... [truncated]"
- )
-
- # Show observation summary with actual content
- obs_preview = observation[
- : self.OBSERVATION_PREVIEW_LENGTH
- ].replace("\n", " ")
- self._update_progress(
- f"RESULT: {obs_preview}",
- progress + 4,
- {
- "phase": "observation",
- "tool": self._display_tool_name(tool_name),
- "result_length": len(observation),
- "content": obs_preview,
- },
- )
-
- except Exception as e:
- logger.exception("Tool execution failed")
- observation = f"Error: Tool '{tool_name}' failed: {e}"
- self._update_progress(
- f"ERROR: {tool_name} failed - {str(e)[:100]}",
- progress + 4,
- {"phase": "error", "tool": tool_name, "error": str(e)},
- )
-
- # Add to history
- self._history.append(
- {
- "role": "assistant",
- "thought": thought,
- "action": tool_name,
- "arguments": arguments,
- }
- )
- self._history.append(
- {
- "role": "tool",
- "tool": tool_name,
- "observation": observation,
- }
- )
-
- elif parsed["type"] == "error":
- # Parsing error - show what the LLM said anyway
- raw_response = parsed.get("raw", "")[
- : self.RAW_RESPONSE_PREVIEW_LENGTH
- ]
- logger.warning(
- f"Failed to parse LLM response: {parsed['message']}"
- )
-
- # Show the raw LLM output to the user so they can see what it's thinking
- self._update_progress(
- f"LLM Response (unparsed): {raw_response}",
- progress,
- {
- "phase": "thought",
- "thought": raw_response,
- "parse_error": True,
- },
- )
-
- self._history.append(
- {
- "role": "system",
- "error": f"Invalid response format: {parsed['message']}. Please use the correct format.",
- }
- )
-
- # If we hit max iterations without an answer, synthesize one
- if final_answer is None:
- logger.warning(
- f"Max iterations ({self.max_iterations}) reached, synthesizing answer"
- )
- final_answer = self._synthesize_answer(query)
-
- # Use citation handler for final synthesis with proper source formatting
- self._update_progress(
- f"Synthesizing {len(self.all_search_results)} sources with citations...",
- 90,
- {"phase": "synthesis", "type": "milestone"},
- )
-
- # If we have search results, use citation handler for proper formatting
- synthesized_content = final_answer
- documents = []
- if self.all_search_results:
- try:
- citation_result = self.citation_handler.analyze_followup(
- query,
- self.all_search_results,
- previous_knowledge=final_answer,
- nr_of_links=0,
- )
- # Handle case where citation_result is None or not a dict
- if citation_result is None or not isinstance(
- citation_result, dict
- ):
- logger.warning(
- "Citation handler returned None or non-dict, using raw answer"
- )
- synthesized_content = final_answer
- else:
- synthesized_content = citation_result.get(
- "content", citation_result.get("response", final_answer)
- )
- documents = citation_result.get("documents", [])
- logger.info(
- f"Citation handler produced {len(documents)} documents"
- )
- except Exception:
- logger.warning("Citation handler failed, using raw answer")
- synthesized_content = final_answer
-
- # Format sources as markdown bibliography and append to output
- logger.info(
- f"MCP Strategy: all_search_results has {len(self.all_search_results)} items"
- )
- if not self.all_search_results:
- logger.warning("MCP Strategy: all_search_results is empty")
- # Delegate to base helper; logs only on failure
- formatted_output = self._format_citations(
- synthesized_content, self.all_search_results
- )
-
- # Add final finding WITH search_results for research_service.py to extract
- # This is critical for sources to be saved to database and displayed
- final_finding = {
- "content": synthesized_content,
- "question": query,
- "search_results": self.all_search_results,
- "documents": documents,
- }
- self._findings.append(final_finding)
-
- # Build result
- self._update_progress(
- "Research complete",
- 100,
- {"phase": "complete", "iterations": iteration},
- )
-
- # Extract actual search queries from history (not just tool names)
- questions = {}
- q_idx = 0
- for h in self._history:
- if h.get("action") and h.get("arguments"):
- action_query = h["arguments"].get(
- "query", h["arguments"].get("question", "")
- )
- if action_query:
- questions[q_idx] = [action_query]
- q_idx += 1
-
- return {
- "findings": self._findings,
- "iterations": iteration,
- "questions": questions,
- "formatted_findings": formatted_output,
- "current_knowledge": synthesized_content,
- "sources": list({s for s in self._sources if isinstance(s, str)}),
- "search_results": self.all_search_results,
- "documents": documents,
- "reasoning_trace": self._history,
- }
-
- def _build_tool_descriptions(self) -> List[Dict[str, Any]]:
- """Build list of available tools with descriptions."""
- tools = []
-
- # Add web search if enabled
- if self.include_web_search and self.search:
- tools.append(
- {
- "name": "web_search",
- "description": "Search the web for information. Use this for quick searches to find current information, facts, news, or any web content. Returns search result snippets.",
- "parameters": {
- "query": {
- "type": "string",
- "description": "The search query",
- "required": True,
- }
- },
- "executor": self._execute_web_search,
- }
- )
-
- # Add strategy-based research tools if enabled and not at max depth
- logger.info(
- 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:
- _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 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"
- ),
- }
- )
-
- # Egress filter for specialized-engine tools — parity with the
- # LangGraph strategy: hide tools the active scope forbids so the LLM
- # never sees them (the schema + denied-tool latency would otherwise
- # leak policy state). The runtime PEP at create_search_engine still
- # backstops execution, but filtering here is the primary line.
- policy_ctx = None
- policy_blocks_all_specialized = False
- if self.settings_snapshot:
- try:
- from ...security.egress.policy import (
- PolicyDeniedError,
- context_from_snapshot,
- )
-
- _primary = unwrap_setting(
- self.settings_snapshot.get(
- "search.tool", DEFAULT_SEARCH_TOOL
- )
- )
- policy_ctx = context_from_snapshot(
- self.settings_snapshot, _primary or DEFAULT_SEARCH_TOOL
- )
- except PolicyDeniedError:
- # Corrupt / incoherent scope → fail closed: expose no
- # specialized engine tools at all.
- policy_blocks_all_specialized = True
- except (ValueError, ImportError):
- # Unevaluable policy → fall through; the runtime PEP enforces.
- policy_ctx = None
-
- # 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():
- # Skip the currently selected engine (already available via web_search)
- if engine_name == self._get_current_engine_name():
- continue
-
- # Apply the egress filter computed above.
- if policy_blocks_all_specialized:
- continue
- if policy_ctx is not None:
- from ...security.egress.policy import (
- EgressScope,
- evaluate_engine,
- evaluate_retriever,
- )
-
- if policy_ctx.scope == EgressScope.STRICT:
- # STRICT exposes only the primary (web_search); no
- # specialized engines.
- continue
- if engine_config.get("is_retriever"):
- from ...web_search_engines.retriever_registry import (
- retriever_registry,
- )
-
- try:
- _meta = retriever_registry.get_metadata(engine_name)
- except AttributeError:
- _meta = None
- _decision = evaluate_retriever(
- engine_name, policy_ctx, metadata=_meta
- )
- else:
- _decision = evaluate_engine(
- engine_name,
- policy_ctx,
- settings_snapshot=self.settings_snapshot,
- metadata=engine_config,
- )
- if not _decision.allowed:
- logger.bind(policy_audit=True).info(
- "MCP specialized tool filtered by egress policy",
- engine=engine_name,
- scope=policy_ctx.scope.value,
- reason=_decision.reason,
- )
- continue
-
- # Create tool for this engine
- description = engine_config.get(
- "description", f"Search using {engine_name}"
- )
- strengths = engine_config.get("strengths", [])
- if strengths:
- description += f" Best for: {', '.join(strengths[: self.ENGINE_STRENGTHS_DISPLAY_LIMIT])}."
-
- tools.append(
- {
- "name": f"search_{engine_name}",
- "description": description,
- "parameters": {
- "query": {
- "type": "string",
- "description": "The search query",
- "required": True,
- }
- },
- "executor": lambda args, eng=engine_name: (
- self._execute_specialized_search(args, eng)
- ),
- }
- )
-
- # Add content download tool for fetching full papers/articles
- tools.append(
- {
- "name": "download_content",
- "description": "Download and extract full text content from a URL. Works with academic papers (arXiv, PubMed, Semantic Scholar, bioRxiv) and web pages. Use this when you need the complete text of a paper or article found in search results, not just the snippet.",
- "parameters": {
- "url": {
- "type": "string",
- "description": "The URL to download content from",
- "required": True,
- },
- "max_length": {
- "type": "integer",
- "description": f"Maximum characters to return (default {self.DOWNLOAD_DEFAULT_MAX_LENGTH})",
- "required": False,
- },
- },
- "executor": self._execute_download_content,
- }
- )
-
- # Add MCP tools (if configured)
- mcp_tools = self._discover_mcp_tools()
- tools.extend(mcp_tools)
-
- return tools
-
- def _mcp_scope_blocked(self):
- """Decide whether MCP tools must be suppressed under the current
- egress scope.
-
- Returns ``(blocked: bool, reason: str)``. MCP tools execute in
- stdio subprocesses whose egress the PDP cannot inspect, so the
- only safe enforcement is to block them outright under
- ``STRICT`` / ``PRIVATE_ONLY``. When no policy snapshot is
- available we fail closed: scope cannot be evaluated, so we
- cannot certify that MCP tools are safe to expose.
-
- ``self.settings_snapshot`` is set to ``{}`` (truthy-empty
- guard from BaseSearchStrategy) for callers that did not
- forward a snapshot — that path returns ``(True, "no_snapshot")``
- rather than silently allowing MCP tools.
- """
- snapshot = self.settings_snapshot
- if not snapshot:
- return True, "no_snapshot"
- try:
- from ...security.egress.policy import (
- EgressScope,
- PolicyDeniedError,
- context_from_snapshot,
- )
- except ImportError:
- # Module not available — preserve historical behavior
- # (allow MCP). Live deployments always have the module.
- return False, ""
-
- primary = unwrap_setting(
- snapshot.get("search.tool", DEFAULT_SEARCH_TOOL)
- )
- try:
- ctx = context_from_snapshot(
- snapshot, primary or DEFAULT_SEARCH_TOOL
- )
- except (PolicyDeniedError, ValueError) as exc:
- # Policy itself is unevaluable (corrupt scope value).
- # Cannot certify MCP is safe — fail closed.
- return True, f"policy_unavailable:{exc}"
-
- if ctx.scope in (EgressScope.STRICT, EgressScope.PRIVATE_ONLY):
- return True, ctx.scope.value
- return False, ""
-
- def _discover_mcp_tools(self) -> List[Dict[str, Any]]:
- """Discover tools from configured MCP servers.
-
- Results are cached only on successful discovery to allow retry on failure.
- """
- # Return cached tools if available
- if self._mcp_tools_cache is not None:
- return self._mcp_tools_cache
-
- tools = []
-
- if not self.mcp_servers:
- return tools
-
- # Egress-policy gate. Runs BEFORE the broad ``except Exception``
- # block below so a fail-closed decision (no snapshot, corrupt
- # scope, STRICT/PRIVATE_ONLY) cannot be swallowed and silently
- # downgraded to "discovery failed → retry next call". Cache the
- # empty list explicitly: scope is immutable for the strategy's
- # lifetime, so suppression is final.
- blocked, reason = self._mcp_scope_blocked()
- if blocked:
- logger.bind(policy_audit=True).warning(
- "MCP tool discovery suppressed by egress policy",
- reason=reason,
- server_count=len(self.mcp_servers),
- )
- try:
- self._update_progress(
- f"MCP tools disabled by egress policy ({reason})",
- None,
- {
- "phase": "policy",
- "type": "policy_block",
- "reason": "mcp_scope_blocked",
- "scope": reason,
- },
- )
- except Exception: # noqa: silent-exception
- # _update_progress is a best-effort UI signal — never
- # let a progress callback failure mask the policy
- # decision itself.
- logger.debug(
- "MCP scope-block progress callback failed",
- exc_info=True,
- )
- self._mcp_tools_cache = []
- return self._mcp_tools_cache
-
- try:
- from local_deep_research.mcp.client import (
- MCPClientManager,
- run_async,
- )
-
- async def discover():
- manager = MCPClientManager(self.mcp_servers)
- async with manager.connect_all():
- return await manager.list_all_tools()
-
- # Use shorter timeout for discovery instead of default 300s
- all_tools = run_async(
- discover(), timeout=self.MCP_DISCOVERY_TIMEOUT
- )
-
- for server_name, server_tools in all_tools.items():
- for tool in server_tools:
- tools.append(
- {
- "name": f"{server_name}.{tool['name']}",
- "description": tool.get(
- "description", "No description"
- ),
- "parameters": tool.get("input_schema", {}).get(
- "properties", {}
- ),
- "mcp_server": server_name,
- "mcp_tool": tool["name"],
- }
- )
-
- # Only cache successful discoveries (when tools were found)
- if tools:
- self._mcp_tools_cache = tools
- logger.info(f"Discovered and cached {len(tools)} MCP tools")
-
- except Exception:
- # Don't cache failures - allow retry on next call
- logger.warning("Failed to discover MCP tools (will retry)")
-
- return tools
-
- def _format_tool_descriptions(self, tools: List[Dict[str, Any]]) -> str:
- """Format tool descriptions for the LLM."""
- lines = []
- for tool in tools:
- params = tool.get("parameters", {})
- param_str = ", ".join(
- f"{k}: {v.get('type', 'any')}" for k, v in params.items()
- )
- lines.append(f"- **{tool['name']}**({param_str})")
- lines.append(f" {tool['description']}")
- lines.append("")
- return "\n".join(lines)
-
- def _format_history(self) -> str:
- """Format the reasoning history for the LLM."""
- if not self._history:
- return "No research done yet."
-
- lines = []
- for entry in self._history:
- role = entry.get("role", "")
-
- if role == "assistant":
- if "thought" in entry:
- lines.append(f"THOUGHT: {entry['thought']}")
- if "action" in entry:
- lines.append(f"ACTION: {entry['action']}")
- lines.append(
- f"ARGUMENTS: {json.dumps(entry.get('arguments', {}))}"
- )
- if "answer" in entry:
- lines.append(f"ANSWER: {entry['answer'][:500]}...")
-
- elif role == "tool":
- obs = entry.get("observation", "")
- if len(obs) > self.HISTORY_OBSERVATION_MAX_LENGTH:
- obs = obs[: self.HISTORY_OBSERVATION_MAX_LENGTH] + "..."
- lines.append(
- f"OBSERVATION ({entry.get('tool', 'unknown')}): {obs}"
- )
-
- elif role == "system":
- if "error" in entry:
- lines.append(f"SYSTEM: {entry['error']}")
-
- lines.append("")
-
- return "\n".join(lines)
-
- def _get_llm_response(
- self, query: str, tool_descriptions: str, tools: List[Dict[str, Any]]
- ) -> str:
- """Get a response from the LLM with tools bound for native tool calling."""
- history = self._format_history()
-
- prompt = REACT_USER_PROMPT.format(
- query=query,
- tool_descriptions=tool_descriptions,
- history=history,
- )
-
- # Format system prompt with current date
- current_date = datetime.now(UTC).strftime("%Y-%m-%d")
- system_prompt = REACT_SYSTEM_PROMPT.format(current_date=current_date)
-
- messages = [
- {"role": "system", "content": system_prompt},
- {"role": "user", "content": prompt},
- ]
-
- # Build tool schemas for native tool calling
- tool_schemas = self._build_tool_schemas(tools)
- logger.info(
- f"Built {len(tool_schemas)} tool schemas: {[s['function']['name'] for s in tool_schemas]}"
- )
-
- # Bind tools to model if we have schemas.
- # NOTE: bind_tools resolves to the BASE LLM via
- # ProcessingLLMWrapper.__getattr__, bypassing the wrapper's <think>-tag
- # stripping — so reasoning-model output on this tool-calling path is NOT
- # think-stripped (cosmetic leak only; does not crash). The plain
- # self.model.invoke() fallback below DOES go through the wrapper. Known
- # limitation — see ProcessingLLMWrapper in config/llm_config.py.
- if tool_schemas:
- try:
- model_with_tools = self.model.bind_tools(tool_schemas)
- response = model_with_tools.invoke(messages)
- except Exception:
- logger.warning("Failed to bind tools, using text-based")
- response = self.model.invoke(messages)
- else:
- response = self.model.invoke(messages)
-
- # Return the full response object so we can handle both text and tool calls
- return response
-
- def _build_tool_schemas(
- self, tools: List[Dict[str, Any]]
- ) -> List[Dict[str, Any]]:
- """Build tool schemas for native LLM tool calling."""
- schemas = []
- for tool in tools:
- # Build JSON schema for the tool
- properties = {}
- required = []
- for param_name, param_info in tool.get("parameters", {}).items():
- properties[param_name] = {
- "type": param_info.get("type", "string"),
- "description": param_info.get("description", ""),
- }
- if param_info.get("required", False):
- required.append(param_name)
-
- schema = {
- "type": "function",
- "function": {
- "name": tool["name"],
- "description": tool["description"],
- "parameters": {
- "type": "object",
- "properties": properties,
- "required": required,
- },
- },
- }
- schemas.append(schema)
-
- return schemas
-
- def _parse_response(self, response) -> Dict[str, Any]:
- """Parse the LLM's response to extract thought/action/answer.
-
- Handles both native tool calls and text-based responses.
- """
- # Check for native tool calls first (preferred)
- if (
- hasattr(response, "tool_calls")
- and response.tool_calls
- and len(response.tool_calls) > 0
- ):
- tool_call = response.tool_calls[0]
- tool_name = tool_call.get("name", "unknown")
- tool_args = tool_call.get("args", {})
-
- # Get any text content as the "thought"
- thought = ""
- if hasattr(response, "content") and response.content:
- thought = response.content
- else:
- thought = f"Calling {tool_name} to find information"
-
- logger.info(f"Native tool call: {tool_name} with args {tool_args}")
-
- return {
- "type": "action",
- "thought": thought,
- "tool": tool_name,
- "arguments": tool_args,
- }
-
- # Extract text content for text-based parsing
- if hasattr(response, "content"):
- response = response.content
- response = str(response).strip()
-
- # Log raw response at INFO level so we can see what the LLM generates
- logger.info(
- f"Raw LLM response ({len(response)} chars): {response[:800]}..."
- )
-
- # Try to extract THOUGHT
- thought = ""
- thought_match = re.search(
- r"THOUGHT:\s*(.+?)(?=(?:ACTION:|ANSWER:|$))",
- response,
- re.DOTALL | re.IGNORECASE,
- )
- if thought_match:
- thought = thought_match.group(1).strip()
-
- # Check for ANSWER
- answer_match = re.search(
- r"ANSWER:\s*(.+)", response, re.DOTALL | re.IGNORECASE
- )
- if answer_match:
- return {
- "type": "answer",
- "thought": thought,
- "content": answer_match.group(1).strip(),
- }
-
- # Check for ACTION
- action_match = re.search(r"ACTION:\s*(\S+)", response, re.IGNORECASE)
- if action_match:
- tool_name = action_match.group(1).strip()
-
- # Try to extract ARGUMENTS using centralized JSON parser
- arguments = {}
- args_section = re.search(
- r"ARGUMENTS:\s*(.+?)(?=(?:THOUGHT:|ACTION:|ANSWER:|$))",
- response,
- re.DOTALL | re.IGNORECASE,
- )
- if args_section:
- parsed_args = extract_json(
- args_section.group(1), expected_type=dict
- )
- if parsed_args is not None:
- arguments = parsed_args
- else:
- logger.warning(
- f"Failed to parse ARGUMENTS JSON: {args_section.group(1)[:200]}"
- )
-
- # If no JSON arguments, try to find query parameter
- if not arguments:
- query_match = re.search(
- r'["\']?query["\']?\s*[:=]\s*["\'](.+?)["\']',
- response,
- re.IGNORECASE,
- )
- if query_match:
- arguments = {"query": query_match.group(1)}
-
- return {
- "type": "action",
- "thought": thought,
- "tool": tool_name,
- "arguments": arguments,
- }
-
- # FALLBACK: Try to detect intent from response even without proper format
- response_lower = response.lower()
-
- # Check if model wants to search (common patterns)
- search_patterns = [
- r"(?:let me |i will |i should |i need to |going to )(?:search|look up|find|research)",
- r"search(?:ing)? for",
- r"look(?:ing)? up",
- r"find(?:ing)? information",
- ]
- for pattern in search_patterns:
- if re.search(pattern, response_lower):
- # Extract what they want to search for
- # Try to find quoted text or text after "for" or "about"
- search_query = None
- quoted = re.search(r'["\']([^"\']+)["\']', response)
- if quoted:
- search_query = quoted.group(1)
- else:
- about_match = re.search(
- r"(?:for|about|on)\s+(.+?)(?:\.|$)",
- response,
- re.IGNORECASE,
- )
- if about_match:
- search_query = about_match.group(1).strip()[:100]
-
- if search_query:
- logger.info(
- f"Fallback parser detected search intent: {search_query}"
- )
- return {
- "type": "action",
- "thought": response[: self.THOUGHT_PREVIEW_LENGTH],
- "tool": "web_search",
- "arguments": {"query": search_query},
- }
-
- # If response is long and looks like a direct answer, treat as answer
- if len(response) > self.DIRECT_ANSWER_MIN_LENGTH:
- logger.info("Fallback parser treating long response as answer")
- return {
- "type": "answer",
- "thought": "Model provided direct answer without following format",
- "content": response,
- }
-
- # If we can't parse, return error with the full raw response for display
- logger.warning(f"Could not parse LLM response: {response[:300]}...")
- return {
- "type": "error",
- "message": "Could not parse response. Expected THOUGHT/ACTION or THOUGHT/ANSWER format.",
- "raw": response, # Include full response so user can see what LLM said
- }
-
- def _validate_tool_arguments(
- self, arguments: Dict[str, Any]
- ) -> Dict[str, Any]:
- """
- Validate and sanitize tool arguments.
-
- Args:
- arguments: Raw arguments from LLM
-
- Returns:
- Sanitized arguments dictionary
- """
- if not isinstance(arguments, dict):
- return {}
-
- sanitized = {}
- for key, value in arguments.items():
- # Ensure key is a string
- if not isinstance(key, str):
- continue
- # Truncate very long string values
- if isinstance(value, str) and len(value) > self.MAX_ARG_LENGTH:
- value = value[: self.MAX_ARG_LENGTH]
- logger.warning(
- f"Truncated argument '{key}' to {self.MAX_ARG_LENGTH} chars"
- )
- sanitized[key] = value
-
- return sanitized
-
- def _execute_tool(
- self,
- tool_name: str,
- arguments: Dict[str, Any],
- tools: List[Dict[str, Any]],
- ) -> Dict[str, Any]:
- """Execute a tool and return the result."""
- # Validate and sanitize arguments
- arguments = self._validate_tool_arguments(arguments)
-
- # Find the tool
- tool = None
- for t in tools:
- if t["name"] == tool_name:
- tool = t
- break
-
- if not tool:
- return {"status": "error", "content": f"Unknown tool: {tool_name}"}
-
- # Execute based on tool type
- if "executor" in tool:
- # Built-in tool with executor function
- return tool["executor"](arguments)
- if "mcp_server" in tool:
- # MCP tool
- return self._execute_mcp_tool(
- tool["mcp_server"],
- tool["mcp_tool"],
- arguments,
- )
- return {
- "status": "error",
- "content": f"Tool {tool_name} has no executor",
- }
-
- def _execute_web_search(self, arguments: Dict[str, Any]) -> Dict[str, Any]:
- """Execute web search tool."""
- query = arguments.get("query", "")
- if not query:
- return {"status": "error", "content": "No query provided"}
-
- try:
- results = self.search.run(query)
-
- # Track sources and accumulate search results for citation handling
- if isinstance(results, list):
- # Handle empty results
- if not results:
- logger.info(f"Web search returned no results for: {query}")
- return {
- "status": "success",
- "content": f"No search results found for '{query}'. Try rephrasing the query or using a different search approach.",
- }
-
- for r in results:
- if isinstance(r, dict):
- # Track source URLs
- if "link" in r:
- self._sources.append(r["link"])
-
- # Add to all_search_results for citation handler
- # Assign index based on current count
- result_with_index = dict(r)
- result_with_index["index"] = str(
- len(self.all_search_results) + 1
- )
- self.all_search_results.append(result_with_index)
-
- # Also add to shared links
- if self.all_links_of_system is not None:
- self.all_links_of_system.append(result_with_index)
-
- # Format with index, title, URL, and snippet for LLM
- content = "\n\n".join(
- f"[{len(self.all_search_results) - len(results) + i + 1}] {r.get('title', 'No title')} ({r.get('link', 'no url')})\n{r.get('snippet', r.get('body', ''))}"
- for i, r in enumerate(results)
- if isinstance(r, dict)
- )
- else:
- content = str(results)
-
- # Add to findings
- self._findings.append(
- {
- "type": "web_search",
- "query": query,
- "result_count": len(results)
- if isinstance(results, list)
- else 1,
- }
- )
-
- return {"status": "success", "content": content}
-
- except Exception as e:
- logger.exception("Web search failed")
- return {"status": "error", "content": f"Search failed: {e}"}
-
- def _execute_download_content(
- self, arguments: Dict[str, Any]
- ) -> Dict[str, Any]:
- """Execute content download tool.
-
- Downloads full text content from URLs including academic papers
- (arXiv, PubMed, Semantic Scholar) and web pages.
- """
- url = arguments.get("url", "")
- if not url:
- return {"status": "error", "content": "No URL provided"}
-
- max_length = arguments.get(
- "max_length", self.DOWNLOAD_DEFAULT_MAX_LENGTH
- )
-
- try:
- from local_deep_research.content_fetcher import ContentFetcher
- from local_deep_research.utilities.js_rendering import (
- read_js_rendering_setting,
- )
-
- # Build an EgressContext for this fetch so the in-fetcher
- # scope check (content_fetcher/fetcher.py) gates the URL
- # against the user's policy. Without this, MCP
- # download_content would do raw SSRF-only validation while
- # the LangGraph fetch tool's _enforce_url_policy already
- # blocks the same vector.
- egress_context = None
- if self.settings_snapshot:
- try:
- from local_deep_research.security.egress.policy import (
- PolicyDeniedError,
- context_from_snapshot,
- )
- except ImportError:
- logger.debug(
- "egress_policy unavailable for MCP "
- "download_content; using SSRF-only check"
- )
- else:
- primary = unwrap_setting(
- self.settings_snapshot.get(
- "search.tool", DEFAULT_SEARCH_TOOL
- )
- )
- try:
- egress_context = context_from_snapshot(
- self.settings_snapshot,
- primary or DEFAULT_SEARCH_TOOL,
- )
- except (PolicyDeniedError, ValueError) as exc:
- # Snapshot was supplied but the policy itself
- # cannot be evaluated (corrupt scope value).
- # Fail closed
- # — the previous bare-except dropped to
- # SSRF-only here, which allows public-IP fetches
- # under PRIVATE_ONLY.
- logger.bind(policy_audit=True).warning(
- "MCP download_content refused: egress "
- "policy could not be evaluated",
- reason=str(exc),
- )
- return {
- "status": "error",
- "content": (
- "Egress policy could not be evaluated; "
- "refusing fetch"
- ),
- }
-
- with ContentFetcher(
- timeout=self.CONTENT_FETCHER_TIMEOUT,
- enable_js_rendering=read_js_rendering_setting(
- self.settings_snapshot
- ),
- egress_context=egress_context,
- ) as fetcher:
- result = fetcher.fetch(url, max_length=max_length)
-
- if result.get("status") == "success":
- content = result.get("content", "")
- source_type = result.get("source_type", "unknown")
- title = result.get("title", "")
-
- # Format output
- output_parts = []
- if title:
- output_parts.append(f"Title: {title}")
- output_parts.append(f"Source: {source_type}")
- output_parts.append(f"URL: {url}")
- output_parts.append("")
- output_parts.append(content)
-
- formatted_content = "\n".join(output_parts)
-
- # Track as a finding
- self._findings.append(
- {
- "type": "content_download",
- "url": url,
- "source_type": source_type,
- "title": title,
- "content_length": len(content),
- }
- )
-
- # Track source
- self._sources.append(url)
-
- logger.info(
- f"Downloaded {len(content)} chars from {source_type}: {url}"
- )
-
- return {"status": "success", "content": formatted_content}
-
- error_msg = result.get("error", "Download failed")
- logger.warning(f"Content download failed: {error_msg}")
- return {"status": "error", "content": error_msg}
-
- except ImportError:
- logger.warning("ContentFetcher not available")
- return {
- "status": "error",
- "content": "Content fetcher module not available",
- }
- except Exception as e:
- logger.exception(f"Content download failed for {url}")
- return {"status": "error", "content": f"Download failed: {e}"}
-
- def _execute_strategy_research(
- self, arguments: Dict[str, Any], strategy_name: str
- ) -> Dict[str, Any]:
- """Execute research using a specific strategy.
-
- 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:
- return {"status": "error", "content": "No query provided"}
-
- # Check recursion depth
- if self.depth >= self.max_depth:
- return {
- "status": "error",
- "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:
- # 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:
- logger.warning(
- f"Failed to create engine '{search_engine_name}'"
- 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(
- progress_msg,
- 50,
- {
- "phase": "sub_research",
- "strategy": strategy_name,
- "depth": self.depth + 1,
- "query": sub_query[:100],
- },
- )
-
- # 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=search_instance,
- all_links_of_system=self.all_links_of_system,
- settings_snapshot=self.settings_snapshot,
- **strategy_kwargs,
- )
-
- # Run the research
- result = child_strategy.analyze_topic(sub_query)
-
- # Merge sources from child into parent
- child_sources = []
- child_findings = result.get("findings", [])
- logger.info(
- f"MCP Strategy: Merging sources from {strategy_name}, got {len(child_findings)} findings"
- )
- for finding in child_findings:
- finding_sources = finding.get("search_results", [])
- logger.info(
- f"MCP Strategy: Finding has {len(finding_sources)} search_results"
- )
- for source in finding_sources:
- # Re-index sources to continue from parent's count
- source_copy = dict(source)
- source_copy["index"] = str(len(self.all_search_results) + 1)
- self.all_search_results.append(source_copy)
- child_sources.append(source_copy)
-
- if self.all_links_of_system is not None:
- self.all_links_of_system.append(source_copy)
-
- logger.info(
- f"MCP Strategy: After merge, all_search_results has {len(self.all_search_results)} items"
- )
-
- # Add findings to parent
- for finding in child_findings:
- finding["from_strategy"] = strategy_name
- finding["sub_query"] = sub_query
- self._findings.append(finding)
-
- # Track sources (only strings)
- for src in result.get("sources", []):
- if isinstance(src, str):
- self._sources.append(src)
- elif isinstance(src, dict) and "link" in src:
- self._sources.append(src["link"])
-
- # Return the synthesized content
- content = result.get("formatted_findings", "")
- if not content:
- content = result.get("current_knowledge", "No results found")
-
- # Add source references to the content
- if child_sources:
- source_refs = ", ".join(
- f"[{s.get('index', '?')}]"
- for s in child_sources[-self.SOURCE_REFS_DISPLAY_LIMIT :]
- )
- content = f"{content}\n\nSources: {source_refs}"
-
- logger.info(
- f"{strategy_name} research completed with {len(child_sources)} sources"
- )
-
- return {"status": "success", "content": content}
-
- except Exception as e:
- logger.exception(f"{strategy_name} research failed")
- return {
- "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
- and with valid API keys)."""
- try:
- from local_deep_research.web_search_engines.search_engines_config import (
- get_available_engines,
- )
-
- return get_available_engines(
- settings_snapshot=self.settings_snapshot,
- )
- except Exception:
- logger.warning("Failed to get available search engines")
- return {}
-
- def _get_current_engine_name(self) -> str:
- """Get the name of the currently selected search engine."""
- try:
- if hasattr(self.search, "__class__"):
- # Extract engine name from class name
- class_name = self.search.__class__.__name__
- # Convert "ArXivSearchEngine" -> "arxiv"
- return class_name.replace("SearchEngine", "").lower()
- except Exception:
- logger.debug("best-effort class name extraction", exc_info=True)
- return ""
-
- def _display_tool_name(self, tool_name: str) -> str:
- """Return a user-friendly display name for a tool.
-
- ``web_search`` is a generic tool wrapper — show the user's selected
- search engine so the UI says e.g. "selected engine (searxng)"
- instead of "web_search".
- """
- if tool_name == "web_search":
- engine = self._get_current_engine_name() or "web search"
- return f"{engine} (primary)"
- return tool_name
-
- def _execute_specialized_search(
- self, arguments: Dict[str, Any], engine_name: str
- ) -> Dict[str, Any]:
- """Execute search using a specific search engine."""
- query = arguments.get("query", "")
- if not query:
- return {"status": "error", "content": "No query provided"}
-
- try:
- from local_deep_research.web_search_engines.search_engine_factory import (
- create_search_engine,
- )
- from ...security.egress.policy import PolicyDeniedError
-
- logger.info(f"Specialized search with {engine_name}: {query[:100]}")
-
- # Create the specialized search engine
- engine = create_search_engine(
- engine_name=engine_name,
- llm=self.model,
- settings_snapshot=self.settings_snapshot,
- )
-
- if not engine:
- return {
- "status": "error",
- "content": f"Failed to create {engine_name} search engine",
- }
-
- try:
- # Run the search
- results = engine.run(query)
-
- # Track sources and accumulate search results
- if isinstance(results, list):
- for r in results:
- if isinstance(r, dict):
- if "link" in r:
- self._sources.append(r["link"])
-
- result_with_index = dict(r)
- result_with_index["index"] = str(
- len(self.all_search_results) + 1
- )
- result_with_index["source_engine"] = engine_name
- self.all_search_results.append(result_with_index)
-
- if self.all_links_of_system is not None:
- self.all_links_of_system.append(
- result_with_index
- )
-
- # Format results for LLM
- content = "\n\n".join(
- f"[{len(self.all_search_results) - len(results) + i + 1}] {r.get('title', 'No title')} ({r.get('link', 'no url')})\n{r.get('snippet', r.get('body', ''))}"
- for i, r in enumerate(results)
- if isinstance(r, dict)
- )
- else:
- content = str(results)
-
- self._findings.append(
- {
- "type": "specialized_search",
- "engine": engine_name,
- "query": query,
- "result_count": len(results)
- if isinstance(results, list)
- else 1,
- }
- )
-
- return {"status": "success", "content": content}
- finally:
- from local_deep_research.utilities.resource_utils import (
- safe_close,
- )
-
- safe_close(engine, "specialized search engine")
-
- except PolicyDeniedError as exc:
- # The tool-list filter should already hide forbidden engines, but
- # if a denied engine is invoked anyway (cached tool list, race),
- # surface the policy denial in the audit trail instead of letting
- # the broad handler below downgrade it to a generic tool error.
- logger.bind(policy_audit=True).warning(
- "MCP specialized search refused by egress policy",
- engine=engine_name,
- reason=exc.decision.reason,
- )
- return {
- "status": "error",
- "content": (
- f"{engine_name} search refused by egress policy "
- f"({exc.decision.reason})"
- ),
- }
- except Exception as e:
- logger.exception(f"Specialized search with {engine_name} failed")
- return {
- "status": "error",
- "content": f"{engine_name} search failed: {e}",
- }
-
- def _execute_mcp_tool(
- self,
- server_name: str,
- tool_name: str,
- arguments: Dict[str, Any],
- timeout: Optional[float] = None,
- ) -> Dict[str, Any]:
- """Execute an MCP tool.
-
- Args:
- server_name: Name of the MCP server
- tool_name: Name of the tool to call
- arguments: Arguments to pass to the tool
- timeout: Timeout in seconds for the tool call
- (defaults to MCP_TOOL_CALL_TIMEOUT)
- """
- if timeout is None:
- timeout = self.MCP_TOOL_CALL_TIMEOUT
-
- # Defense-in-depth: discovery should already have suppressed
- # MCP tools under STRICT/PRIVATE_ONLY/no-snapshot. Re-check
- # before any subprocess egress in case a cached tool list
- # survives a config drift. Runs BEFORE the broad try so the
- # decision is not converted to a generic "MCP tool failed".
- blocked, reason = self._mcp_scope_blocked()
- if blocked:
- logger.bind(policy_audit=True).warning(
- "MCP tool execution refused by egress policy",
- reason=reason,
- server=server_name,
- tool=tool_name,
- )
- return {
- "status": "error",
- "content": (
- f"MCP tool '{server_name}.{tool_name}' blocked by "
- f"egress policy ({reason})"
- ),
- }
- try:
- from local_deep_research.mcp.client import (
- MCPClientManager,
- run_async,
- )
-
- # Find the server config
- server_config = None
- for config in self.mcp_servers:
- if config.get("name") == server_name:
- server_config = config
- break
-
- if not server_config:
- return {
- "status": "error",
- "content": f"Unknown server: {server_name}",
- }
-
- async def call():
- manager = MCPClientManager([server_config])
- async with manager.connect_all():
- return await manager.call_tool(
- server_name, tool_name, arguments
- )
-
- result = run_async(call(), timeout=timeout)
-
- # Ensure result is a dict
- if not isinstance(result, dict):
- result = {
- "status": "success",
- "content": str(result) if result else "",
- }
-
- # Track findings
- self._findings.append(
- {
- "type": "mcp_tool",
- "server": server_name,
- "tool": tool_name,
- "arguments": arguments,
- }
- )
-
- return result
-
- except Exception as e:
- logger.exception("MCP tool call failed")
- return {"status": "error", "content": f"MCP tool failed: {e}"}
-
- def _synthesize_answer(self, query: str) -> str:
- """Synthesize an answer from the gathered information when max iterations reached."""
- history = self._format_history()
-
- prompt = f"""Based on the research conducted, provide a comprehensive answer to the query.
-
-Query: {query}
-
-Research History:
-{history}
-
-Please synthesize all the information gathered into a clear, comprehensive answer.
-If some information is missing, note what couldn't be found."""
-
- try:
- response = self.model.invoke(prompt)
- if hasattr(response, "content"):
- return response.content
- return str(response)
- except Exception as e:
- logger.exception("Failed to synthesize answer")
- return f"Research completed but synthesis failed: {e}"
diff --git a/src/local_deep_research/constants.py b/src/local_deep_research/constants.py
index 85ca490e6f..340bef1a60 100644
--- a/src/local_deep_research/constants.py
+++ b/src/local_deep_research/constants.py
@@ -141,11 +141,6 @@ AVAILABLE_STRATEGIES: List[Dict[str, str]] = [
"label": "Topic Organization (Clusters by topic)",
"description": "Clusters sources into topics with lead texts. Organizes research by themes for structured output.",
},
- {
- "name": "mcp",
- "label": "MCP ReAct (Agentic research - LLM decides tools)",
- "description": "Agentic research using ReAct pattern. LLM decides what tools to call, analyzes results, and iterates.",
- },
{
"name": "langgraph-agent",
"label": "LangGraph Agent (Autonomous agentic research)",
diff --git a/src/local_deep_research/database/migrations/versions/0018_remove_mcp_strategy.py b/src/local_deep_research/database/migrations/versions/0018_remove_mcp_strategy.py
new file mode 100644
index 0000000000..d7dd1074e1
--- /dev/null
+++ b/src/local_deep_research/database/migrations/versions/0018_remove_mcp_strategy.py
@@ -0,0 +1,227 @@
+"""Remove the 'mcp'/'agentic' search strategy from stored data.
+
+Background
+==========
+``MCPSearchStrategy`` (factory keys ``mcp`` / ``agentic``) was removed: the
+``langgraph-agent`` strategy (the default) is a near functional superset and
+the parallel ReAct loop was redundant. The strategy factory now routes the
+``mcp``/``agentic`` aliases to ``langgraph-agent`` at runtime, but persisted
+references should be rewritten so the deprecation warning does not fire
+forever and the orphaned ``mcp.servers`` setting is cleaned up.
+
+What this migration does
+========================
+1. ``settings``: rewrites ``search.search_strategy`` values of ``mcp`` /
+ ``agentic`` to ``langgraph-agent``.
+2. ``settings``: deletes the orphaned ``mcp.servers`` row (its only consumer,
+ the MCP strategy, is gone).
+3. ``news_subscriptions``: sets ``search_strategy`` to NULL where it names a
+ removed strategy — the subscription runner treats a falsy value as the
+ default ``news_aggregation`` strategy (``subscription_runner.py``:
+ ``search_strategy or "news_aggregation"``), which is the desired fallback.
+4. ``queued_researches``: queued rows are replayed after a restart, so the
+ ``settings_snapshot`` JSON is rewritten (both the top-level
+ ``submission.strategy`` and any embedded ``search.search_strategy``
+ setting) to ``langgraph-agent``.
+5. ``benchmark_runs`` / ``benchmark_configs``: ``search_config`` JSON
+ ``search_strategy`` values are rewritten so saved configs and resumable
+ runs keep working.
+
+Storage note: the settings ``value`` column uses SQLAlchemy's ``JSON`` type,
+which stores strings as quoted TEXT — the WHERE clause matches the
+JSON-encoded form (``'"mcp"'`` with quotes). The lightweight ``sa.table``
+definitions below declare these columns as **untyped** on purpose: an untyped
+column reads/writes the raw stored value verbatim, whereas attaching
+``sa.JSON`` would re-encode the bound value and corrupt it. See migration 0013
+for the same overall pattern.
+
+Revision ID: 0018
+Revises: 0017
+Create Date: 2026-06-13
+"""
+
+from __future__ import annotations
+
+import json
+
+import sqlalchemy as sa
+from alembic import op
+from loguru import logger
+from sqlalchemy import inspect
+
+revision = "0018"
+down_revision = "0017"
+branch_labels = None
+depends_on = None
+
+REMOVED_STRATEGIES = ("mcp", "agentic")
+# JSON-encoded form for the ``settings.value`` JSON column (stored quoted).
+REMOVED_STRATEGIES_JSON = tuple(json.dumps(name) for name in REMOVED_STRATEGIES)
+REPLACEMENT_STRATEGY = "langgraph-agent"
+REPLACEMENT_STRATEGY_JSON = json.dumps(REPLACEMENT_STRATEGY)
+
+STRATEGY_SETTING_KEY = "search.search_strategy"
+MCP_SERVERS_KEY = "mcp.servers"
+
+# Untyped table definitions — raw stored values, no JSON re-encoding.
+_settings = sa.table("settings", sa.column("key"), sa.column("value"))
+_news = sa.table("news_subscriptions", sa.column("search_strategy"))
+_queued = sa.table(
+ "queued_researches", sa.column("id"), sa.column("settings_snapshot")
+)
+
+
+def _rewrite_search_strategy_setting(conn) -> None:
+ result = conn.execute(
+ sa.update(_settings)
+ .where(_settings.c.key == STRATEGY_SETTING_KEY)
+ .where(_settings.c.value.in_(list(REMOVED_STRATEGIES_JSON)))
+ .values(value=REPLACEMENT_STRATEGY_JSON)
+ )
+ if result.rowcount:
+ logger.info(
+ "Migrated {} setting row(s) from a removed strategy to {!r}.",
+ result.rowcount,
+ REPLACEMENT_STRATEGY,
+ )
+
+
+def _delete_mcp_servers_setting(conn) -> None:
+ result = conn.execute(
+ sa.delete(_settings).where(_settings.c.key == MCP_SERVERS_KEY)
+ )
+ if result.rowcount:
+ logger.info(
+ "Deleted {} orphaned 'mcp.servers' setting row(s).",
+ result.rowcount,
+ )
+
+
+def _null_news_subscription_strategies(conn) -> None:
+ result = conn.execute(
+ sa.update(_news)
+ .where(_news.c.search_strategy.in_(list(REMOVED_STRATEGIES)))
+ .values(search_strategy=None)
+ )
+ if result.rowcount:
+ logger.info(
+ "Cleared a removed strategy from {} news subscription(s); "
+ "they fall back to the user's default search strategy.",
+ result.rowcount,
+ )
+
+
+def _rewrite_snapshot(snapshot: dict) -> bool:
+ """Rewrite a removed strategy name inside a queued-research snapshot.
+
+ Handles both the structure ({"submission": {...},
+ "settings_snapshot": {...}}) and the legacy flat structure where the
+ submission params are the snapshot itself.
+ """
+ changed = False
+
+ submission = (
+ snapshot.get("submission")
+ if isinstance(snapshot.get("submission"), dict)
+ else snapshot
+ )
+ if submission.get("strategy") in REMOVED_STRATEGIES:
+ submission["strategy"] = REPLACEMENT_STRATEGY
+ changed = True
+
+ complete = snapshot.get("settings_snapshot")
+ if isinstance(complete, dict) and STRATEGY_SETTING_KEY in complete:
+ entry = complete[STRATEGY_SETTING_KEY]
+ if isinstance(entry, dict):
+ if entry.get("value") in REMOVED_STRATEGIES:
+ entry["value"] = REPLACEMENT_STRATEGY
+ changed = True
+ elif entry in REMOVED_STRATEGIES:
+ complete[STRATEGY_SETTING_KEY] = REPLACEMENT_STRATEGY
+ changed = True
+
+ return changed
+
+
+def _rewrite_queued_research_snapshots(conn) -> None:
+ rows = conn.execute(
+ sa.select(_queued.c.id, _queued.c.settings_snapshot)
+ ).fetchall()
+
+ rewritten = 0
+ for row_id, raw in rows:
+ if not raw:
+ continue
+ snapshot = json.loads(raw) if isinstance(raw, str) else raw
+ if not isinstance(snapshot, dict):
+ continue
+ if _rewrite_snapshot(snapshot):
+ conn.execute(
+ sa.update(_queued)
+ .where(_queued.c.id == row_id)
+ .values(settings_snapshot=json.dumps(snapshot))
+ )
+ rewritten += 1
+
+ if rewritten:
+ logger.info(
+ "Rewrote a removed strategy in {} queued research row(s).",
+ rewritten,
+ )
+
+
+def _rewrite_benchmark_search_configs(conn, table: str) -> None:
+ t = sa.table(table, sa.column("id"), sa.column("search_config"))
+ rows = conn.execute(sa.select(t.c.id, t.c.search_config)).fetchall()
+
+ rewritten = 0
+ for row_id, raw in rows:
+ if not raw:
+ continue
+ config = json.loads(raw) if isinstance(raw, str) else raw
+ if not isinstance(config, dict):
+ continue
+ if config.get("search_strategy") in REMOVED_STRATEGIES:
+ config["search_strategy"] = REPLACEMENT_STRATEGY
+ conn.execute(
+ sa.update(t)
+ .where(t.c.id == row_id)
+ .values(search_config=json.dumps(config))
+ )
+ rewritten += 1
+
+ if rewritten:
+ logger.info(
+ "Rewrote a removed strategy in {} {} row(s).",
+ rewritten,
+ table,
+ )
+
+
+def upgrade() -> None:
+ conn = op.get_bind()
+ inspector = inspect(conn)
+
+ if inspector.has_table("settings"):
+ _rewrite_search_strategy_setting(conn)
+ _delete_mcp_servers_setting(conn)
+
+ if inspector.has_table("news_subscriptions"):
+ _null_news_subscription_strategies(conn)
+
+ if inspector.has_table("queued_researches"):
+ _rewrite_queued_research_snapshots(conn)
+
+ for table in ("benchmark_runs", "benchmark_configs"):
+ if inspector.has_table(table):
+ _rewrite_benchmark_search_configs(conn, table)
+
+
+def downgrade() -> None:
+ """No-op.
+
+ The removed strategy no longer exists in the codebase, so restoring
+ references to it would only recreate broken state. The deleted
+ ``mcp.servers`` row is re-seeded from defaults files by older code
+ versions if ever needed.
+ """
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index f36bd570f1..03a2a441fc 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -1174,7 +1174,7 @@
},
"search.search_strategy": {
"category": "search_parameters",
- "description": "Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'topic-organization': Organizes research around discovered topic clusters. 'mcp': Agentic ReAct-pattern research using MCP tools. 'langgraph-agent': Autonomous agentic research where the LLM decides what to search and when to synthesize.",
+ "description": "Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'topic-organization': Organizes research around discovered topic clusters. 'langgraph-agent': Autonomous agentic research where the LLM decides what to search and when to synthesize.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -4634,20 +4634,6 @@
"value": false,
"visible": true
},
- "mcp.servers": {
- "category": "mcp",
- "description": "List of external MCP servers to connect to. Each entry should have 'command' (required), and optionally 'name', 'args', and 'env'. Allowed commands: node, npx, python, python3, uv, uvx, docker. See <a href=\"https://github.com/LearningCircuit/local-deep-research/blob/main/docs/mcp-server.md#mcp-client-connecting-external-mcp-servers\" target=\"_blank\">MCP Client documentation</a> for details.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "MCP Servers",
- "options": null,
- "step": null,
- "type": "APP",
- "ui_element": "textarea",
- "value": [],
- "visible": true
- },
"notifications.enabled": {
"category": "notifications",
"description": "Enable external notifications for research events (email, Discord, Slack, etc.). When disabled, no notifications are sent regardless of individual event settings below. Requires service URL to be configured.",
diff --git a/src/local_deep_research/mcp/client.py b/src/local_deep_research/mcp/client.py
deleted file mode 100644
index 3c59b82093..0000000000
--- a/src/local_deep_research/mcp/client.py
+++ /dev/null
@@ -1,486 +0,0 @@
-"""
-MCP Client utilities for connecting to MCP servers.
-
-This module provides a wrapper around the MCP client SDK for connecting
-to and calling tools on MCP servers.
-"""
-
-import asyncio
-from contextlib import AsyncExitStack, asynccontextmanager
-from pathlib import Path
-from typing import Any, Dict, List, Optional
-
-from tenacity import (
- AsyncRetrying,
- retry_if_exception_message,
- retry_if_exception_type,
- stop_after_attempt,
- wait_exponential,
-)
-
-from loguru import logger
-
-# Allowed commands for MCP server execution (security whitelist)
-ALLOWED_COMMANDS = {"node", "npx", "python", "python3", "uv", "uvx", "docker"}
-
-# Retry configuration for subprocess startup race condition
-INIT_RETRY_ATTEMPTS = 5
-INIT_RETRY_BASE_DELAY = 0.1 # seconds
-INIT_RETRY_MAX_DELAY = 2.0 # seconds
-INIT_RETRY_BACKOFF_FACTOR = 2.0
-
-# The MCP SDK is an optional dependency (installed via the [mcp] extras group),
-# so we guard the import and set a flag for runtime availability checks.
-try:
- from mcp import ClientSession
- from mcp.client.stdio import StdioServerParameters, stdio_client
-
- MCP_AVAILABLE = True
-except ImportError:
- MCP_AVAILABLE = False
- logger.warning(
- "MCP client not available. Install with: pip install mcp[cli]"
- )
-
-
-class MCPClientError(Exception):
- """Error during MCP client operations."""
-
- pass
-
-
-class MCPClient:
- """
- Client for connecting to and calling tools on MCP servers.
-
- Usage:
- async with MCPClient(config) as client:
- tools = await client.list_tools()
- result = await client.call_tool("tool_name", {"arg": "value"})
- """
-
- def __init__(
- self,
- server_config: Dict[str, Any],
- timeout: float = 60.0,
- ):
- """
- Initialize MCP client.
-
- Args:
- server_config: Server configuration with keys:
- - command: str - Command to run (e.g., "python")
- - args: List[str] - Command arguments
- - env: Dict[str, str] - Environment variables (optional)
- - name: str - Server name for logging (optional)
- timeout: Timeout in seconds for tool calls
- """
- if not MCP_AVAILABLE:
- raise MCPClientError(
- "MCP client not available. Install with: pip install mcp[cli]"
- )
-
- # Validate server configuration for security
- self._validate_server_config(server_config)
-
- self.config = server_config
- self.timeout = timeout
- self.name = server_config.get("name", "unnamed")
- self._session: Optional[ClientSession] = None
- self._read_stream = None
- self._write_stream = None
- self._connected = False
-
- def _validate_server_config(self, config: Dict[str, Any]) -> None:
- """
- Validate server configuration for security.
-
- Args:
- config: Server configuration dictionary
-
- Raises:
- MCPClientError: If configuration is invalid or insecure
- """
- # Check command exists
- command = config.get("command", "")
- command = command.strip()
- if not command:
- raise MCPClientError("Server config missing 'command'")
-
- if " " in command or "\t" in command:
- raise MCPClientError(
- "'command' must be a single executable name without spaces; "
- "pass arguments via the 'args' field"
- )
-
- # Write stripped command back for use by connect()
- config["command"] = command
-
- # Extract base command (handle paths like /usr/bin/node)
- base_cmd = Path(command).name
- if base_cmd not in ALLOWED_COMMANDS:
- raise MCPClientError(
- f"Command '{base_cmd}' not in allowed list: {ALLOWED_COMMANDS}. "
- f"Add to ALLOWED_COMMANDS if this is a trusted command."
- )
-
- # Validate args are a list of strings
- args = config.get("args", [])
- if not isinstance(args, list):
- raise MCPClientError("Server 'args' must be a list")
- if not all(isinstance(a, str) for a in args):
- raise MCPClientError("Server 'args' must contain only strings")
-
- # Validate env is a dict of strings if provided
- env = config.get("env")
- if env is not None:
- if not isinstance(env, dict):
- raise MCPClientError("Server 'env' must be a dictionary")
- if not all(
- isinstance(k, str) and isinstance(v, str)
- for k, v in env.items()
- ):
- raise MCPClientError(
- "Server 'env' must contain only string keys and values"
- )
-
- @asynccontextmanager
- async def connect(self):
- """
- Connect to the MCP server as an async context manager.
-
- Yields:
- self: The connected client instance
- """
- server_params = StdioServerParameters(
- command=self.config["command"],
- args=self.config.get("args", []),
- env=self.config.get("env"),
- )
-
- logger.info(f"Connecting to MCP server '{self.name}'...")
-
- try:
- async with stdio_client(server_params) as (
- read_stream,
- write_stream,
- ):
- self._read_stream = read_stream
- self._write_stream = write_stream
-
- # ClientSession must be used as async context manager
- async with ClientSession(read_stream, write_stream) as session:
- self._session = session
-
- await self._initialize_with_retry()
-
- self._connected = True
- logger.info(f"Connected to MCP server '{self.name}'")
-
- yield self
-
- except Exception as e:
- logger.exception(f"Failed to connect to MCP server '{self.name}'")
- raise MCPClientError(f"Connection failed: {e}") from e
- finally:
- self._connected = False
- self._session = None
- self._read_stream = None
- self._write_stream = None
-
- async def _initialize_with_retry(self) -> None:
- """Initialize the MCP session with retry logic for subprocess startup race.
-
- Retries on TimeoutError and "before initialization" errors using
- exponential backoff, then wraps final failures in MCPClientError.
- """
- try:
- async for attempt in AsyncRetrying(
- stop=stop_after_attempt(INIT_RETRY_ATTEMPTS),
- wait=wait_exponential(
- multiplier=INIT_RETRY_BASE_DELAY,
- max=INIT_RETRY_MAX_DELAY,
- exp_base=INIT_RETRY_BACKOFF_FACTOR,
- ),
- retry=(
- retry_if_exception_type(asyncio.TimeoutError)
- | retry_if_exception_message(
- match="(?i)before initialization"
- )
- ),
- before_sleep=lambda rs: logger.debug(
- f"Server '{self.name}' not ready "
- f"(attempt {rs.attempt_number}/{INIT_RETRY_ATTEMPTS}), retrying..."
- ),
- reraise=True,
- ):
- with attempt:
- if self._session is None:
- raise MCPClientError("Session not initialized") # noqa: TRY301 — re-raised by except MCPClientError
- await asyncio.wait_for(
- self._session.initialize(),
- timeout=min(5.0, self.timeout),
- )
- except asyncio.TimeoutError as e:
- raise MCPClientError(
- f"Timeout initializing connection to '{self.name}' "
- f"after {INIT_RETRY_ATTEMPTS} attempts"
- ) from e
- except MCPClientError:
- raise
- except Exception as e:
- if "before initialization" in str(e).lower():
- raise MCPClientError(
- f"Failed to initialize connection to '{self.name}' "
- f"after {INIT_RETRY_ATTEMPTS} attempts: {e}"
- ) from e
- raise
-
- async def list_tools(self) -> List[Dict[str, Any]]:
- """
- List available tools on the connected server.
-
- Returns:
- List of tool definitions with name, description, and input schema
- """
- if not self._connected or not self._session:
- raise MCPClientError("Not connected to server")
-
- try:
- result = await asyncio.wait_for(
- self._session.list_tools(),
- timeout=self.timeout,
- )
- tools = []
- for tool in result.tools:
- tools.append(
- {
- "name": tool.name,
- "description": tool.description or "",
- "input_schema": (
- tool.inputSchema
- if hasattr(tool, "inputSchema")
- else {}
- ),
- }
- )
- return tools
- except asyncio.TimeoutError:
- logger.warning(
- f"Timeout listing tools from '{self.name}' after {self.timeout}s"
- )
- raise MCPClientError(f"Timeout listing tools after {self.timeout}s")
- except Exception as e:
- logger.exception(f"Failed to list tools from '{self.name}'")
- raise MCPClientError(f"Failed to list tools: {e}") from e
-
- async def call_tool(
- self,
- name: str,
- arguments: Optional[Dict[str, Any]] = None,
- ) -> Dict[str, Any]:
- """
- Call a tool on the connected server.
-
- Args:
- name: Name of the tool to call
- arguments: Arguments to pass to the tool
-
- Returns:
- Tool result as a dictionary
- """
- if not self._connected or not self._session:
- raise MCPClientError("Not connected to server")
-
- try:
- logger.debug(
- f"Calling tool '{name}' on '{self.name}' with args: {arguments}"
- )
-
- result = await asyncio.wait_for(
- self._session.call_tool(name, arguments or {}),
- timeout=self.timeout,
- )
-
- # Parse the result
- if result.isError:
- return {
- "status": "error",
- "error": str(result.content),
- }
-
- # Extract content from the result
- content = []
- # Check if result.content is iterable (not None or other non-iterable types)
- if result.content is not None and hasattr(
- result.content, "__iter__"
- ):
- for item in result.content:
- if hasattr(item, "text"):
- content.append(item.text)
- elif hasattr(item, "data"):
- content.append(str(item.data))
- else:
- content.append(str(item))
- elif result.content is not None:
- # Handle non-iterable content by converting to string
- content.append(str(result.content))
-
- return {
- "status": "success",
- "content": "\n".join(content) if content else "",
- "raw": result.content,
- }
-
- except asyncio.TimeoutError:
- logger.exception(
- f"Tool call '{name}' timed out after {self.timeout}s"
- )
- raise MCPClientError(f"Tool call timed out after {self.timeout}s")
- except Exception as e:
- logger.exception(f"Failed to call tool '{name}' on '{self.name}'")
- raise MCPClientError(f"Tool call failed: {e}") from e
-
-
-class MCPClientManager:
- """
- Manager for multiple MCP client connections.
-
- Handles connecting to multiple MCP servers and aggregating their tools.
- """
-
- def __init__(self, server_configs: List[Dict[str, Any]]):
- """
- Initialize the manager with server configurations.
-
- Args:
- server_configs: List of server configurations
- """
- self.server_configs = server_configs
- self._clients: Dict[str, MCPClient] = {}
-
- @asynccontextmanager
- async def connect_all(self):
- """
- Connect to all configured MCP servers.
-
- Yields:
- self: The manager with all clients connected
- """
- # Create clients for each server
- clients = [MCPClient(config) for config in self.server_configs]
-
- # Connect to all servers
- # Connect sequentially to avoid overwhelming the system.
- # AsyncExitStack manages cleanup of successfully-entered contexts.
- async with AsyncExitStack() as stack:
- for client in clients:
- ctx = None
- try:
- ctx = client.connect()
- connected = await stack.enter_async_context(ctx)
- self._clients[client.name] = connected
- except Exception:
- logger.warning(
- f"Failed to connect to server '{client.name}'. Skipping."
- )
- # If ctx was created but __aenter__ failed, clean up
- # manually — AsyncExitStack only tracks contexts that
- # were successfully entered, but the MCP subprocess
- # may already be running.
- if ctx is not None:
- try:
- await ctx.__aexit__(None, None, None)
- except Exception:
- logger.debug(
- "best-effort cleanup of partially-entered async context",
- exc_info=True,
- )
-
- try:
- yield self
- finally:
- self._clients.clear()
-
- async def list_all_tools(self) -> Dict[str, List[Dict[str, Any]]]:
- """
- List tools from all connected servers.
-
- Returns:
- Dictionary mapping server name to list of tools
- """
- all_tools = {}
- for name, client in self._clients.items():
- try:
- tools = await client.list_tools()
- all_tools[name] = tools
- except MCPClientError:
- logger.warning(f"Failed to list tools from '{name}'")
- all_tools[name] = []
- return all_tools
-
- async def call_tool(
- self,
- server_name: str,
- tool_name: str,
- arguments: Optional[Dict[str, Any]] = None,
- ) -> Dict[str, Any]:
- """
- Call a tool on a specific server.
-
- Args:
- server_name: Name of the server
- tool_name: Name of the tool to call
- arguments: Arguments to pass to the tool
-
- Returns:
- Tool result
- """
- if server_name not in self._clients:
- raise MCPClientError(f"Server '{server_name}' not connected")
-
- return await self._clients[server_name].call_tool(tool_name, arguments)
-
- def get_connected_servers(self) -> List[str]:
- """Get list of connected server names."""
- return list(self._clients.keys())
-
-
-def run_async(coro, timeout: float = 300.0):
- """
- Run an async coroutine synchronously.
-
- Helper for running async MCP operations from sync code.
-
- Args:
- coro: The coroutine to run
- timeout: Maximum time to wait in seconds (default 5 minutes)
-
- Returns:
- The result of the coroutine
-
- Raises:
- MCPClientError: If the operation times out
- """
- import concurrent.futures
-
- try:
- # Check if we're already in an async context
- asyncio.get_running_loop()
- # We are in an async context - use thread pool to avoid nesting
- with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
- future = executor.submit(
- asyncio.run, asyncio.wait_for(coro, timeout=timeout)
- )
- try:
- return future.result(timeout=timeout + 5.0)
- except TimeoutError:
- raise MCPClientError(
- f"Async operation timed out after {timeout}s"
- )
- except RuntimeError:
- # No running event loop - safe to use asyncio.run()
- try:
- return asyncio.run(asyncio.wait_for(coro, timeout=timeout))
- except TimeoutError:
- raise MCPClientError(f"Async operation timed out after {timeout}s")
diff --git a/src/local_deep_research/search_system_factory.py b/src/local_deep_research/search_system_factory.py
index e20f7b4e15..58d6e50ea5 100644
--- a/src/local_deep_research/search_system_factory.py
+++ b/src/local_deep_research/search_system_factory.py
@@ -334,30 +334,22 @@ def create_strategy(
generate_text=kwargs.get("generate_text", True),
)
- # MCP strategy (ReAct pattern - agentic research)
- if strategy_name_lower in ["mcp", "agentic"]:
- from .advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- # Get MCP server configurations from settings
- mcp_servers = kwargs.get(
- "mcp_servers",
- _get_setting(settings_snapshot, "mcp.servers", []),
- )
-
- return MCPSearchStrategy(
- model=model,
- search=search,
- mcp_servers=mcp_servers,
- max_iterations=kwargs.get("max_iterations", 10),
- include_web_search=kwargs.get("include_web_search", True),
- all_links_of_system=all_links_of_system,
- settings_snapshot=settings_snapshot,
- )
-
- # LangGraph agent strategy (parallel subagent research)
- if strategy_name_lower in ["langgraph-agent", "langgraph_agent"]:
+ # LangGraph agent strategy (parallel subagent research).
+ # ``mcp`` / ``agentic`` were removed (#4548); they remain here as
+ # deprecated aliases so existing saved settings, queued runs, and API
+ # callers route to the closest successor (langgraph-agent) instead of
+ # the source-based fallback below.
+ if strategy_name_lower in [
+ "langgraph-agent",
+ "langgraph_agent",
+ "mcp",
+ "agentic",
+ ]:
+ if strategy_name_lower in ("mcp", "agentic"):
+ logger.warning(
+ f"Strategy {strategy_name!r} was removed (#4548); "
+ "using 'langgraph-agent' instead."
+ )
from .advanced_search_system.strategies.langgraph_agent_strategy import (
LangGraphAgentStrategy,
)
diff --git a/src/local_deep_research/security/egress/README.md b/src/local_deep_research/security/egress/README.md
index bf95b7e4bb..048554412c 100644
--- a/src/local_deep_research/security/egress/README.md
+++ b/src/local_deep_research/security/egress/README.md
@@ -105,7 +105,6 @@ actually enforces the policy":
|---|---|---|
| Search engine creation | `web_search_engines/search_engine_factory.py` (`create_search_engine`) | `evaluate_engine` / `evaluate_retriever` |
| LangGraph agent tools | `advanced_search_system/strategies/langgraph_agent_strategy.py` (`_build_tools`) | `evaluate_engine` / `evaluate_retriever` (tool-list filter) |
-| MCP agent tools | `advanced_search_system/strategies/mcp_strategy.py` (`_build_tool_descriptions`) | `evaluate_engine` / `evaluate_retriever` (tool-list filter) |
| Full-content fetch | `web_search_engines/engines/full_search.py` | `evaluate_url` |
| Content fetcher tool | `content_fetcher/fetcher.py` | `policy_aware_validate_url` + `evaluate_url` |
| Library downloads | `research_library/services/download_service.py` | `evaluate_url` at the fetch fire-points |
@@ -188,7 +187,7 @@ silent-expansion timing leak.
- `tests/security/test_egress_audit_hook.py` — the PEP-578 hook (context
lifecycle, re-entrancy, scope gating).
- `tests/security/test_egress_pep_coverage.py` — the distributed PEPs.
-- Plus per-domain tests (factory, langgraph/mcp strategies, embeddings,
+- Plus per-domain tests (factory, langgraph strategy, embeddings,
download service, settings validators, warning banners, collections API).
## Data-flow reference (private vs public)
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index b2d11ff503..cecb8c9e81 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -157,7 +157,6 @@ ALLOWED_SETTING_PREFIXES = frozenset(
"langgraph_agent.",
"llm.",
"local_search_",
- "mcp.",
"news.",
"notifications.",
"rag.",
diff --git a/src/local_deep_research/web_search_engines/search_engines_config.py b/src/local_deep_research/web_search_engines/search_engines_config.py
index ebee4c2c91..4068121270 100644
--- a/src/local_deep_research/web_search_engines/search_engines_config.py
+++ b/src/local_deep_research/web_search_engines/search_engines_config.py
@@ -282,7 +282,7 @@ def get_available_engines(
and with valid API keys when required.
This is the single shared filter used by the langgraph-agent tool
- builder and MCPSearchStrategy so they all agree on which engines are
+ builder so it agrees with the rest of the system on which engines are
available.
Args:
diff --git a/tests/advanced_search_system/strategies/test_mcp_strategy_pure_logic.py b/tests/advanced_search_system/strategies/test_mcp_strategy_pure_logic.py
deleted file mode 100644
index 90ee8e35ac..0000000000
--- a/tests/advanced_search_system/strategies/test_mcp_strategy_pure_logic.py
+++ /dev/null
@@ -1,278 +0,0 @@
-"""
-Pure-logic tests for MCPSearchStrategy helper methods.
-
-Tests _to_bool, _build_tool_schemas, _get_current_engine_name,
-_format_tool_descriptions, _format_history, _parse_response fallback
-branches, and _validate_tool_arguments — no LLM or search calls.
-"""
-
-from unittest.mock import Mock
-
-from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- _to_bool,
-)
-
-
-# ---------------------------------------------------------------------------
-# _to_bool (module-level helper)
-# ---------------------------------------------------------------------------
-
-
-class TestToBool:
- """Verify string-to-bool conversion handling."""
-
- def test_string_false(self):
- assert _to_bool("false") is False
-
- def test_string_FALSE_case_insensitive(self):
- assert _to_bool("FALSE") is False
-
- def test_string_zero(self):
- assert _to_bool("0") is False
-
- def test_string_no(self):
- assert _to_bool("no") is False
-
- def test_string_empty(self):
- assert _to_bool("") is False
-
- def test_string_whitespace_false(self):
- assert _to_bool(" false ") is False
-
- def test_string_true(self):
- assert _to_bool("true") is True
-
- def test_string_yes(self):
- assert _to_bool("yes") is True
-
- def test_string_one(self):
- assert _to_bool("1") is True
-
- def test_string_arbitrary(self):
- assert _to_bool("anything") is True
-
- def test_bool_true(self):
- assert _to_bool(True) is True
-
- def test_bool_false(self):
- assert _to_bool(False) is False
-
- def test_int_zero(self):
- assert _to_bool(0) is False
-
- def test_int_nonzero(self):
- assert _to_bool(42) is True
-
- def test_none(self):
- assert _to_bool(None) is False
-
-
-# ---------------------------------------------------------------------------
-# _build_tool_schemas
-# ---------------------------------------------------------------------------
-
-
-def _make_strategy():
- """Build a minimal Mock for MCPSearchStrategy."""
- s = Mock(spec=[])
- s.OBSERVATION_MAX_LENGTH = 5000
- s.MAX_ARG_LENGTH = 10000
- s.HISTORY_OBSERVATION_MAX_LENGTH = 1000
- s.DIRECT_ANSWER_MIN_LENGTH = 300
- s.THOUGHT_PREVIEW_LENGTH = 200
- s.OBSERVATION_PREVIEW_LENGTH = 500
- s.RAW_RESPONSE_PREVIEW_LENGTH = 500
- s._history = []
- s._sources = []
- return s
-
-
-class TestBuildToolSchemas:
- """Verify OpenAI-style schema generation from tool dicts."""
-
- def test_empty_tools(self):
- s = _make_strategy()
- result = MCPSearchStrategy._build_tool_schemas(s, [])
- assert result == []
-
- def test_single_tool_no_params(self):
- s = _make_strategy()
- tools = [
- {
- "name": "search",
- "description": "Search the web",
- "parameters": {},
- }
- ]
- result = MCPSearchStrategy._build_tool_schemas(s, tools)
- assert len(result) == 1
- schema = result[0]
- assert schema["type"] == "function"
- assert schema["function"]["name"] == "search"
- assert schema["function"]["description"] == "Search the web"
- assert schema["function"]["parameters"]["properties"] == {}
- assert schema["function"]["parameters"]["required"] == []
-
- def test_tool_with_required_param(self):
- s = _make_strategy()
- tools = [
- {
- "name": "lookup",
- "description": "Look up a term",
- "parameters": {
- "query": {
- "type": "string",
- "description": "search query",
- "required": True,
- }
- },
- }
- ]
- result = MCPSearchStrategy._build_tool_schemas(s, tools)
- func = result[0]["function"]
- assert "query" in func["parameters"]["properties"]
- assert func["parameters"]["required"] == ["query"]
-
- def test_tool_with_optional_param(self):
- s = _make_strategy()
- tools = [
- {
- "name": "fetch",
- "description": "Fetch URL",
- "parameters": {
- "url": {
- "type": "string",
- "description": "target URL",
- "required": False,
- }
- },
- }
- ]
- result = MCPSearchStrategy._build_tool_schemas(s, tools)
- assert result[0]["function"]["parameters"]["required"] == []
-
- def test_multiple_tools(self):
- s = _make_strategy()
- tools = [
- {"name": "a", "description": "A", "parameters": {}},
- {"name": "b", "description": "B", "parameters": {}},
- ]
- result = MCPSearchStrategy._build_tool_schemas(s, tools)
- assert len(result) == 2
- assert result[0]["function"]["name"] == "a"
- assert result[1]["function"]["name"] == "b"
-
- def test_param_type_defaults_to_string(self):
- s = _make_strategy()
- tools = [
- {
- "name": "t",
- "description": "T",
- "parameters": {
- "x": {"description": "val"} # no "type" key
- },
- }
- ]
- result = MCPSearchStrategy._build_tool_schemas(s, tools)
- props = result[0]["function"]["parameters"]["properties"]
- assert props["x"]["type"] == "string"
-
- def test_missing_parameters_key(self):
- s = _make_strategy()
- tools = [{"name": "t", "description": "T"}]
- result = MCPSearchStrategy._build_tool_schemas(s, tools)
- assert result[0]["function"]["parameters"]["properties"] == {}
-
-
-# ---------------------------------------------------------------------------
-# _get_current_engine_name
-# ---------------------------------------------------------------------------
-
-
-class TestGetCurrentEngineName:
- """Verify engine name extraction from class name."""
-
- def test_typical_engine_name(self):
- s = _make_strategy()
-
- class ArXivSearchEngine:
- pass
-
- s.search = ArXivSearchEngine()
- result = MCPSearchStrategy._get_current_engine_name(s)
- assert result == "arxiv"
-
- def test_google_engine(self):
- s = _make_strategy()
-
- class GoogleSearchEngine:
- pass
-
- s.search = GoogleSearchEngine()
- assert MCPSearchStrategy._get_current_engine_name(s) == "google"
-
- def test_no_class_attr(self):
- s = _make_strategy()
- s.search = 42 # int has __class__ but no "SearchEngine" in name
- result = MCPSearchStrategy._get_current_engine_name(s)
- # Should return the lowered class name with SearchEngine removed
- assert isinstance(result, str)
-
- def test_plain_class(self):
- s = _make_strategy()
-
- class CustomEngine:
- pass
-
- s.search = CustomEngine()
- assert MCPSearchStrategy._get_current_engine_name(s) == "customengine"
-
-
-# ---------------------------------------------------------------------------
-# _validate_tool_arguments
-# ---------------------------------------------------------------------------
-
-
-class TestValidateToolArguments:
- """Verify argument sanitization logic."""
-
- def test_non_dict_returns_empty(self):
- s = _make_strategy()
- assert MCPSearchStrategy._validate_tool_arguments(s, "not a dict") == {}
-
- def test_none_returns_empty(self):
- s = _make_strategy()
- assert MCPSearchStrategy._validate_tool_arguments(s, None) == {}
-
- def test_passthrough_normal_args(self):
- s = _make_strategy()
- args = {"query": "test", "count": 5}
- result = MCPSearchStrategy._validate_tool_arguments(s, args)
- assert result == args
-
- def test_non_string_keys_filtered(self):
- s = _make_strategy()
- args = {"valid": "yes", 123: "no"}
- result = MCPSearchStrategy._validate_tool_arguments(s, args)
- assert "valid" in result
- assert 123 not in result
-
- def test_long_string_truncated(self):
- s = _make_strategy()
- long_val = "x" * (s.MAX_ARG_LENGTH + 100)
- args = {"text": long_val}
- result = MCPSearchStrategy._validate_tool_arguments(s, args)
- assert len(result["text"]) == s.MAX_ARG_LENGTH
-
- def test_short_string_not_truncated(self):
- s = _make_strategy()
- args = {"text": "short"}
- result = MCPSearchStrategy._validate_tool_arguments(s, args)
- assert result["text"] == "short"
-
- def test_non_string_values_preserved(self):
- s = _make_strategy()
- args = {"count": 42, "flag": True, "items": [1, 2]}
- result = MCPSearchStrategy._validate_tool_arguments(s, args)
- assert result == args
diff --git a/tests/database/test_alembic_migrations.py b/tests/database/test_alembic_migrations.py
index ea72d7f0dc..d7a9f4df40 100644
--- a/tests/database/test_alembic_migrations.py
+++ b/tests/database/test_alembic_migrations.py
@@ -6047,6 +6047,9 @@ class TestMigrationSafetyGuards:
# 0016: the dropped cache tables were orphaned dead code holding no
# data, and their models are removed — nothing to recreate.
"0016_drop_orphaned_cache_tables.py",
+ # 0018: restoring 'mcp'/'agentic' strategy references would recreate
+ # broken state — that strategy no longer exists in the codebase.
+ "0018_remove_mcp_strategy.py",
}
# Migrations whose downgrade is intentionally NotImplementedError
diff --git a/tests/database/test_migration_0017_download_queue_research_status_index.py b/tests/database/test_migration_0017_download_queue_research_status_index.py
index c693695c8e..7e671c6a7a 100644
--- a/tests/database/test_migration_0017_download_queue_research_status_index.py
+++ b/tests/database/test_migration_0017_download_queue_research_status_index.py
@@ -15,7 +15,6 @@ from sqlalchemy import create_engine, inspect, text
from local_deep_research.database.alembic_runner import (
get_alembic_config,
- get_head_revision,
stamp_database,
)
@@ -141,7 +140,6 @@ class TestMigration0017Downgrade:
).scalar()
assert count == 1
-
-class TestMigration0017HeadAlignment:
- def test_head_revision_is_0017(self):
- assert get_head_revision() == "0017"
+# Head-alignment guard moved to test_migration_0018_remove_mcp_strategy.py:
+# 0017 is no longer the latest revision (0018 chains after it). The guard
+# always lives in the newest migration's test file.
diff --git a/tests/database/test_migration_0018_remove_mcp_strategy.py b/tests/database/test_migration_0018_remove_mcp_strategy.py
new file mode 100644
index 0000000000..4831697702
--- /dev/null
+++ b/tests/database/test_migration_0018_remove_mcp_strategy.py
@@ -0,0 +1,379 @@
+"""Tests for migration 0018: remove the 'mcp'/'agentic' search strategy.
+
+Pins the upgrade semantics:
+- ``search.search_strategy`` rows naming a removed strategy (mcp / agentic)
+ are rewritten to ``langgraph-agent``; concrete choices are preserved.
+- The orphaned ``mcp.servers`` setting row is deleted.
+- ``news_subscriptions.search_strategy`` is NULLed for removed strategies
+ (falsy means "use the user's default strategy" in the scheduler).
+- ``queued_researches.settings_snapshot`` JSON has both the top-level
+ ``submission.strategy`` and the embedded ``search.search_strategy``
+ rewritten, for the nested and the legacy flat snapshot structure.
+- ``benchmark_runs`` / ``benchmark_configs`` ``search_config.search_strategy``
+ is rewritten.
+- The settings ``value`` column stores JSON text (``"mcp"`` with quotes); the
+ rewritten value must be stored as ``"langgraph-agent"`` (single JSON
+ encoding) — a raw-bytes assertion guards against double-encoding.
+- Idempotency: re-running the upgrade is a no-op.
+"""
+
+import json
+
+import pytest
+from alembic import command
+from sqlalchemy import create_engine, text
+
+from local_deep_research.database.alembic_runner import (
+ get_alembic_config,
+)
+
+REMOVED = ["mcp", "agentic"]
+REPLACEMENT = "langgraph-agent"
+
+
+def _run_upgrade_to(engine, revision):
+ config = get_alembic_config(engine)
+ with engine.begin() as conn:
+ config.attributes["connection"] = conn
+ command.upgrade(config, revision)
+
+
+def _seed_setting(engine, key, value):
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO settings "
+ "(key, value, type, name, ui_element, visible, editable) "
+ "VALUES (:key, :value, 'search', :name, 'select', 1, 1)"
+ ),
+ {"key": key, "value": json.dumps(value), "name": key},
+ )
+
+
+def _read_setting(engine, key):
+ with engine.begin() as conn:
+ row = conn.execute(
+ text("SELECT value FROM settings WHERE key = :key"),
+ {"key": key},
+ ).fetchone()
+ if row is None:
+ return None
+ raw = row[0]
+ return json.loads(raw) if isinstance(raw, str) else raw
+
+
+def _read_setting_raw(engine, key):
+ """Return the stored bytes of ``settings.value`` without decoding."""
+ with engine.begin() as conn:
+ row = conn.execute(
+ text("SELECT value FROM settings WHERE key = :key"),
+ {"key": key},
+ ).fetchone()
+ return None if row is None else row[0]
+
+
+def migrated_to_0017_engine(tmp_path):
+ """Database fully migrated through 0017 (the revision before 0018)."""
+ db_path = tmp_path / "test_0018.db"
+ engine = create_engine(f"sqlite:///{db_path}")
+ _run_upgrade_to(engine, "0017")
+ yield engine
+ engine.dispose()
+
+
+class TestMigration0018Settings:
+ @pytest.mark.parametrize("removed_value", REMOVED)
+ def test_strategy_rewritten_to_langgraph_agent(
+ self, migrated_to_0017_engine, removed_value
+ ):
+ engine = migrated_to_0017_engine
+ _seed_setting(engine, "search.search_strategy", removed_value)
+
+ _run_upgrade_to(engine, "0018")
+
+ assert _read_setting(engine, "search.search_strategy") == REPLACEMENT
+
+ @pytest.mark.parametrize("removed_value", REMOVED)
+ def test_rewritten_value_stored_single_encoded(
+ self, migrated_to_0017_engine, removed_value
+ ):
+ """The stored bytes must be ``"langgraph-agent"`` (single JSON
+ encoding), not a double-encoded ``"\\"langgraph-agent\\""``."""
+ engine = migrated_to_0017_engine
+ _seed_setting(engine, "search.search_strategy", removed_value)
+
+ _run_upgrade_to(engine, "0018")
+
+ assert _read_setting_raw(
+ engine, "search.search_strategy"
+ ) == json.dumps(REPLACEMENT)
+
+ @pytest.mark.parametrize(
+ "concrete", ["source-based", "focused-iteration", "topic-organization"]
+ )
+ def test_concrete_strategy_preserved(
+ self, migrated_to_0017_engine, concrete
+ ):
+ engine = migrated_to_0017_engine
+ _seed_setting(engine, "search.search_strategy", concrete)
+
+ _run_upgrade_to(engine, "0018")
+
+ assert _read_setting(engine, "search.search_strategy") == concrete
+
+ def test_mcp_servers_setting_deleted(self, migrated_to_0017_engine):
+ engine = migrated_to_0017_engine
+ _seed_setting(engine, "mcp.servers", [{"command": "npx"}])
+
+ _run_upgrade_to(engine, "0018")
+
+ assert _read_setting(engine, "mcp.servers") is None
+
+ def test_upgrade_is_idempotent(self, migrated_to_0017_engine):
+ engine = migrated_to_0017_engine
+ _seed_setting(engine, "search.search_strategy", "mcp")
+
+ _run_upgrade_to(engine, "0018")
+ _run_upgrade_to(engine, "0018")
+
+ assert _read_setting(engine, "search.search_strategy") == REPLACEMENT
+
+ def test_missing_rows_are_a_clean_noop(self, migrated_to_0017_engine):
+ engine = migrated_to_0017_engine
+
+ _run_upgrade_to(engine, "0018")
+
+ assert _read_setting(engine, "search.search_strategy") is None
+
+
+class TestMigration0018NewsSubscriptions:
+ def _seed_subscription(self, engine, sub_id, search_strategy):
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO news_subscriptions "
+ "(id, subscription_type, query_or_topic, search_strategy) "
+ "VALUES (:id, 'search', 'test query', :ss)"
+ ),
+ {"id": sub_id, "ss": search_strategy},
+ )
+
+ def _read_subscription_strategy(self, engine, sub_id):
+ with engine.begin() as conn:
+ return conn.execute(
+ text(
+ "SELECT search_strategy FROM news_subscriptions "
+ "WHERE id = :id"
+ ),
+ {"id": sub_id},
+ ).fetchone()[0]
+
+ def test_removed_strategy_nulled_concrete_preserved(
+ self, migrated_to_0017_engine
+ ):
+ engine = migrated_to_0017_engine
+ self._seed_subscription(engine, "sub-mcp", "mcp")
+ self._seed_subscription(engine, "sub-agentic", "agentic")
+ self._seed_subscription(engine, "sub-lg", "langgraph-agent")
+ self._seed_subscription(engine, "sub-null", None)
+
+ _run_upgrade_to(engine, "0018")
+
+ assert self._read_subscription_strategy(engine, "sub-mcp") is None
+ assert self._read_subscription_strategy(engine, "sub-agentic") is None
+ assert (
+ self._read_subscription_strategy(engine, "sub-lg")
+ == "langgraph-agent"
+ )
+ assert self._read_subscription_strategy(engine, "sub-null") is None
+
+
+class TestMigration0018QueuedResearches:
+ def _seed_queued(self, engine, research_id, snapshot):
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO queued_researches "
+ "(username, research_id, query, mode, settings_snapshot, "
+ "position) "
+ "VALUES ('tester', :rid, 'q', 'quick', :snap, 1)"
+ ),
+ {"rid": research_id, "snap": json.dumps(snapshot)},
+ )
+
+ def _read_snapshot(self, engine, research_id):
+ with engine.begin() as conn:
+ raw = conn.execute(
+ text(
+ "SELECT settings_snapshot FROM queued_researches "
+ "WHERE research_id = :rid"
+ ),
+ {"rid": research_id},
+ ).fetchone()[0]
+ return json.loads(raw) if isinstance(raw, str) else raw
+
+ def test_nested_submission_strategy_rewritten(
+ self, migrated_to_0017_engine
+ ):
+ engine = migrated_to_0017_engine
+ self._seed_queued(
+ engine,
+ "rid-nested",
+ {
+ "submission": {"strategy": "mcp", "model": "m"},
+ "settings_snapshot": {
+ "search.search_strategy": {
+ "value": "agentic",
+ "type": "SEARCH",
+ }
+ },
+ },
+ )
+
+ _run_upgrade_to(engine, "0018")
+
+ snap = self._read_snapshot(engine, "rid-nested")
+ assert snap["submission"]["strategy"] == "langgraph-agent"
+ assert (
+ snap["settings_snapshot"]["search.search_strategy"]["value"]
+ == "langgraph-agent"
+ )
+
+ def test_legacy_flat_snapshot_rewritten(self, migrated_to_0017_engine):
+ engine = migrated_to_0017_engine
+ self._seed_queued(
+ engine, "rid-flat", {"strategy": "agentic", "model": "m"}
+ )
+
+ _run_upgrade_to(engine, "0018")
+
+ snap = self._read_snapshot(engine, "rid-flat")
+ assert snap["strategy"] == "langgraph-agent"
+
+ def test_concrete_strategy_snapshot_untouched(
+ self, migrated_to_0017_engine
+ ):
+ engine = migrated_to_0017_engine
+ original = {
+ "submission": {"strategy": "source-based"},
+ "settings_snapshot": {"search.search_strategy": "source-based"},
+ }
+ self._seed_queued(engine, "rid-src", original)
+
+ _run_upgrade_to(engine, "0018")
+
+ assert self._read_snapshot(engine, "rid-src") == original
+
+
+class TestMigration0018Benchmarks:
+ def _seed_config(self, engine, name, search_strategy):
+ search_config = json.dumps(
+ {"search_strategy": search_strategy, "iterations": 2}
+ )
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO benchmark_configs "
+ "(name, config_hash, search_config, evaluation_config, "
+ "datasets_config, created_at, updated_at, is_default, "
+ "is_public, usage_count) "
+ "VALUES (:name, 'abcd1234', :sc, '{}', '{}', "
+ "CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 0, 0, 0)"
+ ),
+ {"name": name, "sc": search_config},
+ )
+
+ def _read_config_strategy(self, engine, name):
+ with engine.begin() as conn:
+ raw = conn.execute(
+ text(
+ "SELECT search_config FROM benchmark_configs "
+ "WHERE name = :name"
+ ),
+ {"name": name},
+ ).fetchone()[0]
+ config = json.loads(raw) if isinstance(raw, str) else raw
+ return config["search_strategy"]
+
+ def test_benchmark_config_strategy_rewritten(self, migrated_to_0017_engine):
+ engine = migrated_to_0017_engine
+ self._seed_config(engine, "cfg-mcp", "mcp")
+ self._seed_config(engine, "cfg-src", "source-based")
+
+ _run_upgrade_to(engine, "0018")
+
+ assert (
+ self._read_config_strategy(engine, "cfg-mcp") == "langgraph-agent"
+ )
+ assert self._read_config_strategy(engine, "cfg-src") == "source-based"
+
+ def _seed_run(self, engine, run_name, search_strategy):
+ search_config = json.dumps(
+ {"search_strategy": search_strategy, "iterations": 2}
+ )
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO benchmark_runs "
+ "(run_name, config_hash, query_hash_list, search_config, "
+ "evaluation_config, datasets_config, status, created_at, "
+ "updated_at, total_examples, completed_examples, "
+ "failed_examples) "
+ "VALUES (:name, 'h0', '[]', :sc, '{}', '{}', 'PENDING', "
+ "'2026-01-01 00:00:00', '2026-01-01 00:00:00', 0, 0, 0)"
+ ),
+ {"name": run_name, "sc": search_config},
+ )
+
+ def _read_run_strategy(self, engine, run_name):
+ with engine.begin() as conn:
+ raw = conn.execute(
+ text(
+ "SELECT search_config FROM benchmark_runs "
+ "WHERE run_name = :name"
+ ),
+ {"name": run_name},
+ ).fetchone()[0]
+ config = json.loads(raw) if isinstance(raw, str) else raw
+ return config["search_strategy"]
+
+ def test_benchmark_run_strategy_rewritten(self, migrated_to_0017_engine):
+ # upgrade() rewrites search_config in BOTH benchmark_runs and
+ # benchmark_configs; this pins the benchmark_runs branch (the
+ # benchmark_configs path is covered above), guarding against a
+ # regression that breaks only one table binding.
+ engine = migrated_to_0017_engine
+ self._seed_run(engine, "run-mcp", "mcp")
+ self._seed_run(engine, "run-src", "source-based")
+
+ _run_upgrade_to(engine, "0018")
+
+ assert self._read_run_strategy(engine, "run-mcp") == "langgraph-agent"
+ assert self._read_run_strategy(engine, "run-src") == "source-based"
+
+
+class TestMigration0018HeadAlignment:
+ def test_0018_chains_correctly_to_0017(self):
+ from alembic.config import Config
+ from alembic.script import ScriptDirectory
+
+ from local_deep_research.database.alembic_runner import (
+ get_migrations_dir,
+ )
+
+ config = Config()
+ config.set_main_option("script_location", str(get_migrations_dir()))
+ script = ScriptDirectory.from_config(config)
+ rev_0018 = script.get_revision("0018")
+ assert rev_0018.down_revision == "0017"
+
+ def test_head_revision_is_0018(self):
+ # 0018 is now the latest revision. The head-alignment guard lives in
+ # the newest migration's test file (moved here from the 0017 test
+ # when this migration was rechained onto 0017 during the main merge).
+ from local_deep_research.database.alembic_runner import (
+ get_head_revision,
+ )
+
+ assert get_head_revision() == "0018"
diff --git a/tests/mcp/test_additional_coverage.py b/tests/mcp/test_additional_coverage.py
index 977cb10d2b..b1374176d8 100644
--- a/tests/mcp/test_additional_coverage.py
+++ b/tests/mcp/test_additional_coverage.py
@@ -414,7 +414,6 @@ class TestAvailableStrategiesContent:
"focused-iteration",
"focused-iteration-standard",
"topic-organization",
- "mcp",
"langgraph-agent",
]
diff --git a/tests/mcp/test_client_coverage.py b/tests/mcp/test_client_coverage.py
deleted file mode 100644
index 0b61173bca..0000000000
--- a/tests/mcp/test_client_coverage.py
+++ /dev/null
@@ -1,389 +0,0 @@
-"""Coverage tests for mcp/client.py.
-
-Focuses on:
-- MCPClient._validate_server_config error paths
-- MCPClient._initialize_with_retry timeout/error handling
-- MCPClient.list_tools / call_tool when not connected
-- MCPClient.call_tool result parsing (error flag, content types)
-- MCPClientManager.call_tool server not connected
-- MCPClientManager.list_all_tools error handling
-- MCPClientManager.get_connected_servers
-- run_async helper (sync and async context)
-- ALLOWED_COMMANDS constant
-"""
-
-import asyncio
-from unittest.mock import AsyncMock, MagicMock
-
-import pytest
-
-MODULE = "local_deep_research.mcp.client"
-
-
-# ---------------------------------------------------------------------------
-# Skip if MCP not installed
-# ---------------------------------------------------------------------------
-
-
-def _mcp_available():
- try:
- import mcp # noqa: F401
-
- return True
- except ImportError:
- return False
-
-
-pytestmark = pytest.mark.skipif(
- not _mcp_available(),
- reason="mcp package not installed",
-)
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _valid_config(command="python", name="test-server"):
- return {"command": command, "args": ["server.py"], "name": name}
-
-
-def _get_client_class():
- from local_deep_research.mcp.client import MCPClient
-
- return MCPClient
-
-
-def _get_error_class():
- from local_deep_research.mcp.client import MCPClientError
-
- return MCPClientError
-
-
-def _get_manager_class():
- from local_deep_research.mcp.client import MCPClientManager
-
- return MCPClientManager
-
-
-# ---------------------------------------------------------------------------
-# _validate_server_config
-# ---------------------------------------------------------------------------
-
-
-class TestValidateServerConfig:
- def test_missing_command_raises(self):
- MCPClientError = _get_error_class()
- MCPClient = _get_client_class()
- with pytest.raises(MCPClientError, match="missing 'command'"):
- MCPClient({})
-
- def test_empty_command_raises(self):
- MCPClientError = _get_error_class()
- MCPClient = _get_client_class()
- with pytest.raises(MCPClientError, match="missing 'command'"):
- MCPClient({"command": " "})
-
- def test_command_with_spaces_raises(self):
- MCPClientError = _get_error_class()
- MCPClient = _get_client_class()
- with pytest.raises(
- MCPClientError, match="single executable name without spaces"
- ):
- MCPClient({"command": "python script.py"})
-
- def test_disallowed_command_raises(self):
- MCPClientError = _get_error_class()
- MCPClient = _get_client_class()
- with pytest.raises(MCPClientError, match="not in allowed list"):
- MCPClient({"command": "bash"})
-
- def test_args_not_list_raises(self):
- MCPClientError = _get_error_class()
- MCPClient = _get_client_class()
- with pytest.raises(MCPClientError, match="'args' must be a list"):
- MCPClient({"command": "python", "args": "script.py"})
-
- def test_args_with_non_strings_raises(self):
- MCPClientError = _get_error_class()
- MCPClient = _get_client_class()
- with pytest.raises(
- MCPClientError, match="'args' must contain only strings"
- ):
- MCPClient({"command": "python", "args": [123]})
-
- def test_env_not_dict_raises(self):
- MCPClientError = _get_error_class()
- MCPClient = _get_client_class()
- with pytest.raises(MCPClientError, match="'env' must be a dictionary"):
- MCPClient({"command": "python", "env": ["KEY=VAL"]})
-
- def test_env_with_non_string_values_raises(self):
- MCPClientError = _get_error_class()
- MCPClient = _get_client_class()
- with pytest.raises(MCPClientError, match="only string keys and values"):
- MCPClient({"command": "python", "env": {"KEY": 42}})
-
- def test_valid_config_accepted(self):
- MCPClient = _get_client_class()
- client = MCPClient(_valid_config())
- assert client.name == "test-server"
- assert client.timeout == 60.0
-
- def test_path_based_command_accepted(self):
- """Full path to an allowed command like /usr/bin/node is accepted."""
- MCPClient = _get_client_class()
- client = MCPClient({"command": "/usr/bin/node", "args": []})
- assert client is not None
-
- def test_command_with_tab_raises(self):
- MCPClientError = _get_error_class()
- MCPClient = _get_client_class()
- with pytest.raises(
- MCPClientError, match="single executable name without spaces"
- ):
- MCPClient({"command": "python\tscript"})
-
-
-# ---------------------------------------------------------------------------
-# MCPClient when not connected
-# ---------------------------------------------------------------------------
-
-
-class TestMCPClientNotConnected:
- def test_list_tools_not_connected(self):
- MCPClient = _get_client_class()
- MCPClientError = _get_error_class()
- client = MCPClient(_valid_config())
- client._connected = False
- with pytest.raises(MCPClientError, match="Not connected"):
- asyncio.run(client.list_tools())
-
- def test_call_tool_not_connected(self):
- MCPClient = _get_client_class()
- MCPClientError = _get_error_class()
- client = MCPClient(_valid_config())
- client._connected = False
- with pytest.raises(MCPClientError, match="Not connected"):
- asyncio.run(client.call_tool("some_tool", {}))
-
-
-# ---------------------------------------------------------------------------
-# MCPClient.call_tool result parsing
-# ---------------------------------------------------------------------------
-
-
-class TestCallToolResultParsing:
- def _run(self, coro):
- return asyncio.run(coro)
-
- def _make_connected_client(self):
- MCPClient = _get_client_class()
- client = MCPClient(_valid_config())
- client._connected = True
- client._session = MagicMock()
- return client
-
- def test_error_result_returns_error_status(self):
- client = self._make_connected_client()
- mock_result = MagicMock()
- mock_result.isError = True
- mock_result.content = "Something went wrong"
- client._session.call_tool = AsyncMock(return_value=mock_result)
- result = self._run(client.call_tool("bad_tool"))
- assert result["status"] == "error"
-
- def test_success_result_with_text_content(self):
- client = self._make_connected_client()
- item = MagicMock()
- item.text = "result text"
- del item.data # Ensure no .data attr
- mock_result = MagicMock()
- mock_result.isError = False
- mock_result.content = [item]
- client._session.call_tool = AsyncMock(return_value=mock_result)
- result = self._run(client.call_tool("good_tool"))
- assert result["status"] == "success"
- assert "result text" in result["content"]
-
- def test_success_result_with_data_content(self):
- client = self._make_connected_client()
- item = MagicMock(spec=["data"])
- item.data = b"\x00\x01"
- mock_result = MagicMock()
- mock_result.isError = False
- mock_result.content = [item]
- client._session.call_tool = AsyncMock(return_value=mock_result)
- result = self._run(client.call_tool("data_tool"))
- assert result["status"] == "success"
-
- def test_success_result_with_none_content(self):
- client = self._make_connected_client()
- mock_result = MagicMock()
- mock_result.isError = False
- mock_result.content = None
- client._session.call_tool = AsyncMock(return_value=mock_result)
- result = self._run(client.call_tool("empty_tool"))
- assert result["status"] == "success"
- assert result["content"] == ""
-
- def test_timeout_raises_mcp_client_error(self):
- from local_deep_research.mcp.client import MCPClientError
-
- client = self._make_connected_client()
- client._session.call_tool = AsyncMock(
- side_effect=asyncio.TimeoutError("timed out")
- )
- with pytest.raises(MCPClientError, match="timed out"):
- self._run(client.call_tool("slow_tool"))
-
- def test_other_exception_raises_mcp_client_error(self):
- from local_deep_research.mcp.client import MCPClientError
-
- client = self._make_connected_client()
- client._session.call_tool = AsyncMock(
- side_effect=RuntimeError("unexpected")
- )
- with pytest.raises(MCPClientError, match="Tool call failed"):
- self._run(client.call_tool("fail_tool"))
-
-
-# ---------------------------------------------------------------------------
-# MCPClient.list_tools
-# ---------------------------------------------------------------------------
-
-
-class TestListTools:
- def _run(self, coro):
- return asyncio.run(coro)
-
- def _make_connected_client(self):
- MCPClient = _get_client_class()
- client = MCPClient(_valid_config())
- client._connected = True
- client._session = MagicMock()
- return client
-
- def test_list_tools_returns_tool_dicts(self):
- client = self._make_connected_client()
- tool = MagicMock()
- tool.name = "search"
- tool.description = "Search the web"
- tool.inputSchema = {"type": "object"}
- mock_result = MagicMock()
- mock_result.tools = [tool]
- client._session.list_tools = AsyncMock(return_value=mock_result)
- result = self._run(client.list_tools())
- assert len(result) == 1
- assert result[0]["name"] == "search"
- assert result[0]["description"] == "Search the web"
-
- def test_timeout_raises_mcp_client_error(self):
- from local_deep_research.mcp.client import MCPClientError
-
- client = self._make_connected_client()
- client._session.list_tools = AsyncMock(
- side_effect=asyncio.TimeoutError()
- )
- with pytest.raises(MCPClientError, match="Timeout listing tools"):
- self._run(client.list_tools())
-
- def test_tool_without_input_schema(self):
- client = self._make_connected_client()
- tool = MagicMock(spec=["name", "description"])
- tool.name = "no_schema"
- tool.description = None
- mock_result = MagicMock()
- mock_result.tools = [tool]
- client._session.list_tools = AsyncMock(return_value=mock_result)
- result = self._run(client.list_tools())
- assert result[0]["input_schema"] == {}
- assert result[0]["description"] == ""
-
-
-# ---------------------------------------------------------------------------
-# MCPClientManager
-# ---------------------------------------------------------------------------
-
-
-class TestMCPClientManager:
- def test_call_tool_unknown_server_raises(self):
- from local_deep_research.mcp.client import MCPClientError
-
- MCPClientManager = _get_manager_class()
- mgr = MCPClientManager([])
- with pytest.raises(MCPClientError, match="not connected"):
- asyncio.run(mgr.call_tool("unknown_server", "tool_name"))
-
- def test_get_connected_servers_empty(self):
- MCPClientManager = _get_manager_class()
- mgr = MCPClientManager([])
- assert mgr.get_connected_servers() == []
-
- def test_get_connected_servers_with_clients(self):
- MCPClientManager = _get_manager_class()
- mgr = MCPClientManager([])
- mgr._clients = {"server1": MagicMock(), "server2": MagicMock()}
- servers = mgr.get_connected_servers()
- assert set(servers) == {"server1", "server2"}
-
- def test_list_all_tools_handles_errors(self):
- MCPClientManager = _get_manager_class()
- from local_deep_research.mcp.client import MCPClientError
-
- mgr = MCPClientManager([])
- failing_client = MagicMock()
- failing_client.list_tools = AsyncMock(
- side_effect=MCPClientError("list failed")
- )
- mgr._clients = {"fail_server": failing_client}
-
- result = asyncio.run(mgr.list_all_tools())
- assert result["fail_server"] == []
-
-
-# ---------------------------------------------------------------------------
-# run_async helper
-# ---------------------------------------------------------------------------
-
-
-class TestRunAsync:
- def test_run_async_no_event_loop(self):
- from local_deep_research.mcp.client import run_async
-
- async def simple_coro():
- return 42
-
- # Should work fine outside event loop
- result = run_async(simple_coro())
- assert result == 42
-
- def test_run_async_timeout_raises(self):
- from local_deep_research.mcp.client import MCPClientError, run_async
-
- async def slow_coro():
- await asyncio.sleep(999)
-
- with pytest.raises((MCPClientError, Exception)):
- run_async(slow_coro(), timeout=0.001)
-
-
-# ---------------------------------------------------------------------------
-# ALLOWED_COMMANDS constant
-# ---------------------------------------------------------------------------
-
-
-class TestAllowedCommands:
- def test_expected_commands_present(self):
- from local_deep_research.mcp.client import ALLOWED_COMMANDS
-
- assert "node" in ALLOWED_COMMANDS
- assert "python" in ALLOWED_COMMANDS
- assert "python3" in ALLOWED_COMMANDS
- assert "uvx" in ALLOWED_COMMANDS
-
- def test_is_set_type(self):
- from local_deep_research.mcp.client import ALLOWED_COMMANDS
-
- assert isinstance(ALLOWED_COMMANDS, set)
diff --git a/tests/mcp/test_mcp_call_tool_parsing.py b/tests/mcp/test_mcp_call_tool_parsing.py
deleted file mode 100644
index 0353299486..0000000000
--- a/tests/mcp/test_mcp_call_tool_parsing.py
+++ /dev/null
@@ -1,213 +0,0 @@
-"""
-Tests for MCPClient.call_tool() result parsing logic.
-
-The parsing logic is extracted and tested directly since the mcp package
-may not be installed in the test environment. This tests the exact same
-branching logic from client.py:303-331.
-"""
-
-import asyncio
-from unittest.mock import AsyncMock, Mock
-
-import pytest
-
-# Skip if mcp package not available
-try:
- import mcp # noqa: F401
-
- MCP_AVAILABLE = True
-except ImportError:
- MCP_AVAILABLE = False
-
-
-def _parse_tool_result(result):
- """
- Extract the parsing logic from MCPClient.call_tool() (lines 303-331).
-
- This is the exact logic from client.py, isolated for unit testing.
- """
- if result.isError:
- return {
- "status": "error",
- "error": str(result.content),
- }
-
- content = []
- if result.content is not None and hasattr(result.content, "__iter__"):
- for item in result.content:
- if hasattr(item, "text"):
- content.append(item.text)
- elif hasattr(item, "data"):
- content.append(str(item.data))
- else:
- content.append(str(item))
- elif result.content is not None:
- content.append(str(result.content))
-
- return {
- "status": "success",
- "content": "\n".join(content) if content else "",
- "raw": result.content,
- }
-
-
-def _make_result(is_error=False, content=None):
- """Create a mock tool result."""
- result = Mock()
- result.isError = is_error
- result.content = content
- return result
-
-
-class TestErrorResult:
- """Tests for error result handling."""
-
- def test_error_returns_status_error(self):
- """isError=True → status=error dict."""
- result = _make_result(is_error=True, content=[Mock(text="bad")])
- output = _parse_tool_result(result)
- assert output["status"] == "error"
- assert "error" in output
-
- def test_error_content_stringified(self):
- """Error content is converted to string."""
- result = _make_result(is_error=True, content="timeout occurred")
- output = _parse_tool_result(result)
- assert "timeout occurred" in output["error"]
-
-
-class TestTextContent:
- """Tests for success results with .text attributes."""
-
- def test_text_content_joined_with_newlines(self):
- """Multiple .text items → joined with newlines."""
- items = [
- Mock(text="line1", spec=["text"]),
- Mock(text="line2", spec=["text"]),
- ]
- result = _make_result(content=items)
- output = _parse_tool_result(result)
- assert output["status"] == "success"
- assert output["content"] == "line1\nline2"
-
- def test_single_text_item(self):
- """Single .text item → correct extraction."""
- items = [Mock(text="only", spec=["text"])]
- result = _make_result(content=items)
- output = _parse_tool_result(result)
- assert output["content"] == "only"
-
-
-class TestDataContent:
- """Tests for success results with .data attributes."""
-
- def test_data_content_stringified(self):
- """Items with .data → str(data) joined."""
- item1 = Mock(spec=["data"])
- item1.data = b"bytes1"
- item2 = Mock(spec=["data"])
- item2.data = b"bytes2"
- result = _make_result(content=[item1, item2])
- output = _parse_tool_result(result)
- assert "bytes1" in output["content"]
- assert "bytes2" in output["content"]
-
-
-class TestMixedContent:
- """Tests for mixed content types."""
-
- def test_mixed_text_and_data(self):
- """Mixed .text and .data items → all extracted."""
- text_item = Mock(spec=["text"])
- text_item.text = "hello"
- data_item = Mock(spec=["data"])
- data_item.data = "world"
- result = _make_result(content=[text_item, data_item])
- output = _parse_tool_result(result)
- assert "hello" in output["content"]
- assert "world" in output["content"]
-
- def test_item_without_text_or_data_uses_str(self):
- """Item without .text/.data → str() fallback."""
- result = _make_result(content=["plain string"])
- output = _parse_tool_result(result)
- assert output["content"] == "plain string"
-
-
-class TestEdgeCases:
- """Edge cases for result parsing."""
-
- def test_none_content_returns_empty(self):
- """None content → empty string."""
- result = _make_result(content=None)
- output = _parse_tool_result(result)
- assert output["status"] == "success"
- assert output["content"] == ""
-
- def test_empty_list_returns_empty(self):
- """Empty list → empty string."""
- result = _make_result(content=[])
- output = _parse_tool_result(result)
- assert output["content"] == ""
-
- def test_non_iterable_content_str_fallback(self):
- """Non-iterable (int) → str conversion."""
- result = _make_result(content=42)
- output = _parse_tool_result(result)
- assert output["content"] == "42"
-
- def test_bare_string_content_iterates_characters(self):
- """Bare string content iterates char-by-char (documents production behavior).
-
- A bare string has __iter__, so the code enters the iterable branch
- and iterates character by character. Each char lacks .text/.data,
- so str(char) is used → characters joined with newlines.
-
- This documents the current behavior. If the production code is fixed
- to check `isinstance(content, str)` first, update this test.
- """
- result = _make_result(content="hello")
- output = _parse_tool_result(result)
- # Current behavior: iterates characters, joins with \n
- assert output["content"] == "h\ne\nl\nl\no"
-
- def test_result_has_raw_key(self):
- """Output includes 'raw' with original content."""
- items = [Mock(text="data", spec=["text"])]
- result = _make_result(content=items)
- output = _parse_tool_result(result)
- assert output["raw"] is items
-
-
[email protected](not MCP_AVAILABLE, reason="MCP package not installed")
-class TestCallToolIntegration:
- """Integration tests that require the actual MCPClient class."""
-
- @pytest.mark.asyncio
- async def test_not_connected_raises_error(self):
- """Not connected → MCPClientError."""
- from local_deep_research.mcp.client import MCPClient, MCPClientError
-
- client = MCPClient.__new__(MCPClient)
- client._connected = False
- client._session = None
-
- with pytest.raises(MCPClientError, match="Not connected"):
- await client.call_tool("tool", {})
-
- @pytest.mark.asyncio
- async def test_timeout_raises_mcp_error(self):
- """Timeout → MCPClientError."""
- from local_deep_research.mcp.client import MCPClient, MCPClientError
-
- client = MCPClient.__new__(MCPClient)
- client.name = "test"
- client.timeout = 0.01
- client._connected = True
- client._session = AsyncMock()
- client._session.call_tool = AsyncMock(
- side_effect=asyncio.TimeoutError()
- )
-
- with pytest.raises(MCPClientError, match="timed out"):
- await client.call_tool("tool", {})
diff --git a/tests/mcp/test_mcp_client.py b/tests/mcp/test_mcp_client.py
deleted file mode 100644
index ee430d6012..0000000000
--- a/tests/mcp/test_mcp_client.py
+++ /dev/null
@@ -1,310 +0,0 @@
-"""
-Tests for the MCP client wrapper utilities.
-
-These tests verify:
-- MCPClient connection and tool operations
-- MCPClientManager multi-server management
-- Error handling
-- Async utilities
-"""
-
-from unittest.mock import patch
-
-import pytest
-
-# Skip all tests if MCP is not available
-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"
-)
-
-
-class TestMCPClientInit:
- """Tests for MCPClient initialization."""
-
- def test_init_basic(self):
- """Test basic initialization."""
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- from local_deep_research.mcp.client import MCPClient
-
- config = {
- "name": "test-server",
- "command": "python",
- "args": ["-m", "test"],
- }
-
- client = MCPClient(config)
-
- assert client.name == "test-server"
- assert client.config == config
- assert client.timeout == 60.0
- assert not client._connected
-
- def test_init_with_custom_timeout(self):
- """Test initialization with custom timeout."""
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- from local_deep_research.mcp.client import MCPClient
-
- config = {"name": "test", "command": "python"}
- client = MCPClient(config, timeout=120.0)
-
- assert client.timeout == 120.0
-
- def test_init_unnamed_server(self):
- """Test initialization without name uses default."""
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- from local_deep_research.mcp.client import MCPClient
-
- config = {"command": "python"}
- client = MCPClient(config)
-
- assert client.name == "unnamed"
-
- def test_init_mcp_not_available(self):
- """Test initialization raises error when MCP not installed."""
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", False):
- # Need to reload the module to get the error
- from local_deep_research.mcp.client import MCPClient, MCPClientError
-
- config = {"command": "python"}
-
- with pytest.raises(MCPClientError) as exc_info:
- MCPClient(config)
-
- assert "not available" in str(exc_info.value)
-
-
-class TestMCPClientError:
- """Tests for MCPClientError exception."""
-
- def test_error_inherits_from_exception(self):
- """Test MCPClientError is a proper exception."""
- from local_deep_research.mcp.client import MCPClientError
-
- with pytest.raises(MCPClientError):
- raise MCPClientError("Test error")
-
- def test_error_message(self):
- """Test error message is preserved."""
- from local_deep_research.mcp.client import MCPClientError
-
- error = MCPClientError("Custom error message")
- assert str(error) == "Custom error message"
-
-
-class TestMCPClientManagerInit:
- """Tests for MCPClientManager initialization."""
-
- def test_init_with_configs(self):
- """Test initialization with server configs."""
- from local_deep_research.mcp.client import MCPClientManager
-
- configs = [
- {"name": "server1", "command": "command1"},
- {"name": "server2", "command": "command2"},
- ]
-
- manager = MCPClientManager(configs)
-
- assert manager.server_configs == configs
- assert len(manager._clients) == 0 # Not connected yet
-
- def test_init_empty_configs(self):
- """Test initialization with empty configs."""
- from local_deep_research.mcp.client import MCPClientManager
-
- manager = MCPClientManager([])
-
- assert manager.server_configs == []
-
- def test_get_connected_servers_empty(self):
- """Test getting connected servers when none connected."""
- from local_deep_research.mcp.client import MCPClientManager
-
- manager = MCPClientManager([])
-
- assert manager.get_connected_servers() == []
-
-
-class TestRunAsync:
- """Tests for the run_async helper function."""
-
- def test_run_async_simple_coroutine(self):
- """Test running a simple coroutine."""
- from local_deep_research.mcp.client import run_async
-
- async def simple_coro():
- return "result"
-
- result = run_async(simple_coro())
-
- assert result == "result"
-
- def test_run_async_with_exception(self):
- """Test run_async propagates exceptions."""
- from local_deep_research.mcp.client import run_async
-
- async def error_coro():
- raise ValueError("Test error")
-
- with pytest.raises(ValueError) as exc_info:
- run_async(error_coro())
-
- assert "Test error" in str(exc_info.value)
-
- def test_run_async_from_async_context(self):
- """Test run_async works when called from within an async context.
-
- This tests the nested event loop path that uses ThreadPoolExecutor.
- """
- import asyncio
- from local_deep_research.mcp.client import run_async
-
- async def inner_coro():
- return "inner_result"
-
- async def outer_coro():
- # This simulates calling run_async from within an async context
- # which triggers the ThreadPoolExecutor path
- result = run_async(inner_coro())
- return result
-
- # Run the outer coroutine which will call run_async internally
- result = asyncio.run(outer_coro())
- assert result == "inner_result"
-
- def test_run_async_nested_with_exception(self):
- """Test run_async propagates exceptions from nested context."""
- import asyncio
- from local_deep_research.mcp.client import run_async
-
- async def inner_coro():
- raise ValueError("Nested error")
-
- async def outer_coro():
- return run_async(inner_coro())
-
- with pytest.raises(ValueError) as exc_info:
- asyncio.run(outer_coro())
-
- assert "Nested error" in str(exc_info.value)
-
- def test_run_async_timeout_in_nested_context(self):
- """Test run_async respects timeout parameter in nested async context.
-
- Note: Timeout only applies when calling from within an existing event loop,
- where ThreadPoolExecutor is used. In the simple case (no event loop),
- asyncio.run() is used which doesn't have timeout.
- """
- import asyncio
- from local_deep_research.mcp.client import run_async, MCPClientError
-
- async def slow_coro():
- await asyncio.sleep(10)
- return "never reached"
-
- async def outer_coro():
- # Call run_async from within an async context to trigger
- # the ThreadPoolExecutor path which respects timeout
- return run_async(slow_coro(), timeout=0.1)
-
- with pytest.raises(MCPClientError) as exc_info:
- asyncio.run(outer_coro())
-
- assert "timed out" in str(exc_info.value)
-
-
-class TestMCPClientNotConnected:
- """Tests for operations when client is not connected."""
-
- def test_list_tools_not_connected(self):
- """Test list_tools raises error when not connected."""
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- from local_deep_research.mcp.client import (
- MCPClient,
- MCPClientError,
- run_async,
- )
-
- config = {"name": "test", "command": "python"}
- client = MCPClient(config)
-
- async def test():
- return await client.list_tools()
-
- with pytest.raises(MCPClientError) as exc_info:
- run_async(test())
-
- assert "Not connected" in str(exc_info.value)
-
- def test_call_tool_not_connected(self):
- """Test call_tool raises error when not connected."""
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- from local_deep_research.mcp.client import (
- MCPClient,
- MCPClientError,
- run_async,
- )
-
- config = {"name": "test", "command": "python"}
- client = MCPClient(config)
-
- async def test():
- return await client.call_tool("test_tool", {})
-
- with pytest.raises(MCPClientError) as exc_info:
- run_async(test())
-
- assert "Not connected" in str(exc_info.value)
-
-
-class TestMCPClientManagerOperations:
- """Tests for MCPClientManager operations."""
-
- def test_call_tool_server_not_connected(self):
- """Test calling tool on non-connected server raises error."""
- from local_deep_research.mcp.client import (
- MCPClientManager,
- MCPClientError,
- run_async,
- )
-
- manager = MCPClientManager([])
-
- async def test():
- return await manager.call_tool("unknown_server", "tool", {})
-
- with pytest.raises(MCPClientError) as exc_info:
- run_async(test())
-
- assert "not connected" in str(exc_info.value)
-
-
-class TestModuleExports:
- """Tests for module exports."""
-
- def test_mcp_available_exported(self):
- """Test MCP_AVAILABLE is exported."""
- from local_deep_research.mcp.client import MCP_AVAILABLE
-
- assert isinstance(MCP_AVAILABLE, bool)
-
- def test_all_classes_exported(self):
- """Test all main classes are exported."""
- from local_deep_research.mcp.client import (
- MCPClient,
- MCPClientManager,
- MCPClientError,
- run_async,
- )
-
- assert MCPClient is not None
- assert MCPClientManager is not None
- assert MCPClientError is not None
- assert callable(run_async)
diff --git a/tests/mcp/test_mcp_client_gaps.py b/tests/mcp/test_mcp_client_gaps.py
deleted file mode 100644
index 2ef4e24df5..0000000000
--- a/tests/mcp/test_mcp_client_gaps.py
+++ /dev/null
@@ -1,109 +0,0 @@
-"""
-Branch-coverage gap tests for mcp/client.py.
-
-Targets uncovered paths that existing tests miss:
-- Init retry loop exhausting on asyncio.TimeoutError → MCPClientError with
- "Timeout initializing" (lines 224-228)
-- Init retry loop exhausting on an exception whose message contains
- "before initialization" → MCPClientError (lines 231-236)
-- call_tool with a non-iterable, non-None content value — goes through the
- elif branch at line 325-327 and stringifies the value. The existing
- test_mcp_call_tool_parsing.py tests a LOCAL copy of this logic; this
- exercises the real MCPClient.call_tool().
-"""
-
-import asyncio
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-
-MODULE = "local_deep_research.mcp.client"
-
-
-def _mcp_available():
- try:
- import mcp # noqa: F401
-
- return True
- except ImportError:
- return False
-
-
-pytestmark = pytest.mark.skipif(
- not _mcp_available(),
- reason="mcp package not installed",
-)
-
-
-def _valid_config(command="python", name="test-server"):
- return {"command": command, "args": ["server.py"], "name": name}
-
-
-def _make_client():
- from local_deep_research.mcp.client import MCPClient
-
- return MCPClient(_valid_config())
-
-
-def _make_connected_client():
- client = _make_client()
- client._connected = True
- client._session = MagicMock()
- return client
-
-
-class TestInitializeWithRetry:
- """Retry loop exhaustion paths for _initialize_with_retry."""
-
- @patch(f"{MODULE}.INIT_RETRY_ATTEMPTS", 2)
- @patch(f"{MODULE}.INIT_RETRY_BASE_DELAY", 0.01)
- @patch(f"{MODULE}.INIT_RETRY_MAX_DELAY", 0.01)
- def test_timeout_exhaustion_raises_mcp_timeout_error(self):
- from local_deep_research.mcp.client import MCPClientError
-
- client = _make_client()
- client._session = MagicMock()
- client._session.initialize = AsyncMock(
- side_effect=asyncio.TimeoutError()
- )
- client.timeout = 0.1
-
- with pytest.raises(MCPClientError, match="Timeout initializing"):
- asyncio.run(client._initialize_with_retry())
-
- @patch(f"{MODULE}.INIT_RETRY_ATTEMPTS", 2)
- @patch(f"{MODULE}.INIT_RETRY_BASE_DELAY", 0.01)
- @patch(f"{MODULE}.INIT_RETRY_MAX_DELAY", 0.01)
- def test_before_initialization_exhaustion_raises_mcp_client_error(self):
- from local_deep_research.mcp.client import MCPClientError
-
- client = _make_client()
- client._session = MagicMock()
- client._session.initialize = AsyncMock(
- side_effect=RuntimeError(
- "Received request before initialization was complete"
- )
- )
- client.timeout = 0.1
-
- with pytest.raises(MCPClientError, match="Failed to initialize"):
- asyncio.run(client._initialize_with_retry())
-
-
-class TestCallToolNonIterableContent:
- """call_tool stringifies non-None content that lacks __iter__."""
-
- def test_integer_content_stringified(self):
- client = _make_connected_client()
-
- mock_result = MagicMock()
- mock_result.isError = False
- # Plain int — not None, no __iter__ — must hit the elif branch.
- mock_result.content = 42
- client._session.call_tool = AsyncMock(return_value=mock_result)
-
- result = asyncio.run(client.call_tool("numeric_tool"))
-
- assert result["status"] == "success"
- assert result["content"] == "42"
- assert result["raw"] == 42
diff --git a/tests/mcp/test_mcp_client_server_integration.py b/tests/mcp/test_mcp_client_server_integration.py
deleted file mode 100644
index 73bbf5a86a..0000000000
--- a/tests/mcp/test_mcp_client_server_integration.py
+++ /dev/null
@@ -1,242 +0,0 @@
-"""Fast mock-based tests for MCP client logic.
-
-The subprocess-based integration tests (spawning a real echo server)
-now live at tests/performance/mcp/test_mcp_client_server_live.py —
-co-located with the echo_server.py they rely on.
-"""
-
-import asyncio
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-
-# Skip all tests if MCP is not available
-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"
-)
-
-
-class TestMCPClientWithMockedSession:
- """Tests for MCPClient using mocked session for fast, reliable testing."""
-
- @pytest.fixture
- def mock_tool_result(self):
- """Create a mock tool result."""
-
- def _make_result(text_content, is_error=False):
- mock_item = MagicMock()
- mock_item.text = text_content
- mock_result = MagicMock()
- mock_result.isError = is_error
- mock_result.content = [mock_item]
- return mock_result
-
- return _make_result
-
- @pytest.fixture
- def mock_list_tools_result(self):
- """Create a mock list tools result."""
- mock_tool1 = MagicMock()
- mock_tool1.name = "echo"
- mock_tool1.description = "Echo a message"
- mock_tool1.inputSchema = {
- "type": "object",
- "properties": {"message": {"type": "string"}},
- }
-
- mock_tool2 = MagicMock()
- mock_tool2.name = "add_numbers"
- mock_tool2.description = "Add two numbers"
- mock_tool2.inputSchema = {
- "type": "object",
- "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}},
- }
-
- mock_result = MagicMock()
- mock_result.tools = [mock_tool1, mock_tool2]
- return mock_result
-
- @pytest.mark.asyncio
- async def test_list_tools_with_mock(self, mock_list_tools_result):
- """Test list_tools returns properly formatted tool list."""
- from local_deep_research.mcp.client import MCPClient
-
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- config = {"name": "mock-server", "command": "python"}
- client = MCPClient(config)
-
- # Set up mocked connected state
- client._connected = True
- client._session = MagicMock()
- client._session.list_tools = AsyncMock(
- return_value=mock_list_tools_result
- )
-
- tools = await client.list_tools()
-
- assert len(tools) == 2
- assert tools[0]["name"] == "echo"
- assert tools[0]["description"] == "Echo a message"
- assert tools[1]["name"] == "add_numbers"
-
- @pytest.mark.asyncio
- async def test_call_tool_success_with_mock(self, mock_tool_result):
- """Test call_tool returns success result."""
- from local_deep_research.mcp.client import MCPClient
-
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- config = {"name": "mock-server", "command": "python"}
- client = MCPClient(config)
-
- client._connected = True
- client._session = MagicMock()
- client._session.call_tool = AsyncMock(
- return_value=mock_tool_result(
- '{"status": "success", "message": "Hello, World!"}'
- )
- )
-
- result = await client.call_tool(
- "echo", {"message": "Hello, World!"}
- )
-
- assert result["status"] == "success"
- assert "Hello, World!" in result["content"]
-
- @pytest.mark.asyncio
- async def test_call_tool_error_result_with_mock(self, mock_tool_result):
- """Test call_tool handles error results from server."""
- from local_deep_research.mcp.client import MCPClient
-
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- config = {"name": "mock-server", "command": "python"}
- client = MCPClient(config)
-
- client._connected = True
- client._session = MagicMock()
- client._session.call_tool = AsyncMock(
- return_value=mock_tool_result(
- "Tool execution failed", is_error=True
- )
- )
-
- result = await client.call_tool("failing_tool", {})
-
- assert result["status"] == "error"
-
- @pytest.mark.asyncio
- async def test_call_tool_timeout_with_mock(self):
- """Test call_tool raises error on timeout."""
- from local_deep_research.mcp.client import MCPClient, MCPClientError
-
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- config = {"name": "mock-server", "command": "python"}
- client = MCPClient(config, timeout=0.1)
-
- client._connected = True
- client._session = MagicMock()
-
- async def slow_call(*args, **kwargs):
- await asyncio.sleep(1.0)
-
- client._session.call_tool = slow_call
-
- with pytest.raises(MCPClientError) as exc_info:
- await client.call_tool("slow_tool", {})
-
- assert "timed out" in str(exc_info.value).lower()
-
- @pytest.mark.asyncio
- async def test_multiple_sequential_calls_with_mock(self, mock_tool_result):
- """Test multiple sequential tool calls work correctly."""
- from local_deep_research.mcp.client import MCPClient
-
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- config = {"name": "mock-server", "command": "python"}
- client = MCPClient(config)
-
- client._connected = True
- client._session = MagicMock()
-
- call_count = 0
-
- async def mock_call_tool(name, args):
- nonlocal call_count
- call_count += 1
- return mock_tool_result(f"Result {call_count}")
-
- client._session.call_tool = mock_call_tool
-
- result1 = await client.call_tool("tool1", {})
- result2 = await client.call_tool("tool2", {})
- result3 = await client.call_tool("tool3", {})
-
- assert "Result 1" in result1["content"]
- assert "Result 2" in result2["content"]
- assert "Result 3" in result3["content"]
- assert call_count == 3
-
-
-class TestMCPClientValidation:
- """Tests for client configuration validation with real commands."""
-
- def test_allowed_commands_includes_python(self):
- """Test that python is in allowed commands."""
- from local_deep_research.mcp.client import ALLOWED_COMMANDS
-
- assert "python" in ALLOWED_COMMANDS
- assert "python3" in ALLOWED_COMMANDS
-
- def test_missing_command_raises_error(self):
- """Test that missing command raises MCPClientError."""
- from local_deep_research.mcp.client import MCPClient, MCPClientError
-
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- config = {
- "name": "no-command",
- # Missing 'command' key
- }
-
- with pytest.raises(MCPClientError) as exc_info:
- MCPClient(config)
-
- assert "missing" in str(exc_info.value).lower()
-
- def test_invalid_args_type_raises_error(self):
- """Test that non-list args raises MCPClientError."""
- from local_deep_research.mcp.client import MCPClient, MCPClientError
-
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- config = {
- "name": "bad-args",
- "command": "python",
- "args": "not-a-list", # Should be a list
- }
-
- with pytest.raises(MCPClientError) as exc_info:
- MCPClient(config)
-
- assert "must be a list" in str(exc_info.value)
-
- def test_invalid_env_type_raises_error(self):
- """Test that non-dict env raises MCPClientError."""
- from local_deep_research.mcp.client import MCPClient, MCPClientError
-
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- config = {
- "name": "bad-env",
- "command": "python",
- "env": ["not", "a", "dict"], # Should be a dict
- }
-
- with pytest.raises(MCPClientError) as exc_info:
- MCPClient(config)
-
- assert "must be a dictionary" in str(exc_info.value)
diff --git a/tests/mcp/test_mcp_protocol.py b/tests/mcp/test_mcp_protocol.py
index 1b5cdd90a4..85be6b99f8 100644
--- a/tests/mcp/test_mcp_protocol.py
+++ b/tests/mcp/test_mcp_protocol.py
@@ -208,7 +208,7 @@ class TestAvailableStrategies:
)
strategies = get_available_strategies()
- assert len(strategies) >= 6
+ assert len(strategies) >= 5
def test_available_strategies_have_required_fields(self):
"""Verify each strategy has name and description."""
diff --git a/tests/mcp/test_mcp_strategy.py b/tests/mcp/test_mcp_strategy.py
deleted file mode 100644
index 16befbf319..0000000000
--- a/tests/mcp/test_mcp_strategy.py
+++ /dev/null
@@ -1,1984 +0,0 @@
-"""
-Tests for the MCP Search Strategy (ReAct pattern).
-
-These tests verify:
-- ReAct loop behavior (thought → action → observation)
-- LLM response parsing
-- Tool execution (web search, MCP tools)
-- Error handling and recovery
-- Max iteration limits
-"""
-
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-# Skip all tests if MCP is not available
-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"
-)
-
-
-class TestMCPSearchStrategyInit:
- """Tests for MCPSearchStrategy initialization."""
-
- def test_init_with_defaults(self):
- """Test initialization with default parameters."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=mock_search,
- )
-
- assert strategy.model == mock_model
- assert strategy.search == mock_search
- assert strategy.mcp_servers == []
- assert strategy.max_iterations == 10
- assert strategy.include_web_search is True
-
- def test_init_with_custom_params(self):
- """Test initialization with custom parameters."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_model = MagicMock()
- mock_search = MagicMock()
- mcp_servers = [{"name": "test", "command": "test"}]
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=mock_search,
- mcp_servers=mcp_servers,
- max_iterations=5,
- include_web_search=False,
- )
-
- assert strategy.mcp_servers == mcp_servers
- assert strategy.max_iterations == 5
- assert strategy.include_web_search is False
-
- def test_init_with_settings_snapshot(self):
- """Test initialization with settings snapshot."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_model = MagicMock()
- mock_search = MagicMock()
- settings = {"test.setting": {"value": "test"}}
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=mock_search,
- settings_snapshot=settings,
- )
-
- assert strategy.settings_snapshot == settings
-
-
-class TestResponseParsing:
- """Tests for LLM response parsing."""
-
- def test_parse_thought_and_answer(self):
- """Test parsing response with thought and answer."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- response = """THOUGHT: I have gathered enough information about quantum computing.
-ANSWER: Quantum computing is a type of computation that uses quantum bits (qubits)."""
-
- result = strategy._parse_response(response)
-
- assert result["type"] == "answer"
- assert "quantum" in result["thought"].lower()
- assert "qubits" in result["content"].lower()
-
- def test_parse_thought_and_action(self):
- """Test parsing response with thought and action."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- response = """THOUGHT: I need to search for more information about quantum computing.
-ACTION: web_search
-ARGUMENTS: {"query": "quantum computing basics"}"""
-
- result = strategy._parse_response(response)
-
- assert result["type"] == "action"
- assert result["tool"] == "web_search"
- assert result["arguments"]["query"] == "quantum computing basics"
-
- def test_parse_action_without_json_arguments(self):
- """Test parsing action with non-JSON arguments format."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- response = """THOUGHT: Let me search.
-ACTION: web_search
-ARGUMENTS: query = "test query" """
-
- result = strategy._parse_response(response)
-
- assert result["type"] == "action"
- assert result["tool"] == "web_search"
- # Falls back to query extraction
- assert result["arguments"].get("query") == "test query"
-
- def test_parse_invalid_response(self):
- """Test parsing invalid response."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- response = "This is just some text without proper format"
-
- result = strategy._parse_response(response)
-
- assert result["type"] == "error"
- assert "Could not parse" in result["message"]
-
- def test_parse_case_insensitive(self):
- """Test parsing is case insensitive."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- response = """thought: I have the answer.
-answer: The answer is 42."""
-
- result = strategy._parse_response(response)
-
- assert result["type"] == "answer"
- assert "42" in result["content"]
-
-
-class TestToolBuilding:
- """Tests for tool description building."""
-
- def test_build_tools_with_web_search(self):
- """Test building tools includes web search when enabled."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_search = MagicMock()
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=mock_search,
- include_web_search=True,
- )
-
- tools = strategy._build_tool_descriptions()
-
- assert any(t["name"] == "web_search" for t in tools)
-
- def test_build_tools_without_web_search(self):
- """Test building tools excludes web search when disabled."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- include_web_search=False,
- )
-
- tools = strategy._build_tool_descriptions()
-
- assert not any(t["name"] == "web_search" for t in tools)
-
- def test_strict_scope_exposes_no_specialized_tools(self):
- """Egress parity with LangGraph: under STRICT scope the specialized
- search-engine tools must NOT appear in the tool list (the LLM never
- sees them)."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- include_web_search=True,
- include_sub_research=False,
- settings_snapshot={
- "policy.egress_scope": {"value": "strict"},
- "search.tool": {"value": "arxiv"},
- },
- )
- strategy._get_available_search_engines = lambda: {
- "pubmed": {"description": "PubMed", "is_retriever": False},
- "semantic_scholar": {"description": "S2", "is_retriever": False},
- }
- strategy._get_current_engine_name = lambda: "arxiv"
-
- tools = strategy._build_tool_descriptions()
- specialized = [t for t in tools if t["name"].startswith("search_")]
- assert specialized == []
-
- def test_both_scope_exposes_specialized_tools(self):
- """Under BOTH scope the specialized public engines ARE exposed."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- include_web_search=True,
- include_sub_research=False,
- settings_snapshot={
- "policy.egress_scope": {"value": "both"},
- "search.tool": {"value": "arxiv"},
- },
- )
- strategy._get_available_search_engines = lambda: {
- "pubmed": {"description": "PubMed", "is_retriever": False},
- }
- strategy._get_current_engine_name = lambda: "arxiv"
-
- tool_names = {t["name"] for t in strategy._build_tool_descriptions()}
- assert "search_pubmed" in tool_names
-
- def test_format_tool_descriptions(self):
- """Test formatting tool descriptions for the LLM."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- tools = [
- {
- "name": "test_tool",
- "description": "A test tool",
- "parameters": {
- "arg1": {"type": "string"},
- "arg2": {"type": "number"},
- },
- }
- ]
-
- formatted = strategy._format_tool_descriptions(tools)
-
- assert "test_tool" in formatted
- assert "A test tool" in formatted
- assert "arg1" in formatted
-
-
-class TestWebSearchExecution:
- """Tests for web search tool execution."""
-
- def test_execute_web_search_success(self):
- """Test successful web search execution."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_search = MagicMock()
- mock_search.run.return_value = [
- {
- "title": "Result 1",
- "snippet": "Content 1",
- "link": "https://example.com/1",
- },
- {
- "title": "Result 2",
- "snippet": "Content 2",
- "link": "https://example.com/2",
- },
- ]
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=mock_search,
- )
-
- result = strategy._execute_web_search({"query": "test query"})
-
- assert result["status"] == "success"
- assert "Result 1" in result["content"]
- assert "Result 2" in result["content"]
- assert len(strategy._sources) == 2
-
- def test_execute_web_search_empty_query(self):
- """Test web search with empty query."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- result = strategy._execute_web_search({})
-
- assert result["status"] == "error"
- assert "No query" in result["content"]
-
- def test_execute_web_search_error(self):
- """Test web search error handling."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_search = MagicMock()
- mock_search.run.side_effect = Exception("Search API error")
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=mock_search,
- )
-
- result = strategy._execute_web_search({"query": "test"})
-
- assert result["status"] == "error"
- assert "Search failed" in result["content"]
-
-
-class TestToolExecution:
- """Tests for general tool execution."""
-
- def test_execute_unknown_tool(self):
- """Test executing an unknown tool."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- tools = [
- {"name": "web_search", "executor": strategy._execute_web_search}
- ]
-
- result = strategy._execute_tool("unknown_tool", {}, tools)
-
- assert result["status"] == "error"
- assert "Unknown tool" in result["content"]
-
- def test_execute_tool_no_executor(self):
- """Test executing tool without executor."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- tools = [{"name": "no_exec_tool", "description": "No executor"}]
-
- result = strategy._execute_tool("no_exec_tool", {}, tools)
-
- assert result["status"] == "error"
- assert "no executor" in result["content"]
-
-
-class TestReActLoop:
- """Tests for the main ReAct loop."""
-
- def test_analyze_topic_immediate_answer(self):
- """Test analyze_topic when LLM immediately provides answer."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = """THOUGHT: I already know this.
-ANSWER: The capital of France is Paris."""
- mock_response.tool_calls = []
- mock_model.invoke.return_value = mock_response
-
- bound_model = MagicMock()
- bound_model.invoke.return_value = mock_response
- mock_model.bind_tools.return_value = bound_model
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=MagicMock(),
- )
-
- result = strategy.analyze_topic("What is the capital of France?")
-
- assert result["iterations"] == 1
- assert "Paris" in result["formatted_findings"]
- assert "Paris" in result["current_knowledge"]
-
- def test_analyze_topic_with_search(self):
- """Test analyze_topic with web search action."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- # First response: action, second response: answer
- mock_model = MagicMock()
- responses = [
- MagicMock(
- content="""THOUGHT: I need to search.
-ACTION: web_search
-ARGUMENTS: {"query": "quantum computing"}"""
- ),
- MagicMock(
- content="""THOUGHT: Now I have enough info.
-ANSWER: Quantum computing uses qubits."""
- ),
- ]
- responses[0].tool_calls = []
- responses[1].tool_calls = []
- mock_model.invoke.side_effect = responses
-
- bound_model = MagicMock()
- bound_model.invoke.side_effect = responses
- mock_model.bind_tools.return_value = bound_model
-
- mock_search = MagicMock()
- mock_search.run.return_value = [
- {
- "title": "Quantum",
- "snippet": "Quantum info",
- "link": "https://example.com",
- }
- ]
-
- # Mock the citation handler so it preserves the ReAct answer instead
- # of re-invoking the model (which would consume from side_effect and
- # return unrelated content).
- mock_citation_handler = MagicMock()
- mock_citation_handler.analyze_followup.return_value = {
- "content": "Quantum computing uses qubits.",
- "documents": [],
- }
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=mock_search,
- citation_handler=mock_citation_handler,
- )
-
- result = strategy.analyze_topic("What is quantum computing?")
-
- assert result["iterations"] == 2
- assert mock_search.run.called
- assert "qubits" in result["formatted_findings"]
-
- def test_analyze_topic_max_iterations(self):
- """Test analyze_topic respects max iterations limit."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- # Always return action, never answer
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = """THOUGHT: Need more info.
-ACTION: web_search
-ARGUMENTS: {"query": "test"}"""
- mock_response.tool_calls = []
- mock_model.invoke.return_value = mock_response
-
- bound_model = MagicMock()
- bound_model.invoke.return_value = mock_response
- mock_model.bind_tools.return_value = bound_model
-
- mock_search = MagicMock()
- mock_search.run.return_value = [
- {"title": "T", "snippet": "S", "link": "L"}
- ]
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=mock_search,
- max_iterations=3,
- )
-
- result = strategy.analyze_topic("Test query")
-
- # Should stop at max iterations
- assert result["iterations"] == 3
-
- def test_analyze_topic_still_has_research_tools(self):
- """Test analyze_topic still works without web_search because research tools are available."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = """THOUGHT: I have the information.
-ANSWER: The answer based on research."""
- mock_model.invoke.return_value = mock_response
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=None, # No search
- include_web_search=False, # Web search disabled
- mcp_servers=[], # No MCP servers
- )
-
- # Strategy still has research tools available (sub-research and download_content)
- # When include_sub_research=True (default) and depth < max_depth:
- # - focused_research, download_content
- tools = strategy._build_tool_descriptions()
- assert len(tools) >= 2 # focused_research, download_content
- assert any(t["name"] == "focused_research" for t in tools)
- assert any(t["name"] == "download_content" for t in tools)
-
- def test_analyze_topic_llm_error_recovery(self):
- """Test analyze_topic handles LLM errors."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_model = MagicMock()
- mock_model.invoke.side_effect = Exception("LLM API error")
- mock_model.bind_tools.return_value = (
- mock_model # bind_tools returns model that also raises
- )
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=MagicMock(),
- )
-
- result = strategy.analyze_topic("Test query")
-
- # The error should be captured in either the error key or the formatted_findings
- error_captured = (
- "error" in result
- or "LLM error" in result.get("formatted_findings", "")
- or "Error:" in result.get("formatted_findings", "")
- or "failed" in result.get("formatted_findings", "").lower()
- or "failed" in result.get("current_knowledge", "").lower()
- )
- assert error_captured, f"Error should be captured in result: {result}"
-
-
-class TestHistoryFormatting:
- """Tests for reasoning history formatting."""
-
- def test_format_empty_history(self):
- """Test formatting empty history."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
- strategy._history = []
-
- formatted = strategy._format_history()
-
- assert "No research done yet" in formatted
-
- def test_format_history_with_entries(self):
- """Test formatting history with entries."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
- strategy._history = [
- {
- "role": "assistant",
- "thought": "I need to search",
- "action": "web_search",
- "arguments": {"query": "test"},
- },
- {
- "role": "tool",
- "tool": "web_search",
- "observation": "Found some results",
- },
- ]
-
- formatted = strategy._format_history()
-
- assert "THOUGHT:" in formatted
- assert "ACTION:" in formatted
- assert "OBSERVATION" in formatted
-
-
-class TestAnswerSynthesis:
- """Tests for answer synthesis when max iterations reached."""
-
- def test_synthesize_answer(self):
- """Test answer synthesis with gathered info."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "Synthesized answer based on research."
- mock_model.invoke.return_value = mock_response
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=MagicMock(),
- )
- strategy._history = [
- {
- "role": "tool",
- "tool": "web_search",
- "observation": "Some findings",
- }
- ]
-
- answer = strategy._synthesize_answer("Test query")
-
- assert "Synthesized answer" in answer
-
- def test_synthesize_answer_error(self):
- """Test answer synthesis error handling."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_model = MagicMock()
- mock_model.invoke.side_effect = Exception("Synthesis failed")
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=MagicMock(),
- )
-
- answer = strategy._synthesize_answer("Test query")
-
- assert "synthesis failed" in answer.lower()
-
-
-class TestProgressCallback:
- """Tests for progress callback functionality."""
-
- def test_progress_callback_called(self):
- """Test progress callback is called during analysis."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = """THOUGHT: Done.
-ANSWER: The answer."""
- mock_model.invoke.return_value = mock_response
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=MagicMock(),
- )
-
- progress_calls = []
-
- def callback(message, progress, data):
- progress_calls.append((message, progress, data))
-
- strategy.set_progress_callback(callback)
- strategy.analyze_topic("Test")
-
- assert len(progress_calls) > 0
- assert any("init" in str(call) for call in progress_calls)
-
-
-class TestMCPToolDiscovery:
- """Tests for MCP tool discovery."""
-
- def test_discover_mcp_tools_no_servers(self):
- """Test MCP discovery with no servers configured."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- mcp_servers=[],
- )
-
- tools = strategy._discover_mcp_tools()
-
- assert tools == []
-
- def test_discover_mcp_tools_connection_error(self):
- """Test MCP discovery handles connection errors gracefully."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- mcp_servers=[{"name": "test", "command": "nonexistent-command"}],
- # Permissive scope so the policy gate passes and this test
- # exercises the connection-error path (not the scope block).
- settings_snapshot={"policy.egress_scope": "both"},
- )
-
- # The discovery should handle errors gracefully and return empty
- # when connection fails (import is inside the method)
- with patch(
- "local_deep_research.mcp.client.MCPClientManager"
- ) as mock_manager:
- # Make the manager raise on connect
- mock_instance = MagicMock()
- mock_instance.connect_all.side_effect = Exception(
- "Connection failed"
- )
- mock_manager.return_value = mock_instance
-
- tools = strategy._discover_mcp_tools()
-
- # Should return empty list on error, not raise
- assert tools == []
-
-
-class TestMCPEgressScopeGate:
- """Tests for the MCP discovery/execution scope gate. MCP tools run
- in stdio subprocesses whose egress the PDP cannot inspect, so the
- only safe enforcement under STRICT/PRIVATE_ONLY (or when no
- snapshot is available) is to block them outright.
- """
-
- @staticmethod
- def _build(scope_value, *, snapshot_override=None):
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- if snapshot_override is not None:
- snapshot = snapshot_override
- else:
- snapshot = {"policy.egress_scope": scope_value}
- return MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- mcp_servers=[{"name": "srv", "command": "python"}],
- settings_snapshot=snapshot,
- )
-
- @pytest.mark.parametrize("scope", ["strict", "private_only"])
- def test_discover_mcp_tools_blocked_under_restrictive_scope(self, scope):
- strategy = self._build(scope)
- with patch(
- "local_deep_research.mcp.client.MCPClientManager"
- ) as mock_manager:
- tools = strategy._discover_mcp_tools()
- assert tools == []
- # Connection manager must never be touched — scope gate runs
- # before subprocess startup.
- mock_manager.assert_not_called()
- # Cache the empty list so subsequent ReAct iterations don't
- # re-run the policy work.
- assert strategy._mcp_tools_cache == []
-
- def test_discover_mcp_tools_blocked_when_no_snapshot(self):
- """``settings_snapshot={}`` (BaseSearchStrategy's "or {}" guard)
- must fail closed — without a snapshot the gate cannot certify
- MCP tools are safe to expose.
- """
- strategy = self._build("ignored", snapshot_override={})
- with patch(
- "local_deep_research.mcp.client.MCPClientManager"
- ) as mock_manager:
- tools = strategy._discover_mcp_tools()
- assert tools == []
- mock_manager.assert_not_called()
- assert strategy._mcp_tools_cache == []
-
- def test_discover_mcp_tools_blocked_when_policy_unevaluable(self):
- """A corrupted scope value raises PolicyDeniedError inside
- context_from_snapshot — that must fail CLOSED at discovery.
- """
- strategy = self._build(
- "ignored",
- snapshot_override={"policy.egress_scope": "not_a_real_scope"},
- )
- with patch(
- "local_deep_research.mcp.client.MCPClientManager"
- ) as mock_manager:
- tools = strategy._discover_mcp_tools()
- assert tools == []
- mock_manager.assert_not_called()
- assert strategy._mcp_tools_cache == []
-
- @pytest.mark.parametrize("scope", ["both", "public_only"])
- def test_discover_mcp_tools_passes_under_permissive_scope(self, scope):
- """BOTH and PUBLIC_ONLY allow MCP through the gate. The
- downstream connection may still fail for unrelated reasons; we
- only assert the gate did not block.
- """
- strategy = self._build(scope)
- with patch(
- "local_deep_research.mcp.client.MCPClientManager"
- ) as mock_manager:
- mock_instance = MagicMock()
- mock_instance.connect_all.side_effect = Exception(
- "Connection failed"
- )
- mock_manager.return_value = mock_instance
- tools = strategy._discover_mcp_tools()
- # Connection was attempted (and failed) — meaning the gate
- # allowed the call through.
- mock_manager.assert_called_once()
- assert tools == []
-
- @pytest.mark.parametrize("scope", ["strict", "private_only"])
- def test_execute_mcp_tool_refused_under_restrictive_scope(self, scope):
- """Defense-in-depth: even if a cached tool list survives, the
- executor must independently re-check scope.
- """
- strategy = self._build(scope)
- result = strategy._execute_mcp_tool(
- "srv", "some_tool", {"arg": "value"}
- )
- assert result["status"] == "error"
- assert "egress policy" in result["content"].lower()
-
-
-class TestMCPDownloadContentPolicy:
- """Tests for the narrowed exception handling in
- ``_execute_download_content``. The bare ``except Exception`` used to
- swallow PolicyDeniedError/ValueError and drop to SSRF-only, which
- fails open under PRIVATE_ONLY.
- """
-
- @staticmethod
- def _build_strategy(snapshot):
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- return MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- mcp_servers=[],
- settings_snapshot=snapshot,
- )
-
- def test_download_content_refuses_when_policy_unevaluable(self):
- """Corrupt scope → ``context_from_snapshot`` raises
- PolicyDeniedError → previously dropped to SSRF-only → now must
- return a clear error without ever constructing ContentFetcher.
- """
- strategy = self._build_strategy(
- {"policy.egress_scope": "not_a_real_scope"}
- )
- with patch(
- "local_deep_research.content_fetcher.ContentFetcher"
- ) as MockFetcher:
- result = strategy._execute_download_content(
- {"url": "https://example.com"}
- )
- assert result["status"] == "error"
- assert "egress policy" in result["content"].lower()
- # The fetcher must never be constructed — that is the whole
- # point of failing closed before fetch.
- MockFetcher.assert_not_called()
-
- """Tests for strategy export and import."""
-
- def test_strategy_registered_in_factory(self):
- """Test strategy is registered in search_system_factory."""
- from local_deep_research.search_system_factory import create_strategy
-
- # Just verify the import path works - actual creation would need mocks
- assert callable(create_strategy)
-
-
-class TestErrorResponse:
- """Tests for error response creation."""
-
- def test_create_error_response(self):
- """Test error response structure."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- response = strategy._create_error_response("Test error")
-
- assert response["findings"] == []
- assert response["iterations"] == 0
- assert response["questions"] == {}
- assert "Test error" in response["formatted_findings"]
- assert response["error"] == "Test error"
-
-
-class TestCriticalBugFixes:
- """Tests for critical bug fixes identified in PR review."""
-
- def test_child_strategy_inherits_depth(self):
- """Verify child strategy gets parent.depth + 1 to prevent infinite recursion."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- # Create a parent strategy at depth 1
- parent_strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- depth=1,
- max_depth=3,
- include_sub_research=True,
- )
-
- # Mock the strategy factory at the module level import
- with patch(
- "local_deep_research.search_system_factory.create_strategy"
- ) as mock_create:
- # Set up mock to return a strategy-like object
- mock_child = MagicMock()
- mock_child.analyze_topic.return_value = {
- "findings": [],
- "sources": [],
- "formatted_findings": "test",
- "current_knowledge": "test",
- }
- mock_create.return_value = mock_child
-
- # Execute strategy research
- parent_strategy._execute_strategy_research(
- {"query": "test query"}, "focused-iteration"
- )
-
- # Verify create_strategy was called with depth=parent.depth+1
- mock_create.assert_called_once()
- call_kwargs = mock_create.call_args[1]
- assert call_kwargs.get("depth") == 2, (
- "Child strategy should have depth = parent.depth + 1"
- )
- assert call_kwargs.get("max_depth") == 3, (
- "Child strategy should inherit max_depth"
- )
-
- def test_parse_response_missing_tool_key(self):
- """Test graceful handling when parsed response missing 'tool' key."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_model = MagicMock()
- # Return an action-like response but with no valid tool parsing
- mock_response = MagicMock()
- mock_response.content = """THOUGHT: I need to do something.
-ACTION:
-ARGUMENTS: {"query": "test"}"""
- mock_response.tool_calls = []
-
- # Expect this to continue the loop, not crash
- bound_model = MagicMock()
- bound_model.invoke.return_value = mock_response
- mock_model.bind_tools.return_value = bound_model
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=MagicMock(),
- max_iterations=1, # Limit iterations
- )
-
- # This should not raise KeyError
- result = strategy.analyze_topic("Test query")
-
- # Should complete without crashing
- assert "iterations" in result
-
- def test_parse_response_empty_tool_calls_list(self):
- """Test handling when tool_calls exists but is empty list."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- # Create a mock response with empty tool_calls list
- mock_response = MagicMock()
- mock_response.tool_calls = [] # Empty list (truthy but no elements)
- mock_response.content = """THOUGHT: I have the answer.
-ANSWER: The answer is 42."""
-
- # This should not raise IndexError
- result = strategy._parse_response(mock_response)
-
- # Should fall back to text-based parsing
- assert result["type"] == "answer"
- assert "42" in result["content"]
-
- def test_citation_handler_returns_none(self):
- """Test graceful fallback when citation handler returns None."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = """THOUGHT: Done.
-ANSWER: The answer is here."""
- mock_response.tool_calls = []
- mock_model.invoke.return_value = mock_response
-
- bound_model = MagicMock()
- bound_model.invoke.return_value = mock_response
- mock_model.bind_tools.return_value = bound_model
-
- mock_citation_handler = MagicMock()
- mock_citation_handler.analyze_followup.return_value = (
- None # Returns None
- )
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=MagicMock(),
- citation_handler=mock_citation_handler,
- )
-
- # Add some search results to trigger citation handling
- strategy.all_search_results = [
- {"title": "Test", "link": "http://test.com"}
- ]
-
- # This should not raise AttributeError
- result = strategy.analyze_topic("Test query")
-
- # Should complete and have the answer
- assert "current_knowledge" in result
- 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."""
-
- def test_execute_web_search_empty_results(self):
- """Test handling when search returns empty list."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_search = MagicMock()
- mock_search.run.return_value = [] # Empty results
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=mock_search,
- )
-
- result = strategy._execute_web_search({"query": "test query"})
-
- assert result["status"] == "success"
- assert "No search results found" in result["content"]
- assert "test query" in result["content"]
-
- def test_execute_web_search_tracks_all_sources(self):
- """Test that all source URLs are tracked across multiple searches."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_search = MagicMock()
- # Return search results
- mock_search.run.return_value = [
- {
- "title": "Result 1",
- "snippet": "Content 1",
- "link": "https://example.com/1",
- },
- {
- "title": "Result 2",
- "snippet": "Content 2",
- "link": "https://example.com/2",
- },
- ]
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=mock_search,
- )
-
- # Execute twice
- strategy._execute_web_search({"query": "test1"})
- strategy._execute_web_search({"query": "test2"})
-
- # All results should be tracked (deduplication is not required here,
- # the test verifies that sources are properly tracked)
- assert len(strategy.all_search_results) == 4
- assert len(strategy._sources) == 4
-
- def test_analyze_topic_large_history(self):
- """Test ReAct loop with 10+ iterations of history doesn't cause issues."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_model = MagicMock()
-
- # Build a sequence of responses: many actions, then an answer
- # Use proper string content instead of MagicMock
- def make_action_response():
- response = MagicMock()
- response.content = """THOUGHT: Need more info.
-ACTION: web_search
-ARGUMENTS: {"query": "test"}"""
- response.tool_calls = []
- return response
-
- def make_answer_response():
- response = MagicMock()
- response.content = """THOUGHT: Got enough info.
-ANSWER: Final answer after many iterations."""
- response.tool_calls = []
- return response
-
- # 9 actions, then answer on 10th
- responses = [make_action_response() for _ in range(9)] + [
- make_answer_response()
- ]
-
- bound_model = MagicMock()
- bound_model.invoke.side_effect = responses
- mock_model.bind_tools.return_value = bound_model
-
- mock_search = MagicMock()
- mock_search.run.return_value = [
- {"title": "T", "snippet": "S", "link": "L"}
- ]
-
- # Mock citation handler to return proper dict with the final answer
- mock_citation_handler = MagicMock()
- mock_citation_handler.analyze_followup.return_value = {
- "content": "Final answer after many iterations.",
- "documents": [],
- }
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=mock_search,
- max_iterations=10,
- citation_handler=mock_citation_handler,
- )
-
- result = strategy.analyze_topic("Test query")
-
- assert result["iterations"] == 10
- # The test verifies we can handle 10+ iterations without errors
- # and that the loop completes successfully
- assert "findings" in result
- assert len(result.get("reasoning_trace", [])) > 0
-
- def test_synthesize_answer_no_search_results(self):
- """Test answer synthesis when no search has been performed."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "Synthesized answer from no search results."
- mock_model.invoke.return_value = mock_response
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=MagicMock(),
- )
- # No history, no search results
- strategy._history = []
- strategy.all_search_results = []
-
- answer = strategy._synthesize_answer("Test query")
-
- # Should still produce an answer
- assert answer
- assert "Synthesized answer" in answer
-
-
-class TestTimeoutAndRetry:
- """Tests for timeout handling and retry logic."""
-
- def test_run_async_timeout_parameter_exists(self):
- """Test that run_async accepts timeout parameter."""
- import inspect
-
- from local_deep_research.mcp.client import run_async
-
- # Verify run_async has timeout parameter
- sig = inspect.signature(run_async)
- assert "timeout" in sig.parameters
- # Default timeout should be 300 seconds (5 minutes)
- assert sig.parameters["timeout"].default == 300.0
-
- def test_execute_mcp_tool_has_timeout_parameter(self):
- """Test that _execute_mcp_tool accepts timeout parameter."""
- import inspect
-
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- # Verify _execute_mcp_tool has timeout parameter
- sig = inspect.signature(MCPSearchStrategy._execute_mcp_tool)
- assert "timeout" in sig.parameters
- # Default is None sentinel; actual timeout comes from MCP_TOOL_CALL_TIMEOUT
- assert sig.parameters["timeout"].default is None
- assert MCPSearchStrategy.MCP_TOOL_CALL_TIMEOUT == 60.0
-
- def test_mcp_discovery_failure_not_permanently_cached(self):
- """Test that MCP discovery failure doesn't permanently cache empty result."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- mcp_servers=[{"name": "test", "command": "nonexistent"}],
- # Permissive scope so this exercises the connection-failure
- # retry semantics, not the policy gate (which caches []).
- settings_snapshot={"policy.egress_scope": "both"},
- )
-
- # First discovery fails
- tools1 = strategy._discover_mcp_tools()
- assert tools1 == []
-
- # Cache should NOT be set on failure (allows retry)
- assert strategy._mcp_tools_cache is None
-
- # Second attempt should try again (not use stale cache)
- tools2 = strategy._discover_mcp_tools()
- # Still fails, but the point is it tried again (cache still None)
- assert tools2 == []
- assert strategy._mcp_tools_cache is None
-
-
-class TestMCPPartialFailure:
- """Tests for MCP discovery and execution with partial failures."""
-
- def test_mcp_discovery_partial_failure_returns_working_tools(self):
- """Test when some MCP servers connect but others fail."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- mcp_servers=[
- {"name": "working", "command": "python"},
- {"name": "broken", "command": "nonexistent"},
- ],
- settings_snapshot={"policy.egress_scope": "both"},
- )
-
- # Mock the client manager to simulate partial failure
- with patch(
- "local_deep_research.mcp.client.MCPClientManager"
- ) as MockManager:
- mock_instance = MagicMock()
-
- # Simulate: working server returns tools, broken server fails silently
- async def mock_connect_all():
- return mock_instance
-
- mock_instance.connect_all.return_value.__aenter__ = MagicMock(
- return_value=mock_instance
- )
- mock_instance.connect_all.return_value.__aexit__ = MagicMock(
- return_value=None
- )
-
- # Return tools only from working server
- async def mock_list_tools():
- return {
- "working": [
- {"name": "tool1", "description": "A working tool"}
- ]
- # "broken" server not in results (failed to connect)
- }
-
- mock_instance.list_all_tools = mock_list_tools
- MockManager.return_value = mock_instance
-
- # The discovery should return tools from working servers
- # even if some servers failed
- tools = strategy._discover_mcp_tools()
-
- # Should have tools from working server
- # (exact behavior depends on implementation)
- assert isinstance(tools, list)
-
- def test_mcp_tool_call_with_server_not_found(self):
- """Test calling a tool on a server that doesn't exist."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- mcp_servers=[{"name": "real_server", "command": "python"}],
- settings_snapshot={"policy.egress_scope": "both"},
- )
-
- # Try to call tool on non-existent server
- result = strategy._execute_mcp_tool(
- "nonexistent_server", "some_tool", {"arg": "value"}
- )
-
- assert result["status"] == "error"
- assert "Unknown server" in result["content"]
-
-
-class TestReActLoopRobustness:
- """Tests for ReAct loop edge cases and robustness."""
-
- def test_repeated_identical_searches_tracked(self):
- """Test that repeated identical search queries are tracked in history."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_model = MagicMock()
-
- # LLM keeps requesting the same search
- def make_same_action():
- response = MagicMock()
- response.content = """THOUGHT: Need to search.
-ACTION: web_search
-ARGUMENTS: {"query": "same query every time"}"""
- response.tool_calls = []
- return response
-
- # After 3 identical searches, finally gives answer
- answer_response = MagicMock()
- answer_response.content = """THOUGHT: Done.
-ANSWER: Final answer."""
- answer_response.tool_calls = []
-
- responses = [make_same_action() for _ in range(3)] + [answer_response]
-
- bound_model = MagicMock()
- bound_model.invoke.side_effect = responses
- mock_model.bind_tools.return_value = bound_model
-
- mock_search = MagicMock()
- mock_search.run.return_value = [
- {"title": "Result", "snippet": "Content", "link": "http://test.com"}
- ]
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=mock_search,
- max_iterations=5,
- )
-
- result = strategy.analyze_topic("Test")
-
- # Should complete and track all searches in history
- assert result["iterations"] == 4
- # All 3 identical searches should be in history
- search_actions = [
- h
- for h in result["reasoning_trace"]
- if h.get("action") == "web_search"
- ]
- assert len(search_actions) == 3
-
- def test_nested_json_arguments_parsing(self):
- """Test parsing action with nested JSON arguments via native tool calls."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- # Native tool calls handle nested JSON properly
- mock_response = MagicMock()
- mock_response.tool_calls = [
- {
- "name": "web_search",
- "args": {
- "query": "test",
- "filters": {
- "date": {"start": "2024-01-01", "end": "2024-12-31"},
- "sources": ["arxiv", "pubmed"],
- },
- },
- }
- ]
- mock_response.content = "Complex search"
-
- result = strategy._parse_response(mock_response)
-
- assert result["type"] == "action"
- assert result["tool"] == "web_search"
- assert result["arguments"]["query"] == "test"
- assert "filters" in result["arguments"]
- assert result["arguments"]["filters"]["date"]["start"] == "2024-01-01"
-
- def test_multiple_tool_calls_uses_first(self):
- """Test that when LLM returns multiple tool_calls, first is used."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- # Mock response with multiple tool calls
- mock_response = MagicMock()
- mock_response.tool_calls = [
- {"name": "web_search", "args": {"query": "first query"}},
- {"name": "web_search", "args": {"query": "second query"}},
- {"name": "download_content", "args": {"url": "http://test.com"}},
- ]
- mock_response.content = "Multiple tool calls"
-
- result = strategy._parse_response(mock_response)
-
- # Should use the first tool call
- assert result["type"] == "action"
- assert result["tool"] == "web_search"
- assert result["arguments"]["query"] == "first query"
-
- def test_tool_execution_exception_recorded_in_history(self):
- """Test that tool execution exceptions are properly recorded."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- mock_model = MagicMock()
-
- # First: action that will fail, Second: answer
- action_response = MagicMock()
- action_response.content = """THOUGHT: Search.
-ACTION: web_search
-ARGUMENTS: {"query": "test"}"""
- action_response.tool_calls = []
-
- answer_response = MagicMock()
- answer_response.content = """THOUGHT: Done.
-ANSWER: Answer after error."""
- answer_response.tool_calls = []
-
- bound_model = MagicMock()
- bound_model.invoke.side_effect = [action_response, answer_response]
- mock_model.bind_tools.return_value = bound_model
-
- # Search raises exception
- mock_search = MagicMock()
- mock_search.run.side_effect = Exception("Search API unavailable")
-
- strategy = MCPSearchStrategy(
- model=mock_model,
- search=mock_search,
- max_iterations=5,
- )
-
- result = strategy.analyze_topic("Test")
-
- # Should complete despite error
- assert result["iterations"] == 2
- # Error should be in history as observation
- observations = [
- h for h in result["reasoning_trace"] if h.get("role") == "tool"
- ]
- assert len(observations) == 1
- # Error message format is "Search failed: <error>"
- assert "failed" in observations[0]["observation"].lower()
-
-
-class TestSpecializedSearchEngines:
- """Tests for specialized search engine tool execution."""
-
- def test_execute_specialized_search_tracks_source_engine(self):
- """Test that specialized search results include source engine info."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- # Mock the search engine factory
- with patch(
- "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"
- ) as mock_factory:
- mock_engine = MagicMock()
- mock_engine.run.return_value = [
- {
- "title": "arXiv Paper",
- "snippet": "Abstract",
- "link": "http://arxiv.org/123",
- }
- ]
- mock_factory.return_value = mock_engine
-
- result = strategy._execute_specialized_search(
- {"query": "quantum computing"}, "arxiv"
- )
-
- assert result["status"] == "success"
- # Check source engine is tracked
- assert len(strategy.all_search_results) == 1
- assert strategy.all_search_results[0]["source_engine"] == "arxiv"
-
-
-class TestClientContentHandling:
- """Tests for MCP client content handling edge cases."""
-
- def test_call_tool_with_error_response(self):
- """Test client properly handles error responses from MCP tools."""
-
- # Simulate the content extraction logic
- mock_result = MagicMock()
- mock_result.isError = True
- mock_result.content = "Tool execution failed: invalid arguments"
-
- # Error responses should be detected
- assert mock_result.isError is True
-
- def test_empty_content_list_returns_empty_string(self):
- """Test that empty content list returns empty string, not error."""
- # Simulate content extraction with empty list
- content = []
- result_content = "\n".join(content) if content else ""
-
- assert result_content == ""
-
-
-class TestArgumentValidation:
- """Tests for tool argument validation and sanitization."""
-
- def test_validate_tool_arguments_truncates_long_strings(self):
- """Test that very long argument strings are truncated."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- # Create arguments with very long string
- long_string = "x" * 20000 # 20K chars
- arguments = {"query": long_string, "normal": "value"}
-
- sanitized = strategy._validate_tool_arguments(arguments)
-
- # Long string should be truncated to MAX_ARG_LENGTH (10000)
- assert len(sanitized["query"]) == 10000
- assert sanitized["normal"] == "value"
-
- def test_validate_tool_arguments_handles_non_dict(self):
- """Test that non-dict arguments return empty dict."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- # Non-dict should return empty dict
- assert strategy._validate_tool_arguments(None) == {}
- assert strategy._validate_tool_arguments("string") == {}
- assert strategy._validate_tool_arguments([1, 2, 3]) == {}
-
- def test_validate_tool_arguments_filters_non_string_keys(self):
- """Test that non-string keys are filtered out."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- )
-
- # Dict with mixed key types
- arguments = {"valid": "value", 123: "invalid_key", "also_valid": "ok"}
-
- sanitized = strategy._validate_tool_arguments(arguments)
-
- # Only string keys should remain
- assert "valid" in sanitized
- assert "also_valid" in sanitized
- assert 123 not in sanitized
-
-
-class TestDownloadContentJSRendering:
- """The MCP ``download_content`` tool must read
- ``web.enable_javascript_rendering`` from the strategy's settings
- snapshot and forward it to ``ContentFetcher`` (issue #3826).
- """
-
- @staticmethod
- def _snapshot(value: bool) -> dict:
- return {
- "web.enable_javascript_rendering": {
- "value": value,
- "ui_element": "checkbox",
- }
- }
-
- def _capture_content_fetcher_kwargs(
- self, settings_snapshot, monkeypatch
- ) -> dict:
- """Drive ``_execute_download_content`` with a patched
- ``ContentFetcher`` and return the constructor kwargs from the
- captured call."""
- from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
- )
-
- cm = MagicMock()
- cm.__enter__.return_value.fetch.return_value = {
- "status": "success",
- "title": "T",
- "content": "body",
- "source_type": "html",
- }
- cm.__exit__.return_value = False
-
- factory = MagicMock(return_value=cm)
- monkeypatch.setattr(
- "local_deep_research.content_fetcher.ContentFetcher",
- factory,
- )
-
- strategy = MCPSearchStrategy(
- model=MagicMock(),
- search=MagicMock(),
- settings_snapshot=settings_snapshot,
- )
- result = strategy._execute_download_content(
- {"url": "https://example.com/"}
- )
- assert result["status"] == "success"
- assert factory.call_args is not None
- return factory.call_args.kwargs
-
- def test_passes_js_off_when_snapshot_disables(self, monkeypatch):
- kwargs = self._capture_content_fetcher_kwargs(
- self._snapshot(False), monkeypatch
- )
- assert kwargs.get("enable_js_rendering") is False
-
- def test_passes_js_on_when_snapshot_enables(self, monkeypatch):
- kwargs = self._capture_content_fetcher_kwargs(
- self._snapshot(True), monkeypatch
- )
- assert kwargs.get("enable_js_rendering") is True
-
- def test_defaults_to_js_off_without_snapshot(self, monkeypatch):
- kwargs = self._capture_content_fetcher_kwargs(None, monkeypatch)
- assert kwargs.get("enable_js_rendering") is False
diff --git a/tests/news/test_web_routes_comprehensive.py b/tests/news/test_web_routes_comprehensive.py
index ffad9cce01..856b08ac78 100644
--- a/tests/news/test_web_routes_comprehensive.py
+++ b/tests/news/test_web_routes_comprehensive.py
@@ -471,23 +471,3 @@ class TestStrategyList:
call_kwargs = mock_render.call_args[1]
strategy_names = [s["name"] for s in call_kwargs["strategies"]]
assert "focused-iteration" in strategy_names
-
- def test_strategies_include_mcp(self):
- """Test strategies list includes mcp."""
- from local_deep_research.news.web import create_news_blueprint
- from flask import Flask
-
- with patch(
- "local_deep_research.news.web.render_template"
- ) as mock_render:
- mock_render.return_value = "rendered"
-
- app = Flask(__name__)
- bp = create_news_blueprint()
- app.register_blueprint(bp, url_prefix="/news")
-
- with app.test_client() as client:
- client.get("/news/")
- call_kwargs = mock_render.call_args[1]
- strategy_names = [s["name"] for s in call_kwargs["strategies"]]
- assert "mcp" in strategy_names
diff --git a/tests/performance/mcp/__init__.py b/tests/performance/mcp/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/tests/performance/mcp/echo_server.py b/tests/performance/mcp/echo_server.py
deleted file mode 100644
index 3d34772ac8..0000000000
--- a/tests/performance/mcp/echo_server.py
+++ /dev/null
@@ -1,152 +0,0 @@
-"""
-Simple echo MCP server for integration testing.
-
-This is a minimal MCP server that provides basic tools for testing
-client-server communication without requiring the full LDR stack.
-"""
-
-import sys
-from typing import Any, Dict
-
-from loguru import logger
-
-# Configure loguru to output to stderr to avoid stdout pollution
-# (MCP uses stdout for JSON-RPC communication)
-logger.remove() # Remove default handler
-# diagnose=False mirrors the production MCP server (#4394) — loguru's
-# default would dump repr() of every traceback frame's locals on exception,
-# which we do not want even for the test echo server.
-logger.add(
- sys.stderr,
- level="INFO",
- format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {message}",
- diagnose=False,
-)
-
-
-try:
- from mcp.server.fastmcp import FastMCP
-
- MCP_AVAILABLE = True
-except ImportError:
- MCP_AVAILABLE = False
- logger.warning("MCP package not available")
-
-
-if MCP_AVAILABLE:
- # Create FastMCP server instance
- mcp = FastMCP(
- "echo-test-server",
- instructions="Simple echo server for testing MCP client-server communication",
- )
-
- @mcp.tool()
- def echo(message: str) -> Dict[str, Any]:
- """
- Echo back the provided message.
-
- Args:
- message: The message to echo back.
-
- Returns:
- Dictionary with the echoed message.
- """
- logger.info(f"Echo tool called with: {message}")
- return {
- "status": "success",
- "message": message,
- "echoed": True,
- }
-
- @mcp.tool()
- def add_numbers(a: int, b: int) -> Dict[str, Any]:
- """
- Add two numbers together.
-
- Args:
- a: First number.
- b: Second number.
-
- Returns:
- Dictionary with the sum.
- """
- logger.info(f"Add tool called with: {a} + {b}")
- return {
- "status": "success",
- "result": a + b,
- }
-
- @mcp.tool()
- def get_info() -> Dict[str, Any]:
- """
- Get server information.
-
- Returns:
- Dictionary with server details.
- """
- return {
- "status": "success",
- "server_name": "echo-test-server",
- "tools": [
- "echo",
- "add_numbers",
- "get_info",
- "slow_operation",
- "fail_on_demand",
- ],
- }
-
- @mcp.tool()
- def slow_operation(delay_ms: int = 100) -> Dict[str, Any]:
- """
- Simulate a slow operation for timeout testing.
-
- Args:
- delay_ms: Delay in milliseconds (capped at 5000ms for safety).
-
- Returns:
- Dictionary confirming completion.
- """
- import time
-
- # Cap delay to 5 seconds for safety
- actual_delay = min(delay_ms, 5000) / 1000.0
- logger.info(f"Slow operation sleeping for {actual_delay}s")
- time.sleep(actual_delay)
- return {
- "status": "success",
- "slept_ms": int(actual_delay * 1000),
- }
-
- @mcp.tool()
- def fail_on_demand(
- should_fail: bool = False, error_message: str = "Intentional failure"
- ) -> Dict[str, Any]:
- """
- A tool that can be made to fail for error handling tests.
-
- Args:
- should_fail: Whether to raise an exception.
- error_message: The error message to use if failing.
-
- Returns:
- Success dict or raises exception.
- """
- if should_fail:
- raise ValueError(error_message)
- return {
- "status": "success",
- "failed": False,
- }
-
- def run_server():
- """Run the echo MCP server using STDIO transport."""
- logger.info("Starting echo test MCP server...")
- mcp.run(transport="stdio")
-
-
-if __name__ == "__main__":
- if not MCP_AVAILABLE:
- print("MCP package not available", file=sys.stderr)
- sys.exit(1)
- run_server()
diff --git a/tests/performance/mcp/test_concurrent_mcp_calls.py b/tests/performance/mcp/test_concurrent_mcp_calls.py
deleted file mode 100644
index 097ab0bc47..0000000000
--- a/tests/performance/mcp/test_concurrent_mcp_calls.py
+++ /dev/null
@@ -1,500 +0,0 @@
-"""
-Tests for concurrent MCP tool calls and MCPClientManager.
-
-These tests verify that multiple concurrent tool calls work correctly
-without race conditions or deadlocks.
-
-Tests are organized into:
-1. Mock-based tests for fast, reliable testing of concurrency logic
-2. Subprocess tests (marked with `integration`) for real-world verification
-
-To run the subprocess tests locally:
- pytest tests/mcp/test_concurrent_mcp_calls.py -m integration
-"""
-
-import asyncio
-import sys
-from pathlib import Path
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-# Skip all tests if MCP is not available
-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"
-)
-
-# Path to the echo server for testing
-ECHO_SERVER_PATH = Path(__file__).parent / "echo_server.py"
-
-
-class TestConcurrentToolCallsWithMocks:
- """Tests for concurrent tool calls using mocks for reliable testing."""
-
- @pytest.fixture
- def mock_tool_result(self):
- """Create a mock tool result factory."""
-
- def _make_result(text_content, is_error=False):
- mock_item = MagicMock()
- mock_item.text = text_content
- mock_result = MagicMock()
- mock_result.isError = is_error
- mock_result.content = [mock_item]
- return mock_result
-
- return _make_result
-
- @pytest.mark.asyncio
- async def test_parallel_tool_calls_with_mock(self, mock_tool_result):
- """Test multiple tool calls running in parallel."""
- from local_deep_research.mcp.client import MCPClient
-
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- config = {"name": "mock-server", "command": "python"}
- client = MCPClient(config)
-
- client._connected = True
- client._session = MagicMock()
-
- call_order = []
-
- async def mock_call(name, args):
- call_order.append(f"start_{args.get('id', 0)}")
- await asyncio.sleep(0.01) # Simulate async work
- call_order.append(f"end_{args.get('id', 0)}")
- return mock_tool_result(f"Result for {args.get('id', 0)}")
-
- client._session.call_tool = mock_call
-
- # Launch concurrent calls
- tasks = [client.call_tool("echo", {"id": i}) for i in range(5)]
-
- results = await asyncio.gather(*tasks)
-
- assert len(results) == 5
- for result in results:
- assert result["status"] == "success"
-
- @pytest.mark.asyncio
- async def test_concurrent_calls_no_data_corruption_with_mock(
- self, mock_tool_result
- ):
- """Test that concurrent calls don't corrupt each other's data."""
- from local_deep_research.mcp.client import MCPClient
-
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- config = {"name": "mock-server", "command": "python"}
- client = MCPClient(config)
-
- client._connected = True
- client._session = MagicMock()
-
- # Track what was received
- received_messages = []
-
- async def mock_call(name, args):
- msg = args.get("message", "")
- received_messages.append(msg)
- await asyncio.sleep(0.001) # Tiny delay
- return mock_tool_result(f'{{"echoed": "{msg}"}}')
-
- client._session.call_tool = mock_call
-
- # Create unique messages
- messages = [f"UNIQUE_{i}_MSG" for i in range(20)]
- tasks = [
- client.call_tool("echo", {"message": msg}) for msg in messages
- ]
-
- results = await asyncio.gather(*tasks)
-
- # All messages should have been received
- assert len(received_messages) == 20
- assert set(received_messages) == set(messages)
-
- # All results should succeed
- for result in results:
- assert result["status"] == "success"
-
- @pytest.mark.asyncio
- async def test_mixed_parallel_tools_with_mock(self, mock_tool_result):
- """Test different tools called in parallel."""
- from local_deep_research.mcp.client import MCPClient
-
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- config = {"name": "mock-server", "command": "python"}
- client = MCPClient(config)
-
- client._connected = True
- client._session = MagicMock()
-
- async def mock_call(name, args):
- await asyncio.sleep(0.001)
- if name == "echo":
- return mock_tool_result(
- f'{{"message": "{args.get("message", "")}"}}'
- )
- if name == "add":
- result = args.get("a", 0) + args.get("b", 0)
- return mock_tool_result(f'{{"result": {result}}}')
- return mock_tool_result('{"status": "unknown"}')
-
- client._session.call_tool = mock_call
-
- tasks = [
- client.call_tool("echo", {"message": "hello"}),
- client.call_tool("add", {"a": 1, "b": 2}),
- client.call_tool("echo", {"message": "world"}),
- client.call_tool("add", {"a": 10, "b": 20}),
- ]
-
- results = await asyncio.gather(*tasks)
-
- assert len(results) == 4
- assert all(r["status"] == "success" for r in results)
-
-
-class TestMCPClientManagerWithMocks:
- """Tests for MCPClientManager using mocks."""
-
- @pytest.mark.asyncio
- async def test_manager_call_tool_on_unknown_server(self):
- """Test calling tool on non-existent server raises error."""
- from local_deep_research.mcp.client import (
- MCPClientManager,
- MCPClientError,
- )
-
- manager = MCPClientManager([])
-
- async with manager.connect_all():
- with pytest.raises(MCPClientError) as exc_info:
- await manager.call_tool("unknown-server", "echo", {})
-
- assert "not connected" in str(exc_info.value)
-
- @pytest.mark.asyncio
- async def test_manager_empty_configs(self):
- """Test manager with empty config list."""
- from local_deep_research.mcp.client import MCPClientManager
-
- manager = MCPClientManager([])
-
- async with manager.connect_all():
- servers = manager.get_connected_servers()
- assert servers == []
-
- @pytest.mark.asyncio
- async def test_manager_cleanup_tracking(self):
- """Test that manager properly tracks cleanup."""
- from local_deep_research.mcp.client import MCPClientManager
-
- # Use empty configs to avoid actual connections
- manager = MCPClientManager([])
-
- assert len(manager._clients) == 0
-
- async with manager.connect_all():
- assert len(manager._clients) == 0 # No servers configured
-
- assert len(manager._clients) == 0
-
-
-# =============================================================================
-# Subprocess-based integration tests - marked for opt-in execution
-# =============================================================================
-
-
-class TestConcurrentToolCallsSubprocess:
- """Tests for concurrent tool calls using real subprocess."""
-
- @pytest.fixture
- def echo_server_config(self):
- """Configuration for the echo test server."""
- return {
- "name": "echo-concurrent-test",
- "command": sys.executable,
- "args": [str(ECHO_SERVER_PATH)],
- }
-
- @pytest.mark.asyncio
- async def test_parallel_tool_calls(self, echo_server_config):
- """Test multiple tool calls running in parallel."""
- from local_deep_research.mcp.client import MCPClient
-
- client = MCPClient(echo_server_config, timeout=60.0)
-
- async with client.connect() as connected:
- # Launch multiple tool calls concurrently
- tasks = [
- connected.call_tool("echo", {"message": f"Message {i}"})
- for i in range(5)
- ]
-
- results = await asyncio.gather(*tasks)
-
- # All should succeed
- assert len(results) == 5
- for i, result in enumerate(results):
- assert result["status"] == "success"
- assert f"Message {i}" in result["content"]
-
- @pytest.mark.asyncio
- async def test_mixed_parallel_tool_calls(self, echo_server_config):
- """Test different tools called in parallel."""
- from local_deep_research.mcp.client import MCPClient
-
- client = MCPClient(echo_server_config, timeout=60.0)
-
- async with client.connect() as connected:
- # Launch different tools concurrently
- tasks = [
- connected.call_tool("echo", {"message": "test"}),
- connected.call_tool("add_numbers", {"a": 1, "b": 2}),
- connected.call_tool("get_info", {}),
- connected.call_tool("add_numbers", {"a": 10, "b": 20}),
- ]
-
- results = await asyncio.gather(*tasks)
-
- # All should succeed
- assert len(results) == 4
- for result in results:
- assert result["status"] == "success"
-
- # Verify specific results
- assert "test" in results[0]["content"]
- assert "3" in results[1]["content"]
- assert "echo-test-server" in results[2]["content"]
- assert "30" in results[3]["content"]
-
- @pytest.mark.asyncio
- async def test_concurrent_calls_no_data_corruption(
- self, echo_server_config
- ):
- """Test that concurrent calls don't corrupt each other's data."""
- from local_deep_research.mcp.client import MCPClient
-
- client = MCPClient(echo_server_config, timeout=60.0)
-
- async with client.connect() as connected:
- # Create unique messages to verify no cross-contamination
- messages = [f"UNIQUE_{i}_MESSAGE_{i * 100}" for i in range(10)]
-
- tasks = [
- connected.call_tool("echo", {"message": msg})
- for msg in messages
- ]
-
- results = await asyncio.gather(*tasks)
-
- # Each result should contain its corresponding message
- for i, (msg, result) in enumerate(zip(messages, results)):
- assert result["status"] == "success"
- assert msg in result["content"], f"Message {i} was corrupted"
-
-
-class TestMCPClientManagerSubprocess:
- """Tests for MCPClientManager with real subprocess servers."""
-
- @pytest.mark.asyncio
- async def test_manager_connect_all_single_server(self):
- """Test MCPClientManager connecting to a single server."""
- from local_deep_research.mcp.client import MCPClientManager
-
- configs = [
- {
- "name": "echo-1",
- "command": sys.executable,
- "args": [str(ECHO_SERVER_PATH)],
- }
- ]
-
- manager = MCPClientManager(configs)
-
- async with manager.connect_all():
- servers = manager.get_connected_servers()
- assert "echo-1" in servers
-
- # Test calling a tool
- result = await manager.call_tool(
- "echo-1", "echo", {"message": "Manager test"}
- )
- assert result["status"] == "success"
- assert "Manager test" in result["content"]
-
- @pytest.mark.asyncio
- async def test_manager_list_all_tools(self):
- """Test listing tools from all connected servers."""
- from local_deep_research.mcp.client import MCPClientManager
-
- configs = [
- {
- "name": "echo-tools",
- "command": sys.executable,
- "args": [str(ECHO_SERVER_PATH)],
- }
- ]
-
- manager = MCPClientManager(configs)
-
- async with manager.connect_all():
- all_tools = await manager.list_all_tools()
-
- assert "echo-tools" in all_tools
- tool_names = [t["name"] for t in all_tools["echo-tools"]]
- assert "echo" in tool_names
- assert "add_numbers" in tool_names
-
- @pytest.mark.asyncio
- async def test_manager_cleanup_on_exit(self):
- """Test that manager properly cleans up connections."""
- from local_deep_research.mcp.client import MCPClientManager
-
- configs = [
- {
- "name": "cleanup-test",
- "command": sys.executable,
- "args": [str(ECHO_SERVER_PATH)],
- }
- ]
-
- manager = MCPClientManager(configs)
-
- async with manager.connect_all():
- assert len(manager.get_connected_servers()) == 1
-
- # After exit, should have no connected servers
- assert len(manager._clients) == 0
-
- @pytest.mark.asyncio
- async def test_manager_handles_connection_failure_gracefully(self):
- """Test that manager continues when one server fails to connect."""
- from local_deep_research.mcp.client import MCPClientManager
-
- configs = [
- {
- "name": "good-server",
- "command": sys.executable,
- "args": [str(ECHO_SERVER_PATH)],
- },
- {
- "name": "bad-server",
- "command": "python",
- "args": ["/nonexistent/path.py"],
- },
- ]
-
- manager = MCPClientManager(configs)
-
- async with manager.connect_all():
- servers = manager.get_connected_servers()
- # The good server should be connected
- assert "good-server" in servers
- # The bad server should NOT be connected (failed gracefully)
- assert "bad-server" not in servers
-
-
-class TestConcurrencyMocking:
- """Tests for concurrent behavior using mocks (for faster/deterministic testing)."""
-
- @pytest.mark.asyncio
- async def test_concurrent_calls_with_mocked_session(self):
- """Test concurrent behavior with mocked MCP session."""
- from local_deep_research.mcp.client import MCPClient
-
- # Create a mock that simulates some async delay
- async def mock_call_tool(name, args):
- await asyncio.sleep(0.01) # Small delay to test concurrency
- mock_result = MagicMock()
- mock_result.isError = False
- mock_item = MagicMock()
- mock_item.text = f"Result for {name} with {args}"
- mock_result.content = [mock_item]
- return mock_result
-
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- config = {"name": "mock-server", "command": "python"}
- client = MCPClient(config)
-
- # Manually set up the client as if connected
- client._connected = True
- client._session = MagicMock()
- client._session.call_tool = mock_call_tool
-
- # Run concurrent calls
- tasks = [client.call_tool("tool", {"id": i}) for i in range(10)]
-
- results = await asyncio.gather(*tasks)
-
- assert len(results) == 10
- for result in results:
- assert result["status"] == "success"
-
- @pytest.mark.asyncio
- async def test_no_race_condition_on_connection_state(self):
- """Test that connection state is properly synchronized."""
- from local_deep_research.mcp.client import MCPClient, MCPClientError
-
- with patch("local_deep_research.mcp.client.MCP_AVAILABLE", True):
- config = {"name": "race-test", "command": "python"}
- client = MCPClient(config)
-
- # Not connected - should raise
- async def attempt_call():
- return await client.call_tool("test", {})
-
- tasks = [attempt_call() for _ in range(5)]
-
- # All should raise MCPClientError since not connected
- results = await asyncio.gather(*tasks, return_exceptions=True)
-
- for result in results:
- assert isinstance(result, MCPClientError)
- assert "Not connected" in str(result)
-
-
-class TestAsyncUtilityConcurrency:
- """Tests for the run_async utility with concurrent scenarios."""
-
- def test_run_async_multiple_sequential_calls(self):
- """Test run_async handles multiple sequential calls."""
- from local_deep_research.mcp.client import run_async
-
- async def coro(n):
- return n * 2
-
- results = [run_async(coro(i)) for i in range(5)]
-
- assert results == [0, 2, 4, 6, 8]
-
- def test_run_async_with_exception_in_one(self):
- """Test run_async propagates exceptions correctly."""
- from local_deep_research.mcp.client import run_async
-
- async def success_coro():
- return "ok"
-
- async def fail_coro():
- raise ValueError("failed")
-
- # First call succeeds
- assert run_async(success_coro()) == "ok"
-
- # Second call fails
- with pytest.raises(ValueError) as exc_info:
- run_async(fail_coro())
- assert "failed" in str(exc_info.value)
-
- # Third call succeeds (exception doesn't affect future calls)
- assert run_async(success_coro()) == "ok"
diff --git a/tests/performance/mcp/test_mcp_client_server_live.py b/tests/performance/mcp/test_mcp_client_server_live.py
deleted file mode 100644
index a2777d0b1d..0000000000
--- a/tests/performance/mcp/test_mcp_client_server_live.py
+++ /dev/null
@@ -1,208 +0,0 @@
-"""Live MCP client-server integration tests (subprocess-spawned server).
-
-Hit a real MCP echo-server subprocess — excluded from CI via `-m 'not integration'`.
-Run locally with:
-
- pdm run pytest tests/performance/mcp/test_mcp_client_server_live.py -v -m integration
-"""
-
-import sys
-from pathlib import Path
-
-import pytest
-
-# Skip all tests if MCP is not available
-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"
-)
-
-# Path to the echo server (co-located with this file).
-ECHO_SERVER_PATH = Path(__file__).parent / "echo_server.py"
-
-
-# =============================================================================
-# Subprocess-based integration tests - marked for opt-in execution
-# These tests spawn actual MCP servers and test real communication
-# =============================================================================
-
-
-class TestRealMCPClientServerCommunication:
- """Tests for actual MCP client-server communication via subprocess.
-
- These tests are slower and require subprocess spawning. Run with:
- pytest -m integration
- """
-
- @pytest.fixture
- def echo_server_config(self):
- """Configuration for the echo test server."""
- return {
- "name": "echo-test",
- "command": sys.executable,
- "args": [str(ECHO_SERVER_PATH)],
- }
-
- @pytest.mark.asyncio
- async def test_connect_to_echo_server(self, echo_server_config):
- """Test connecting to the echo server subprocess."""
- from local_deep_research.mcp.client import MCPClient
-
- client = MCPClient(echo_server_config, timeout=60.0)
-
- async with client.connect() as connected:
- assert connected._connected is True
-
- @pytest.mark.asyncio
- async def test_list_tools_from_echo_server(self, echo_server_config):
- """Test listing tools from the running echo server."""
- from local_deep_research.mcp.client import MCPClient
-
- client = MCPClient(echo_server_config, timeout=60.0)
-
- async with client.connect() as connected:
- tools = await connected.list_tools()
-
- # Verify we got the expected tools
- tool_names = [t["name"] for t in tools]
- assert "echo" in tool_names
- assert "add_numbers" in tool_names
- assert "get_info" in tool_names
-
- @pytest.mark.asyncio
- async def test_call_echo_tool(self, echo_server_config):
- """Test calling the echo tool on the real server."""
- from local_deep_research.mcp.client import MCPClient
-
- client = MCPClient(echo_server_config, timeout=60.0)
-
- async with client.connect() as connected:
- result = await connected.call_tool(
- "echo", {"message": "Hello, MCP!"}
- )
-
- assert result["status"] == "success"
- # The content should contain the echoed message
- assert "Hello, MCP!" in result["content"]
-
- @pytest.mark.asyncio
- async def test_call_add_numbers_tool(self, echo_server_config):
- """Test calling the add_numbers tool."""
- from local_deep_research.mcp.client import MCPClient
-
- client = MCPClient(echo_server_config, timeout=60.0)
-
- async with client.connect() as connected:
- result = await connected.call_tool("add_numbers", {"a": 5, "b": 3})
-
- assert result["status"] == "success"
- # Result should contain 8
- assert "8" in result["content"]
-
- @pytest.mark.asyncio
- async def test_call_get_info_tool(self, echo_server_config):
- """Test calling the get_info tool."""
- from local_deep_research.mcp.client import MCPClient
-
- client = MCPClient(echo_server_config, timeout=60.0)
-
- async with client.connect() as connected:
- result = await connected.call_tool("get_info", {})
-
- assert result["status"] == "success"
- assert "echo-test-server" in result["content"]
-
- @pytest.mark.asyncio
- async def test_multiple_tool_calls_sequential(self, echo_server_config):
- """Test multiple sequential tool calls on one connection."""
- from local_deep_research.mcp.client import MCPClient
-
- client = MCPClient(echo_server_config, timeout=60.0)
-
- async with client.connect() as connected:
- # Call multiple tools sequentially
- result1 = await connected.call_tool("echo", {"message": "First"})
- result2 = await connected.call_tool(
- "add_numbers", {"a": 10, "b": 20}
- )
- result3 = await connected.call_tool("echo", {"message": "Third"})
-
- assert result1["status"] == "success"
- assert "First" in result1["content"]
- assert result2["status"] == "success"
- assert "30" in result2["content"]
- assert result3["status"] == "success"
- assert "Third" in result3["content"]
-
- @pytest.mark.asyncio
- async def test_connection_context_manager_cleanup(self, echo_server_config):
- """Test that connection is properly cleaned up after context exit."""
- from local_deep_research.mcp.client import MCPClient
-
- client = MCPClient(echo_server_config, timeout=60.0)
-
- async with client.connect() as connected:
- assert connected._connected is True
-
- # After context exit, should be disconnected
- assert client._connected is False
- assert client._session is None
-
-
-class TestMCPClientServerErrorHandling:
- """Tests for error handling in real client-server communication."""
-
- @pytest.fixture
- def echo_server_config(self):
- """Configuration for the echo test server."""
- return {
- "name": "echo-test",
- "command": sys.executable,
- "args": [str(ECHO_SERVER_PATH)],
- }
-
- @pytest.mark.asyncio
- async def test_tool_error_handling(self, echo_server_config):
- """Test handling of errors from tools."""
- from local_deep_research.mcp.client import MCPClient
-
- client = MCPClient(echo_server_config, timeout=60.0)
-
- async with client.connect() as connected:
- # Request the tool to fail intentionally
- result = await connected.call_tool(
- "fail_on_demand",
- {"should_fail": True, "error_message": "Test failure"},
- )
-
- # The MCP SDK returns error results, not exceptions for tool errors
- # Check if the result indicates an error
- assert (
- result["status"] == "error"
- or "error" in result.get("content", "").lower()
- )
-
- @pytest.mark.asyncio
- async def test_connection_to_invalid_command(self):
- """Test connection failure for invalid command."""
- from local_deep_research.mcp.client import MCPClient, MCPClientError
-
- config = {
- "name": "invalid",
- "command": "python",
- "args": ["/nonexistent/path/to/server.py"],
- }
-
- client = MCPClient(config, timeout=10.0)
-
- with pytest.raises(MCPClientError):
- async with client.connect():
- pass # Should not reach here
diff --git a/tests/security/test_egress_mcp_scope_gating.py b/tests/security/test_egress_mcp_scope_gating.py
deleted file mode 100644
index 06296db699..0000000000
--- a/tests/security/test_egress_mcp_scope_gating.py
+++ /dev/null
@@ -1,264 +0,0 @@
-"""Integration tests for MCP egress scope gating (PR #4300, Stage 1a).
-
-Drives the REAL policy enforcement points in
-``advanced_search_system/strategies/mcp_strategy.py``:
-
-* ``MCPSearchStrategy._mcp_scope_blocked`` — the scope decision that
- certifies whether stdio MCP subprocesses may be exposed at all.
-* ``MCPSearchStrategy._discover_mcp_tools`` — suppresses (and caches an
- empty list for) discovery when the scope blocks it, and never launches
- an MCP client/subprocess on the blocked path.
-* ``MCPSearchStrategy._build_tool_descriptions`` — scope-filters the
- specialized search-engine tool descriptions exposed to the LLM.
-
-These exercise the real call-site logic; the only mocked pieces are the
-LLM/citation handler (never invoked here), the available-engine catalog,
-and the MCP client transport (so no subprocess launches). Every test is
-written as an allow/deny pair so it fails if the guarded property is
-reverted.
-"""
-
-from __future__ import annotations
-
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-from local_deep_research.advanced_search_system.strategies.mcp_strategy import (
- MCPSearchStrategy,
-)
-
-MCP_CLIENT = "local_deep_research.mcp.client"
-
-
-def make_strategy(
- *,
- snapshot,
- mcp_servers=None,
- include_web_search=True,
- include_sub_research=False,
-):
- """Construct an ``MCPSearchStrategy`` with only the heavy collaborators
- stubbed (model + citation handler are never invoked by the methods under
- test). ``settings_snapshot`` and ``mcp_servers`` are real inputs."""
- return MCPSearchStrategy(
- model=MagicMock(name="model"),
- search=MagicMock(name="search"),
- citation_handler=MagicMock(name="citation_handler"),
- mcp_servers=mcp_servers,
- include_web_search=include_web_search,
- include_sub_research=include_sub_research,
- settings_snapshot=snapshot,
- )
-
-
-def snap(scope=None, primary="arxiv"):
- """Build a settings snapshot in the {key: {value: ...}} / plain shapes
- the strategy reads."""
- s = {}
- if scope is not None:
- s["policy.egress_scope"] = {"value": scope}
- if primary is not None:
- s["search.tool"] = primary
- return s
-
-
-SERVERS = [{"name": "srv", "command": "echo", "args": []}]
-
-
-# ---------------------------------------------------------------------------
-# _mcp_scope_blocked
-# ---------------------------------------------------------------------------
-
-
-def test_scope_blocked_strict_concrete_primary():
- """STRICT with a concrete primary blocks MCP and reports the scope."""
- strat = make_strategy(snapshot=snap("strict", primary="arxiv"))
- assert strat._mcp_scope_blocked() == (True, "strict")
-
-
-def test_scope_blocked_private_only():
- """PRIVATE_ONLY blocks MCP (stdio egress is uninspectable)."""
- strat = make_strategy(snapshot=snap("private_only", primary="arxiv"))
- assert strat._mcp_scope_blocked() == (True, "private_only")
-
-
-def test_scope_not_blocked_public_only():
- """PUBLIC_ONLY does not block MCP discovery."""
- strat = make_strategy(snapshot=snap("public_only", primary="arxiv"))
- assert strat._mcp_scope_blocked() == (False, "")
-
-
-def test_scope_not_blocked_both():
- """BOTH (the permissive default scope) does not block MCP."""
- strat = make_strategy(snapshot=snap("both", primary="arxiv"))
- assert strat._mcp_scope_blocked() == (False, "")
-
-
-def test_scope_blocked_no_snapshot_fails_closed():
- """An empty snapshot ({}) cannot certify safety -> fail closed."""
- strat = make_strategy(snapshot={})
- # BaseSearchStrategy coerces None/{} to {} (falsy) -> no_snapshot.
- assert strat.settings_snapshot == {}
- assert strat._mcp_scope_blocked() == (True, "no_snapshot")
-
-
-def test_scope_blocked_corrupt_scope_fails_closed():
- """A corrupt/unknown scope value is unevaluable -> fail closed."""
- strat = make_strategy(snapshot=snap("bogus_scope", primary="arxiv"))
- blocked, reason = strat._mcp_scope_blocked()
- assert blocked is True
- assert reason.startswith("policy_unavailable:")
-
-
-def test_scope_blocked_strict_stray_meta_primary_still_blocks():
- """STRICT with a stray removed meta-engine primary ('auto') no longer
- raises at context construction, but the scope is still STRICT — MCP stays
- blocked, never a silent allow."""
- strat = make_strategy(snapshot=snap("strict", primary="auto"))
- assert strat._mcp_scope_blocked() == (True, "strict")
-
-
-# ---------------------------------------------------------------------------
-# _discover_mcp_tools
-# ---------------------------------------------------------------------------
-
-
[email protected]("scope", ["strict", "private_only"])
-def test_discover_suppressed_under_blocking_scope(scope):
- """Under a blocking scope, discovery returns [], caches it, and NEVER
- invokes the MCP client transport (no subprocess launch)."""
- strat = make_strategy(
- snapshot=snap(scope, primary="arxiv"), mcp_servers=SERVERS
- )
- with (
- patch(f"{MCP_CLIENT}.run_async") as run_async,
- patch(f"{MCP_CLIENT}.MCPClientManager") as manager,
- ):
- tools = strat._discover_mcp_tools()
-
- assert tools == []
- # Fail-closed suppression is final: cached as empty.
- assert strat._mcp_tools_cache == []
- run_async.assert_not_called()
- manager.assert_not_called()
-
-
-def test_discover_no_snapshot_suppressed():
- """No snapshot ({}) fails closed at discovery too: [] and no transport."""
- strat = make_strategy(snapshot={}, mcp_servers=SERVERS)
- with patch(f"{MCP_CLIENT}.run_async") as run_async:
- tools = strat._discover_mcp_tools()
- assert tools == []
- assert strat._mcp_tools_cache == []
- run_async.assert_not_called()
-
-
-def test_discover_proceeds_under_allowing_scope():
- """Under BOTH, discovery is NOT suppressed: the strategy reaches the
- (mocked) MCP transport and surfaces the discovered tools."""
- strat = make_strategy(
- snapshot=snap("both", primary="arxiv"), mcp_servers=SERVERS
- )
-
- discovered = {
- "srv": [
- {
- "name": "tool1",
- "description": "a tool",
- "input_schema": {"properties": {"q": {"type": "string"}}},
- }
- ]
- }
-
- def run_async_stub(coro, timeout=None):
- # Close the un-awaited discover() coroutine so MCPClientManager is
- # never instantiated and no "coroutine was never awaited" warning
- # leaks; return the canned discovery result.
- coro.close()
- return discovered
-
- with patch(f"{MCP_CLIENT}.run_async", side_effect=run_async_stub) as ra:
- tools = strat._discover_mcp_tools()
-
- ra.assert_called_once()
- assert [t["name"] for t in tools] == ["srv.tool1"]
- # Successful discovery is cached.
- assert strat._mcp_tools_cache == tools
-
-
-def test_discover_no_servers_is_noop():
- """With no configured servers there is nothing to discover or block."""
- strat = make_strategy(snapshot=snap("both"), mcp_servers=[])
- with patch(f"{MCP_CLIENT}.run_async") as run_async:
- assert strat._discover_mcp_tools() == []
- run_async.assert_not_called()
-
-
-# ---------------------------------------------------------------------------
-# _build_tool_descriptions — specialized engine scope filtering
-# ---------------------------------------------------------------------------
-
-
-def _engines():
- """A small available-engine catalog: a public engine and a private
- collection."""
- return {
- "wikipedia": {"description": "Wikipedia"},
- "collection_x": {"description": "Local docs", "is_public": False},
- }
-
-
-def _build_with_engines(strat):
- """Run _build_tool_descriptions with a controlled engine catalog and a
- non-matching 'current engine' so nothing is skipped as the primary."""
- strat._get_available_search_engines = lambda: _engines()
- strat._get_current_engine_name = lambda: "magicmock"
- return strat._build_tool_descriptions()
-
-
-def _tool_names(tools):
- return {t["name"] for t in tools}
-
-
-def test_build_tools_strict_hides_all_specialized():
- """STRICT exposes only the primary (web_search) — no specialized
- search_<engine> tools leak into the LLM's tool list."""
- strat = make_strategy(
- snapshot=snap("strict", primary="arxiv"), mcp_servers=[]
- )
- names = _tool_names(_build_with_engines(strat))
- assert "web_search" in names
- assert not any(n.startswith("search_") for n in names)
-
-
-def test_build_tools_both_exposes_specialized():
- """BOTH exposes classified specialized engines (allow side of the pair)."""
- strat = make_strategy(
- snapshot=snap("both", primary="arxiv"), mcp_servers=[]
- )
- names = _tool_names(_build_with_engines(strat))
- assert "search_wikipedia" in names
- assert "search_collection_x" in names
-
-
-def test_build_tools_public_only_filters_private_collection():
- """PUBLIC_ONLY keeps the public engine but filters the private
- collection — scope-correct per-engine filtering, not all-or-nothing."""
- strat = make_strategy(
- snapshot=snap("public_only", primary="arxiv"), mcp_servers=[]
- )
- names = _tool_names(_build_with_engines(strat))
- assert "search_wikipedia" in names
- assert "search_collection_x" not in names
-
-
-def test_build_tools_corrupt_scope_blocks_all_specialized():
- """A corrupt scope raises PolicyDeniedError during context build, which
- fails closed: NO specialized engines are exposed at all."""
- strat = make_strategy(
- snapshot=snap("bogus_scope", primary="arxiv"), mcp_servers=[]
- )
- names = _tool_names(_build_with_engines(strat))
- assert "web_search" in names
- assert not any(n.startswith("search_") for n in names)
diff --git a/tests/security/test_egress_pep_coverage.py b/tests/security/test_egress_pep_coverage.py
index 8a90b50aaa..5c9c0e6fd5 100644
--- a/tests/security/test_egress_pep_coverage.py
+++ b/tests/security/test_egress_pep_coverage.py
@@ -125,7 +125,7 @@ class TestJournalFetchScopeSkip:
"""Journal sources (OpenAlex/DOAJ/JabRef) are public, so under
PRIVATE_ONLY/STRICT the filter should skip the fetch. A corrupt scope
(PolicyDeniedError) must ALSO skip — fail closed — matching the
- hardened mcp_strategy/notifications siblings. Regression: the bare
+ hardened notifications sibling. Regression: the bare
except previously swallowed PolicyDeniedError and returned False
(fail open)."""
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index f5a10d00a7..03b4cca460 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -1752,20 +1752,6 @@
],
"visible": true
},
- "mcp.servers": {
- "category": "mcp",
- "description": "List of external MCP servers to connect to. Each entry should have 'command' (required), and optionally 'name', 'args', and 'env'. Allowed commands: node, npx, python, python3, uv, uvx, docker. See <a href=\"https://github.com/LearningCircuit/local-deep-research/blob/main/docs/mcp-server.md#mcp-client-connecting-external-mcp-servers\" target=\"_blank\">MCP Client documentation</a> for details.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "MCP Servers",
- "options": null,
- "step": null,
- "type": "APP",
- "ui_element": "textarea",
- "value": [],
- "visible": true
- },
"news.display.default_headline_max_length": {
"category": "news",
"description": "Default maximum headline length",
@@ -7792,7 +7778,7 @@
},
"search.search_strategy": {
"category": "search_parameters",
- "description": "Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'topic-organization': Organizes research around discovered topic clusters. 'mcp': Agentic ReAct-pattern research using MCP tools. 'langgraph-agent': Autonomous agentic research where the LLM decides what to search and when to synthesize.",
+ "description": "Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'topic-organization': Organizes research around discovered topic clusters. 'langgraph-agent': Autonomous agentic research where the LLM decides what to search and when to synthesize.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -7814,10 +7800,6 @@
"label": "Topic Organization (Clusters by topic)",
"value": "topic-organization"
},
- {
- "label": "MCP ReAct (Agentic research - LLM decides tools)",
- "value": "mcp"
- },
{
"label": "LangGraph Agent (Autonomous agentic research)",
"value": "langgraph-agent"
diff --git a/tests/settings/test_settings_defaults_integrity.py b/tests/settings/test_settings_defaults_integrity.py
index b37ce0d567..9e9eb26cab 100644
--- a/tests/settings/test_settings_defaults_integrity.py
+++ b/tests/settings/test_settings_defaults_integrity.py
@@ -92,8 +92,6 @@ KNOWN_SNAPSHOT_DIVERGENCES = {
"search.engine.web.semantic_scholar",
"search.engine.web.stackexchange",
"search.engine.web.zenodo",
- # List values stored as JSON strings in snapshot but parsed by get_setting()
- "mcp.servers",
}
# ---------------------------------------------------------------------------
diff --git a/tests/strategies/conftest.py b/tests/strategies/conftest.py
index 5bb1e02926..29a4ebe0ce 100644
--- a/tests/strategies/conftest.py
+++ b/tests/strategies/conftest.py
@@ -237,7 +237,6 @@ FACTORY_STRATEGY_NAMES = [
"focused-iteration-standard",
"news",
"topic-organization",
- "mcp",
"langgraph-agent",
]
@@ -248,6 +247,5 @@ STRATEGY_IMPORTS = [
("focused_iteration_strategy", "FocusedIterationStrategy"),
("news_strategy", "NewsAggregationStrategy"),
("topic_organization_strategy", "TopicOrganizationStrategy"),
- ("mcp_strategy", "MCPSearchStrategy"),
("langgraph_agent_strategy", "LangGraphAgentStrategy"),
]
diff --git a/tests/test_search_system_factory.py b/tests/test_search_system_factory.py
index 2fa4e82388..3d17101c8b 100644
--- a/tests/test_search_system_factory.py
+++ b/tests/test_search_system_factory.py
@@ -80,12 +80,14 @@ class TestStrategyCreation:
strategy = create_strategy("focused-iteration", mock_model, mock_search)
assert strategy is not None
- def test_create_mcp_strategy(self, mock_model, mock_search):
- """Test creating MCP strategy."""
+ def test_mcp_alias_routes_to_langgraph(self, mock_model, mock_search):
+ """The removed 'mcp'/'agentic' keys are deprecated aliases that
+ route to langgraph-agent (not the source-based fallback)."""
from local_deep_research.search_system_factory import create_strategy
- strategy = create_strategy("mcp", mock_model, mock_search)
- assert strategy is not None
+ for alias in ("mcp", "agentic"):
+ strategy = create_strategy(alias, mock_model, mock_search)
+ assert type(strategy).__name__ == "LangGraphAgentStrategy"
def test_create_rapid_strategy(self, mock_model, mock_search):
"""Test creating rapid strategy."""
diff --git a/tests/test_search_system_factory_high_value.py b/tests/test_search_system_factory_high_value.py
index cd99dd04c2..12031cd8e0 100644
--- a/tests/test_search_system_factory_high_value.py
+++ b/tests/test_search_system_factory_high_value.py
@@ -20,7 +20,7 @@ class TestAvailableStrategiesList:
assert isinstance(AVAILABLE_STRATEGIES, list)
def test_expected_count(self):
- assert len(AVAILABLE_STRATEGIES) == 6
+ assert len(AVAILABLE_STRATEGIES) == 5
def test_all_entries_are_dicts(self):
for entry in AVAILABLE_STRATEGIES:
@@ -51,7 +51,6 @@ class TestAvailableStrategiesList:
"focused-iteration",
"focused-iteration-standard",
"topic-organization",
- "mcp",
"langgraph-agent",
],
)
diff --git a/tests/web/routes/test_metrics_routes_coverage.py b/tests/web/routes/test_metrics_routes_coverage.py
index 76b177b571..c060de78f1 100644
--- a/tests/web/routes/test_metrics_routes_coverage.py
+++ b/tests/web/routes/test_metrics_routes_coverage.py
@@ -214,7 +214,11 @@ class TestGetAvailableStrategies:
def test_returns_list(self):
result = get_available_strategies()
assert isinstance(result, list)
- assert len(result) == 6
+ # 5 strategies after the 'mcp'/'agentic' strategy was removed (#4548):
+ # source-based, focused-iteration, focused-iteration-standard,
+ # topic-organization, langgraph-agent.
+ assert len(result) == 5
+ assert "mcp" not in {s["name"] for s in result}
def test_each_strategy_has_name_and_description(self):
for s in get_available_strategies():
diff --git a/tests/web/services/test_research_service_deep_coverage.py b/tests/web/services/test_research_service_deep_coverage.py
index d578fc8a2d..ae2c2fdd9a 100644
--- a/tests/web/services/test_research_service_deep_coverage.py
+++ b/tests/web/services/test_research_service_deep_coverage.py
@@ -375,6 +375,10 @@ class TestGetResearchStrategyDeep:
assert result is None
def test_returns_strategy_name(self):
+ """``get_research_strategy`` returns the stored strategy name
+ verbatim — including the removed ``mcp`` value (#4548). It is a
+ display-only read that never feeds the factory, so a saved 'mcp'
+ research keeps loading after the strategy is gone."""
from local_deep_research.web.services.research_service import (
get_research_strategy,
)
diff --git a/tests/web/services/test_research_service_extra_coverage.py b/tests/web/services/test_research_service_extra_coverage.py
index 99cfdcd44c..e70f612f96 100644
--- a/tests/web/services/test_research_service_extra_coverage.py
+++ b/tests/web/services/test_research_service_extra_coverage.py
@@ -556,9 +556,9 @@ class TestSaveResearchStrategy:
)
with patch(f"{MODULE}.get_user_db_session", _fake_session_ctx(ms)):
- save_research_strategy("res-1", "mcp", username="user")
+ save_research_strategy("res-1", "langgraph-agent", username="user")
- assert existing.strategy_name == "mcp"
+ assert existing.strategy_name == "langgraph-agent"
ms.commit.assert_called_once()
def test_exception_swallowed(self):