Skip to main content
Glama
OEvortex

DuckDuckGo Search MCP

by OEvortex

Web Search

web-search

Search the web using DuckDuckGo to find relevant information, web pages, and summaries for any query. Get results with titles, URLs, and detailed content to access real-time web data.

Instructions

Perform a web search using DuckDuckGo and receive detailed results including titles, URLs, and summaries.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesEnter your search query to find the most relevant web pages.
numResultsNoSpecify how many results to display (default: 3, maximum: 20).
modeNoChoose 'short' for basic results (no Description) or 'detailed' for full results (includes Description).short

Implementation Reference

  • The handler function that processes input parameters, calls the underlying searchDuckDuckGo function, formats the search results into a markdown-like text structure, and returns the response in MCP format.
    export async function searchToolHandler(params) {
      const { query, numResults = 3, mode = 'short' } = params;
      console.log(`Searching for: ${query} (${numResults} results, mode: ${mode})`);
    
      const results = await searchDuckDuckGo(query, numResults, mode);
      console.log(`Found ${results.length} results`);
    
      // Format results as readable text, similar to other search tools
      const formattedResults = results.map((result, index) => {
        let formatted = `${index + 1}. **${result.title}**\n`;
        formatted += `URL: ${result.url}\n`;
        
        if (result.displayUrl) {
          formatted += `Display URL: ${result.displayUrl}\n`;
        }
        
        if (result.snippet) {
          formatted += `Snippet: ${result.snippet}\n`;
        }
        
        if (mode === 'detailed' && result.description) {
          formatted += `Content: ${result.description}\n`;
        }
        
        if (result.favicon) {
          formatted += `Favicon: ${result.favicon}\n`;
        }
        
        return formatted;
      }).join('\n');
    
      return {
        content: [
          {
            type: 'text',
            text: formattedResults || 'No results found.'
          }
        ]
      };
    }
  • Tool metadata and input schema definition, specifying parameters for query, number of results, and result detail mode.
    export const searchToolDefinition = {
      name: 'web-search',
      title: 'Web Search',
      description: 'Perform a web search using DuckDuckGo and receive detailed results including titles, URLs, and summaries.',
      inputSchema: {
        type: 'object',
        properties: {
          query: {
            type: 'string',
            description: 'Enter your search query to find the most relevant web pages.'
          },
          numResults: {
            type: 'integer',
            description: 'Specify how many results to display (default: 3, maximum: 20).',
            default: 3,
            minimum: 1,
            maximum: 20
          },
          mode: {
            type: 'string',
            description: "Choose 'short' for basic results (no Description) or 'detailed' for full results (includes Description).",
            enum: ['short', 'detailed'],
            default: 'short'
          }
        },
        required: ['query']
      }
    };
  • src/index.ts:14-18 (registration)
    Adds the web-search tool definition to the list of available tools served via ListToolsRequestHandler.
    const availableTools = [
      searchToolDefinition,
      iaskToolDefinition,
      monicaToolDefinition
    ];
  • src/index.ts:49-52 (registration)
    Registers the searchToolHandler for execution when 'web-search' tool is called via CallToolRequestHandler.
    switch (name) {
      case 'web-search':
        return await searchToolHandler(args);
  • Underlying utility function that performs the actual DuckDuckGo web search: fetches HTML, parses results, extracts clean URLs, generates favicons, optionally scrapes content via Jina.ai, with caching and robust error handling.
    async function searchDuckDuckGo(query, numResults = 10, mode = 'short') {
      try {
        // Input validation
        if (!query || typeof query !== 'string') {
          throw new Error('Invalid query: query must be a non-empty string');
        }
        
        if (!Number.isInteger(numResults) || numResults < 1 || numResults > 20) {
          throw new Error('Invalid numResults: must be an integer between 1 and 20');
        }
        
        if (!['short', 'detailed'].includes(mode)) {
          throw new Error('Invalid mode: must be "short" or "detailed"');
        }
    
        // Clear old cache entries
        clearOldCache();
    
        // Check cache first
        const cacheKey = getCacheKey(query);
        const cachedResults = resultsCache.get(cacheKey);
    
        if (cachedResults && Date.now() - cachedResults.timestamp < CACHE_DURATION) {
          console.log(`Cache hit for query: "${query}"`);
          return cachedResults.results.slice(0, numResults);
        }
    
        // Get a random user agent
        const userAgent = getRandomUserAgent();
    
        console.log(`Searching DuckDuckGo for: "${query}" (${numResults} results, mode: ${mode})`);
    
        // Fetch results with timeout
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT);
    
        try {
          const response = await axios.get(
            `https://duckduckgo.com/html/?q=${encodeURIComponent(query)}`,
            {
              signal: controller.signal,
              headers: {
                'User-Agent': userAgent
              },
              httpsAgent: httpsAgent,
              timeout: REQUEST_TIMEOUT
            }
          );
    
          clearTimeout(timeoutId);
    
          if (response.status !== 200) {
            throw new Error(`HTTP ${response.status}: Failed to fetch search results`);
          }
    
          const html = response.data;
    
          // Parse results using cheerio
          const $ = cheerio.load(html);
    
          const results = [];
          const jinaFetchPromises = [];
    
          $('.result').each((i, result) => {
            const $result = $(result);
            const titleEl = $result.find('.result__title a');
            const linkEl = $result.find('.result__url');
            const snippetEl = $result.find('.result__snippet');
    
            const title = titleEl.text()?.trim();
            const rawLink = titleEl.attr('href');
            const description = snippetEl.text()?.trim();
            const displayUrl = linkEl.text()?.trim();
    
            const directLink = extractDirectUrl(rawLink || '');
            const favicon = getFaviconUrl(directLink);
            const jinaUrl = getJinaAiUrl(directLink);
    
            if (title && directLink) {
              if (mode === 'detailed') {
                jinaFetchPromises.push(
                  axios.get(jinaUrl, {
                    headers: {
                      'User-Agent': getRandomUserAgent()
                    },
                    httpsAgent: httpsAgent,
                    timeout: 8000
                  })
                    .then(jinaRes => {
                      let jinaContent = '';
                      if (jinaRes.status === 200 && typeof jinaRes.data === 'string') {
                        const $jina = cheerio.load(jinaRes.data);
                        jinaContent = $jina('body').text();
                      }
                      return {
                        title,
                        url: directLink,
                        snippet: description || '',
                        favicon: favicon,
                        displayUrl: displayUrl || '',
                        description: jinaContent
                      };
                    })
                    .catch(() => {
                      // Return fallback without content
                      return {
                        title,
                        url: directLink,
                        snippet: description || '',
                        favicon: favicon,
                        displayUrl: displayUrl || '',
                        description: ''
                      };
                    })
                );
              } else {
                // short mode: omit description
                jinaFetchPromises.push(
                  Promise.resolve({
                    title,
                    url: directLink,
                    snippet: description || '',
                    favicon: favicon,
                    displayUrl: displayUrl || ''
                  })
                );
              }
            }
          });
    
          // Wait for all Jina AI fetches to complete with timeout
          const jinaResults = await Promise.race([
            Promise.all(jinaFetchPromises),
            new Promise((_, reject) => 
              setTimeout(() => reject(new Error('Content fetch timeout')), 15000)
            )
          ]);
    
          results.push(...jinaResults);
    
          // Get limited results
          const limitedResults = results.slice(0, numResults);
    
          // Cache the results
          resultsCache.set(cacheKey, {
            results: limitedResults,
            timestamp: Date.now()
          });
    
          // If cache is too big, remove oldest entries
          if (resultsCache.size > MAX_CACHE_PAGES) {
            const oldestKey = Array.from(resultsCache.keys())[0];
            resultsCache.delete(oldestKey);
          }
    
          console.log(`Found ${limitedResults.length} results for query: "${query}"`);
          return limitedResults;
        } catch (fetchError) {
          clearTimeout(timeoutId);
          
          if (fetchError.name === 'AbortError') {
            throw new Error('Search request timeout: took longer than 10 seconds');
          }
          
          if (fetchError.code === 'ENOTFOUND') {
            throw new Error('Network error: unable to resolve host');
          }
          
          if (fetchError.code === 'ECONNREFUSED') {
            throw new Error('Network error: connection refused');
          }
          
          throw fetchError;
        }
      } catch (error) {
        console.error('Error searching DuckDuckGo:', error.message);
        
        // Enhanced error reporting
        if (error.message.includes('Invalid')) {
          throw error; // Re-throw validation errors as-is
        }
        
        throw new Error(`Search failed for "${query}": ${error.message}`);
      }
    }
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. It mentions the search engine (DuckDuckGo) and result details, but lacks critical behavioral traits such as rate limits, authentication needs, privacy implications, or error handling. This is a significant gap for a tool with no annotation coverage.

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

Conciseness5/5

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

The description is a single, efficient sentence that front-loads the core purpose and key details without any wasted words. It's appropriately sized and structured for quick comprehension.

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?

Given the tool's moderate complexity (3 parameters, no output schema, no annotations), the description is minimally adequate. It covers the basic purpose and output format but lacks completeness in behavioral context and usage guidelines, leaving gaps for the agent to infer.

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

Parameters3/5

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

The schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema, such as examples or edge cases, meeting the baseline for high schema coverage.

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 action ('Perform a web search') and the resource ('using DuckDuckGo'), with specific output details ('titles, URLs, and summaries'). However, it doesn't explicitly differentiate from sibling tools like 'iask-search' or 'monica-search' beyond mentioning DuckDuckGo, which is good but not fully distinguishing.

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 the sibling tools 'iask-search' or 'monica-search'. It mentions DuckDuckGo but doesn't explain if this is preferred for certain types of queries or contexts, leaving the agent without clear usage alternatives.

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/OEvortex/ddg_search'

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