"""MCP server: the primary interface. Tools call the same pipeline as REST. Mounted into the FastAPI app at /mcp (streamable HTTP, stateless). """ import json from mcp.server.fastmcp import FastMCP from mcp.server.transport_security import TransportSecuritySettings from . import config, pipeline # Populated by main.py's lifespan with the shared httpx client + cache. runtime: dict = {"client": None, "cache": None} def _transport_security() -> TransportSecuritySettings: """DNS-rebinding protection tuned for reverse-proxy deployment. Default allowed_hosts is empty, which rejects every non-localhost Host with 421 'Invalid Host header' — so a proxied public domain must be allowlisted (MCP_ALLOWED_HOSTS) or protection disabled with '*'. """ hosts = config.MCP_ALLOWED_HOSTS if hosts == ["*"]: return TransportSecuritySettings(enable_dns_rebinding_protection=False) if not hosts: return TransportSecuritySettings() # localhost-only default allowed_hosts = list(hosts) + ["localhost", "127.0.0.1"] allowed_origins = [f"https://{h}" for h in hosts] + [f"http://{h}" for h in hosts] return TransportSecuritySettings(allowed_hosts=allowed_hosts, allowed_origins=allowed_origins) mcp = FastMCP( "local-web-search", instructions=( "Private, self-hosted web search and page fetching. web_search returns " "ranked open-web results (optionally with full page content); fetch_url " "returns the cleaned text of a single page. Content is mechanically " "extracted (boilerplate stripped); rank/filter relevance yourself." ), streamable_http_path="/", stateless_http=True, transport_security=_transport_security(), ) def _compact(trace: dict) -> dict: return {"total_ms": round(sum(s["ms"] for s in trace["stages"]), 1), "degraded": trace["degraded"]} @mcp.tool() async def web_search(query: str, max_results: int = 5, include_content: bool = True) -> str: """Search the web. Returns ranked results as JSON: url, title, snippet, and (when include_content is true) the cleaned full text of each page.""" client, cache = runtime["client"], runtime["cache"] if include_content: data = await pipeline.search_contents(client, query, max_results, cache) results, trace = data["results"], data["trace"] else: trace_obj = pipeline.Trace() results = await pipeline.search(client, query, max_results, trace_obj) trace = trace_obj.as_dict() return json.dumps({"results": results, "meta": _compact(trace)}) @mcp.tool() async def fetch_url(url: str) -> str: """Fetch one URL (with JS rendering) and return its cleaned text content, title, and metadata as JSON.""" client, cache = runtime["client"], runtime["cache"] result = await pipeline.scrape_url(client, url, cache) trace = result.pop("trace") return json.dumps({**result, "meta": _compact(trace)})