File size: 1,780 Bytes
e44e5dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from __future__ import annotations

from typing import Mapping

from duckduckgo_search import DDGS

from backend.mcp_server.common.tenant import TenantContext
from backend.mcp_server.common.utils import ToolExecutionError, ToolValidationError, tool_handler


@tool_handler("web.search")
async def web_search(context: TenantContext, payload: Mapping[str, object]) -> dict[str, object]:
    """
    Perform a DuckDuckGo web search with an English-results bias.
    """

    query = payload.get("query")
    if not isinstance(query, str) or not query.strip():
        raise ToolValidationError("query must be a non-empty string")

    max_results = payload.get("max_results", 5)
    try:
        max_results_value = max(1, min(int(max_results), 10))
    except (TypeError, ValueError):
        raise ToolValidationError("max_results must be an integer between 1 and 10")

    region = str(payload.get("region", "us-en"))

    try:
        ddg = DDGS()
        query_string = query
        if "lang:en" not in query_string.lower():
            query_string = f"{query_string} lang:en"

        try:
            results = ddg.text(query_string, max_results=max_results_value, region=region)
        except TypeError:
            results = ddg.text(query_string, max_results=max_results_value)

        formatted = [
            {
                "title": item.get("title"),
                "snippet": item.get("body"),
                "url": item.get("href"),
            }
            for item in results
        ]

        return {
            "query": query,
            "results": formatted,
            "metadata": {"max_results": max_results_value, "region": region},
        }
    except Exception as exc:
        raise ToolExecutionError(f"web search failed: {exc}") from exc