File size: 2,192 Bytes
2f235a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# =============================================================
# File: backend/mcp_servers/web_server.py
# =============================================================

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from duckduckgo_search import DDGS
import sys
import os

# Fix Python module paths
current_dir = os.path.dirname(__file__)
sys.path.insert(0, current_dir)

from models.web import WebSearchRequest

web_app = FastAPI(title="Web Search MCP Server")

# Enable CORS
web_app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@web_app.post("/search")
async def web_search(req: WebSearchRequest):
    """
    Web search endpoint using DuckDuckGo.
    Accepts tenant_id for multi-tenant support (currently not used but kept for API consistency).
    Forces English language results by using region parameter and query modification.
    """
    try:
        ddg = DDGS()
        
        # Modify query to prefer English results
        # Add language hint to help get English content
        query = req.query
        # Only add language hint if not already present
        if "lang:en" not in query.lower() and "site:en" not in query.lower():
            query = f"{query} lang:en"
        
        # Try to use region parameter for English results
        # Common region codes: 'us-en' for US English, 'uk-en' for UK English
        try:
            results = ddg.text(query, max_results=5, region='us-en')
        except (TypeError, KeyError):
            # If region parameter not supported, try without it
            # The lang:en in query should still help
            results = ddg.text(query, max_results=5)
        
        formatted = []
        for r in results:
            formatted.append({
                "title": r.get("title"),
                "snippet": r.get("body"),
                "url": r.get("href"),
            })

        return {"results": formatted}

    except Exception as e:
        return {"error": str(e), "results": []}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(web_app, host="0.0.0.0", port=8002)