Skip to main content
Glama

rag_search_ddgs

Searches the web via DuckDuckGo and returns the most semantically relevant results based on similarity scoring, providing focused context for the query.

Instructions

Search the web for a given query using DuckDuckGo. Returns context to the LLM with RAG-like similarity scoring to prioritize the most relevant results.

This tool fetches web search results, scores them by semantic similarity to the query using text embeddings, and returns the top-ranked content as markdown text.

Args: query (str): The search query. Use natural language questions or keywords. Example: "latest developments in quantum computing" num_results (int): Number of initial search results to fetch from DuckDuckGo. More results provide better coverage but increase processing time. Default: 10 top_k (int): Number of top-scored results to include in the final output. These are the most semantically relevant results after scoring. Default: 5 include_urls (bool): Whether to include source URLs in the results. If True, each result includes its URL for citation. Default: True

Returns: Dict: A dictionary with a single key "content" containing the search results. The content is formatted as markdown text with the most relevant information from the top_k web pages. If include_urls is True, each section includes its source URL.

Example: {"content": "# Result 1\n\nContent here...\n\nSource: https://example.com"}

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
num_resultsNo
top_kNo
include_urlsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The main handler function for the 'rag_search_ddgs' MCP tool. Uses DuckDuckGo (DDGS) to perform a web search, scores results by semantic similarity using text embeddings, fetches content from the top-ranked URLs via a thread pool, and returns markdown-formatted content as a Dict.
    def rag_search_ddgs(query: str, num_results:int=10, top_k:int=5, include_urls:bool=True) -> Dict:
        """
        Search the web for a given query using DuckDuckGo. Returns context to the LLM
        with RAG-like similarity scoring to prioritize the most relevant results.
        
        This tool fetches web search results, scores them by semantic similarity to the query
        using text embeddings, and returns the top-ranked content as markdown text.
        
        Args:
            query (str): The search query. Use natural language questions or keywords.
                        Example: "latest developments in quantum computing"
            num_results (int): Number of initial search results to fetch from DuckDuckGo.
                              More results provide better coverage but increase processing time.
                              Default: 10
            top_k (int): Number of top-scored results to include in the final output.
                        These are the most semantically relevant results after scoring.
                        Default: 5
            include_urls (bool): Whether to include source URLs in the results.
                                If True, each result includes its URL for citation.
                                Default: True
        
        Returns:
            Dict: A dictionary with a single key "content" containing the search results.
                  The content is formatted as markdown text with the most relevant information
                  from the top_k web pages. If include_urls is True, each section includes
                  its source URL.
                  
        Example:
            {"content": "# Result 1\\n\\nContent here...\\n\\nSource: https://example.com"}
        """
        
        # Import heavy dependencies only when tool is invoked
        from ddgs import DDGS
        from .utils.fetch import fetch_all_content
        from .utils.tools import sort_by_score
        
        ddgs = DDGS()
        results = ddgs.text(query, max_results=num_results) 
        scored_results = sort_by_score(add_score_to_dict(query, results))
        top_results = scored_results[0:top_k]
    
        # fetch content using thread pool
        md_content = fetch_all_content(top_results, include_urls)
    
        # formatted as dict
        return {
            "content": md_content
                }
  • The tool is registered with FastMCP using the @mcp.tool() decorator on line 25.
    @mcp.tool()
  • add_score_to_dict computes cosine similarity scores between the query and each search result using a MediaPipe text embedder.
    def add_score_to_dict(query: str, results: List[Dict]) -> List[Dict]:
        """Add similarity scores to search results."""
        # Import heavy dependencies only when needed (slow import!)
        from importlib.resources import files
        from mediapipe.tasks.python import text
        from .utils.fetch import fetch_embedder, get_path_str
        
        path = get_path_str(files('mcp_local_rag.embedder').joinpath('embedder.tflite'))
        embedder = fetch_embedder(path)
        query_embedding = embedder.embed(query)
    
        for i in results:
            i['score'] = text.TextEmbedder.cosine_similarity(
                            embedder.embed(i['body']).embeddings[0],
                            query_embedding.embeddings[0])
    
        return results
  • sort_by_score sorts the list of result dicts by their 'score' field in descending order.
    def sort_by_score(results: List[Dict]) -> List[Dict]:
        """Sort results by similarity score."""
        return sorted(results, key=lambda x: x['score'], reverse=True)
  • fetch_all_content fetches content from all result URLs in parallel using a ThreadPoolExecutor, optionally including URLs in the output.
    def fetch_all_content(results: List[Dict], include_urls:bool=True) -> List[str]:
        """Fetch content from all URLs using a thread pool."""
        urls = [site['href'] for site in results if site.get('href')]
        
        # parallelize requests
        with ThreadPoolExecutor(max_workers=5) as executor:
            # submit fetch tasks to executor
            future_to_url = {executor.submit(fetch_content, url): url for url in urls}
            
            content_list = []
            for future, url in future_to_url.items():
                try:
                    content = future.result()
                    if content:
                        result = {
                            "type": "text",
                            "text": content,
                        }
                        if include_urls:
                            result["url"] = url
                        content_list.append(result)
                except Exception as e:
                    print(f"Request failed with exception: {e}")
            
        return content_list
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations were provided, so the description bears full responsibility. It discloses the full workflow: fetching web results, semantic scoring via embeddings, returning top-ranked markdown content. It also covers the return format and parameter defaults. There are no contradictions, and all significant behaviors (scoring, markdown output) are clearly stated.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with separate Args and Returns sections, plus an example. However, it is slightly verbose with some redundancy (e.g., 'Returns context to the LLM' and 'returns the top-ranked content as markdown text' are similar). Overall, it efficiently conveys necessary information, but minor trimming could improve conciseness.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (web search + RAG scoring), the description covers purpose, parameters, workflow, and return format. Missing details such as error handling, rate limits, or explicit guidance on when to prefer this over deep_research tools. Still, the information is sufficient for effective agent use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 0% description coverage, so the tool description provides all parameter meaning. The Args section explains each parameter: query (natural language), num_results (coverage vs speed trade-off), top_k (final top-ranked count), include_urls (citation inclusion). This fully compensates for the schema's lack of descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool searches the web using DuckDuckGo and applies RAG-like similarity scoring to return the most relevant results. The verb 'Search' combined with the specific resource (web via DuckDuckGo) and the unique scoring mechanism distinguishes it from siblings like rag_search_google or deep_research.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description directly states the tool's use case but does not explicitly contrast it with sibling tools like deep_research or rag_search_google. The user must infer from the name which tool to use. The lack of explicit when-to-use or when-not-to-use guidance prevents a perfect score.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/nkapila6/mcp-local-rag'

If you have feedback or need assistance with the MCP directory API, please join our Discord server