Spaces:
Sleeping
Sleeping
Download src/streamlit_app.py from Rehan12345678/FirecrawlMCPserver: direct link, hf CLI and curl.
- Browser
- Download file 4 kB
-
https://huggingface.co/spaces/Rehan12345678/FirecrawlMCPserver/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/Rehan12345678/FirecrawlMCPserver/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/Rehan12345678/FirecrawlMCPserver/resolve/main/src/streamlit_app.py
4 kB
| # server.py | |
| import os | |
| from typing import Any, Dict, List, Optional, Union | |
| from typing import Literal | |
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel, Field | |
| # Firecrawl official Python SDK client | |
| # pip install firecrawl-py | |
| from firecrawl import Firecrawl | |
| app = FastAPI() | |
| # Optional: typed spec for a JSON format request item | |
| class JsonFormatSpec(BaseModel): | |
| # Pydantic v2: replace const=True with a Literal to enforce a fixed string | |
| type: Literal["json"] = "json" | |
| # Optional helpers for structured extraction | |
| prompt: Optional[str] = None | |
| # If passing a schema, use a plain mapping so it serializes over HTTP cleanly | |
| schema: Optional[Dict[str, Any]] = None | |
| # Optional: typed spec for a screenshot format request item | |
| class ScreenshotFormatSpec(BaseModel): | |
| type: Literal["screenshot"] = "screenshot" | |
| fullPage: Optional[bool] = None | |
| quality: Optional[int] = Field(default=None, ge=1, le=100) | |
| viewport: Optional[Dict[str, int]] = None # e.g., {"width": 1280, "height": 720} | |
| # Clients may send strings like "markdown" or structured dicts like {"type":"json",...} | |
| FormatsType = List[Union[str, JsonFormatSpec, ScreenshotFormatSpec, Dict[str, Any]]] | |
| class ScrapeRequest(BaseModel): | |
| url: str | |
| # Default to markdown output; callers can also add "html", "links", etc. | |
| formats: Optional[FormatsType] = Field(default_factory=lambda: ["markdown"]) | |
| # Match Firecrawl options: main content filter, include/exclude tags, wait/maxAge, etc. | |
| only_main_content: Optional[bool] = False | |
| include_tags: Optional[List[str]] = None | |
| exclude_tags: Optional[List[str]] = None | |
| # Milliseconds; Firecrawl docs show timeouts and other scrapeOptions knobs | |
| timeout_ms: Optional[int] = 120000 | |
| # Advanced options (optional) | |
| wait_for: Optional[int] = None # ms | |
| max_age: Optional[int] = None # ms | |
| def scrape_url(req: ScrapeRequest): | |
| api_key = os.getenv("FIRECRAWL_API_KEY") | |
| if not api_key: | |
| raise HTTPException(status_code=500, detail="FIRECRAWL_API_KEY not set") # [11] | |
| try: | |
| client = Firecrawl(api_key=api_key) # [11] | |
| # Build scrape options following Firecrawl docs | |
| scrape_options: Dict[str, Any] = {} | |
| if req.formats: | |
| # Convert Pydantic models to plain dicts | |
| def to_plain(x: Any) -> Any: | |
| if isinstance(x, BaseModel): | |
| return x.model_dump(exclude_none=True) | |
| return x | |
| scrape_options["formats"] = [to_plain(f) for f in req.formats] # [10] | |
| if req.only_main_content is not None: | |
| scrape_options["onlyMainContent"] = req.only_main_content # [10] | |
| if req.include_tags: | |
| scrape_options["includeTags"] = req.include_tags # [10] | |
| if req.exclude_tags: | |
| scrape_options["excludeTags"] = req.exclude_tags # [10] | |
| # Call the SDK scrape method; Firecrawl accepts extra options like timeout/wait/maxAge | |
| result = client.scrape( | |
| req.url, | |
| formats=scrape_options.get("formats"), | |
| only_main_content=scrape_options.get("onlyMainContent"), | |
| include_tags=scrape_options.get("includeTags"), | |
| exclude_tags=scrape_options.get("excludeTags"), | |
| timeout=req.timeout_ms, | |
| wait_for=req.wait_for, | |
| max_age=req.max_age, | |
| ) # [11][10] | |
| # Normalize common return shape | |
| if isinstance(result, dict): | |
| success = result.get("success", True) | |
| data = result.get("data", result) | |
| return {"success": success, "data": data} # [11][10] | |
| # Fallback for non-dict SDK objects | |
| return {"success": True, "data": getattr(result, "__dict__", str(result))} # [11] | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) # [11] | |
| def root(): | |
| return {"message": "Firecrawl MCP Server is running."} # [11] | |