-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathserver.py
More file actions
1949 lines (1649 loc) Β· 69.8 KB
/
server.py
File metadata and controls
1949 lines (1649 loc) Β· 69.8 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#82](https://github.com/ScrapeGraphAI/scrapegraph-py/pull/82)):
- markdownify: Page content via POST /scrape (markdown by default)
- smartscraper: Structured extraction via POST /extract (URL input only)
- searchscraper: Web search via POST /search
- smartcrawler_initiate / smartcrawler_fetch_results: Async crawl via /crawl (markdown or html only)
- crawl_stop / crawl_resume: Control running crawl jobs
- scrape: Format-specific fetch (markdown, html, screenshot, branding)
- credits / sgai_history: Account usage and request history
- monitor_*: Scheduled extraction jobs (replaces legacy scheduled jobs)
Removed on v2 (no API equivalent): sitemap, agentic_scrapper, markdownify_status, smartscraper_status.
Optional base URL override: SCRAPEGRAPH_API_BASE_URL (default https://api.scrapegraphai.com/api/v2).
## 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"
DEFAULT_API_BASE_URL = "https://api.scrapegraphai.com/api/v2"
def _api_base_url() -> str:
return os.environ.get("SCRAPEGRAPH_API_BASE_URL", DEFAULT_API_BASE_URL).rstrip("/")
class ScapeGraphClient:
"""HTTP client for ScrapeGraphAI API v2 (see scrapegraph-py PR #82)."""
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("/")
self.headers = {
"Authorization": f"Bearer {api_key}",
"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(120.0))
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,
*,
headers: Optional[Dict[str, str]] = None,
stealth: Optional[bool] = None,
mock: Optional[bool] = None,
scrolls: Optional[int] = None,
render_js: Optional[bool] = None,
wait_ms: Optional[int] = None,
) -> Optional[Dict[str, Any]]:
cfg: Dict[str, Any] = {}
if headers is not None:
cfg["headers"] = headers
if stealth is not None:
cfg["stealth"] = stealth
if mock is not None:
cfg["mock"] = mock
if scrolls is not None:
cfg["scrolls"] = scrolls
if render_js is not None:
cfg["render_js"] = render_js
if wait_ms is not None:
cfg["wait_ms"] = wait_ms
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,
) -> Dict[str, Any]:
fmt = output_format.lower()
body: Dict[str, Any] = {"url": website_url}
if fmt == "markdown":
body["markdown"] = {"mode": "normal"}
elif fmt == "html":
body["html"] = {"mode": "normal"}
elif fmt == "screenshot":
body["screenshot"] = {"full_page": screenshot_full_page}
elif fmt == "branding":
body["branding"] = {}
else:
raise ValueError(
f"Invalid output_format {output_format!r}; use markdown, html, screenshot, or branding"
)
if fetch_config_dict:
body["fetch_config"] = fetch_config_dict
return self._request("POST", "/scrape", json_body=body)
def markdownify(
self,
website_url: str,
headers: Optional[Dict[str, str]] = None,
stealth: Optional[bool] = None,
stream: Optional[bool] = None,
mock: Optional[bool] = None,
) -> Dict[str, Any]:
if stream is not None:
logger.warning("stream is not supported on API v2 /scrape; ignoring")
fc = self._fetch_config(headers=headers, stealth=stealth, mock=mock)
return self.scrape_v2(website_url, "markdown", fetch_config_dict=fc)
def extract(
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]:
body: Dict[str, Any] = {"url": website_url, "prompt": user_prompt}
if output_schema is not None:
body["output_schema"] = output_schema
if fetch_config_dict:
body["fetch_config"] = fetch_config_dict
return self._request("POST", "/extract", json_body=body)
def smartscraper(
self,
user_prompt: str,
website_url: Optional[str] = None,
website_html: Optional[str] = None,
website_markdown: Optional[str] = None,
output_schema: Optional[Dict[str, Any]] = None,
number_of_scrolls: Optional[int] = None,
total_pages: Optional[int] = None,
render_heavy_js: Optional[bool] = None,
stealth: Optional[bool] = None,
) -> Dict[str, Any]:
if website_html is not None or website_markdown is not None:
raise ValueError(
"API v2 extract supports URL input only; website_html and website_markdown "
"are not supported."
)
if website_url is None:
raise ValueError("Must provide website_url")
if total_pages is not None and total_pages != 1:
raise ValueError(
"total_pages is not supported for extract on API v2; omit it or use 1, or use "
"smartcrawler_initiate for multi-page markdown/html crawl."
)
fc = self._fetch_config(
stealth=stealth, scrolls=number_of_scrolls, render_js=render_heavy_js
)
return self.extract(user_prompt, website_url, output_schema, fc)
def search_api(
self,
query: str,
num_results: Optional[int] = None,
output_schema: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
n = 5 if num_results is None else num_results
n = max(3, min(20, n))
body: Dict[str, Any] = {"query": query, "num_results": n}
if output_schema is not None:
body["output_schema"] = output_schema
return self._request("POST", "/search", json_body=body)
def searchscraper(
self,
user_prompt: str,
num_results: Optional[int] = None,
number_of_scrolls: Optional[int] = None,
time_range: Optional[str] = None,
) -> Dict[str, Any]:
if time_range is not None:
logger.warning("time_range is not supported on API v2 /search; ignoring")
if number_of_scrolls is not None:
logger.warning("number_of_scrolls is not supported on API v2 /search; ignoring")
return self.search_api(user_prompt, num_results=num_results)
def scrape(
self,
website_url: str,
render_heavy_js: Optional[bool] = None,
mock: Optional[bool] = None,
stealth: Optional[bool] = None,
stream: Optional[bool] = None,
output_format: str = "markdown",
screenshot_full_page: bool = False,
) -> Dict[str, Any]:
if stream is not None:
logger.warning("stream is not supported on API v2 /scrape; ignoring")
fc = self._fetch_config(stealth=stealth, mock=mock, render_js=render_heavy_js)
return self.scrape_v2(
website_url,
output_format,
fetch_config_dict=fc,
screenshot_full_page=screenshot_full_page,
)
def crawl_start(
self,
url: str,
*,
depth: int = 2,
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,
) -> Dict[str, Any]:
cf = crawl_format.lower()
if cf not in ("markdown", "html"):
raise ValueError("crawl_format must be 'markdown' or 'html'")
body: Dict[str, Any] = {
"url": url,
"depth": depth,
"max_pages": max_pages,
"format": cf,
}
if include_patterns is not None:
body["include_patterns"] = include_patterns
if exclude_patterns is not None:
body["exclude_patterns"] = exclude_patterns
if fetch_config_dict:
body["fetch_config"] = fetch_config_dict
return self._request("POST", "/crawl", json_body=body)
def smartcrawler_initiate(
self,
url: str,
prompt: Optional[str] = None,
extraction_mode: str = "markdown",
depth: Optional[int] = None,
max_pages: Optional[int] = None,
same_domain_only: Optional[bool] = None,
include_patterns: Optional[List[str]] = None,
exclude_patterns: Optional[List[str]] = None,
) -> Dict[str, Any]:
if extraction_mode == "ai":
raise ValueError(
"API v2 crawl does not support AI extraction across pages. Use smartscraper "
"(extract) for a single URL, or monitor_create for scheduled jobs. Use "
"extraction_mode 'markdown' or 'html' for multi-page crawl."
)
if extraction_mode not in ("markdown", "html"):
raise ValueError("extraction_mode must be 'markdown', 'html', or (deprecated) 'ai'")
if prompt is not None and extraction_mode in ("markdown", "html"):
logger.warning("prompt is ignored for markdown/html crawl on API v2")
if same_domain_only is not None:
logger.warning(
"same_domain_only is not supported on API v2 crawl; use include_patterns / "
"exclude_patterns"
)
d = 2 if depth is None else depth
mp = 10 if max_pages is None else max_pages
if d < 1 or d > 10:
raise ValueError("depth must be between 1 and 10")
if mp < 1 or mp > 100:
raise ValueError("max_pages must be between 1 and 100")
return self.crawl_start(
url,
depth=d,
max_pages=mp,
crawl_format="markdown" if extraction_mode == "markdown" else "html",
include_patterns=include_patterns,
exclude_patterns=exclude_patterns,
)
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,
endpoint: Optional[str] = None,
status_filter: Optional[str] = None,
limit: Optional[int] = None,
offset: Optional[int] = None,
) -> Dict[str, Any]:
params = {
k: v
for k, v in {
"endpoint": endpoint,
"status": status_filter,
"limit": limit,
"offset": offset,
}.items()
if v is not None
}
return self._request("GET", "/history", params=params or None)
def monitor_create(
self,
name: str,
url: str,
prompt: str,
cron: str,
output_schema: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
body: Dict[str, Any] = {
"name": name,
"url": url,
"prompt": prompt,
"cron": cron,
}
if output_schema is not None:
body["output_schema"] = output_schema
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 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#82](https://github.com/ScrapeGraphAI/scrapegraph-py/pull/82) for the upstream SDK migration.
## Core tools
- **markdownify** β `POST /scrape` (markdown output)
- **scrape** β `POST /scrape` (markdown, html, screenshot, branding)
- **smartscraper** β `POST /extract` (URL + prompt; no inline HTML/markdown source on v2)
- **searchscraper** β `POST /search` (query + num_results 3β20)
- **smartcrawler_initiate** / **smartcrawler_fetch_results** β `POST/GET /crawl` (markdown or html crawl only; no per-page AI crawl on v2)
- **crawl_stop** / **crawl_resume** β control a running job
- **credits** β `GET /credits`
- **sgai_history** β `GET /history`
- **monitor_*** β scheduled jobs (`POST/GET/DELETE /monitor`, pause/resume)
## 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 **SCRAPEGRAPH_API_BASE_URL** if needed (default production v2 base URL).
"""
@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: `SCRAPEGRAPH_API_BASE_URL`.
"""
# 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#82](https://github.com/ScrapeGraphAI/scrapegraph-py/pull/82) API surface)
- **Default API base**: `https://api.scrapegraphai.com/api/v2` (override with `SCRAPEGRAPH_API_BASE_URL`)
- **Auth headers**: `Authorization: Bearer`, `SGAI-APIKEY`, `X-SDK-Version: scrapegraph-mcp@2.0.0`
## Tools
markdownify, scrape, smartscraper, searchscraper, smartcrawler_initiate, smartcrawler_fetch_results, crawl_stop, crawl_resume, credits, sgai_history, monitor_create, monitor_list, monitor_get, monitor_pause, monitor_resume, monitor_delete
## 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**:
- `1`: Single page extraction
- `5`: First 5 pages of results
- `20`: Comprehensive pagination
- **Best Practices**:
- Set reasonable limits to control costs
- Consider total credit usage
- Test with small numbers first
---
## π Performance Parameters
### `render_heavy_js`
**Used in**: smartscraper, scrape
- **Type**: `Optional[bool]`
- **Default**: `false`
- **Purpose**: Enable JavaScript rendering for SPAs
- **When to Use `true`**:
- React/Angular/Vue applications
- Dynamic content loading
- AJAX-heavy interfaces
- Content appearing after page load
- **When to Use `false`**:
- Static websites
- Server-side rendered content
- Traditional HTML pages
- When speed is priority
- **Performance Impact**:
- `false`: 2-5 seconds
- `true`: 15-30 seconds
- **Cost**: Same regardless of setting
### `stealth`
**Used in**: smartscraper
- **Type**: `Optional[bool]`
- **Default**: `false`
- **Purpose**: Bypass basic bot detection
- **When to Use**:
- Sites with anti-scraping measures
- E-commerce sites with protection
- Sites requiring "human-like" behavior
- **Limitations**:
- Not 100% guaranteed
- May increase processing time
- Some advanced detection may still work
---
## π Crawling Parameters
### `prompt`
**Used in**: smartcrawler_initiate
- **Type**: `Optional[str]`
- **Required**: When `extraction_mode="ai"`
- **Purpose**: AI extraction instructions for all crawled pages
- **Examples**:
- `"Extract API endpoint name, method, parameters"`
- `"Get article title, author, publication date"`
- **Best Practices**:
- Use general terms that apply across page types
- Consider varying page structures
- Be specific about desired fields
### `extraction_mode`
**Used in**: smartcrawler_initiate
- **Type**: `str`
- **Default**: `"ai"`
- **Options**:
- `"ai"`: AI-powered extraction (10 credits/page)
- `"markdown"`: Markdown conversion (2 credits/page)
- **Cost Comparison**:
- AI mode: 50 pages = 500 credits
- Markdown mode: 50 pages = 100 credits
- **Use Cases**:
- AI: Data collection, research, analysis
- Markdown: Content archival, documentation backup
### `depth`
**Used in**: smartcrawler_initiate
- **Type**: `Optional[int]`
- **Default**: Unlimited
- **Purpose**: Control link traversal depth
- **Levels**:
- `0`: Only starting URL
- `1`: Starting URL + direct links
- `2`: Two levels of link following
- `3+`: Deeper traversal
- **Considerations**:
- Higher depth = exponential growth
- Use with `max_pages` for control
- Consider site structure
### `max_pages`
**Used in**: smartcrawler_initiate
- **Type**: `Optional[int]`
- **Default**: Unlimited
- **Purpose**: Limit total pages crawled
- **Recommended Ranges**:
- `10-20`: Testing, small sites
- `50-100`: Medium sites
- `200-500`: Large sites
- `1000+`: Enterprise crawling
- **Cost Calculation**:
- AI mode: `max_pages Γ 10` credits
- Markdown mode: `max_pages Γ 2` credits
### `same_domain_only`
**Used in**: smartcrawler_initiate
- **Type**: `Optional[bool]`
- **Default**: `true`
- **Purpose**: Control cross-domain crawling
- **Options**:
- `true`: Stay within same domain (recommended)
- `false`: Allow external domains (use with caution)
- **Best Practices**:
- Use `true` for focused crawling
- Set `max_pages` when using `false`
- Consider crawling scope carefully
---
## π Search Parameters
### `num_results`
**Used in**: searchscraper
- **Type**: `Optional[int]`
- **Default**: 3 websites
- **Range**: 1-20 (recommended β€10)
- **Cost**: `num_results Γ 10` credits
- **Examples**:
- `1`: Quick lookup (10 credits)
- `3`: Standard research (30 credits)
- `5`: Comprehensive (50 credits)
- `10`: Extensive analysis (100 credits)
---
## π€ Agentic Automation Parameters
### `steps`
**Used in**: agentic_scrapper
- **Type**: `Optional[Union[str, List[str]]]`
- **Purpose**: Sequential workflow instructions
- **Formats**:
- List: `['Click search', 'Enter term', 'Extract results']`
- JSON string: `'["Step 1", "Step 2", "Step 3"]'`