Update app.py
Browse files123456789101112131415161718192021222324252627282 unmodified lines313233343536378 unmodified lines464748495051525354556 unmodified lines626364656667683 unmodified lines727374757677787924 unmodified lines10410510610710810911019 unmodified lines1301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631646 unmodified lines1711721731741751761771781791801811821831841851861871881891901911921931941956 unmodified lines2022032042052062072082092102112122132142152162172182192202212222232242252262272285 unmodified lines2342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642651 unmodified line2672682692702712722731 unmodified line2752762772782792802812822832842852862872882892902 unmodified lines29329429529629729829930030116 unmodified lines3183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483495 unmodified lines35535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441534 unmodified lines4504514524534544554564574584594604618 unmodified lines470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500"""High-Performance Stealth Web Scraper & Browser Automation MCP ServerAll-in-one file designed for Hugging Face Spaces (Port 7860)."""import asyncioimport base64import jsonimport loggingimport osimport sysfrom contextlib import asynccontextmanagerfrom typing import Any, AsyncGeneratorfrom bs4 import BeautifulSoupfrom duckduckgo_search import DDGSimport httpxfrom lxml_html_clean import Cleanerimport markdownifyfrom mcp.server.fastmcp import FastMCPfrom patchright.async_api import Browser, BrowserContext, Page, async_playwrightfrom starlette.applications import Starlettefrom starlette.responses import JSONResponsefrom starlette.routing import Mount, Routeimport trafilaturaimport uvicorn# ==========================================2 unmodified lineslogging.basicConfig(level=logging.INFO,format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",handlers=[logging.StreamHandler(sys.stdout)],)logger = logging.getLogger("mcp_server")8 unmodified lines# ==========================================# 2. Browser Pool# ==========================================class StealthBrowserPool:def __init__(self):self._playwright = Noneself._browser: Browser | None = None6 unmodified linesif not self._playwright:self._playwright = await async_playwright().start()if not self._browser or not self._browser.is_connected():logger.info("Starting Chromium Stealth instance...")self._browser = await self._playwright.chromium.launch(headless=True,args=[3 unmodified lines"--disable-gpu","--disable-blink-features=AutomationControlled","--no-first-run","--window-size=1920,1080",],)self._request_counter = 0return self._browser24 unmodified lines"Chrome/131.0.0.0 Safari/537.36"),locale="en-US",timezone_id="America/New_York",)await context.add_init_script("""Object.defineProperty(navigator, 'webdriver', { get: () => undefined });19 unmodified linesself._semaphore.release()await self._check_recycle()browser_pool = StealthBrowserPool()# ==========================================# 3. Content Extraction Pipeline# ==========================================def clean_html(raw_html: str) -> str:cleaner = Cleaner(scripts=True,javascript=True,comments=True,style=True,links=False,meta=False,page_structure=False,safe_attrs_only=False,)return cleaner.clean_html(raw_html)def extract_content(html: str, url: str = "") -> dict[str, Any]:extracted = trafilatura.extract(html,url=url,include_links=True,include_images=True,output_format="markdown",)metadata = trafilatura.extract_metadata(html) or {}meta_dict = {6 unmodified linesif not extracted or len(extracted.strip()) < 100:cleaned = clean_html(html)soup = BeautifulSoup(cleaned, "html.parser")for tag in soup(["nav", "footer", "aside", "header", "script", "style", "noscript"]):tag.decompose()if not meta_dict["title"] and soup.title:meta_dict["title"] = soup.title.string or ""extracted = markdownify.markdownify(str(soup), heading_style="ATX", strip=["svg"])if len(extracted) > MAX_CONTENT_CHARS:extracted = (extracted[:MAX_CONTENT_CHARS]+ f"\n\n... [Truncated: reached {MAX_CONTENT_CHARS} limit]")return {"content": extracted.strip(), "metadata": meta_dict}def extract_json_ld(html: str) -> list[dict]:soup = BeautifulSoup(html, "html.parser")schemas = []6 unmodified linescontinuereturn schemas# ==========================================# 4. Hybrid Scraping Core# ==========================================FAST_HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language": "en-US,en;q=0.9",}async def dismiss_popups(page: Page):selectors = ['button[id*="cookie" i]','button[class*="cookie" i]','button[aria-label*="accept" i]','button:has-text("Accept all")','button:has-text("Accept")','button:has-text("I agree")','button:has-text("Got it")',]for sel in selectors:try:5 unmodified linesexcept Exception:continueasync def scrape_pipeline(url: str,force_browser: bool = False,auto_scroll: bool = True,wait_for_selector: str | None = None,) -> dict:if not force_browser:try:async with httpx.AsyncClient(http2=True,timeout=HTTP_TIMEOUT_SEC,follow_redirects=True,headers=FAST_HEADERS,) as client:resp = await client.get(url)if resp.status_code == 200:html = resp.textif not any(s in html.lower()for s in ["cf-challenge","ray-id","just a moment...",]):parsed = extract_content(html, url=url)if len(parsed["content"]) >= 150:return {1 unmodified line"status": 200,"engine": "fast-http","content": parsed["content"],"metadata": parsed["metadata"],}except Exception:pass1 unmodified lineasync with browser_pool.get_page() as page:await page.goto(url, wait_until="domcontentloaded")try:cf_frame = await page.query_selector("iframe[src*='challenges.cloudflare.com']")if cf_frame:box = await cf_frame.bounding_box()if box:await page.mouse.click(box["x"] + box["width"] / 2,box["y"] + box["height"] / 2,)await asyncio.sleep(2.0)except Exception:pass2 unmodified linesif wait_for_selector:try:await page.wait_for_selector(wait_for_selector, state="visible", timeout=8000)except Exception:pass16 unmodified lines"status": 200,"engine": "patchright-stealth","content": parsed["content"],"metadata": parsed["metadata"],}# ==========================================# 5. MCP Server & Tool Definitions# ==========================================mcp = FastMCP("WebScraper")@mcp.tool()async def scrape_url(url: str,force_browser: bool = False,auto_scroll: bool = True,wait_for_selector: str | None = None,) -> dict:"""Scrapes cleaned Markdown content and metadata from any URL."""return await scrape_pipeline(url, force_browser, auto_scroll, wait_for_selector)@mcp.tool()async def search_and_scrape(query: str, max_results: int = 3) -> dict:"""Searches DuckDuckGo and concurrently extracts content from top results."""max_results = min(max(1, max_results), 5)loop = asyncio.get_running_loop()5 unmodified linesif not results:return {"query": query, "results": []}tasks = [scrape_pipeline(res["href"], force_browser=False, auto_scroll=False)for res in results]scraped_payloads = await asyncio.gather(*tasks, return_exceptions=True)enriched = []for meta, payload in zip(results, scraped_payloads):if isinstance(payload, dict):enriched.append({"title": meta.get("title", ""),"url": meta.get("href", ""),"snippet": meta.get("body", ""),"content": payload.get("content", ""),})else:enriched.append({"title": meta.get("title", ""),"url": meta.get("href", ""),"snippet": meta.get("body", ""),"content": f"[Error: {str(payload)}]",})return {"query": query, "results": enriched}@mcp.tool()async def take_screenshot(url: str, full_page: bool = True, wait_seconds: float = 1.0) -> dict:"""Takes a full-page or viewport screenshot of a webpage."""async with browser_pool.get_page() as page:await page.goto(url, wait_until="networkidle")if wait_seconds > 0:await asyncio.sleep(min(wait_seconds, 10.0))screenshot_bytes = await page.screenshot(full_page=full_page, type="png")b64 = base64.b64encode(screenshot_bytes).decode("utf-8")return {"url": page.url,"title": await page.title(),"format": "image/png;base64","base64_image": b64,}@mcp.tool()async def interact_page(url: str, actions: list[dict[str, Any]], extract_markdown: bool = True) -> dict:"""Executes a list of browser actions (click, type, press, wait, evaluate)."""async with browser_pool.get_page() as page:await page.goto(url, wait_until="domcontentloaded")logs = []34 unmodified linesres["metadata"] = parsed["metadata"]return res@mcp.tool()async def extract_structured_data(url: str, css_selectors: dict[str, str] | None = None) -> dict:"""Parses structured JSON-LD schemas and arbitrary CSS selector targets."""async with browser_pool.get_page() as page:await page.goto(url, wait_until="domcontentloaded")html = await page.content()8 unmodified linesreturn {"url": url,"custom_fields": custom_data,"json_ld_schemas": extract_json_ld(html),}# ==========================================# 6. Starlette SSE Router & Server Runner# ==========================================async def health_check(request):return JSONResponse({"status": "healthy","mcp_sse_endpoint": "/sse","transport": "Server-Sent Events (SSE)",})# Mount the MCP SSE application with health endpointsstarlette_app = Starlette(routes=[Route("/", endpoint=health_check),Route("/healthz", endpoint=health_check),Mount("/", app=mcp.sse_app()),])12345678910111213141516171819202122232425262728293031323334353637382 unmodified lines414243444546478 unmodified lines565758596061626 unmodified lines697071727374753 unmodified lines798081828384858624 unmodified lines11111211311411511611719 unmodified lines1371381391401411421431441451461471481491501511521531541551561571581591601616 unmodified lines1681691701711721731741751761771781791801811821831846 unmodified lines1911921931941951961971981992002012022032042052062072082095 unmodified lines2152162172182192202212222232242252262272281 unmodified line2302312322332342352361 unmodified line2382392402412422432442452462472482 unmodified lines25125225325425525625716 unmodified lines2742752762772782792802812822832842852862872882892902912922932942952962972982993003013023035 unmodified lines30931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735834 unmodified lines3933943953963973983994004014024038 unmodified lines412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447"""High-Performance Stealth Web Scraper & Browser Automation MCP ServerConfigured for Hugging Face Spaces with Cloud Host-Header validation bypass."""import osimport sysimport jsonimport asyncioimport loggingimport base64from typing import Any, AsyncGeneratorfrom contextlib import asynccontextmanagerfrom bs4 import BeautifulSoupimport httpximport trafilaturafrom lxml_html_clean import Cleanerimport markdownifyfrom duckduckgo_search import DDGSfrom patchright.async_api import async_playwright, Browser, BrowserContext, Pagefrom mcp.server.fastmcp import FastMCPtry:from mcp.server.transport_security import TransportSecuritySettingssecurity_settings = TransportSecuritySettings(enable_dns_rebinding_protection=False,allowed_hosts=["*"])except ImportError:security_settings = Nonefrom starlette.applications import Starlettefrom starlette.routing import Route, Mountfrom starlette.responses import JSONResponseimport uvicorn# ==========================================2 unmodified lineslogging.basicConfig(level=logging.INFO,format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",handlers=[logging.StreamHandler(sys.stdout)])logger = logging.getLogger("mcp_server")8 unmodified lines# ==========================================# 2. Browser Pool# ==========================================class StealthBrowserPool:def __init__(self):self._playwright = Noneself._browser: Browser | None = None6 unmodified linesif not self._playwright:self._playwright = await async_playwright().start()if not self._browser or not self._browser.is_connected():logger.info("Initializing Chromium Stealth instance...")self._browser = await self._playwright.chromium.launch(headless=True,args=[3 unmodified lines"--disable-gpu","--disable-blink-features=AutomationControlled","--no-first-run","--window-size=1920,1080"])self._request_counter = 0return self._browser24 unmodified lines"Chrome/131.0.0.0 Safari/537.36"),locale="en-US",timezone_id="America/New_York")await context.add_init_script("""Object.defineProperty(navigator, 'webdriver', { get: () => undefined });19 unmodified linesself._semaphore.release()await self._check_recycle()browser_pool = StealthBrowserPool()# ==========================================# 3. Content Extraction Pipeline# ==========================================def clean_html(raw_html: str) -> str:cleaner = Cleaner(scripts=True, javascript=True, comments=True, style=True,links=False, meta=False, page_structure=False, safe_attrs_only=False)return cleaner.clean_html(raw_html)def extract_content(html: str, url: str = "") -> dict[str, Any]:extracted = trafilatura.extract(html,url=url,include_links=True,include_images=True,output_format="markdown")metadata = trafilatura.extract_metadata(html) or {}meta_dict = {6 unmodified linesif not extracted or len(extracted.strip()) < 100:cleaned = clean_html(html)soup = BeautifulSoup(cleaned, "html.parser")for tag in soup(["nav", "footer", "aside", "header", "script", "style", "noscript"]):tag.decompose()if not meta_dict["title"] and soup.title:meta_dict["title"] = soup.title.string or ""extracted = markdownify.markdownify(str(soup), heading_style="ATX", strip=["svg"])if len(extracted) > MAX_CONTENT_CHARS:extracted = extracted[:MAX_CONTENT_CHARS] + f"\n\n... [Truncated: reached {MAX_CONTENT_CHARS} limit]"return {"content": extracted.strip(), "metadata": meta_dict}def extract_json_ld(html: str) -> list[dict]:soup = BeautifulSoup(html, "html.parser")schemas = []6 unmodified linescontinuereturn schemas# ==========================================# 4. Hybrid Scraping Core# ==========================================FAST_HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language": "en-US,en;q=0.9",}async def dismiss_popups(page: Page):selectors = ['button[id*="cookie" i]', 'button[class*="cookie" i]', 'button[aria-label*="accept" i]','button:has-text("Accept all")', 'button:has-text("Accept")', 'button:has-text("I agree")', 'button:has-text("Got it")']for sel in selectors:try:5 unmodified linesexcept Exception:continueasync def scrape_pipeline(url: str, force_browser: bool = False, auto_scroll: bool = True, wait_for_selector: str | None = None) -> dict:if not force_browser:try:async with httpx.AsyncClient(http2=True, timeout=HTTP_TIMEOUT_SEC, follow_redirects=True, headers=FAST_HEADERS) as client:resp = await client.get(url)if resp.status_code == 200:html = resp.textif not any(s in html.lower() for s in ["cf-challenge", "ray-id", "just a moment..."]):parsed = extract_content(html, url=url)if len(parsed["content"]) >= 150:return {1 unmodified line"status": 200,"engine": "fast-http","content": parsed["content"],"metadata": parsed["metadata"]}except Exception:pass1 unmodified lineasync with browser_pool.get_page() as page:await page.goto(url, wait_until="domcontentloaded")try:cf_frame = await page.query_selector("iframe[src*='challenges.cloudflare.com']")if cf_frame:box = await cf_frame.bounding_box()if box:await page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)await asyncio.sleep(2.0)except Exception:pass2 unmodified linesif wait_for_selector:try:await page.wait_for_selector(wait_for_selector, state="visible", timeout=8000)except Exception:pass16 unmodified lines"status": 200,"engine": "patchright-stealth","content": parsed["content"],"metadata": parsed["metadata"]}# ==========================================# 5. MCP Server & Tool Definitions# ==========================================# Initialize FastMCP with transport_security disabled for public cloud proxyingif security_settings:mcp = FastMCP("WebScraper", host=HOST, transport_security=security_settings)else:mcp = FastMCP("WebScraper", host=HOST)@mcp.tool(name="scrape_url",description="Scrapes cleaned Markdown content and metadata from any URL.")async def scrape_url(url: str, force_browser: bool = False, auto_scroll: bool = True, wait_for_selector: str | None = None) -> dict:return await scrape_pipeline(url, force_browser, auto_scroll, wait_for_selector)@mcp.tool(name="search_and_scrape",description="Searches DuckDuckGo and concurrently extracts content from top results.")async def search_and_scrape(query: str, max_results: int = 3) -> dict:max_results = min(max(1, max_results), 5)loop = asyncio.get_running_loop()5 unmodified linesif not results:return {"query": query, "results": []}tasks = [scrape_pipeline(res["href"], force_browser=False, auto_scroll=False) for res in results]scraped_payloads = await asyncio.gather(*tasks, return_exceptions=True)enriched = []for meta, payload in zip(results, scraped_payloads):if isinstance(payload, dict):enriched.append({"title": meta.get("title", ""),"url": meta.get("href", ""),"snippet": meta.get("body", ""),"content": payload.get("content", "")})else:enriched.append({"title": meta.get("title", ""),"url": meta.get("href", ""),"snippet": meta.get("body", ""),"content": f"[Error: {str(payload)}]"})return {"query": query, "results": enriched}@mcp.tool(name="take_screenshot",description="Takes a full-page or viewport screenshot of a webpage as Base64 PNG.")async def take_screenshot(url: str, full_page: bool = True, wait_seconds: float = 1.0) -> dict:async with browser_pool.get_page() as page:await page.goto(url, wait_until="networkidle")if wait_seconds > 0:await asyncio.sleep(min(wait_seconds, 10.0))screenshot_bytes = await page.screenshot(full_page=full_page, type="png")b64 = base64.b64encode(screenshot_bytes).decode("utf-8")return {"url": page.url,"title": await page.title(),"format": "image/png;base64","base64_image": b64}@mcp.tool(name="interact_page",description="Executes a list of browser actions (click, type, press, wait, evaluate).")async def interact_page(url: str, actions: list[dict[str, Any]], extract_markdown: bool = True) -> dict:async with browser_pool.get_page() as page:await page.goto(url, wait_until="domcontentloaded")logs = []34 unmodified linesres["metadata"] = parsed["metadata"]return res@mcp.tool(name="extract_structured_data",description="Parses structured JSON-LD schemas and arbitrary CSS selector targets.")async def extract_structured_data(url: str, css_selectors: dict[str, str] | None = None) -> dict:async with browser_pool.get_page() as page:await page.goto(url, wait_until="domcontentloaded")html = await page.content()8 unmodified linesreturn {"url": url,"custom_fields": custom_data,"json_ld_schemas": extract_json_ld(html)}# ==========================================# 6. Starlette SSE Router & Tool Inspection# ==========================================async def health_check(request):return JSONResponse({"status": "healthy","mcp_sse_endpoint": "/sse","tools_endpoint": "/tools"})async def list_tools_endpoint(request):"""Direct HTTP endpoint exposing all registered MCP tools and schemas."""tools_list = []for tool_name, tool_obj in mcp._tool_manager._tools.items():tools_list.append({"name": tool_name,"description": getattr(tool_obj, "description", "") or "","parameters": getattr(tool_obj, "parameters", {}) or {}})return JSONResponse({"tools": tools_list})starlette_app = Starlette(routes=[Route("/", endpoint=health_check),Route("/healthz", endpoint=health_check),Route("/tools", endpoint=list_tools_endpoint),Mount("/", app=mcp.sse_app())])
app.py+109-162