-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathserver.py
More file actions
2153 lines (1841 loc) Β· 74.6 KB
/
server.py
File metadata and controls
2153 lines (1841 loc) Β· 74.6 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
MCP server for ScapeGraph API integration (API v2).
Aligned with scrapegraph-py v2 ([ScrapeGraphAI/scrapegraph-py#84](https://github.com/ScrapeGraphAI/scrapegraph-py/pull/84)):
- markdownify: Page content via POST /scrape (markdown by default)
- smartscraper: Structured extraction via POST /extract (url + prompt; schema optional)
- searchscraper: Web search via POST /search (supports numResults, schema, prompt,
locationGeoCode, timeRange, format/mode)
- smartcrawler_initiate / smartcrawler_fetch_results: Async crawl via /crawl
(formats: markdown, html, links, images, summary, branding, screenshot)
- crawl_stop / crawl_resume: Control running crawl jobs
- scrape: Format-specific fetch (markdown, html, screenshot, branding, links,
images, summary) β emitted as v2 `formats[]` entries
- generate_schema: JSON schema generation via POST /schema
- credits / sgai_history: Account usage and request history (page/limit/service)
- monitor_*: Scheduled extraction jobs. `prompt`+`output_schema` are wrapped into
a v2 `{type: "json", ...}` format entry; `webhook_url` is supported.
All v2 request payloads use camelCase keys (fetchConfig, numResults,
locationGeoCode, maxDepth, maxPages, maxLinksPerPage, allowExternal,
includePatterns, excludePatterns, contentTypes, webhookUrl, contentType).
Removed on v2 (no API equivalent): sitemap, agentic_scrapper, markdownify_status, smartscraper_status.
Environment variables (match scrapegraph-py v2):
- SGAI_API_URL (default https://v2-api.scrapegraphai.com/api) β base URL override
- SGAI_TIMEOUT (default 120) β request timeout in seconds
- SCRAPEGRAPH_API_BASE_URL β legacy alias for SGAI_API_URL (still honored)
- SGAI_TIMEOUT_S β legacy alias for SGAI_TIMEOUT (still honored)
## Parameter Validation and Error Handling
All tools include comprehensive parameter validation with detailed error messages:
### Common Validation Rules:
- URLs must include protocol (http:// or https://)
- Numeric parameters must be within specified ranges
- Mutually exclusive parameters cannot be used together
- Required parameters must be provided
- JSON schemas must be valid JSON format
### Error Response Format:
All tools return errors in a consistent format:
```json
{
"error": "Detailed error message explaining the issue",
"error_type": "ValidationError|HTTPError|TimeoutError|etc.",
"parameter": "parameter_name_if_applicable",
"valid_range": "acceptable_values_if_applicable"
}
```
### Example Validation Errors:
- Invalid URL: "website_url must include protocol (http:// or https://)"
- Range violation: "number_of_scrolls must be between 0 and 50"
- Mutual exclusion: "Cannot specify both website_url and website_html"
- Missing required: "prompt is required when extraction_mode is 'ai'"
- Invalid JSON: "output_schema must be valid JSON format"
### Best Practices for Error Handling:
1. Always check the 'error' field in responses
2. Use parameter validation before making requests
3. Implement retry logic for timeout errors
4. Handle rate limiting gracefully
5. Validate URLs before passing to tools
For comprehensive parameter documentation, use the resource:
`scrapegraph://parameters/reference`
"""
import json
import logging
import os
from typing import Annotated, Any, Dict, List, Literal, Optional, Union
import httpx
from fastmcp import Context, FastMCP
from pydantic import AliasChoices, BaseModel, Field
from smithery.decorators import smithery
from starlette.requests import Request
from starlette.responses import JSONResponse
# Configure logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
MCP_SERVER_VERSION = "2.0.0"
# Matches scrapegraph-py v2 (env.py): https://v2-api.scrapegraphai.com/api
DEFAULT_API_BASE_URL = "https://v2-api.scrapegraphai.com/api"
def _api_base_url() -> str:
# SGAI_API_URL mirrors scrapegraph-py v2; SCRAPEGRAPH_API_BASE_URL is a legacy alias.
return (
os.environ.get("SGAI_API_URL")
or os.environ.get("SCRAPEGRAPH_API_BASE_URL")
or DEFAULT_API_BASE_URL
).rstrip("/")
def _api_timeout_s() -> float:
# SGAI_TIMEOUT mirrors scrapegraph-py v2 (default 120s); SGAI_TIMEOUT_S is a legacy alias.
val = os.environ.get("SGAI_TIMEOUT") or os.environ.get("SGAI_TIMEOUT_S")
try:
return float(val) if val else 120.0
except ValueError:
return 120.0
DEFAULT_SCREENSHOT_FORMAT: Dict[str, Any] = {
"type": "screenshot",
"fullPage": False,
"width": 1440,
"height": 900,
"quality": 80,
}
def _build_format_entry(
format_name: str,
*,
screenshot_full_page: bool = False,
) -> Dict[str, Any]:
"""Build a v2 format entry for scrape/crawl/monitor 'formats' arrays.
Mirrors scrapegraph-py v2 utils.payloads.build_single_format_entry.
"""
normalized = format_name.strip().lower()
if normalized == "markdown":
return {"type": "markdown", "mode": "normal"}
if normalized == "html":
return {"type": "html", "mode": "normal"}
if normalized == "screenshot":
entry = dict(DEFAULT_SCREENSHOT_FORMAT)
entry["fullPage"] = bool(screenshot_full_page)
return entry
if normalized == "links":
return {"type": "links"}
if normalized == "images":
return {"type": "images"}
if normalized == "summary":
return {"type": "summary"}
if normalized == "branding":
return {"type": "branding"}
if normalized == "json":
raise ValueError(
"'json' format requires prompt/schema configuration; use _build_json_format_entry."
)
raise ValueError(f"Unsupported format: {format_name}")
def _build_json_format_entry(
prompt: str,
schema: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Build a v2 json format entry (used by monitor prompt compatibility)."""
entry: Dict[str, Any] = {"type": "json", "prompt": prompt, "mode": "normal"}
if schema is not None:
entry["schema"] = schema
return entry
class ScapeGraphClient:
"""HTTP client for ScrapeGraphAI API v2 (see scrapegraph-py PR #84)."""
def __init__(self, api_key: str, base_url: Optional[str] = None) -> None:
self.api_key = api_key
self.base_url = (base_url or _api_base_url()).rstrip("/")
# Match scrapegraph-py v2 wire format: single SGAI-APIKEY header. We keep
# Content-Type/accept for broker compatibility and X-SDK-Version for telemetry.
self.headers = {
"SGAI-APIKEY": api_key,
"Content-Type": "application/json",
"accept": "application/json",
"X-SDK-Version": f"scrapegraph-mcp@{MCP_SERVER_VERSION}",
}
self.client = httpx.Client(timeout=httpx.Timeout(_api_timeout_s()))
def _parse_response(self, response: httpx.Response) -> Dict[str, Any]:
if response.status_code >= 400:
raise Exception(f"Error {response.status_code}: {response.text}")
if not response.content:
return {"ok": True}
try:
out = response.json()
if isinstance(out, dict):
return out
return {"result": out}
except json.JSONDecodeError:
return {"raw": response.text}
def _request(
self,
method: str,
path: str,
*,
json_body: Optional[Dict[str, Any]] = None,
params: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
url = f"{self.base_url}{path}"
r = self.client.request(method, url, headers=self.headers, json=json_body, params=params)
return self._parse_response(r)
def _fetch_config(
self,
*,
mode: Optional[str] = None,
stealth: Optional[bool] = None,
timeout: Optional[int] = None,
wait: Optional[int] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
country: Optional[str] = None,
scrolls: Optional[int] = None,
mock: Optional[bool] = None,
) -> Optional[Dict[str, Any]]:
cfg: Dict[str, Any] = {}
if mode is not None:
cfg["mode"] = mode
if stealth is not None:
cfg["stealth"] = stealth
if timeout is not None:
cfg["timeout"] = timeout
if wait is not None:
cfg["wait"] = wait
if headers is not None:
cfg["headers"] = headers
if cookies is not None:
cfg["cookies"] = cookies
if country is not None:
cfg["country"] = country
if scrolls is not None:
cfg["scrolls"] = scrolls
if mock is not None:
cfg["mock"] = mock
return cfg or None
def scrape_v2(
self,
website_url: str,
output_format: str = "markdown",
*,
fetch_config_dict: Optional[Dict[str, Any]] = None,
screenshot_full_page: bool = False,
content_type: Optional[str] = None,
) -> Dict[str, Any]:
body: Dict[str, Any] = {
"url": website_url,
"formats": [
_build_format_entry(output_format, screenshot_full_page=screenshot_full_page)
],
}
if content_type is not None:
body["contentType"] = content_type
if fetch_config_dict:
body["fetchConfig"] = fetch_config_dict
return self._request("POST", "/scrape", json_body=body)
def markdownify(
self,
website_url: str,
mode: Optional[str] = None,
stealth: Optional[bool] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
country: Optional[str] = None,
timeout: Optional[int] = None,
wait: Optional[int] = None,
scrolls: Optional[int] = None,
mock: Optional[bool] = None,
) -> Dict[str, Any]:
fc = self._fetch_config(
mode=mode, stealth=stealth, timeout=timeout, wait=wait, headers=headers,
cookies=cookies, country=country, scrolls=scrolls, mock=mock,
)
return self.scrape_v2(website_url, "markdown", fetch_config_dict=fc)
def extract(
self,
user_prompt: str,
website_url: Optional[str] = None,
output_schema: Optional[Dict[str, Any]] = None,
fetch_config_dict: Optional[Dict[str, Any]] = None,
*,
html: Optional[str] = None,
markdown: Optional[str] = None,
extract_mode: str = "normal",
content_type: Optional[str] = None,
) -> Dict[str, Any]:
if not any((website_url, html, markdown)):
raise ValueError("extract requires one of url, html, or markdown")
body: Dict[str, Any] = {"prompt": user_prompt, "mode": extract_mode}
if website_url is not None:
body["url"] = website_url
if html is not None:
body["html"] = html
if markdown is not None:
body["markdown"] = markdown
if output_schema is not None:
body["schema"] = output_schema
if content_type is not None:
body["contentType"] = content_type
if fetch_config_dict:
body["fetchConfig"] = fetch_config_dict
return self._request("POST", "/extract", json_body=body)
def smartscraper(
self,
user_prompt: str,
website_url: str,
output_schema: Optional[Dict[str, Any]] = None,
fetch_config_dict: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
return self.extract(user_prompt, website_url, output_schema, fetch_config_dict)
def search_api(
self,
query: str,
num_results: Optional[int] = None,
output_schema: Optional[Dict[str, Any]] = None,
*,
country: Optional[str] = None,
prompt: Optional[str] = None,
search_format: str = "markdown",
search_mode: str = "prune",
time_range: Optional[str] = None,
fetch_config_dict: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
n = 5 if num_results is None else num_results
n = max(1, min(20, n))
body: Dict[str, Any] = {
"query": query,
"numResults": n,
"format": search_format,
"mode": search_mode,
}
if output_schema is not None:
body["schema"] = output_schema
if prompt is not None:
body["prompt"] = prompt
if country is not None:
body["locationGeoCode"] = country
if time_range is not None:
body["timeRange"] = time_range
if fetch_config_dict:
body["fetchConfig"] = fetch_config_dict
return self._request("POST", "/search", json_body=body)
def searchscraper(
self,
user_prompt: str,
num_results: Optional[int] = None,
output_schema: Optional[Dict[str, Any]] = None,
*,
country: Optional[str] = None,
prompt: Optional[str] = None,
search_format: str = "markdown",
search_mode: str = "prune",
time_range: Optional[str] = None,
fetch_config_dict: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
return self.search_api(
user_prompt,
num_results=num_results,
output_schema=output_schema,
country=country,
prompt=prompt,
search_format=search_format,
search_mode=search_mode,
time_range=time_range,
fetch_config_dict=fetch_config_dict,
)
def scrape(
self,
website_url: str,
output_format: str = "markdown",
screenshot_full_page: bool = False,
fetch_config_dict: Optional[Dict[str, Any]] = None,
*,
content_type: Optional[str] = None,
) -> Dict[str, Any]:
return self.scrape_v2(
website_url,
output_format,
fetch_config_dict=fetch_config_dict,
screenshot_full_page=screenshot_full_page,
content_type=content_type,
)
def schema(
self,
prompt: str,
*,
existing_schema: Optional[Dict[str, Any]] = None,
model: Optional[str] = None,
) -> Dict[str, Any]:
"""Generate or augment a JSON Schema from a prompt (POST /schema)."""
body: Dict[str, Any] = {"prompt": prompt}
if existing_schema is not None:
body["existingSchema"] = existing_schema
if model is not None:
body["model"] = model
return self._request("POST", "/schema", json_body=body)
def crawl_start(
self,
url: str,
*,
depth: Optional[int] = None,
max_pages: int = 10,
crawl_format: str = "markdown",
include_patterns: Optional[List[str]] = None,
exclude_patterns: Optional[List[str]] = None,
fetch_config_dict: Optional[Dict[str, Any]] = None,
max_links_per_page: int = 10,
allow_external: bool = False,
content_types: Optional[List[str]] = None,
) -> Dict[str, Any]:
cf = crawl_format.lower()
if cf not in ("markdown", "html", "links", "images", "summary", "branding", "screenshot"):
raise ValueError(
"crawl_format must be one of: markdown, html, links, images, summary, branding, screenshot"
)
body: Dict[str, Any] = {
"url": url,
"formats": [_build_format_entry(cf)],
"maxDepth": 2 if depth is None else depth,
"maxPages": max_pages,
"maxLinksPerPage": max_links_per_page,
"allowExternal": allow_external,
}
if include_patterns is not None:
body["includePatterns"] = include_patterns
if exclude_patterns is not None:
body["excludePatterns"] = exclude_patterns
if content_types is not None:
body["contentTypes"] = content_types
if fetch_config_dict:
body["fetchConfig"] = fetch_config_dict
return self._request("POST", "/crawl", json_body=body)
def smartcrawler_fetch_results(self, request_id: str) -> Dict[str, Any]:
return self._request("GET", f"/crawl/{request_id}")
def crawl_stop(self, crawl_id: str) -> Dict[str, Any]:
return self._request("POST", f"/crawl/{crawl_id}/stop")
def crawl_resume(self, crawl_id: str) -> Dict[str, Any]:
return self._request("POST", f"/crawl/{crawl_id}/resume")
def credits(self) -> Dict[str, Any]:
return self._request("GET", "/credits")
def history(
self,
*,
service: Optional[str] = None,
page: Optional[int] = None,
limit: Optional[int] = None,
endpoint: Optional[str] = None,
status_filter: Optional[str] = None,
offset: Optional[int] = None,
) -> Dict[str, Any]:
"""List recent API requests (GET /history).
v2 supports only page/limit/service. Legacy endpoint/status/offset
inputs are translated (offset->page where it divides limit; status is
rejected since v2 has no status filter) to preserve backward-compat.
"""
if status_filter is not None:
raise ValueError("History status filtering is not supported by SGAI v2")
if service and endpoint and service != endpoint:
raise ValueError("service and endpoint cannot disagree")
resolved_limit = limit
resolved_page = page
if offset is not None:
offset_limit = limit or 20
if offset_limit <= 0 or offset % offset_limit != 0:
raise ValueError("offset must be a non-negative multiple of limit")
inferred = (offset // offset_limit) + 1
if page is not None and page != inferred:
raise ValueError("page and offset point to different result windows")
resolved_limit = offset_limit
resolved_page = inferred
params = {
"page": resolved_page,
"limit": resolved_limit,
"service": service or endpoint,
}
params = {k: v for k, v in params.items() if v is not None}
return self._request("GET", "/history", params=params or None)
def monitor_create(
self,
name: Optional[str],
url: str,
prompt: Optional[str],
interval: str,
output_schema: Optional[Dict[str, Any]] = None,
fetch_config_dict: Optional[Dict[str, Any]] = None,
*,
formats: Optional[List[Dict[str, Any]]] = None,
webhook_url: Optional[str] = None,
) -> Dict[str, Any]:
# Resolve formats: caller-supplied wins, else build a json entry from prompt/schema.
if formats is not None:
resolved_formats = list(formats)
else:
if not prompt:
raise ValueError(
"monitor_create requires either `formats` or a `prompt` for json extraction"
)
resolved_formats = [_build_json_format_entry(prompt=prompt, schema=output_schema)]
body: Dict[str, Any] = {
"url": url,
"formats": resolved_formats,
"interval": interval,
}
if name is not None:
body["name"] = name
if webhook_url is not None:
body["webhookUrl"] = webhook_url
if fetch_config_dict:
body["fetchConfig"] = fetch_config_dict
return self._request("POST", "/monitor", json_body=body)
def monitor_list(self) -> Dict[str, Any]:
return self._request("GET", "/monitor")
def monitor_get(self, monitor_id: str) -> Dict[str, Any]:
return self._request("GET", f"/monitor/{monitor_id}")
def monitor_pause(self, monitor_id: str) -> Dict[str, Any]:
return self._request("POST", f"/monitor/{monitor_id}/pause")
def monitor_resume(self, monitor_id: str) -> Dict[str, Any]:
return self._request("POST", f"/monitor/{monitor_id}/resume")
def monitor_delete(self, monitor_id: str) -> Dict[str, Any]:
return self._request("DELETE", f"/monitor/{monitor_id}")
def monitor_activity(
self,
monitor_id: str,
limit: Optional[int] = None,
cursor: Optional[str] = None,
) -> Dict[str, Any]:
"""GET /monitor/:id/activity β paginated tick history."""
params: Dict[str, Any] = {}
if limit is not None:
params["limit"] = limit
if cursor is not None:
params["cursor"] = cursor
return self._request("GET", f"/monitor/{monitor_id}/activity", params=params or None)
def close(self) -> None:
"""Close the HTTP client."""
self.client.close()
# Pydantic configuration schema for Smithery
class ConfigSchema(BaseModel):
scrapegraph_api_key: Optional[str] = Field(
default=None,
description="Your Scrapegraph API key (optional - can also be set via SGAI_API_KEY environment variable)",
# Accept both camelCase (from smithery.yaml) and snake_case (internal) for validation,
# and serialize back to camelCase to match Smithery expectations.
validation_alias=AliasChoices("scrapegraphApiKey", "scrapegraph_api_key"),
serialization_alias="scrapegraphApiKey",
)
def get_api_key(ctx: Context) -> str:
"""
Get the API key from HTTP header or MCP session config.
Supports two modes:
- HTTP mode (Render): API key from 'X-API-Key' header via mcp-remote
- Stdio mode (Smithery): API key from session_config.scrapegraph_api_key
Args:
ctx: FastMCP context
Returns:
API key string
Raises:
ValueError: If no API key is found
"""
from fastmcp.server.dependencies import get_http_headers
# Try HTTP header first (for remote/Render deployments)
try:
headers = get_http_headers()
api_key = headers.get("x-api-key")
if api_key:
logger.info("API key retrieved from X-API-Key header")
return str(api_key)
except LookupError:
# Not in HTTP context, try session config (Smithery/stdio mode)
pass
# Try session config (for Smithery/stdio deployments)
if hasattr(ctx, "session_config") and ctx.session_config is not None:
api_key = getattr(ctx.session_config, "scrapegraph_api_key", None)
if api_key:
logger.info("API key retrieved from session config")
return str(api_key)
logger.error("No API key found in header or session config")
raise ValueError(
"ScapeGraph API key is required. Please provide it via:\n"
"- HTTP header 'X-API-Key' (for remote server via mcp-remote)\n"
"- MCP config 'scrapegraphApiKey' (for Smithery/local stdio)"
)
# Create MCP server instance
mcp = FastMCP("ScapeGraph API MCP Server")
# Health check endpoint for remote deployments (Render, etc.)
@mcp.custom_route("/health", methods=["GET"])
async def health_check(_request: Request) -> JSONResponse:
"""Health check endpoint for container orchestration and load balancers."""
return JSONResponse({"status": "healthy", "service": "scrapegraph-mcp"})
# Add prompts to help users interact with the server
@mcp.prompt()
def web_scraping_guide() -> str:
"""
A comprehensive guide to using ScapeGraph's web scraping tools effectively.
This prompt provides examples and best practices for each tool in the ScapeGraph MCP server.
"""
return """# ScapeGraph Web Scraping Guide (API v2)
See [scrapegraph-py#84](https://github.com/ScrapeGraphAI/scrapegraph-py/pull/84) for the upstream SDK migration.
## Core tools
- **markdownify** β `POST /scrape` (markdown output)
- **scrape** β `POST /scrape` (markdown, html, screenshot, branding, links, images, summary)
- **smartscraper** β `POST /extract` (url + prompt, optional schema/mode/contentType)
- **searchscraper** β `POST /search` (query + numResults 1β20; optional schema+prompt, locationGeoCode, timeRange)
- **smartcrawler_initiate** / **smartcrawler_fetch_results** β `POST/GET /crawl`
(formats: markdown, html, links, images, summary, branding, screenshot; maxDepth / maxPages / maxLinksPerPage / allowExternal)
- **crawl_stop** / **crawl_resume** β control a running job
- **generate_schema** β `POST /schema`
- **credits** β `GET /credits`
- **sgai_history** β `GET /history` (page/limit/service)
- **monitor_*** β scheduled jobs (`POST/GET/DELETE /monitor`, pause/resume, optional webhook_url)
## Best practices
1. Use **markdownify** or **scrape** before **smartscraper** when you only need readable text.
2. Multi-page **AI** extraction: run **smartscraper** per URL, or use **monitor_create** on a schedule.
3. Poll **smartcrawler_fetch_results** until the crawl finishes.
4. Override API host with env **SGAI_API_URL** if needed (default `https://v2-api.scrapegraphai.com/api`).
"""
@mcp.prompt()
def quick_start_examples() -> str:
"""
Quick start examples for common ScapeGraph use cases.
Ready-to-use examples for immediate productivity.
"""
return """# ScapeGraph Quick Start (API v2)
### Extract structured data (single URL)
```
Tool: smartscraper
website_url: https://example.com/product/1
user_prompt: "Extract name, price, and availability"
```
### Markdown snapshot
```
Tool: markdownify
website_url: https://docs.example.com
```
### Search
```
Tool: searchscraper
user_prompt: "Latest Python 3.12 release highlights"
num_results: 5
```
### Multi-page crawl (markdown/html only)
```
Tool: smartcrawler_initiate
url: https://blog.example.com
extraction_mode: "markdown"
max_pages: 15
depth: 2
```
Then poll `smartcrawler_fetch_results` with the returned `id`.
### Credits and history
```
Tool: credits
Tool: sgai_history
limit: 10
```
Auth: `SGAI_API_KEY` or MCP `scrapegraphApiKey`. Optional: `SGAI_API_URL`, `SGAI_TIMEOUT` (legacy: `SGAI_TIMEOUT_S`).
"""
# Add resources to expose server capabilities and data
@mcp.resource("scrapegraph://api/status")
def api_status() -> str:
"""
Current status and capabilities of the ScapeGraph API server.
Provides real-time information about available tools, credit usage, and server health.
"""
return """# ScapeGraph API Status (MCP v2)
- **MCP package version**: 2.0.0 (matches [scrapegraph-py#84](https://github.com/ScrapeGraphAI/scrapegraph-py/pull/84) API surface)
- **Default API base**: `https://v2-api.scrapegraphai.com/api` (override with `SGAI_API_URL`)
- **Auth headers**: `SGAI-APIKEY`, `X-SDK-Version: scrapegraph-mcp@2.0.0`
## Tools
markdownify, scrape, smartscraper, searchscraper, smartcrawler_initiate, smartcrawler_fetch_results, crawl_stop, crawl_resume, generate_schema, credits, sgai_history, monitor_create, monitor_list, monitor_get, monitor_pause, monitor_resume, monitor_delete, monitor_activity
## Removed vs legacy MCP
sitemap, agentic_scrapper, markdownify_status, smartscraper_status β not available on API v2.
Credit costs are determined by the ScrapeGraphAI API; use **credits** to check balance.
"""
@mcp.resource("scrapegraph://examples/use-cases")
def common_use_cases() -> str:
"""
Common use cases and example implementations for ScapeGraph tools.
Real-world examples with expected inputs and outputs.
"""
return """# ScapeGraph Common Use Cases
## ποΈ E-commerce Data Extraction
### Product Information Scraping
**Tool**: smartscraper
**Input**: Product page URL + "Extract name, price, description, rating, availability"
**Output**: Structured JSON with product details
**Credits**: 10 per page
### Price Monitoring
**Tool**: smartcrawler_initiate (AI mode)
**Input**: Product category page + price extraction prompt
**Output**: Structured price data across multiple products
**Credits**: 10 per page crawled
## π° Content & Research
### News Article Extraction
**Tool**: searchscraper
**Input**: "Latest news about [topic]" + num_results
**Output**: Article titles, summaries, sources, dates
**Credits**: 10 per website searched
### Documentation Conversion
**Tool**: smartcrawler_initiate (markdown mode)
**Input**: Documentation site root URL
**Output**: Clean markdown files for all pages
**Credits**: 2 per page converted
## π’ Business Intelligence
### Contact Information Gathering
**Tool**: smartscraper
**Input**: Company website + "Find contact details"
**Output**: Emails, phones, addresses, social media
**Credits**: 10 per page
### Competitor Analysis
**Tool**: searchscraper + smartscraper combination
**Input**: Search for competitors + extract key metrics
**Output**: Structured competitive intelligence
**Credits**: Variable based on pages analyzed
## π Research & Analysis
### Academic Paper Research
**Tool**: searchscraper
**Input**: Research query + academic site focus
**Output**: Paper titles, abstracts, authors, citations
**Credits**: 10 per source website
### Market Research
**Tool**: smartcrawler_initiate
**Input**: Industry website + data extraction prompts
**Output**: Market trends, statistics, insights
**Credits**: 10 per page (AI mode)
## π€ Automation Workflows
### Form-based Data Collection
**Tool**: agentic_scrapper
**Input**: Site URL + navigation steps + extraction goals
**Output**: Data collected through automated interaction
**Credits**: Variable based on complexity
### Multi-step Research Process
**Workflow**: sitemap β smartcrawler_initiate β smartscraper
**Input**: Target site + research objectives
**Output**: Comprehensive site analysis and data extraction
**Credits**: Cumulative based on tools used
## π‘ Optimization Tips
1. **Start with sitemap** to understand site structure
2. **Use markdown mode** for content archival (cheaper)
3. **Use AI mode** for structured data extraction
4. **Batch similar requests** to optimize credit usage
5. **Set appropriate crawl limits** to control costs
6. **Use specific prompts** for better AI extraction accuracy
## π Expected Response Times
- **Simple scraping**: 5-15 seconds
- **AI extraction**: 15-45 seconds per page
- **Crawling operations**: 1-5 minutes (async)
- **Search operations**: 30-90 seconds
- **Agentic workflows**: 2-10 minutes
## π¨ Common Pitfalls
- Not setting crawl limits (unexpected credit usage)
- Vague extraction prompts (poor AI results)
- Not polling async operations (missing results)
- Ignoring rate limits (request failures)
- Not handling JavaScript-heavy sites (incomplete data)
"""
@mcp.resource("scrapegraph://parameters/reference")
def parameter_reference_guide() -> str:
"""
Comprehensive parameter reference guide for all ScapeGraph MCP tools.
Complete documentation of every parameter with examples, constraints, and best practices.
"""
return """# ScapeGraph MCP Parameter Reference Guide
> **API v2 note:** This document still contains legacy v1-era tool names and parameters in places.
> Trust the live tool schemas in the MCP client and the module docstring in `server.py` for v2.
> New tools: `credits`, `sgai_history`, `crawl_stop`, `crawl_resume`, `monitor_*`. Removed: `sitemap`,
> `agentic_scrapper`, `markdownify_status`, `smartscraper_status`.
## π Complete Parameter Documentation
This guide provides comprehensive documentation for every parameter across all ScapeGraph MCP tools. Use this as your definitive reference for understanding parameter behavior, constraints, and best practices.
---
## π§ Common Parameters
### URL Parameters
**Used in**: markdownify, smartscraper, searchscraper, smartcrawler_initiate, scrape, monitor_*, and related v2 tools
#### `website_url` / `url`
- **Type**: `str` (required)
- **Format**: Must include protocol (http:// or https://)
- **Examples**:
- β
`https://example.com/page`
- β
`https://docs.python.org/3/tutorial/`
- β `example.com` (missing protocol)
- β `ftp://example.com` (unsupported protocol)
- **Best Practices**:
- Always include the full URL with protocol
- Ensure the URL is publicly accessible
- Test URLs manually before automation
---
## π€ AI and Extraction Parameters
### `user_prompt`
**Used in**: smartscraper, searchscraper, agentic_scrapper
- **Type**: `str` (required)
- **Purpose**: Natural language instructions for AI extraction
- **Examples**:
- `"Extract product name, price, description, and availability"`
- `"Find contact information: email, phone, address"`
- `"Get article title, author, publication date, summary"`
- **Best Practices**:
- Be specific about desired fields
- Mention data types (numbers, dates, URLs)
- Include context about data location
- Use clear, descriptive language
### `output_schema`
**Used in**: smartscraper, agentic_scrapper
- **Type**: `Optional[Union[str, Dict[str, Any]]]`
- **Purpose**: Define expected output structure
- **Formats**:
- Dictionary: `{'type': 'object', 'properties': {'title': {'type': 'string'}}, 'required': []}`
- JSON string: `'{"type": "object", "properties": {"name": {"type": "string"}}, "required": []}'`
- **IMPORTANT**: Must include a `"required"` field (can be empty array `[]` if no fields are required)
- **Examples**:
```json
{
"type": "object",
"properties": {
"products": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"price": {"type": "number"},
"available": {"type": "boolean"}
},
"required": []
}
}
},
"required": []
}
```
- **Best Practices**:
- Always include the `"required"` field (use `[]` if no fields are required)
- Use for complex, structured extractions
- Define clear data types
- Consider nested structures for complex data
- Note: If `"required"` field is missing, it will be automatically added as `[]`
---
## π Content Source Parameters
### `website_html`
**Used in**: smartscraper
- **Type**: `Optional[str]`
- **Purpose**: Process local HTML content
- **Constraints**: Maximum 2MB
- **Use Cases**:
- Pre-fetched HTML content
- Generated HTML from other sources
- Offline HTML processing
- **Mutually Exclusive**: Cannot use with `website_url` or `website_markdown`
### `website_markdown`
**Used in**: smartscraper
- **Type**: `Optional[str]`
- **Purpose**: Process local markdown content
- **Constraints**: Maximum 2MB
- **Use Cases**:
- Documentation processing
- README file analysis
- Converted web content
- **Mutually Exclusive**: Cannot use with `website_url` or `website_html`
---
## π Pagination and Scrolling Parameters
### `number_of_scrolls`
**Used in**: smartscraper, searchscraper
- **Type**: `Optional[int]`
- **Range**: 0-50 scrolls
- **Default**: 0 (no scrolling)
- **Purpose**: Handle dynamically loaded content
- **Examples**:
- `0`: Static content, no scrolling needed
- `3`: Social media feeds, product listings
- `10`: Long articles, extensive catalogs
- **Performance Impact**: +5-10 seconds per scroll
- **Best Practices**:
- Start with 0 and increase if content seems incomplete
- Use sparingly to control processing time
- Consider site loading behavior
### `total_pages`
**Used in**: smartscraper
- **Type**: `Optional[int]`
- **Range**: 1-100 pages
- **Default**: 1 (single page)
- **Purpose**: Process paginated content
- **Cost Impact**: 10 credits Γ pages
- **Examples**: