-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathserver.py
More file actions
2611 lines (2213 loc) Β· 104 KB
/
server.py
File metadata and controls
2611 lines (2213 loc) Β· 104 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.
This server exposes methods to use ScapeGraph's AI-powered web scraping services:
- markdownify: Convert any webpage into clean, formatted markdown
- smartscraper: Extract structured data from any webpage using AI
- searchscraper: Perform AI-powered web searches with structured results
- smartcrawler_initiate: Initiate intelligent multi-page web crawling with AI extraction or markdown conversion
- smartcrawler_fetch_results: Retrieve results from asynchronous crawling operations
- scrape: Fetch raw page content with optional JavaScript rendering
- sitemap: Extract and discover complete website structure
- agentic_scrapper: Execute complex multi-step web scraping workflows
## 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 Any, Dict, Optional, List, Union, Annotated, Literal
import httpx
from fastmcp import Context, FastMCP
from smithery.decorators import smithery
from pydantic import BaseModel, Field, AliasChoices
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class ScapeGraphClient:
"""Client for interacting with the ScapeGraph API."""
BASE_URL = "https://api.scrapegraphai.com/v1"
def __init__(self, api_key: str):
"""
Initialize the ScapeGraph API client.
Args:
api_key: API key for ScapeGraph API
"""
self.api_key = api_key
self.headers = {
"SGAI-APIKEY": api_key,
"Content-Type": "application/json"
}
self.client = httpx.Client(timeout=httpx.Timeout(120.0))
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]:
"""
Convert a webpage into clean, formatted markdown.
Args:
website_url: URL of the webpage to convert
headers: HTTP headers to include in the request (optional)
stealth: Enable stealth mode to avoid bot detection (optional)
stream: Enable streaming response for real-time updates (optional)
mock: Return mock data for testing purposes (optional)
Returns:
Dictionary containing the markdown result
"""
url = f"{self.BASE_URL}/markdownify"
data = {"website_url": website_url}
if headers is not None:
data["headers"] = headers
if stealth is not None:
data["stealth"] = stealth
if stream is not None:
data["stream"] = stream
if mock is not None:
data["mock"] = mock
response = self.client.post(url, headers=self.headers, json=data)
if response.status_code != 200:
error_msg = f"Error {response.status_code}: {response.text}"
raise Exception(error_msg)
return response.json()
def markdownify_status(self, request_id: str) -> Dict[str, Any]:
"""
Get the status of a markdownify request.
Args:
request_id: The request ID to check status for
Returns:
Dictionary containing the request status and results
"""
url = f"{self.BASE_URL}/markdownify/{request_id}"
response = self.client.get(url, headers=self.headers)
if response.status_code != 200:
error_msg = f"Error {response.status_code}: {response.text}"
raise Exception(error_msg)
return response.json()
def smartscraper(
self,
user_prompt: str,
website_url: str = None,
website_html: str = None,
website_markdown: str = None,
output_schema: Dict[str, Any] = None,
number_of_scrolls: int = None,
total_pages: int = None,
render_heavy_js: bool = None,
stealth: bool = None
) -> Dict[str, Any]:
"""
Extract structured data from a webpage using AI.
Args:
user_prompt: Instructions for what data to extract
website_url: URL of the webpage to scrape (mutually exclusive with website_html and website_markdown)
website_html: HTML content to process locally (mutually exclusive with website_url and website_markdown, max 2MB)
website_markdown: Markdown content to process locally (mutually exclusive with website_url and website_html, max 2MB)
output_schema: JSON schema defining expected output structure (optional)
number_of_scrolls: Number of infinite scrolls to perform (0-50, default 0)
total_pages: Number of pages to process for pagination (1-100, default 1)
render_heavy_js: Enable heavy JavaScript rendering for dynamic pages (default false)
stealth: Enable stealth mode to avoid bot detection (default false)
Returns:
Dictionary containing the extracted data
"""
url = f"{self.BASE_URL}/smartscraper"
data = {"user_prompt": user_prompt}
# Add input source (mutually exclusive)
if website_url is not None:
data["website_url"] = website_url
elif website_html is not None:
data["website_html"] = website_html
elif website_markdown is not None:
data["website_markdown"] = website_markdown
else:
raise ValueError("Must provide one of: website_url, website_html, or website_markdown")
# Add optional parameters
if output_schema is not None:
data["output_schema"] = output_schema
if number_of_scrolls is not None:
data["number_of_scrolls"] = number_of_scrolls
if total_pages is not None:
data["total_pages"] = total_pages
if render_heavy_js is not None:
data["render_heavy_js"] = render_heavy_js
if stealth is not None:
data["stealth"] = stealth
response = self.client.post(url, headers=self.headers, json=data)
if response.status_code != 200:
error_msg = f"Error {response.status_code}: {response.text}"
raise Exception(error_msg)
return response.json()
def smartscraper_status(self, request_id: str) -> Dict[str, Any]:
"""
Get the status of a smartscraper request.
Args:
request_id: The request ID to check status for
Returns:
Dictionary containing the request status and results
"""
url = f"{self.BASE_URL}/smartscraper/{request_id}"
response = self.client.get(url, headers=self.headers)
if response.status_code != 200:
error_msg = f"Error {response.status_code}: {response.text}"
raise Exception(error_msg)
return response.json()
def searchscraper(self, user_prompt: str, num_results: int = None, number_of_scrolls: int = None, time_range: str = None) -> Dict[str, Any]:
"""
Perform AI-powered web searches with structured results.
Args:
user_prompt: Search query or instructions
num_results: Number of websites to search (optional, default: 3 websites = 30 credits)
number_of_scrolls: Number of infinite scrolls to perform on each website (optional)
time_range: Filter results by time range (optional). Valid values: past_hour, past_24_hours, past_week, past_month, past_year
Returns:
Dictionary containing search results and reference URLs
"""
url = f"{self.BASE_URL}/searchscraper"
data = {
"user_prompt": user_prompt
}
# Add num_results to the request if provided
if num_results is not None:
data["num_results"] = num_results
# Add number_of_scrolls to the request if provided
if number_of_scrolls is not None:
data["number_of_scrolls"] = number_of_scrolls
# Add time_range to the request if provided
if time_range is not None:
data["time_range"] = time_range
response = self.client.post(url, headers=self.headers, json=data)
if response.status_code != 200:
error_msg = f"Error {response.status_code}: {response.text}"
raise Exception(error_msg)
return response.json()
def scrape(
self,
website_url: str,
render_heavy_js: Optional[bool] = None,
mock: Optional[bool] = None,
stealth: Optional[bool] = None,
stream: Optional[bool] = None
) -> Dict[str, Any]:
"""
Basic scrape endpoint to fetch page content.
Args:
website_url: URL to scrape
render_heavy_js: Whether to render heavy JS (optional)
mock: Return mock data for testing purposes (optional)
stealth: Enable stealth mode to avoid bot detection (optional)
stream: Enable streaming response for real-time updates (optional)
Returns:
Dictionary containing the scraped result
"""
url = f"{self.BASE_URL}/scrape"
payload: Dict[str, Any] = {"website_url": website_url}
if render_heavy_js is not None:
payload["render_heavy_js"] = render_heavy_js
if mock is not None:
payload["mock"] = mock
if stealth is not None:
payload["stealth"] = stealth
if stream is not None:
payload["stream"] = stream
response = self.client.post(url, headers=self.headers, json=payload)
response.raise_for_status()
return response.json()
def sitemap(self, website_url: str, stream: Optional[bool] = None) -> Dict[str, Any]:
"""
Extract sitemap for a given website.
Args:
website_url: Base website URL
stream: Enable streaming response for real-time updates (optional)
Returns:
Dictionary containing sitemap URLs/structure
"""
url = f"{self.BASE_URL}/sitemap"
payload: Dict[str, Any] = {"website_url": website_url}
if stream is not None:
payload["stream"] = stream
response = self.client.post(url, headers=self.headers, json=payload)
response.raise_for_status()
return response.json()
def agentic_scrapper(
self,
url: str,
user_prompt: Optional[str] = None,
output_schema: Optional[Dict[str, Any]] = None,
steps: Optional[List[str]] = None,
ai_extraction: Optional[bool] = None,
persistent_session: Optional[bool] = None,
timeout_seconds: Optional[float] = None,
) -> Dict[str, Any]:
"""
Run the Agentic Scraper workflow (no live session/browser interaction).
Args:
url: Target website URL
user_prompt: Instructions for what to do/extract (optional)
output_schema: Desired structured output schema (optional)
steps: High-level steps/instructions for the agent (optional)
ai_extraction: Whether to enable AI extraction mode (optional)
persistent_session: Whether to keep session alive between steps (optional)
timeout_seconds: Per-request timeout override in seconds (optional)
"""
endpoint = f"{self.BASE_URL}/agentic-scrapper"
payload: Dict[str, Any] = {"url": url}
if user_prompt is not None:
payload["user_prompt"] = user_prompt
if output_schema is not None:
payload["output_schema"] = output_schema
if steps is not None:
payload["steps"] = steps
if ai_extraction is not None:
payload["ai_extraction"] = ai_extraction
if persistent_session is not None:
payload["persistent_session"] = persistent_session
if timeout_seconds is not None:
response = self.client.post(endpoint, headers=self.headers, json=payload, timeout=timeout_seconds)
else:
response = self.client.post(endpoint, headers=self.headers, json=payload)
response.raise_for_status()
return response.json()
def smartcrawler_initiate(
self,
url: str,
prompt: str = None,
extraction_mode: str = "ai",
depth: int = None,
max_pages: int = None,
same_domain_only: bool = None
) -> Dict[str, Any]:
"""
Initiate a SmartCrawler request for multi-page web crawling.
SmartCrawler supports two modes:
- AI Extraction Mode (10 credits per page): Extracts structured data based on your prompt
- Markdown Conversion Mode (2 credits per page): Converts pages to clean markdown
Smartcrawler takes some time to process the request and returns the request id.
Use smartcrawler_fetch_results to get the results of the request.
You have to keep polling the smartcrawler_fetch_results until the request is complete.
The request is complete when the status is "completed".
Args:
url: Starting URL to crawl
prompt: AI prompt for data extraction (required for AI mode)
extraction_mode: "ai" for AI extraction or "markdown" for markdown conversion (default: "ai")
depth: Maximum link traversal depth (optional)
max_pages: Maximum number of pages to crawl (optional)
same_domain_only: Whether to crawl only within the same domain (optional)
Returns:
Dictionary containing the request ID for async processing
"""
endpoint = f"{self.BASE_URL}/crawl"
data = {
"url": url
}
# Handle extraction mode
if extraction_mode == "markdown":
data["markdown_only"] = True
elif extraction_mode == "ai":
if prompt is None:
raise ValueError("prompt is required when extraction_mode is 'ai'")
data["prompt"] = prompt
else:
raise ValueError(f"Invalid extraction_mode: {extraction_mode}. Must be 'ai' or 'markdown'")
if depth is not None:
data["depth"] = depth
if max_pages is not None:
data["max_pages"] = max_pages
if same_domain_only is not None:
data["same_domain_only"] = same_domain_only
response = self.client.post(endpoint, headers=self.headers, json=data)
if response.status_code != 200:
error_msg = f"Error {response.status_code}: {response.text}"
raise Exception(error_msg)
return response.json()
def smartcrawler_fetch_results(self, request_id: str) -> Dict[str, Any]:
"""
Fetch the results of a SmartCrawler operation.
Args:
request_id: The request ID returned by smartcrawler_initiate
Returns:
Dictionary containing the crawled data (structured extraction or markdown)
and metadata about processed pages
Note:
It takes some time to process the request and returns the results.
Meanwhile it returns the status of the request.
You have to keep polling the smartcrawler_fetch_results until the request is complete.
The request is complete when the status is "completed". and you get results
Keep polling the smartcrawler_fetch_results until the request is complete.
"""
endpoint = f"{self.BASE_URL}/crawl/{request_id}"
response = self.client.get(endpoint, headers=self.headers)
if response.status_code != 200:
error_msg = f"Error {response.status_code}: {response.text}"
raise Exception(error_msg)
return response.json()
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 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 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):
"""Health check endpoint for container orchestration and load balancers."""
from starlette.responses import JSONResponse
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
## Available Tools Overview
### 1. **markdownify** - Convert webpages to clean markdown
**Use case**: Get clean, readable content from any webpage
**Example**:
- Input: `https://docs.python.org/3/tutorial/`
- Output: Clean markdown of the Python tutorial
### 2. **smartscraper** - AI-powered data extraction
**Use case**: Extract specific structured data using natural language prompts
**Examples**:
- "Extract all product names and prices from this e-commerce page"
- "Get contact information including email, phone, and address"
- "Find all article titles, authors, and publication dates"
### 3. **searchscraper** - AI web search with extraction
**Use case**: Search the web and extract structured information
**Examples**:
- "Find the latest AI research papers and their abstracts"
- "Search for Python web scraping tutorials with ratings"
- "Get current cryptocurrency prices and market caps"
### 4. **smartcrawler_initiate** - Multi-page intelligent crawling
**Use case**: Crawl multiple pages with AI extraction or markdown conversion
**Modes**:
- AI Mode (10 credits/page): Extract structured data
- Markdown Mode (2 credits/page): Convert to markdown
**Example**: Crawl a documentation site to extract all API endpoints
### 5. **smartcrawler_fetch_results** - Get crawling results
**Use case**: Retrieve results from initiated crawling operations
**Note**: Keep polling until status is "completed"
### 6. **scrape** - Basic page content fetching
**Use case**: Get raw page content with optional JavaScript rendering
**Example**: Fetch content from dynamic pages that require JS
### 7. **sitemap** - Extract website structure
**Use case**: Get all URLs and structure of a website
**Example**: Map out a website's architecture before crawling
### 8. **agentic_scrapper** - AI-powered automated scraping
**Use case**: Complex multi-step scraping with AI automation
**Example**: Navigate through forms, click buttons, extract data
## Best Practices
1. **Start Simple**: Use `markdownify` or `scrape` for basic content
2. **Be Specific**: Provide detailed prompts for better AI extraction
3. **Use Crawling Wisely**: Set appropriate limits for `max_pages` and `depth`
4. **Monitor Credits**: AI extraction uses more credits than markdown conversion
5. **Handle Async**: Use `smartcrawler_fetch_results` to poll for completion
## Common Workflows
### Extract Product Information
1. Use `smartscraper` with prompt: "Extract product name, price, description, and availability"
2. For multiple pages: Use `smartcrawler_initiate` in AI mode
### Research and Analysis
1. Use `searchscraper` to find relevant pages
2. Use `smartscraper` on specific pages for detailed extraction
### Site Documentation
1. Use `sitemap` to discover all pages
2. Use `smartcrawler_initiate` in markdown mode to convert all pages
### Complex Navigation
1. Use `agentic_scrapper` for sites requiring interaction
2. Provide step-by-step instructions in the `steps` parameter
"""
@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 Examples
## π Ready-to-Use Examples
### Extract E-commerce Product Data
```
Tool: smartscraper
URL: https://example-shop.com/products/laptop
Prompt: "Extract product name, price, specifications, customer rating, and availability status"
```
### Convert Documentation to Markdown
```
Tool: markdownify
URL: https://docs.example.com/api-reference
```
### Research Latest News
```
Tool: searchscraper
Prompt: "Find latest news about artificial intelligence breakthroughs in 2024"
num_results: 5
```
### Crawl Entire Blog for Articles
```
Tool: smartcrawler_initiate
URL: https://blog.example.com
Prompt: "Extract article title, author, publication date, and summary"
extraction_mode: "ai"
max_pages: 20
```
### Get Website Structure
```
Tool: sitemap
URL: https://example.com
```
### Extract Contact Information
```
Tool: smartscraper
URL: https://company.example.com/contact
Prompt: "Find all contact methods: email addresses, phone numbers, physical address, and social media links"
```
### Automated Form Navigation
```
Tool: agentic_scrapper
URL: https://example.com/search
user_prompt: "Navigate to the search page, enter 'web scraping tools', and extract the top 5 results"
steps: ["Find search box", "Enter search term", "Submit form", "Extract results"]
```
## π‘ Pro Tips
1. **For Dynamic Content**: Use `render_heavy_js: true` with the `scrape` tool
2. **For Large Sites**: Start with `sitemap` to understand structure
3. **For Async Operations**: Always poll `smartcrawler_fetch_results` until complete
4. **For Complex Sites**: Use `agentic_scrapper` with detailed step instructions
5. **For Cost Efficiency**: Use markdown mode for content conversion, AI mode for data extraction
## π§ Configuration
Set your API key via:
- Environment variable: `SGAI_API_KEY=your_key_here`
- MCP configuration: `scrapegraph_api_key: "your_key_here"`
No configuration required - the server works with environment variables!
"""
# 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
## Server Information
- **Status**: β
Online and Ready
- **Version**: 1.0.0
- **Base URL**: https://api.scrapegraphai.com/v1
## Available Tools
1. **markdownify** - Convert webpages to markdown (2 credits/page)
2. **smartscraper** - AI data extraction (10 credits/page)
3. **searchscraper** - AI web search (30 credits for 3 websites)
4. **smartcrawler** - Multi-page crawling (2-10 credits/page)
5. **scrape** - Basic page fetching (1 credit/page)
6. **sitemap** - Website structure extraction (1 credit)
7. **agentic_scrapper** - AI automation (variable credits)
## Credit Costs
- **Markdown Conversion**: 2 credits per page
- **AI Extraction**: 10 credits per page
- **Web Search**: 10 credits per website (default 3 websites)
- **Basic Scraping**: 1 credit per page
- **Sitemap**: 1 credit per request
## Configuration
- **API Key**: Required (set via SGAI_API_KEY env var or config)
- **Timeout**: 120 seconds default (configurable)
- **Rate Limits**: Applied per API key
## Best Practices
- Use markdown mode for content conversion (cheaper)
- Use AI mode for structured data extraction
- Set appropriate limits for crawling operations
- Monitor credit usage for cost optimization
Last Updated: $(date)
"""
@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
## π 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, sitemap, agentic_scrapper
#### `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