File size: 3,998 Bytes
4645f78
f519b48
4645f78
 
 
b390cea
 
4645f78
 
 
b390cea
f519b48
 
 
4645f78
 
b390cea
4645f78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b390cea
 
f519b48
 
4645f78
b390cea
4645f78
b390cea
4645f78
 
 
 
 
 
 
 
f519b48
b390cea
 
 
 
4645f78
 
f519b48
4645f78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b390cea
 
4645f78
 
 
 
b390cea
4645f78
 
 
 
 
b390cea
4645f78
b390cea
4645f78
 
 
 
 
f519b48
4645f78
 
03b157c
f519b48
 
4645f78
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# 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


@app.post("/scrape_url")
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]


@app.get("/")
def root():
    return {"message": "Firecrawl MCP Server is running."}  # [11]