Skip to main content
Glama
988664li-star

DuckDuckGo MCP Server

search

Search DuckDuckGo to find web information using queries and return formatted results for integration with language models.

Instructions

Search DuckDuckGo and return formatted results.

Args:
    query: The search query string
    max_results: Maximum number of results to return (default: 10)
    ctx: MCP context for logging

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
max_resultsNo

Implementation Reference

  • The main handler function for the 'search' tool, registered via the @mcp.tool() decorator. It coordinates the search execution and result formatting.
    @mcp.tool()
    async def search(query: str, ctx: Context, max_results: int = 10) -> str:
        """
        Search DuckDuckGo and return formatted results.
    
        Args:
            query: The search query string
            max_results: Maximum number of results to return (default: 10)
            ctx: MCP context for logging
        """
        try:
            results = await searcher.search(query, ctx, max_results)
            return searcher.format_results_for_llm(results)
        except Exception as e:
            traceback.print_exc(file=sys.stderr)
            return f"An error occurred while searching: {str(e)}"
  • Dataclass defining the schema/structure for individual search results returned by the internal search logic.
    @dataclass
    class SearchResult:
        title: str
        link: str
        snippet: str
        position: int
  • Core helper method in DuckDuckGoSearcher class that performs the actual web scraping of DuckDuckGo, including rate limiting, parsing, and result extraction.
    async def search(
        self, query: str, ctx: Context, max_results: int = 10
    ) -> List[SearchResult]:
        try:
            # Apply rate limiting
            await self.rate_limiter.acquire()
    
            # Create form data for POST request
            data = {
                "q": query,
                "b": "",
                "kl": "",
            }
    
            await ctx.info(f"Searching DuckDuckGo for: {query}")
    
            async with httpx.AsyncClient() as client:
                response = await client.post(
                    self.BASE_URL, data=data, headers=self.HEADERS, timeout=30.0
                )
                response.raise_for_status()
    
            # Parse HTML response
            soup = BeautifulSoup(response.text, "html.parser")
            if not soup:
                await ctx.error("Failed to parse HTML response")
                return []
    
            results = []
            for result in soup.select(".result"):
                title_elem = result.select_one(".result__title")
                if not title_elem:
                    continue
    
                link_elem = title_elem.find("a")
                if not link_elem:
                    continue
    
                title = link_elem.get_text(strip=True)
                link = link_elem.get("href", "")
    
                # Skip ad results
                if "y.js" in link:
                    continue
    
                # Clean up DuckDuckGo redirect URLs
                if link.startswith("//duckduckgo.com/l/?uddg="):
                    link = urllib.parse.unquote(link.split("uddg=")[1].split("&")[0])
    
                snippet_elem = result.select_one(".result__snippet")
                snippet = snippet_elem.get_text(strip=True) if snippet_elem else ""
    
                results.append(
                    SearchResult(
                        title=title,
                        link=link,
                        snippet=snippet,
                        position=len(results) + 1,
                    )
                )
    
                if len(results) >= max_results:
                    break
    
            await ctx.info(f"Successfully found {len(results)} results")
            return results
    
        except httpx.TimeoutException:
            await ctx.error("Search request timed out")
            return []
        except httpx.HTTPError as e:
            await ctx.error(f"HTTP error occurred: {str(e)}")
            return []
        except Exception as e:
            await ctx.error(f"Unexpected error during search: {str(e)}")
            traceback.print_exc(file=sys.stderr)
            return []
  • Helper method that formats the list of SearchResult objects into a human-readable string optimized for LLM consumption.
    def format_results_for_llm(self, results: List[SearchResult]) -> str:
        """Format results in a natural language style that's easier for LLMs to process"""
        if not results:
            return "No results were found for your search query. This could be due to DuckDuckGo's bot detection or the query returned no matches. Please try rephrasing your search or try again in a few minutes."
    
        output = []
        output.append(f"Found {len(results)} search results:\n")
    
        for result in results:
            output.append(f"{result.position}. {result.title}")
            output.append(f"   URL: {result.link}")
            output.append(f"   Summary: {result.snippet}")
            output.append("")  # Empty line between results
    
        return "\n".join(output)
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. While it mentions 'return formatted results,' it doesn't describe what format those results take, whether there are rate limits, authentication requirements, or any side effects. The mention of 'ctx: MCP context for logging' in the description (but not in the schema) suggests logging behavior, but this isn't fully explained.

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 appropriately concise with a clear purpose statement followed by parameter documentation. The structure is logical with the main functionality first. The only minor issue is the inclusion of 'ctx' parameter in the description that doesn't match the schema, which creates some confusion.

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

Completeness3/5

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

For a search tool with 2 parameters, no annotations, and no output schema, the description provides basic functionality but lacks important context. It doesn't explain result format, error conditions, or how it differs from the sibling 'fetch_content' tool. The parameter documentation helps, but behavioral aspects remain underspecified.

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

Parameters4/5

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

The description adds significant value beyond the input schema, which has 0% description coverage. It explains that 'query' is 'The search query string' and 'max_results' is 'Maximum number of results to return (default: 10)'. It also mentions 'ctx: MCP context for logging' which doesn't appear in the schema at all, though this parameter documentation is incomplete.

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

Purpose4/5

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

The description clearly states the tool's purpose: 'Search DuckDuckGo and return formatted results.' It specifies the verb ('Search'), resource ('DuckDuckGo'), and outcome ('return formatted results'). However, it doesn't explicitly differentiate from its sibling tool 'fetch_content' which might have overlapping functionality.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. There's no mention of when this search tool is appropriate versus 'fetch_content' or other potential search methods. The only contextual information is in the parameter documentation, not usage guidance.

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/988664li-star/duckduckgo-mcp-server'

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