# ============================================================= # 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)