Skip to content

Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.

feat(deep-audit): Add Phase 1 - Content accuracy audit system

Jez3e03966a686f
diff --git a/.gitignore b/.gitignore
index fc2a9c6b..6f22f264 100644
--- a/.gitignore
+++ b/.gitignore
@@ -59,3 +59,6 @@ SESSION.md # Working session tracking (constantly changing)
SKILLS_CATALOG.md # Generated catalog (regenerate with scripts)
archive/session-logs/ # Working audit logs (archived when needed)
.claude/settings.local.json # Local Claude Code settings
+.venv/
+archive/audit-cache/*
+!archive/audit-cache/.gitkeep
diff --git a/archive/audit-cache/.gitkeep b/archive/audit-cache/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/commands/deep-audit.md b/commands/deep-audit.md
new file mode 100644
index 00000000..f63a517c
--- /dev/null
+++ b/commands/deep-audit.md
@@ -0,0 +1,183 @@
+# /deep-audit - Content Accuracy Audit
+
+Validate skill CONTENT against official documentation using Firecrawl for web scraping and sub-agents for semantic comparison. Complements version-number audits by catching content errors.
+
+## Usage
+
+```bash
+/deep-audit <skill-name> # Audit single skill
+/deep-audit cloudflare-* # Audit skills matching pattern
+/deep-audit --tier 1 # Audit all Tier 1 skills
+/deep-audit --all # Audit all skills (expensive)
+/deep-audit --diff <skill-name> # Only if docs changed since last audit
+```
+
+## What This Does
+
+Unlike `/audit` which checks structural aspects (YAML frontmatter, file organization), `/deep-audit` validates that skill **content** matches current official documentation.
+
+**Problem it solves**: Version audits can pass while content is wrong. Example: fastmcp skill referenced npm version 3.26.8 when the Python package (PyPI) is at 2.14.2 - completely different ecosystem!
+
+## Prerequisites
+
+1. **Firecrawl API Key**: Set in environment or `.env`:
+ ```bash
+ export FIRECRAWL_API_KEY=fc-xxxxxxxx
+ ```
+
+2. **Skill Metadata**: Skills should have `doc_sources` in YAML frontmatter:
+ ```yaml
+ metadata:
+ doc_sources:
+ primary: "https://docs.example.com/getting-started"
+ api: "https://docs.example.com/api-reference"
+ changelog: "https://github.com/org/repo/releases"
+ ecosystem: pypi # npm | pypi | github
+ package_name: example-package
+ ```
+
+## Workflow
+
+### Step 1: Discovery
+
+Extract documentation URLs from skill's `metadata.doc_sources`. If not present, attempt to infer from:
+- Links in SKILL.md
+- Package registry (npm/PyPI) URLs
+- GitHub repository
+
+### Step 2: Scrape Documentation
+
+Use Firecrawl to fetch official docs as markdown:
+
+```bash
+python scripts/deep-audit-scrape.py <skill-name>
+```
+
+Output cached to `archive/audit-cache/<skill>/`:
+- `YYYY-MM-DD_primary.md` - Scraped content
+- `YYYY-MM-DD_hash` - Content hash for change detection
+
+### Step 3: Sub-Agent Comparison
+
+Launch 4 parallel sub-agents to compare skill against scraped docs:
+
+| Agent | Focus | Checks |
+|-------|-------|--------|
+| **API Coverage** | Methods & features | Are documented APIs covered in skill? Missing new features? |
+| **Pattern Validation** | Code examples | Deprecated syntax? New patterns not reflected? |
+| **Error Check** | Known issues | Fixed bugs still documented? New common errors? |
+| **Ecosystem** | Package info | Correct registry? Right install commands? Version accuracy? |
+
+### Step 4: Generate Report
+
+Output to `planning/CONTENT_AUDIT_<skill>.md`:
+
+```markdown
+# Content Audit: <skill-name>
+**Date**: YYYY-MM-DD
+**Accuracy Score**: 85-92%
+
+## Summary
+- [x] API coverage current
+- [ ] 2 deprecated patterns found
+- [x] Error documentation accurate
+- [ ] Install command uses wrong package manager
+
+## Findings
+
+### Critical
+- Pattern `oldMethod()` deprecated in v2.0, skill still recommends
+
+### Warnings
+- New feature `newFeature()` not documented in skill
+- Changelog shows breaking change not mentioned
+
+### OK
+- Core concepts accurate
+- Error handling patterns correct
+```
+
+## Cost Estimates
+
+| Scope | Firecrawl Cost | Tokens |
+|-------|---------------|--------|
+| Single skill | ~$0.003 | ~35k |
+| Pattern (10 skills) | ~$0.03 | ~350k |
+| Tier 1 (10 skills) | ~$0.03 | ~350k |
+| All skills (68) | ~$0.20 | ~2.4M |
+
+**Optimization**:
+- Cache lasts 7 days
+- Use `--diff` flag to only audit if docs changed
+- Prioritize Tier 1/2 skills
+
+## Integration with Existing Tools
+
+| Tool | What It Checks | Relationship |
+|------|---------------|--------------|
+| `/audit` | Structure (YAML, files) | Run first for quick checks |
+| `review-skill.sh` | Links, versions, TODOs | Complements deep-audit |
+| `check-all-versions.sh` | Package version numbers | Deep-audit validates content |
+| **`/deep-audit`** | **Content accuracy** | **Catches semantic errors** |
+
+## Recommended Workflow
+
+```bash
+# 1. Quick structural audit
+/audit <skill-name>
+
+# 2. If passes, deep content audit
+/deep-audit <skill-name>
+
+# 3. Review findings
+cat planning/CONTENT_AUDIT_<skill>.md
+
+# 4. Fix issues and commit
+git add skills/<skill-name>/
+git commit -m "audit(<skill>): Fix content accuracy issues"
+```
+
+## Cache Management
+
+```bash
+# View cached audits
+ls archive/audit-cache/
+
+# Clear cache for skill (force re-scrape)
+rm -rf archive/audit-cache/<skill-name>/
+
+# Clear all cache
+rm -rf archive/audit-cache/*/
+```
+
+## Adding doc_sources to Skills
+
+For skills without `doc_sources`, add to YAML frontmatter:
+
+```yaml
+---
+name: my-skill
+description: |
+ [description]
+metadata:
+ doc_sources:
+ primary: "https://official-docs.com/getting-started"
+ api: "https://official-docs.com/api"
+ changelog: "https://github.com/org/repo/releases"
+ ecosystem: npm # or pypi, github
+ package_name: package-name
+---
+```
+
+## Example: fastmcp Audit
+
+```bash
+/deep-audit fastmcp
+```
+
+**Found Issue** (actual example that motivated this tool):
+- Skill referenced `fastmcp>=3.26.8` (npm package)
+- PyPI shows `fastmcp>=2.14.2` (Python package)
+- **Completely different ecosystems!**
+
+This error passed all version checks because the npm version exists - but the skill is for Python!
diff --git a/scripts/deep-audit-scrape.py b/scripts/deep-audit-scrape.py
new file mode 100755
index 00000000..f009a973
--- /dev/null
+++ b/scripts/deep-audit-scrape.py
@@ -0,0 +1,414 @@
+#!/usr/bin/env python3
+"""
+Deep Audit Documentation Scraper
+
+Scrapes official documentation for a skill using Firecrawl API.
+Outputs markdown to archive/audit-cache/<skill>/ with content hashing for change detection.
+
+Requirements:
+ pip install firecrawl-py python-dotenv pyyaml
+
+Environment Variables:
+ FIRECRAWL_API_KEY - Your Firecrawl API key
+
+Usage:
+ python scripts/deep-audit-scrape.py <skill-name>
+ python scripts/deep-audit-scrape.py fastmcp
+ python scripts/deep-audit-scrape.py --list-sources fastmcp
+ python scripts/deep-audit-scrape.py --force fastmcp # Ignore cache
+"""
+
+import argparse
+import hashlib
+import json
+import os
+import re
+import sys
+from datetime import datetime
+from pathlib import Path
+
+import yaml
+from dotenv import load_dotenv
+
+# Load environment variables
+load_dotenv()
+
+# Constants
+REPO_ROOT = Path(__file__).parent.parent
+SKILLS_DIR = REPO_ROOT / "skills"
+CACHE_DIR = REPO_ROOT / "archive" / "audit-cache"
+CACHE_DAYS = 7 # Cache validity in days
+
+
+def parse_skill_frontmatter(skill_path: Path) -> dict:
+ """
+ Parse YAML frontmatter from SKILL.md.
+
+ Returns dict with keys: name, description, metadata (including doc_sources)
+ """
+ skill_md = skill_path / "SKILL.md"
+ if not skill_md.exists():
+ raise FileNotFoundError(f"SKILL.md not found at {skill_md}")
+
+ content = skill_md.read_text(encoding="utf-8")
+
+ # Extract YAML frontmatter
+ frontmatter_match = re.match(r"^---\s*\n(.*?)\n---", content, re.DOTALL)
+ if not frontmatter_match:
+ return {}
+
+ try:
+ return yaml.safe_load(frontmatter_match.group(1)) or {}
+ except yaml.YAMLError as e:
+ print(f"Warning: Failed to parse YAML frontmatter: {e}")
+ return {}
+
+
+def extract_doc_urls_from_content(skill_path: Path) -> list[str]:
+ """
+ Extract documentation URLs from SKILL.md content.
+ Fallback when metadata.doc_sources is not present.
+ """
+ skill_md = skill_path / "SKILL.md"
+ content = skill_md.read_text(encoding="utf-8")
+
+ # Find all HTTPS URLs that look like documentation
+ url_pattern = r'https?://[^\s\)\]"\'<>]+'
+ urls = re.findall(url_pattern, content)
+
+ # Filter for documentation-like URLs
+ doc_indicators = ['docs', 'documentation', 'guide', 'getting-started', 'reference', 'api']
+ doc_urls = []
+
+ for url in urls:
+ url_lower = url.lower()
+ # Skip GitHub raw/blob URLs (code, not docs)
+ if 'github.com' in url_lower and ('/blob/' in url_lower or '/raw/' in url_lower):
+ continue
+ # Check for doc indicators
+ if any(ind in url_lower for ind in doc_indicators):
+ doc_urls.append(url)
+
+ return list(set(doc_urls))[:3] # Limit to 3 URLs
+
+
+def get_doc_sources(skill_name: str) -> dict:
+ """
+ Get documentation sources for a skill.
+
+ Returns dict with keys like: primary, api, changelog
+ """
+ skill_path = SKILLS_DIR / skill_name
+ if not skill_path.exists():
+ raise FileNotFoundError(f"Skill not found: {skill_name}")
+
+ frontmatter = parse_skill_frontmatter(skill_path)
+
+ # Check for metadata.doc_sources
+ metadata = frontmatter.get("metadata", {})
+ doc_sources = metadata.get("doc_sources", {})
+
+ if doc_sources:
+ return doc_sources
+
+ # Fallback: extract URLs from content
+ urls = extract_doc_urls_from_content(skill_path)
+ if urls:
+ doc_sources = {"primary": urls[0]}
+ if len(urls) > 1:
+ doc_sources["secondary"] = urls[1]
+ if len(urls) > 2:
+ doc_sources["tertiary"] = urls[2]
+ return doc_sources
+
+ return {}
+
+
+def compute_content_hash(content: str) -> str:
+ """Compute SHA256 hash of content for change detection."""
+ return hashlib.sha256(content.encode("utf-8")).hexdigest()[:16]
+
+
+def is_cache_valid(cache_path: Path) -> bool:
+ """Check if cached content is still valid (within CACHE_DAYS)."""
+ if not cache_path.exists():
+ return False
+
+ # Check modification time
+ mtime = datetime.fromtimestamp(cache_path.stat().st_mtime)
+ age_days = (datetime.now() - mtime).days
+
+ return age_days < CACHE_DAYS
+
+
+def scrape_url(url: str) -> dict:
+ """
+ Scrape a URL using Firecrawl API (v4+).
+
+ Returns dict with: markdown, metadata
+ """
+ try:
+ from firecrawl import Firecrawl
+ except ImportError:
+ print("Error: firecrawl-py not installed. Run: pip install firecrawl-py")
+ sys.exit(1)
+
+ api_key = os.environ.get("FIRECRAWL_API_KEY")
+ if not api_key:
+ print("Error: FIRECRAWL_API_KEY environment variable not set")
+ print("Get your key at: https://www.firecrawl.dev")
+ sys.exit(1)
+
+ app = Firecrawl(api_key=api_key)
+
+ print(f" Scraping: {url}")
+
+ try:
+ # Firecrawl v4 API: scrape(url, formats=[], ...)
+ # Returns a Pydantic Document object
+ doc = app.scrape(
+ url=url,
+ formats=["markdown"],
+ only_main_content=True,
+ remove_base64_images=True,
+ )
+ # Convert to dict for consistent handling
+ return {
+ "markdown": doc.markdown or "",
+ "metadata": doc.metadata_dict if hasattr(doc, "metadata_dict") else {},
+ }
+ except Exception as e:
+ print(f" Error scraping {url}: {e}")
+ return {"markdown": "", "error": str(e)}
+
+
+def scrape_skill_docs(skill_name: str, force: bool = False) -> dict:
+ """
+ Scrape all documentation sources for a skill.
+
+ Args:
+ skill_name: Name of the skill
+ force: If True, ignore cache and re-scrape
+
+ Returns dict with:
+ sources: dict of source_name -> {url, markdown, hash, cached}
+ cache_dir: Path to cache directory
+ date: Scrape date (YYYY-MM-DD)
+ """
+ doc_sources = get_doc_sources(skill_name)
+
+ if not doc_sources:
+ print(f"Warning: No doc_sources found for {skill_name}")
+ print("Add metadata.doc_sources to SKILL.md frontmatter")
+ return {"sources": {}, "cache_dir": None, "date": None}
+
+ # Create cache directory
+ cache_dir = CACHE_DIR / skill_name
+ cache_dir.mkdir(parents=True, exist_ok=True)
+
+ today = datetime.now().strftime("%Y-%m-%d")
+ results = {}
+
+ for source_name, url in doc_sources.items():
+ cache_file = cache_dir / f"{today}_{source_name}.md"
+ hash_file = cache_dir / f"{today}_{source_name}.hash"
+
+ # Check cache
+ if not force and is_cache_valid(cache_file):
+ print(f" Using cached: {source_name}")
+ markdown = cache_file.read_text(encoding="utf-8")
+ content_hash = hash_file.read_text(encoding="utf-8") if hash_file.exists() else ""
+ results[source_name] = {
+ "url": url,
+ "markdown": markdown,
+ "hash": content_hash,
+ "cached": True,
+ }
+ continue
+
+ # Scrape fresh
+ result = scrape_url(url)
+ markdown = result.get("markdown", "")
+
+ if markdown:
+ # Save to cache
+ cache_file.write_text(markdown, encoding="utf-8")
+ content_hash = compute_content_hash(markdown)
+ hash_file.write_text(content_hash, encoding="utf-8")
+
+ results[source_name] = {
+ "url": url,
+ "markdown": markdown,
+ "hash": content_hash,
+ "cached": False,
+ }
+ else:
+ results[source_name] = {
+ "url": url,
+ "markdown": "",
+ "hash": "",
+ "cached": False,
+ "error": result.get("error", "Unknown error"),
+ }
+
+ # Update history.json
+ history_file = cache_dir / "history.json"
+ history = []
+ if history_file.exists():
+ try:
+ history = json.loads(history_file.read_text(encoding="utf-8"))
+ except json.JSONDecodeError:
+ history = []
+
+ history.append({
+ "date": today,
+ "sources": {
+ name: {
+ "url": data["url"],
+ "hash": data["hash"],
+ "cached": data["cached"],
+ }
+ for name, data in results.items()
+ }
+ })
+
+ # Keep last 10 audit records
+ history = history[-10:]
+ history_file.write_text(json.dumps(history, indent=2), encoding="utf-8")
+
+ return {
+ "sources": results,
+ "cache_dir": cache_dir,
+ "date": today,
+ }
+
+
+def check_for_changes(skill_name: str) -> dict:
+ """
+ Check if documentation has changed since last audit.
+
+ Returns dict with:
+ changed: bool
+ changes: list of {source, old_hash, new_hash}
+ """
+ cache_dir = CACHE_DIR / skill_name
+ history_file = cache_dir / "history.json"
+
+ if not history_file.exists():
+ return {"changed": True, "changes": [], "reason": "No previous audit"}
+
+ try:
+ history = json.loads(history_file.read_text(encoding="utf-8"))
+ except json.JSONDecodeError:
+ return {"changed": True, "changes": [], "reason": "Corrupted history"}
+
+ if not history:
+ return {"changed": True, "changes": [], "reason": "Empty history"}
+
+ last_audit = history[-1]
+ doc_sources = get_doc_sources(skill_name)
+
+ changes = []
+ for source_name, url in doc_sources.items():
+ # Quick scrape to get current hash
+ result = scrape_url(url)
+ current_hash = compute_content_hash(result.get("markdown", ""))
+
+ old_hash = last_audit.get("sources", {}).get(source_name, {}).get("hash", "")
+
+ if current_hash != old_hash:
+ changes.append({
+ "source": source_name,
+ "old_hash": old_hash,
+ "new_hash": current_hash,
+ })
+
+ return {
+ "changed": len(changes) > 0,
+ "changes": changes,
+ }
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Scrape documentation for deep audit")
+ parser.add_argument("skill", help="Skill name to audit")
+ parser.add_argument("--list-sources", action="store_true", help="List doc sources without scraping")
+ parser.add_argument("--force", action="store_true", help="Ignore cache, force re-scrape")
+ parser.add_argument("--check-changes", action="store_true", help="Only check if docs changed")
+ parser.add_argument("--output", help="Custom output directory")
+
+ args = parser.parse_args()
+
+ skill_name = args.skill
+
+ # Check skill exists
+ skill_path = SKILLS_DIR / skill_name
+ if not skill_path.exists():
+ print(f"Error: Skill not found: {skill_name}")
+ print(f"Available skills: {', '.join(sorted(d.name for d in SKILLS_DIR.iterdir() if d.is_dir()))[:200]}...")
+ sys.exit(1)
+
+ print(f"Deep Audit: {skill_name}")
+ print("=" * 50)
+
+ # List sources only
+ if args.list_sources:
+ doc_sources = get_doc_sources(skill_name)
+ if doc_sources:
+ print("\nDoc Sources:")
+ for name, url in doc_sources.items():
+ print(f" {name}: {url}")
+ else:
+ print("\nNo doc_sources found. Add to SKILL.md frontmatter:")
+ print(" metadata:")
+ print(" doc_sources:")
+ print(' primary: "https://docs.example.com"')
+ return
+
+ # Check changes only
+ if args.check_changes:
+ print("\nChecking for documentation changes...")
+ result = check_for_changes(skill_name)
+ if result["changed"]:
+ print("Documentation HAS CHANGED:")
+ for change in result.get("changes", []):
+ print(f" {change['source']}: {change['old_hash'][:8]} -> {change['new_hash'][:8]}")
+ if result.get("reason"):
+ print(f" Reason: {result['reason']}")
+ else:
+ print("Documentation unchanged since last audit")
+ return
+
+ # Full scrape
+ print("\nScraping documentation...")
+ result = scrape_skill_docs(skill_name, force=args.force)
+
+ if not result["sources"]:
+ print("\nNo documentation scraped.")
+ return
+
+ print(f"\nResults cached to: {result['cache_dir']}")
+ print("\nScraped sources:")
+ for name, data in result["sources"].items():
+ status = "cached" if data["cached"] else "fresh"
+ size = len(data["markdown"])
+ print(f" {name}: {size:,} chars ({status})")
+ if data.get("error"):
+ print(f" Error: {data['error']}")
+
+ # Print summary for Claude to use
+ print("\n" + "=" * 50)
+ print("DOCUMENTATION CONTENT SUMMARY")
+ print("=" * 50)
+
+ for name, data in result["sources"].items():
+ if data["markdown"]:
+ # Print first 500 chars as preview
+ preview = data["markdown"][:500].replace("\n", " ")[:200]
+ print(f"\n[{name.upper()}] {data['url']}")
+ print(f"Preview: {preview}...")
+ print(f"Full content: {result['cache_dir']}/{result['date']}_{name}.md")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/fastmcp/SKILL.md b/skills/fastmcp/SKILL.md
index 1e9e299a..f7780a7e 100644
--- a/skills/fastmcp/SKILL.md
+++ b/skills/fastmcp/SKILL.md
@@ -8,6 +8,17 @@ description: |
storage backends for tokens/cache, adding middleware for logging/rate limiting, deploying to FastMCP Cloud,
or troubleshooting module-level server, storage, lifespan, middleware order, circular imports, or OAuth errors.
+metadata:
+ doc_sources:
+ primary: "https://gofastmcp.com/getting-started/welcome"
+ server: "https://gofastmcp.com/servers/fastmcp"
+ tools: "https://gofastmcp.com/servers/tools"
+ resources: "https://gofastmcp.com/servers/resources"
+ changelog: "https://github.com/jlowin/fastmcp/releases"
+ ecosystem: pypi
+ package_name: fastmcp
+ tier: 2
+ last_verified: "2026-01-09"
---
# FastMCP - Build MCP Servers in Python
diff --git a/skills/firecrawl-scraper/.claude-plugin/plugin.json b/skills/firecrawl-scraper/.claude-plugin/plugin.json
new file mode 100644
index 00000000..1582bbcc
--- /dev/null
+++ b/skills/firecrawl-scraper/.claude-plugin/plugin.json
@@ -0,0 +1,12 @@
+{
+ "name": "firecrawl-scraper",
+ "description": "Complete knowledge domain for Firecrawl v2 API - web scraping and crawling that converts websites into LLM-ready markdown or structured data. Use when: scraping websites, crawling entire sites, extracting web content, converting HTML to markdown, building web scrapers, handling dynamic JavaScript content, bypassing anti-bot protection, extracting structured data from web pages, or when encountering content not loading, JavaScript rendering issues, or blocked by bot detection.",
+ "version": "1.0.0",
+ "author": {
+ "name": "Jeremy Dawes",
+ "email": "[email protected]"
+ },
+ "license": "MIT",
+ "repository": "https://github.com/jezweb/claude-skills",
+ "keywords": ["firecrawl","firecrawl api","web scraping","web crawler","scrape website","crawl website","extract content","html to markdown","site crawler","content extraction","web automation","firecrawl-py","firecrawl-js","llm ready data","structured data extraction"]
+}
diff --git a/skills/firecrawl-scraper/README.md b/skills/firecrawl-scraper/README.md
new file mode 100644
index 00000000..a7079b43
--- /dev/null
+++ b/skills/firecrawl-scraper/README.md
@@ -0,0 +1,341 @@
+# Firecrawl Web Scraper
+
+**Status**: ✅ Production Ready
+**Last Updated**: 2025-10-24
+**API Version**: v2
+**Official Docs**: https://docs.firecrawl.dev
+
+---
+
+## What This Skill Does
+
+Provides complete knowledge for using Firecrawl v2 API - a web scraping service that converts websites into LLM-ready markdown or structured data. This skill covers:
+
+- **Single page scraping** with `/v2/scrape` endpoint
+- **Full site crawling** with `/v2/crawl` endpoint
+- **URL discovery** with `/v2/map` endpoint
+- **Structured data extraction** with `/v2/extract` endpoint
+- **Python SDK** (firecrawl-py v4.5.0+)
+- **TypeScript/Node.js SDK** (firecrawl-js v1.7.x+)
+- **JavaScript rendering**, anti-bot bypass, screenshot capture
+- **Error handling**, rate limits, and best practices
+- **Cloudflare Workers integration**
+
+**Prevents common issues** with API authentication, rate limiting, timeout errors, and content extraction failures.
+
+---
+
+## Auto-Trigger Keywords
+
+Claude automatically uses this skill when you mention:
+
+### Primary Triggers (Technologies)
+- firecrawl
+- firecrawl api
+- firecrawl-py
+- firecrawl-js
+- web scraping
+- web crawler
+- site crawler
+- scrape website
+- crawl website
+- web scraper
+
+### Secondary Triggers (Use Cases)
+- extract web content
+- html to markdown
+- convert website to markdown
+- scrape documentation
+- crawl documentation site
+- extract structured data
+- parse website
+- content extraction
+- web automation
+- website to llm
+- llm ready data
+- rag from website
+- scrape articles
+- extract product data
+- map website urls
+
+### Error-Based Triggers
+- "content not loading"
+- "javascript rendering issues"
+- "blocked by bot detection"
+- "scraping blocked"
+- "captcha blocking scraper"
+- "dynamic content not scraping"
+- "anti-bot protection"
+- "scraper detected"
+- "cloudflare challenge"
+- "timeout scraping"
+- "empty scrape result"
+- "rate limit exceeded firecrawl"
+- "invalid api key firecrawl"
+
+### Framework Integration
+- firecrawl cloudflare workers
+- firecrawl python
+- firecrawl typescript
+- firecrawl node.js
+- scraping with cloudflare
+- serverless web scraping
+
+---
+
+## Known Issues Prevented
+
+| Issue | Error Message | Prevention |
+|-------|---------------|------------|
+| **#1: API Key Not Set** | "Invalid API Key" | Proper environment variable setup with examples |
+| **#2: Rate Limits** | "Rate limit exceeded" | Best practices for credit optimization |
+| **#3: Timeout Errors** | "Request timeout" | `waitFor` parameter configuration |
+| **#4: Empty Content** | "Content is empty" | JavaScript rendering with actions/wait strategies |
+| **#5: Bot Detection** | "Access denied" | Firecrawl's built-in anti-bot bypass |
+| **#6: Hardcoded API Keys** | Security vulnerability | Environment variable patterns |
+
+---
+
+## Quick Start
+
+### Python
+
+```bash
+# Install
+pip install firecrawl-py
+
+# Set API key
+export FIRECRAWL_API_KEY=fc-your-api-key
+```
+
+```python
+import os
+from firecrawl import FirecrawlApp
+
+app = FirecrawlApp(api_key=os.environ.get("FIRECRAWL_API_KEY"))
+
+# Scrape single page
+result = app.scrape_url("https://example.com", params={
+ "formats": ["markdown"],
+ "onlyMainContent": True
+})
+
+print(result.get("markdown"))
+```
+
+### TypeScript/Node.js
+
+```bash
+# Install
+npm install @mendable/firecrawl-js
+# or: npm install firecrawl
+
+# Set API key
+export FIRECRAWL_API_KEY=fc-your-api-key
+```
+
+```typescript
+import FirecrawlApp from '@mendable/firecrawl-js';
+
+const app = new FirecrawlApp({
+ apiKey: process.env.FIRECRAWL_API_KEY
+});
+
+// Scrape single page
+const result = await app.scrapeUrl('https://example.com', {
+ formats: ['markdown'],
+ onlyMainContent: true
+});
+
+console.log(result.markdown);
+```
+
+**Full instructions**: See `SKILL.md`
+
+---
+
+## ⚠️ Cloudflare Workers Compatibility
+
+**Important**: The Firecrawl SDK uses Node.js dependencies (`axios`) and **cannot run in Cloudflare Workers**.
+
+**For Cloudflare Workers**, use one of these approaches:
+- ✅ **Direct REST API** with `fetch` (recommended - see `templates/firecrawl-worker-fetch.ts`)
+- ✅ **Self-hosted**: [workers-firecrawl](https://github.com/G4brym/workers-firecrawl) (requires Workers Paid Plan)
+
+**For other environments** (Node.js, serverless functions, Python):
+- ✅ Use the SDK normally as documented above
+
+See the **Cloudflare Workers Integration** section in `SKILL.md` for complete working examples.
+
+---
+
+## Token Savings Estimate
+
+**Without this skill**: ~10,000 tokens (API docs lookup + trial-and-error + debugging)
+**With this skill**: ~4,000 tokens (direct implementation with best practices)
+
+**Savings**: ~60% token reduction + prevents all 6 common issues
+
+---
+
+## File Structure
+
+```
+firecrawl-scraper/
+├── SKILL.md # Full instructions (read this first)
+├── README.md # This file
+├── templates/ # Copy-ready code templates
+│ ├── firecrawl-scrape-python.py # Basic Python scraping (Node.js/Python)
+│ ├── firecrawl-scrape-typescript.ts # Basic TypeScript scraping (Node.js)
+│ ├── firecrawl-worker-fetch.ts # Cloudflare Workers (fetch API)
+│ └── firecrawl-crawl-example.py # Full crawl with storage
+└── reference/ # Deep-dive documentation
+ ├── endpoints.md # All 4 API endpoints explained
+ └── common-patterns.md # Error handling, retries, batching
+```
+
+---
+
+## Package Versions (Verified 2025-10-24)
+
+| Package | Version | Status |
+|---------|---------|--------|
+| firecrawl-py | 4.5.0+ | ✅ Latest stable |
+| @mendable/firecrawl-js (or firecrawl) | 4.4.1+ | ✅ Latest stable (Node.js >=22.0.0) |
+| API Version | v2 | ✅ Current |
+
+**Note**: Node.js SDK cannot run in Cloudflare Workers. Use direct REST API (see templates/firecrawl-worker-fetch.ts).
+
+---
+
+## When to Use This Skill
+
+✅ **Use this skill when:**
+- Scraping modern websites with JavaScript
+- Converting websites to markdown for RAG/LLMs
+- Extracting structured data from web pages
+- Building documentation scrapers
+- Need to bypass bot protection
+- Crawling entire sites
+- Handling dynamic content
+
+❌ **Don't use this skill for:**
+- Simple static HTML scraping (use BeautifulSoup/Cheerio)
+- APIs with official SDKs (use the SDK directly)
+- Sites you control (just export the data)
+- Real-time live data (consider WebSockets/SSE)
+
+---
+
+## API Endpoints Overview
+
+1. **`/v2/scrape`** - Scrape a single webpage
+ - Best for: Articles, product pages, specific URLs
+ - Returns: Markdown, HTML, screenshot
+
+2. **`/v2/crawl`** - Crawl entire website
+ - Best for: Documentation sites, full site archives
+ - Returns: Array of scraped pages
+
+3. **`/v2/map`** - Discover all URLs on site
+ - Best for: Sitemap generation, planning crawls
+ - Returns: List of URLs found
+
+4. **`/v2/extract`** - Extract structured data with AI
+ - Best for: Product catalogs, directory listings
+ - Returns: JSON matching your schema
+
+---
+
+## Common Use Cases
+
+### 1. Documentation Scraping for RAG
+```python
+docs = app.crawl_url("https://docs.example.com", params={
+ "limit": 500,
+ "scrapeOptions": {"formats": ["markdown"]}
+})
+```
+
+### 2. Product Data Extraction
+```typescript
+const schema = z.object({
+ title: z.string(),
+ price: z.number(),
+ in_stock: z.boolean()
+});
+
+const products = await app.extract({
+ urls: productUrls,
+ schema: schema
+});
+```
+
+### 3. News Article Scraping
+```python
+article = app.scrape_url("https://news.com/article", params={
+ "formats": ["markdown"],
+ "onlyMainContent": True
+})
+```
+
+---
+
+## Cloudflare Workers Integration
+
+Works seamlessly with Cloudflare Workers for serverless scraping:
+
+```typescript
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ const app = new FirecrawlApp({ apiKey: env.FIRECRAWL_API_KEY });
+
+ const { url } = await request.json();
+ const result = await app.scrapeUrl(url, {
+ formats: ['markdown'],
+ onlyMainContent: true
+ });
+
+ return Response.json({ markdown: result.markdown });
+ }
+};
+```
+
+---
+
+## Official Documentation
+
+- **Docs**: https://docs.firecrawl.dev
+- **Python SDK**: https://docs.firecrawl.dev/sdks/python
+- **Node.js SDK**: https://docs.firecrawl.dev/sdks/node
+- **API Reference**: https://docs.firecrawl.dev/api-reference
+- **GitHub**: https://github.com/mendableai/firecrawl
+- **Get API Key**: https://www.firecrawl.dev
+
+---
+
+## Research Validation
+
+- ✅ API v2 verified (2025-10-20)
+- ✅ Python SDK v4.5.0+ verified on PyPI
+- ✅ Node.js SDK v1.7.x+ verified on npm
+- ✅ All endpoints documented from official docs
+- ✅ Rate limits and best practices confirmed
+
+---
+
+## Next Steps After Using This Skill
+
+1. **Store scraped data**: Use `cloudflare-d1` skill for database storage
+2. **Build vector search**: Use `cloudflare-vectorize` skill for RAG
+3. **Schedule scraping**: Use `cloudflare-queues` skill for async jobs
+4. **Process with AI**: Use `cloudflare-workers-ai` skill for content analysis
+
+---
+
+**Production Tested**: ✅
+**Token Efficiency**: ~60% savings
+**Error Prevention**: 6 common issues prevented
+**Composable**: Works with other Cloudflare skills
+
+**Ready to use!** Start with `SKILL.md` for complete instructions.
diff --git a/skills/firecrawl-scraper/SKILL.md b/skills/firecrawl-scraper/SKILL.md
new file mode 100644
index 00000000..419c6b7c
--- /dev/null
+++ b/skills/firecrawl-scraper/SKILL.md
@@ -0,0 +1,688 @@
+---
+name: firecrawl-scraper
+description: |
+ Complete knowledge domain for Firecrawl v4 API - web scraping and crawling that converts websites into LLM-ready markdown or structured data.
+
+ Use when: scraping websites, crawling entire sites, extracting web content, converting HTML to markdown, building web scrapers, handling dynamic JavaScript content, bypassing anti-bot protection, extracting structured data from web pages, or when encountering "content not loading", "JavaScript rendering issues", or "blocked by bot detection".
+
+metadata:
+ doc_sources:
+ primary: "https://docs.firecrawl.dev"
+ python_sdk: "https://docs.firecrawl.dev/sdks/python"
+ changelog: "https://github.com/mendableai/firecrawl/releases"
+ ecosystem: pypi
+ package_name: firecrawl-py
+ tier: 2
+ last_verified: "2026-01-09"
+---
+
+# Firecrawl Web Scraper Skill
+
+**Status**: Production Ready ✅
+**Last Updated**: 2026-01-09
+**Official Docs**: https://docs.firecrawl.dev
+**API Version**: v4 (firecrawl-py 4.12.0+)
+
+---
+
+## What is Firecrawl?
+
+Firecrawl is a **Web Data API for AI** that turns entire websites into LLM-ready markdown or structured data. It handles:
+
+- **JavaScript rendering** - Executes client-side JavaScript to capture dynamic content
+- **Anti-bot bypass** - Gets past CAPTCHA and bot detection systems
+- **Format conversion** - Outputs as markdown, JSON, or structured data
+- **Screenshot capture** - Saves visual representations of pages
+- **Browser automation** - Full headless browser capabilities
+
+---
+
+## API Endpoints
+
+### 1. `/v2/scrape` - Single Page Scraping
+Scrapes a single webpage and returns clean, structured content.
+
+**Use Cases**:
+- Extract article content
+- Get product details
+- Scrape specific pages
+- Convert HTML to markdown
+
+**Key Options**:
+- `formats`: ["markdown", "html", "screenshot"]
+- `onlyMainContent`: true/false (removes nav, footer, ads)
+- `waitFor`: milliseconds to wait before scraping
+- `actions`: browser automation actions (click, scroll, etc.)
+
+### 2. `/v2/crawl` - Full Site Crawling
+Crawls all accessible pages from a starting URL.
+
+**Use Cases**:
+- Index entire documentation sites
+- Archive website content
+- Build knowledge bases
+- Scrape multi-page content
+
+**Key Options**:
+- `limit`: max pages to crawl
+- `maxDepth`: how many links deep to follow
+- `allowedDomains`: restrict to specific domains
+- `excludePaths`: skip certain URL patterns
+
+### 3. `/v2/map` - URL Discovery
+Maps all URLs on a website without scraping content.
+
+**Use Cases**:
+- Find sitemap
+- Discover all pages
+- Plan crawling strategy
+- Audit website structure
+
+### 4. `/v2/extract` - Structured Data Extraction
+Uses AI to extract specific data fields from pages.
+
+**Use Cases**:
+- Extract product prices and names
+- Parse contact information
+- Build structured datasets
+- Custom data schemas
+
+**Key Options**:
+- `schema`: Zod or JSON schema defining desired structure
+- `systemPrompt`: guide AI extraction behavior
+
+---
+
+## Authentication
+
+Firecrawl requires an API key for all requests.
+
+### Get API Key
+1. Sign up at https://www.firecrawl.dev
+2. Go to dashboard → API Keys
+3. Copy your API key (starts with `fc-`)
+
+### Store Securely
+**NEVER hardcode API keys in code!**
+
+```bash
+# .env file
+FIRECRAWL_API_KEY=fc-your-api-key-here
+```
+
+```bash
+# .env.local (for local development)
+FIRECRAWL_API_KEY=fc-your-api-key-here
+```
+
+---
+
+## Python SDK Usage
+
+### Installation
+
+```bash
+pip install firecrawl-py
+```
+
+**Latest Version**: `firecrawl-py v4.12.0+` (Jan 2026)
+
+### Basic Scrape (v4 API)
+
+```python
+import os
+from firecrawl import Firecrawl
+
+# Initialize client (reads FIRECRAWL_API_KEY from env automatically)
+app = Firecrawl(api_key=os.environ.get("FIRECRAWL_API_KEY"))
+
+# Scrape a single page - returns Pydantic Document object
+doc = app.scrape(
+ url="https://example.com/article",
+ formats=["markdown", "html"],
+ only_main_content=True
+)
+
+# Access content via attributes (not .get())
+print(doc.markdown)
+print(doc.metadata) # Page metadata (title, description, etc.)
+```
+
+### Crawl Multiple Pages
+
+```python
+import os
+from firecrawl import Firecrawl
+
+app = Firecrawl(api_key=os.environ.get("FIRECRAWL_API_KEY"))
+
+# Start crawl - returns Pydantic CrawlResult
+result = app.crawl(
+ url="https://docs.example.com",
+ limit=100,
+ scrape_options={
+ "formats": ["markdown"]
+ }
+)
+
+# Process results - result.data is list of Document objects
+for page in result.data:
+ print(f"Scraped: {page.metadata.source_url}")
+ print(f"Content: {page.markdown[:200]}...")
+```
+
+### Extract Structured Data
+
+```python
+import os
+from firecrawl import Firecrawl
+
+app = Firecrawl(api_key=os.environ.get("FIRECRAWL_API_KEY"))
+
+# Define schema (JSON Schema format)
+schema = {
+ "type": "object",
+ "properties": {
+ "company_name": {"type": "string"},
+ "product_price": {"type": "number"},
+ "availability": {"type": "string"}
+ },
+ "required": ["company_name", "product_price"]
+}
+
+# Extract data
+result = app.extract(
+ urls=["https://example.com/product"],
+ schema=schema,
+ system_prompt="Extract product information from the page"
+)
+
+print(result)
+```
+
+---
+
+## TypeScript/Node.js SDK Usage
+
+### Installation
+
+```bash
+npm install @mendable/firecrawl-js
+# or
+pnpm add @mendable/firecrawl-js
+# or use the unscoped package:
+npm install firecrawl
+```
+
+**Latest Version**: `@mendable/firecrawl-js v4.4.1+` (or `firecrawl v4.4.1+`)
+
+### Basic Scrape
+
+```typescript
+import FirecrawlApp from '@mendable/firecrawl-js';
+
+// Initialize client
+const app = new FirecrawlApp({
+ apiKey: process.env.FIRECRAWL_API_KEY
+});
+
+// Scrape a single page
+const result = await app.scrapeUrl('https://example.com/article', {
+ formats: ['markdown', 'html'],
+ onlyMainContent: true
+});
+
+// Access markdown content
+const markdown = result.markdown;
+console.log(markdown);
+```
+
+### Crawl Multiple Pages
+
+```typescript
+import FirecrawlApp from '@mendable/firecrawl-js';
+
+const app = new FirecrawlApp({
+ apiKey: process.env.FIRECRAWL_API_KEY
+});
+
+// Start crawl
+const crawlResult = await app.crawlUrl('https://docs.example.com', {
+ limit: 100,
+ scrapeOptions: {
+ formats: ['markdown']
+ }
+});
+
+// Process results
+for (const page of crawlResult.data) {
+ console.log(`Scraped: ${page.url}`);
+ console.log(page.markdown);
+}
+```
+
+### Extract Structured Data with Zod
+
+```typescript
+import FirecrawlApp from '@mendable/firecrawl-js';
+import { z } from 'zod';
+
+const app = new FirecrawlApp({
+ apiKey: process.env.FIRECRAWL_API_KEY
+});
+
+// Define schema with Zod
+const schema = z.object({
+ company_name: z.string(),
+ product_price: z.number(),
+ availability: z.string()
+});
+
+// Extract data
+const result = await app.extract({
+ urls: ['https://example.com/product'],
+ schema: schema,
+ systemPrompt: 'Extract product information from the page'
+});
+
+console.log(result);
+```
+
+---
+
+## Common Use Cases
+
+### 1. Documentation Scraping
+
+**Scenario**: Convert entire documentation site to markdown for RAG/chatbot
+
+```python
+app = FirecrawlApp(api_key=os.environ.get("FIRECRAWL_API_KEY"))
+
+docs = app.crawl_url(
+ url="https://docs.myapi.com",
+ params={
+ "limit": 500,
+ "scrapeOptions": {
+ "formats": ["markdown"],
+ "onlyMainContent": True
+ },
+ "allowedDomains": ["docs.myapi.com"]
+ }
+)
+
+# Save to files
+for page in docs.get("data", []):
+ filename = page["url"].replace("https://", "").replace("/", "_") + ".md"
+ with open(f"docs/{filename}", "w") as f:
+ f.write(page["markdown"])
+```
+
+### 2. Product Data Extraction
+
+**Scenario**: Extract structured product data for e-commerce
+
+```typescript
+const schema = z.object({
+ title: z.string(),
+ price: z.number(),
+ description: z.string(),
+ images: z.array(z.string()),
+ in_stock: z.boolean()
+});
+
+const products = await app.extract({
+ urls: productUrls,
+ schema: schema,
+ systemPrompt: 'Extract all product details including price and availability'
+});
+```
+
+### 3. News Article Scraping
+
+**Scenario**: Extract clean article content without ads/navigation
+
+```python
+article = app.scrape_url(
+ url="https://news.com/article",
+ params={
+ "formats": ["markdown"],
+ "onlyMainContent": True,
+ "removeBase64Images": True
+ }
+)
+
+# Get clean markdown
+content = article.get("markdown")
+```
+
+---
+
+## Error Handling
+
+### Python
+
+```python
+from firecrawl import FirecrawlApp
+from firecrawl.exceptions import FirecrawlException
+
+app = FirecrawlApp(api_key=os.environ.get("FIRECRAWL_API_KEY"))
+
+try:
+ result = app.scrape_url("https://example.com")
+except FirecrawlException as e:
+ print(f"Firecrawl error: {e}")
+except Exception as e:
+ print(f"Unexpected error: {e}")
+```
+
+### TypeScript
+
+```typescript
+import FirecrawlApp from '@mendable/firecrawl-js';
+
+const app = new FirecrawlApp({
+ apiKey: process.env.FIRECRAWL_API_KEY
+});
+
+try {
+ const result = await app.scrapeUrl('https://example.com');
+} catch (error) {
+ if (error.response) {
+ // API error
+ console.error('API Error:', error.response.data);
+ } else {
+ // Network or other error
+ console.error('Error:', error.message);
+ }
+}
+```
+
+---
+
+## Rate Limits & Best Practices
+
+### Rate Limits
+- **Free tier**: 500 credits/month
+- **Paid tiers**: Higher limits based on plan
+- Credits consumed vary by endpoint and options
+
+### Best Practices
+
+1. **Use `onlyMainContent: true`** to reduce credits and get cleaner data
+2. **Set reasonable limits** on crawls to avoid excessive costs
+3. **Handle retries** with exponential backoff for transient errors
+4. **Cache results** locally to avoid re-scraping same content
+5. **Use `map` endpoint first** to plan crawling strategy
+6. **Batch extract calls** when processing multiple URLs
+7. **Monitor credit usage** in dashboard
+
+---
+
+## Cloudflare Workers Integration
+
+### ⚠️ Important: SDK Compatibility
+
+**The Firecrawl SDK cannot run in Cloudflare Workers** due to Node.js dependencies (specifically `axios` which uses Node.js `http` module). Workers require Web Standard APIs.
+
+**✅ Use the direct REST API with `fetch` instead** (see example below).
+
+**Alternative**: Self-host with [workers-firecrawl](https://github.com/G4brym/workers-firecrawl) - a Workers-native implementation (requires Workers Paid Plan, only implements `/search` endpoint).
+
+---
+
+### Workers Example: Direct REST API
+
+This example uses the `fetch` API to call Firecrawl directly - works perfectly in Cloudflare Workers:
+
+```typescript
+interface Env {
+ FIRECRAWL_API_KEY: string;
+ SCRAPED_CACHE?: KVNamespace; // Optional: for caching results
+}
+
+interface FirecrawlScrapeResponse {
+ success: boolean;
+ data: {
+ markdown?: string;
+ html?: string;
+ metadata: {
+ title?: string;
+ description?: string;
+ language?: string;
+ sourceURL: string;
+ };
+ };
+}
+
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ if (request.method !== 'POST') {
+ return Response.json({ error: 'Method not allowed' }, { status: 405 });
+ }
+
+ try {
+ const { url } = await request.json<{ url: string }>();
+
+ if (!url) {
+ return Response.json({ error: 'URL is required' }, { status: 400 });
+ }
+
+ // Check cache (optional)
+ if (env.SCRAPED_CACHE) {
+ const cached = await env.SCRAPED_CACHE.get(url, 'json');
+ if (cached) {
+ return Response.json({ cached: true, data: cached });
+ }
+ }
+
+ // Call Firecrawl API directly using fetch
+ const response = await fetch('https://api.firecrawl.dev/v2/scrape', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.FIRECRAWL_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ url: url,
+ formats: ['markdown'],
+ onlyMainContent: true,
+ removeBase64Images: true
+ })
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(`Firecrawl API error (${response.status}): ${errorText}`);
+ }
+
+ const result = await response.json<FirecrawlScrapeResponse>();
+
+ // Cache for 1 hour (optional)
+ if (env.SCRAPED_CACHE && result.success) {
+ await env.SCRAPED_CACHE.put(
+ url,
+ JSON.stringify(result.data),
+ { expirationTtl: 3600 }
+ );
+ }
+
+ return Response.json({
+ cached: false,
+ data: result.data
+ });
+
+ } catch (error) {
+ console.error('Scraping error:', error);
+ return Response.json(
+ { error: error instanceof Error ? error.message : 'Unknown error' },
+ { status: 500 }
+ );
+ }
+ }
+};
+```
+
+**Environment Setup**: Add `FIRECRAWL_API_KEY` in Wrangler secrets:
+
+```bash
+npx wrangler secret put FIRECRAWL_API_KEY
+```
+
+**Optional KV Binding** (for caching - add to `wrangler.jsonc`):
+
+```jsonc
+{
+ "kv_namespaces": [
+ {
+ "binding": "SCRAPED_CACHE",
+ "id": "your-kv-namespace-id"
+ }
+ ]
+}
+```
+
+See `templates/firecrawl-worker-fetch.ts` for a complete production-ready example.
+
+---
+
+## When to Use This Skill
+
+✅ **Use Firecrawl when:**
+- Scraping modern websites with JavaScript
+- Need clean markdown output for LLMs
+- Building RAG systems from web content
+- Extracting structured data at scale
+- Dealing with bot protection
+- Need reliable, production-ready scraping
+
+❌ **Don't use Firecrawl when:**
+- Scraping simple static HTML (use cheerio/beautifulsoup)
+- Have existing Puppeteer/Playwright setup working well
+- Working with APIs (use direct API calls instead)
+- Budget constraints (free tier has limits)
+
+---
+
+## Common Issues & Solutions
+
+### Issue: "Invalid API Key"
+**Cause**: API key not set or incorrect
+**Fix**:
+```bash
+# Check env variable is set
+echo $FIRECRAWL_API_KEY
+
+# Verify key format (should start with fc-)
+```
+
+### Issue: "Rate limit exceeded"
+**Cause**: Exceeded monthly credits
+**Fix**:
+- Check usage in dashboard
+- Upgrade plan or wait for reset
+- Use `onlyMainContent: true` to reduce credits
+
+### Issue: "Timeout error"
+**Cause**: Page takes too long to load
+**Fix**:
+```python
+result = app.scrape_url(url, params={"waitFor": 10000}) # Wait 10s
+```
+
+### Issue: "Content is empty"
+**Cause**: Content loaded via JavaScript after initial render
+**Fix**:
+```python
+result = app.scrape_url(url, params={
+ "waitFor": 5000,
+ "actions": [{"type": "wait", "milliseconds": 3000}]
+})
+```
+
+---
+
+## Advanced Features
+
+### Browser Actions
+
+Perform interactions before scraping:
+
+```python
+result = app.scrape_url(
+ url="https://example.com",
+ params={
+ "actions": [
+ {"type": "click", "selector": "button.load-more"},
+ {"type": "wait", "milliseconds": 2000},
+ {"type": "scroll", "direction": "down"}
+ ]
+ }
+)
+```
+
+### Custom Headers
+
+```python
+result = app.scrape_url(
+ url="https://example.com",
+ params={
+ "headers": {
+ "User-Agent": "Custom Bot 1.0",
+ "Accept-Language": "en-US"
+ }
+ }
+)
+```
+
+### Webhooks for Long Crawls
+
+Instead of polling, receive results via webhook:
+
+```python
+crawl = app.crawl_url(
+ url="https://docs.example.com",
+ params={
+ "limit": 1000,
+ "webhook": "https://your-domain.com/webhook"
+ }
+)
+```
+
+---
+
+## Package Versions
+
+| Package | Version | Last Checked |
+|---------|---------|--------------|
+| firecrawl-py | 4.5.0+ | 2025-10-20 |
+| @mendable/firecrawl-js (or firecrawl) | 4.4.1+ | 2025-10-24 |
+| API Version | v2 | Current |
+
+**Note**: The Node.js SDK requires Node.js >=22.0.0 and cannot run in Cloudflare Workers. Use direct REST API calls in Workers (see Cloudflare Workers Integration section).
+
+---
+
+## Official Documentation
+
+- **Docs**: https://docs.firecrawl.dev
+- **Python SDK**: https://docs.firecrawl.dev/sdks/python
+- **Node.js SDK**: https://docs.firecrawl.dev/sdks/node
+- **API Reference**: https://docs.firecrawl.dev/api-reference
+- **GitHub**: https://github.com/mendableai/firecrawl
+- **Dashboard**: https://www.firecrawl.dev/app
+
+---
+
+## Next Steps After Using This Skill
+
+1. **Store scraped data**: Use Cloudflare D1, R2, or KV to persist results
+2. **Build RAG system**: Combine with Vectorize for semantic search
+3. **Add scheduling**: Use Cloudflare Queues for recurring scrapes
+4. **Process content**: Use Workers AI to analyze scraped data
+
+---
+
+**Token Savings**: ~60% vs manual integration
+**Error Prevention**: API authentication, rate limiting, format handling
+**Production Ready**: ✅
diff --git a/skills/firecrawl-scraper/references/common-patterns.md b/skills/firecrawl-scraper/references/common-patterns.md
new file mode 100644
index 00000000..1b6dbe4e
--- /dev/null
+++ b/skills/firecrawl-scraper/references/common-patterns.md
@@ -0,0 +1,702 @@
+# Firecrawl Common Patterns & Best Practices
+
+**Last Updated**: 2025-10-24
+
+---
+
+## Table of Contents
+
+1. [Error Handling](#error-handling)
+2. [Retry Strategies](#retry-strategies)
+3. [Rate Limit Management](#rate-limit-management)
+4. [Batch Processing](#batch-processing)
+5. [Caching Strategies](#caching-strategies)
+6. [Progress Tracking](#progress-tracking)
+7. [Data Storage Patterns](#data-storage-patterns)
+8. [Cloudflare Workers Integration](#cloudflare-workers-integration)
+
+---
+
+## Error Handling
+
+### Python: Comprehensive Error Handling
+
+```python
+from firecrawl import FirecrawlApp
+from firecrawl.exceptions import FirecrawlException
+import time
+
+def scrape_with_error_handling(url: str, retries: int = 3) -> dict:
+ """
+ Scrape a URL with comprehensive error handling and retries.
+ """
+ app = FirecrawlApp(api_key=os.environ.get("FIRECRAWL_API_KEY"))
+
+ for attempt in range(retries):
+ try:
+ result = app.scrape_url(url, params={
+ "formats": ["markdown"],
+ "onlyMainContent": True
+ })
+ return result
+
+ except FirecrawlException as e:
+ # Firecrawl-specific errors
+ if "Rate limit" in str(e):
+ print(f"Rate limited. Waiting before retry {attempt + 1}/{retries}")
+ time.sleep(60) # Wait 1 minute
+ continue
+ elif "Invalid API key" in str(e):
+ print("Invalid API key. Check your environment variables.")
+ raise
+ else:
+ print(f"Firecrawl error: {e}")
+ if attempt < retries - 1:
+ time.sleep(5 * (attempt + 1)) # Exponential backoff
+ continue
+ raise
+
+ except ConnectionError as e:
+ print(f"Connection error: {e}")
+ if attempt < retries - 1:
+ time.sleep(10)
+ continue
+ raise
+
+ except Exception as e:
+ print(f"Unexpected error: {e}")
+ raise
+
+ raise Exception(f"Failed to scrape {url} after {retries} attempts")
+```
+
+### TypeScript: Comprehensive Error Handling
+
+```typescript
+import FirecrawlApp from 'firecrawl-js';
+
+async function scrapeWithErrorHandling(
+ url: string,
+ retries: number = 3
+): Promise<any> {
+ const app = new FirecrawlApp({
+ apiKey: process.env.FIRECRAWL_API_KEY
+ });
+
+ for (let attempt = 0; attempt < retries; attempt++) {
+ try {
+ const result = await app.scrapeUrl(url, {
+ formats: ['markdown'],
+ onlyMainContent: true
+ });
+ return result;
+
+ } catch (error: any) {
+ // API errors
+ if (error.response) {
+ const status = error.response.status;
+ const message = error.response.data?.error || error.message;
+
+ if (status === 429) {
+ // Rate limited
+ console.log(`Rate limited. Waiting before retry ${attempt + 1}/${retries}`);
+ await new Promise(resolve => setTimeout(resolve, 60000));
+ continue;
+ } else if (status === 401) {
+ // Invalid API key
+ console.error('Invalid API key. Check your environment variables.');
+ throw error;
+ } else if (status >= 500) {
+ // Server error
+ console.log(`Server error (${status}). Retrying...`);
+ await new Promise(resolve => setTimeout(resolve, 5000 * (attempt + 1)));
+ continue;
+ } else {
+ console.error(`API error (${status}): ${message}`);
+ throw error;
+ }
+ }
+
+ // Network errors
+ if (error.code === 'ECONNREFUSED' || error.code === 'ETIMEDOUT') {
+ console.log(`Network error: ${error.message}`);
+ if (attempt < retries - 1) {
+ await new Promise(resolve => setTimeout(resolve, 10000));
+ continue;
+ }
+ }
+
+ // Unexpected errors
+ throw error;
+ }
+ }
+
+ throw new Error(`Failed to scrape ${url} after ${retries} attempts`);
+}
+```
+
+---
+
+## Retry Strategies
+
+### Exponential Backoff
+
+```python
+import time
+from typing import Callable, Any
+
+def exponential_backoff(
+ func: Callable,
+ max_retries: int = 5,
+ base_delay: int = 1
+) -> Any:
+ """
+ Retry a function with exponential backoff.
+ """
+ for attempt in range(max_retries):
+ try:
+ return func()
+ except Exception as e:
+ if attempt == max_retries - 1:
+ raise
+
+ delay = base_delay * (2 ** attempt)
+ print(f"Attempt {attempt + 1} failed. Retrying in {delay}s...")
+ time.sleep(delay)
+
+# Usage
+result = exponential_backoff(
+ lambda: app.scrape_url("https://example.com"),
+ max_retries=5,
+ base_delay=2
+)
+```
+
+### Circuit Breaker Pattern
+
+```python
+from datetime import datetime, timedelta
+
+class CircuitBreaker:
+ """
+ Circuit breaker to prevent cascading failures.
+ """
+ def __init__(self, failure_threshold: int = 5, timeout: int = 60):
+ self.failure_threshold = failure_threshold
+ self.timeout = timeout
+ self.failures = 0
+ self.last_failure_time = None
+ self.state = "closed" # closed, open, half-open
+
+ def call(self, func: Callable, *args, **kwargs) -> Any:
+ if self.state == "open":
+ if datetime.now() - self.last_failure_time > timedelta(seconds=self.timeout):
+ self.state = "half-open"
+ else:
+ raise Exception("Circuit breaker is OPEN")
+
+ try:
+ result = func(*args, **kwargs)
+ if self.state == "half-open":
+ self.state = "closed"
+ self.failures = 0
+ return result
+
+ except Exception as e:
+ self.failures += 1
+ self.last_failure_time = datetime.now()
+
+ if self.failures >= self.failure_threshold:
+ self.state = "open"
+ print(f"Circuit breaker OPEN after {self.failures} failures")
+
+ raise
+
+# Usage
+breaker = CircuitBreaker(failure_threshold=5, timeout=60)
+
+for url in urls:
+ try:
+ result = breaker.call(app.scrape_url, url)
+ except Exception as e:
+ print(f"Failed: {e}")
+```
+
+---
+
+## Rate Limit Management
+
+### Credit Tracking
+
+```python
+class CreditTracker:
+ """
+ Track credit usage and prevent exceeding limits.
+ """
+ def __init__(self, daily_limit: int = 500):
+ self.daily_limit = daily_limit
+ self.credits_used = 0
+
+ def estimate_credits(self, operation: str, **kwargs) -> int:
+ """Estimate credits for an operation."""
+ if operation == "scrape":
+ credits = 1
+ if kwargs.get("screenshot"):
+ credits += 1
+ if kwargs.get("actions"):
+ credits += 1
+ return credits
+ elif operation == "crawl":
+ pages = kwargs.get("limit", 100)
+ return pages * self.estimate_credits("scrape", **kwargs.get("scrapeOptions", {}))
+ elif operation == "extract":
+ return len(kwargs.get("urls", [])) * 5
+ return 1
+
+ def check_and_use(self, credits: int) -> bool:
+ """Check if enough credits and mark as used."""
+ if self.credits_used + credits > self.daily_limit:
+ print(f"⚠️ Would exceed daily limit ({self.credits_used + credits}/{self.daily_limit})")
+ return False
+
+ self.credits_used += credits
+ print(f"Credits used: {self.credits_used}/{self.daily_limit}")
+ return True
+
+# Usage
+tracker = CreditTracker(daily_limit=500)
+
+for url in urls:
+ credits_needed = tracker.estimate_credits("scrape", screenshot=False)
+ if tracker.check_and_use(credits_needed):
+ result = app.scrape_url(url)
+ else:
+ print("Daily limit reached. Stopping.")
+ break
+```
+
+---
+
+## Batch Processing
+
+### Process URLs in Batches
+
+```python
+from typing import List
+import time
+
+def batch_scrape(
+ urls: List[str],
+ batch_size: int = 10,
+ delay_between_batches: int = 5
+) -> List[dict]:
+ """
+ Scrape URLs in batches with delays.
+ """
+ app = FirecrawlApp(api_key=os.environ.get("FIRECRAWL_API_KEY"))
+ results = []
+
+ for i in range(0, len(urls), batch_size):
+ batch = urls[i:i + batch_size]
+ print(f"Processing batch {i // batch_size + 1} ({len(batch)} URLs)")
+
+ for url in batch:
+ try:
+ result = app.scrape_url(url, params={
+ "formats": ["markdown"],
+ "onlyMainContent": True
+ })
+ results.append(result)
+ except Exception as e:
+ print(f"Failed to scrape {url}: {e}")
+ results.append({"url": url, "error": str(e)})
+
+ # Delay between batches
+ if i + batch_size < len(urls):
+ print(f"Waiting {delay_between_batches}s before next batch...")
+ time.sleep(delay_between_batches)
+
+ return results
+
+# Usage
+urls = ["https://example.com/page1", "https://example.com/page2", ...]
+results = batch_scrape(urls, batch_size=10, delay_between_batches=5)
+```
+
+---
+
+## Caching Strategies
+
+### Simple File-Based Cache
+
+```python
+import os
+import json
+import hashlib
+from pathlib import Path
+
+class ScrapeCache:
+ """
+ Cache scraped content to avoid re-scraping.
+ """
+ def __init__(self, cache_dir: str = ".cache"):
+ self.cache_dir = Path(cache_dir)
+ self.cache_dir.mkdir(exist_ok=True)
+
+ def _get_cache_key(self, url: str) -> str:
+ """Generate cache key from URL."""
+ return hashlib.md5(url.encode()).hexdigest()
+
+ def get(self, url: str) -> dict | None:
+ """Get cached result."""
+ cache_key = self._get_cache_key(url)
+ cache_file = self.cache_dir / f"{cache_key}.json"
+
+ if cache_file.exists():
+ with open(cache_file, "r") as f:
+ return json.load(f)
+ return None
+
+ def set(self, url: str, data: dict):
+ """Cache result."""
+ cache_key = self._get_cache_key(url)
+ cache_file = self.cache_dir / f"{cache_key}.json"
+
+ with open(cache_file, "w") as f:
+ json.dump(data, f)
+
+# Usage
+cache = ScrapeCache()
+
+def cached_scrape(url: str) -> dict:
+ # Check cache first
+ cached = cache.get(url)
+ if cached:
+ print(f"Using cached result for {url}")
+ return cached
+
+ # Scrape and cache
+ result = app.scrape_url(url)
+ cache.set(url, result)
+ return result
+```
+
+---
+
+## Progress Tracking
+
+### Progress Bar for Crawling
+
+```python
+from tqdm import tqdm
+
+def crawl_with_progress(url: str, limit: int = 100) -> list:
+ """
+ Crawl with progress bar.
+ """
+ app = FirecrawlApp(api_key=os.environ.get("FIRECRAWL_API_KEY"))
+
+ # Start crawl
+ crawl_id = app.crawl_url(
+ url=url,
+ params={"limit": limit},
+ wait_until_done=False # Don't wait
+ )
+
+ # Poll with progress bar
+ with tqdm(total=limit, desc="Crawling") as pbar:
+ while True:
+ status = app.check_crawl_status(crawl_id)
+
+ if status["status"] == "completed":
+ pbar.n = status["total"]
+ pbar.refresh()
+ break
+
+ pbar.n = status["completed"]
+ pbar.refresh()
+ time.sleep(5)
+
+ return status["data"]
+```
+
+---
+
+## Data Storage Patterns
+
+### Save to Cloudflare D1
+
+```python
+# Assuming D1 binding available in Cloudflare Worker context
+
+async def save_to_d1(pages: list, db):
+ """
+ Save scraped pages to D1 database.
+ """
+ for page in pages:
+ await db.prepare(
+ """
+ INSERT INTO scraped_pages (url, title, content, scraped_at)
+ VALUES (?, ?, ?, ?)
+ """
+ ).bind(
+ page["url"],
+ page["metadata"].get("title"),
+ page["markdown"],
+ datetime.now().isoformat()
+ ).run()
+```
+
+### Save to Cloudflare R2
+
+```python
+# Assuming R2 binding available
+
+async def save_to_r2(pages: list, bucket):
+ """
+ Save scraped pages to R2 storage.
+ """
+ for page in pages:
+ key = f"scraped/{page['url'].replace('https://', '')}.md"
+
+ await bucket.put(
+ key,
+ page["markdown"],
+ {
+ "httpMetadata": {
+ "contentType": "text/markdown"
+ },
+ "customMetadata": {
+ "url": page["url"],
+ "title": page["metadata"].get("title", ""),
+ "scraped_at": datetime.now().isoformat()
+ }
+ }
+ )
+```
+
+---
+
+## Cloudflare Workers Integration
+
+### ⚠️ Important: SDK Compatibility
+
+**The Firecrawl SDK cannot run in Cloudflare Workers** due to Node.js dependencies (`axios`).
+
+**Use direct REST API calls with `fetch` instead** (see example below).
+
+For a complete production-ready example, see `templates/firecrawl-worker-fetch.ts`.
+
+---
+
+### Complete Worker Example (Direct Fetch API)
+
+```typescript
+interface Env {
+ FIRECRAWL_API_KEY: string;
+ SCRAPED_CONTENT?: KVNamespace;
+}
+
+interface FirecrawlScrapeResponse {
+ success: boolean;
+ data: {
+ markdown?: string;
+ html?: string;
+ metadata: {
+ title?: string;
+ description?: string;
+ sourceURL: string;
+ };
+ };
+}
+
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ if (request.method !== 'POST') {
+ return Response.json({ error: 'Method not allowed' }, { status: 405 });
+ }
+
+ try {
+ const { url } = await request.json<{ url: string }>();
+
+ if (!url) {
+ return Response.json({ error: 'URL is required' }, { status: 400 });
+ }
+
+ // Check cache (KV)
+ if (env.SCRAPED_CONTENT) {
+ const cached = await env.SCRAPED_CONTENT.get(url, 'json');
+ if (cached) {
+ return Response.json({ cached: true, data: cached });
+ }
+ }
+
+ // Call Firecrawl API directly using fetch
+ const response = await fetch('https://api.firecrawl.dev/v2/scrape', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.FIRECRAWL_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ url: url,
+ formats: ['markdown'],
+ onlyMainContent: true,
+ removeBase64Images: true
+ })
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(`Firecrawl API error (${response.status}): ${errorText}`);
+ }
+
+ const result = await response.json<FirecrawlScrapeResponse>();
+
+ // Cache for 1 hour
+ if (env.SCRAPED_CONTENT && result.success) {
+ await env.SCRAPED_CONTENT.put(
+ url,
+ JSON.stringify(result.data),
+ { expirationTtl: 3600 }
+ );
+ }
+
+ return Response.json({
+ cached: false,
+ data: result.data
+ });
+
+ } catch (error) {
+ console.error('Worker error:', error);
+ return Response.json(
+ { error: error instanceof Error ? error.message : 'Unknown error' },
+ { status: 500 }
+ );
+ }
+ }
+};
+```
+
+**Setup**:
+```bash
+# Add API key
+npx wrangler secret put FIRECRAWL_API_KEY
+
+# Optional: Add KV binding to wrangler.jsonc
+{
+ "kv_namespaces": [
+ { "binding": "SCRAPED_CONTENT", "id": "your-kv-namespace-id" }
+ ]
+}
+```
+
+### Scheduled Worker (Cron Job)
+
+```typescript
+interface Env {
+ FIRECRAWL_API_KEY: string;
+ DB: D1Database;
+}
+
+export default {
+ async scheduled(event: ScheduledEvent, env: Env): Promise<void> {
+ try {
+ // Call Firecrawl API directly
+ const response = await fetch('https://api.firecrawl.dev/v2/scrape', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.FIRECRAWL_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ url: 'https://news.example.com',
+ formats: ['markdown'],
+ onlyMainContent: true
+ })
+ });
+
+ if (!response.ok) {
+ throw new Error(`Firecrawl API error: ${response.status}`);
+ }
+
+ const result = await response.json<{
+ success: boolean;
+ data: { markdown: string };
+ }>();
+
+ if (!result.success) {
+ throw new Error('Scraping failed');
+ }
+
+ // Store in D1
+ await env.DB.prepare(
+ `INSERT INTO daily_scrapes (url, content, scraped_at)
+ VALUES (?, ?, ?)`
+ ).bind(
+ 'https://news.example.com',
+ result.data.markdown,
+ new Date().toISOString()
+ ).run();
+
+ console.log('Daily scrape completed successfully');
+ } catch (error) {
+ console.error('Scheduled scrape failed:', error);
+ }
+ }
+};
+```
+
+**Add to wrangler.jsonc**:
+```jsonc
+{
+ "triggers": {
+ "crons": ["0 0 * * *"] // Daily at midnight
+ },
+ "d1_databases": [
+ {
+ "binding": "DB",
+ "database_name": "my-database",
+ "database_id": "your-database-id"
+ }
+ ]
+}
+```
+
+---
+
+## Best Practices Summary
+
+### Do's ✅
+
+1. **Always use environment variables** for API keys
+2. **Implement retry logic** with exponential backoff
+3. **Cache results** to avoid re-scraping
+4. **Use `onlyMainContent: true`** to save credits
+5. **Track credit usage** to avoid unexpected costs
+6. **Handle errors gracefully** with specific error types
+7. **Use batch processing** for large numbers of URLs
+8. **Set reasonable `waitFor` times** for dynamic content
+9. **Use `/v2/map` first** to plan efficient crawls
+10. **Monitor rate limits** and implement backoff
+
+### Don'ts ❌
+
+1. **Don't hardcode API keys** in source code
+2. **Don't scrape without error handling**
+3. **Don't ignore rate limits**
+4. **Don't scrape the same content repeatedly** without caching
+5. **Don't set excessively high `limit` values** on crawls
+6. **Don't assume all scrapes succeed** - always check for errors
+7. **Don't use synchronous code** in production (use async)
+8. **Don't forget to set `removeBase64Images: true`** for large pages
+9. **Don't skip `onlyMainContent`** if you want clean data
+10. **Don't crawl without setting `excludePaths`** for known problematic routes
+
+---
+
+## Official Documentation
+
+- **API Reference**: https://docs.firecrawl.dev/api-reference
+- **Best Practices**: https://docs.firecrawl.dev/best-practices
+- **Rate Limits**: https://docs.firecrawl.dev/rate-limits
diff --git a/skills/firecrawl-scraper/references/endpoints.md b/skills/firecrawl-scraper/references/endpoints.md
new file mode 100644
index 00000000..61159378
--- /dev/null
+++ b/skills/firecrawl-scraper/references/endpoints.md
@@ -0,0 +1,495 @@
+# Firecrawl API Endpoints Reference
+
+**API Version**: v2
+**Base URL**: `https://api.firecrawl.dev`
+**Last Updated**: 2025-10-24
+
+---
+
+## Overview
+
+Firecrawl v2 provides four main endpoints for different web scraping needs:
+
+1. **`/v2/scrape`** - Scrape a single page
+2. **`/v2/crawl`** - Crawl multiple pages from a starting URL
+3. **`/v2/map`** - Discover all URLs on a site
+4. **`/v2/extract`** - Extract structured data with AI
+
+---
+
+## 1. `/v2/scrape` - Single Page Scraping
+
+### Purpose
+Scrape a single webpage and return its content in various formats.
+
+### Use Cases
+- Extract article content
+- Get product details from a page
+- Convert specific pages to markdown
+- Capture screenshots
+- Scrape pages with dynamic JavaScript content
+
+### Request
+
+**Endpoint**: `POST https://api.firecrawl.dev/v2/scrape`
+
+**Headers**:
+```
+Authorization: Bearer YOUR_API_KEY
+Content-Type: application/json
+```
+
+**Body**:
+```json
+{
+ "url": "https://example.com/page",
+ "formats": ["markdown", "html", "screenshot"],
+ "onlyMainContent": true,
+ "waitFor": 3000,
+ "removeBase64Images": true,
+ "actions": [
+ {"type": "click", "selector": "button.load-more"},
+ {"type": "wait", "milliseconds": 2000}
+ ]
+}
+```
+
+### Parameters
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `url` | string | **required** | URL to scrape |
+| `formats` | array | `["markdown"]` | Output formats: `"markdown"`, `"html"`, `"screenshot"` |
+| `onlyMainContent` | boolean | `false` | Remove headers, footers, nav, ads |
+| `waitFor` | number | `0` | Milliseconds to wait before scraping |
+| `removeBase64Images` | boolean | `false` | Remove base64-encoded images |
+| `actions` | array | `[]` | Browser actions to perform before scraping |
+| `headers` | object | `{}` | Custom HTTP headers |
+
+### Response
+
+```json
+{
+ "success": true,
+ "data": {
+ "markdown": "# Page Title\n\nContent...",
+ "html": "<html>...</html>",
+ "screenshot": "data:image/png;base64,...",
+ "metadata": {
+ "title": "Page Title",
+ "description": "Page description",
+ "language": "en",
+ "sourceURL": "https://example.com/page"
+ }
+ }
+}
+```
+
+### Python Example
+
+```python
+result = app.scrape_url(
+ url="https://example.com",
+ params={
+ "formats": ["markdown", "html"],
+ "onlyMainContent": True,
+ "waitFor": 3000
+ }
+)
+
+markdown = result.get("markdown")
+```
+
+### TypeScript Example
+
+```typescript
+const result = await app.scrapeUrl('https://example.com', {
+ formats: ['markdown', 'html'],
+ onlyMainContent: true,
+ waitFor: 3000
+});
+
+const markdown = result.markdown;
+```
+
+---
+
+## 2. `/v2/crawl` - Multi-Page Crawling
+
+### Purpose
+Crawl multiple pages starting from a URL, following links automatically.
+
+### Use Cases
+- Index entire documentation sites
+- Archive website content
+- Build knowledge bases from multiple pages
+- Scrape blog archives
+- Collect all product pages
+
+### Request
+
+**Endpoint**: `POST https://api.firecrawl.dev/v2/crawl`
+
+**Headers**:
+```
+Authorization: Bearer YOUR_API_KEY
+Content-Type: application/json
+```
+
+**Body**:
+```json
+{
+ "url": "https://docs.example.com",
+ "limit": 100,
+ "maxDepth": 3,
+ "scrapeOptions": {
+ "formats": ["markdown"],
+ "onlyMainContent": true
+ },
+ "allowedDomains": ["docs.example.com"],
+ "excludePaths": ["/admin/*", "/login"],
+ "includePaths": ["/docs/*"],
+ "webhook": "https://your-domain.com/webhook"
+}
+```
+
+### Parameters
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `url` | string | **required** | Starting URL to crawl |
+| `limit` | number | `100` | Maximum pages to crawl |
+| `maxDepth` | number | `2` | How many links deep to follow |
+| `scrapeOptions` | object | `{}` | Options to pass to scrape endpoint |
+| `allowedDomains` | array | `[]` | Only crawl these domains |
+| `excludePaths` | array | `[]` | Skip URLs matching these patterns |
+| `includePaths` | array | `[]` | Only crawl URLs matching these patterns |
+| `webhook` | string | `null` | Webhook URL to receive results |
+
+### Response
+
+```json
+{
+ "success": true,
+ "id": "crawl_abc123",
+ "url": "https://api.firecrawl.dev/v2/crawl/abc123"
+}
+```
+
+**Status Check**: `GET https://api.firecrawl.dev/v2/crawl/abc123`
+
+**Status Response**:
+```json
+{
+ "status": "completed",
+ "total": 47,
+ "completed": 47,
+ "creditsUsed": 94,
+ "data": [
+ {
+ "url": "https://docs.example.com/page1",
+ "markdown": "# Content...",
+ "metadata": {...}
+ },
+ ...
+ ]
+}
+```
+
+### Python Example
+
+```python
+crawl_result = app.crawl_url(
+ url="https://docs.example.com",
+ params={
+ "limit": 100,
+ "maxDepth": 3,
+ "scrapeOptions": {
+ "formats": ["markdown"],
+ "onlyMainContent": True
+ }
+ },
+ poll_interval=5 # Check status every 5 seconds
+)
+
+pages = crawl_result.get("data", [])
+for page in pages:
+ print(page["url"])
+```
+
+### TypeScript Example
+
+```typescript
+const crawlResult = await app.crawlUrl('https://docs.example.com', {
+ limit: 100,
+ maxDepth: 3,
+ scrapeOptions: {
+ formats: ['markdown'],
+ onlyMainContent: true
+ }
+});
+
+for (const page of crawlResult.data) {
+ console.log(page.url);
+}
+```
+
+---
+
+## 3. `/v2/map` - URL Discovery
+
+### Purpose
+Map all URLs on a website without scraping their content.
+
+### Use Cases
+- Generate sitemap
+- Discover all pages before crawling
+- Audit website structure
+- Plan crawling strategy
+- Find broken links
+
+### Request
+
+**Endpoint**: `POST https://api.firecrawl.dev/v2/map`
+
+**Headers**:
+```
+Authorization: Bearer YOUR_API_KEY
+Content-Type: application/json
+```
+
+**Body**:
+```json
+{
+ "url": "https://example.com",
+ "search": "documentation",
+ "limit": 5000
+}
+```
+
+### Parameters
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `url` | string | **required** | Starting URL to map |
+| `search` | string | `null` | Filter URLs containing this text |
+| `limit` | number | `5000` | Maximum URLs to discover |
+
+### Response
+
+```json
+{
+ "success": true,
+ "links": [
+ "https://example.com/page1",
+ "https://example.com/page2",
+ "https://example.com/docs/intro",
+ ...
+ ]
+}
+```
+
+### Python Example
+
+```python
+map_result = app.map_url("https://example.com")
+urls = map_result.get("links", [])
+
+print(f"Found {len(urls)} URLs")
+for url in urls:
+ print(url)
+```
+
+### TypeScript Example
+
+```typescript
+const mapResult = await app.mapUrl('https://example.com');
+const urls = mapResult.links;
+
+console.log(`Found ${urls.length} URLs`);
+urls.forEach(url => console.log(url));
+```
+
+---
+
+## 4. `/v2/extract` - Structured Data Extraction
+
+### Purpose
+Extract structured data from web pages using AI and schemas.
+
+### Use Cases
+- Extract product information (price, title, availability)
+- Parse contact details from pages
+- Build structured datasets from unstructured HTML
+- Custom data extraction with schemas
+- Scrape directory listings
+
+### Request
+
+**Endpoint**: `POST https://api.firecrawl.dev/v2/extract`
+
+**Headers**:
+```
+Authorization: Bearer YOUR_API_KEY
+Content-Type: application/json
+```
+
+**Body**:
+```json
+{
+ "urls": [
+ "https://example.com/product1",
+ "https://example.com/product2"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "product_name": {"type": "string"},
+ "price": {"type": "number"},
+ "in_stock": {"type": "boolean"}
+ },
+ "required": ["product_name", "price"]
+ },
+ "systemPrompt": "Extract product details including name, price, and availability"
+}
+```
+
+### Parameters
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `urls` | array | **required** | URLs to extract from |
+| `schema` | object | **required** | JSON schema or Zod schema |
+| `systemPrompt` | string | `null` | Guide AI extraction behavior |
+
+### Response
+
+```json
+{
+ "success": true,
+ "data": [
+ {
+ "product_name": "Widget Pro",
+ "price": 29.99,
+ "in_stock": true
+ },
+ {
+ "product_name": "Gadget Max",
+ "price": 49.99,
+ "in_stock": false
+ }
+ ]
+}
+```
+
+### Python Example
+
+```python
+schema = {
+ "type": "object",
+ "properties": {
+ "title": {"type": "string"},
+ "price": {"type": "number"},
+ "availability": {"type": "string"}
+ },
+ "required": ["title", "price"]
+}
+
+result = app.extract(
+ urls=["https://example.com/product"],
+ params={
+ "schema": schema,
+ "systemPrompt": "Extract product information"
+ }
+)
+
+print(result)
+```
+
+### TypeScript Example (with Zod)
+
+```typescript
+import FirecrawlApp from '@mendable/firecrawl-js';
+import { z } from 'zod';
+
+const app = new FirecrawlApp({
+ apiKey: process.env.FIRECRAWL_API_KEY
+});
+
+const schema = z.object({
+ title: z.string(),
+ price: z.number(),
+ availability: z.string()
+});
+
+const result = await app.extract({
+ urls: ['https://example.com/product'],
+ schema: schema,
+ systemPrompt: 'Extract product information'
+});
+
+console.log(result);
+```
+
+---
+
+## Credit Usage
+
+Different endpoints consume different amounts of credits:
+
+| Endpoint | Base Credits | Notes |
+|----------|--------------|-------|
+| `/v2/scrape` | 1-3 | +1 for screenshot, +1 for actions |
+| `/v2/crawl` | 1-3 per page | Same as scrape, multiplied by pages |
+| `/v2/map` | 1 | Flat rate |
+| `/v2/extract` | 5 per page | Uses AI for extraction |
+
+**Credit Optimization**:
+- Use `onlyMainContent: true` to reduce credits
+- Use `removeBase64Images: true` to reduce response size
+- Use `/v2/map` first to plan crawls efficiently
+- Batch extract calls when possible
+
+---
+
+## Rate Limits
+
+- **Free tier**: 500 credits/month
+- **Paid tiers**: Varies by plan
+- **Rate limiting**: Handled automatically by SDK with retries
+
+---
+
+## Error Responses
+
+### 401 Unauthorized
+```json
+{
+ "success": false,
+ "error": "Invalid API key"
+}
+```
+
+### 429 Rate Limited
+```json
+{
+ "success": false,
+ "error": "Rate limit exceeded. Please upgrade your plan."
+}
+```
+
+### 500 Server Error
+```json
+{
+ "success": false,
+ "error": "Internal server error. Please try again."
+}
+```
+
+---
+
+## Official Documentation
+
+- **API Reference**: https://docs.firecrawl.dev/api-reference
+- **SDKs**: https://docs.firecrawl.dev/sdks
+- **Dashboard**: https://www.firecrawl.dev/app
diff --git a/skills/firecrawl-scraper/templates/firecrawl-crawl-example.py b/skills/firecrawl-scraper/templates/firecrawl-crawl-example.py
new file mode 100644
index 00000000..6b77696f
--- /dev/null
+++ b/skills/firecrawl-scraper/templates/firecrawl-crawl-example.py
@@ -0,0 +1,105 @@
+#!/usr/bin/env python3
+"""
+Firecrawl Crawling Example (Python) - v4 API
+
+This template demonstrates how to crawl multiple pages using Firecrawl v4 API.
+
+Requirements:
+ pip install firecrawl-py python-dotenv
+
+Environment Variables:
+ FIRECRAWL_API_KEY - Your Firecrawl API key (get from https://www.firecrawl.dev)
+
+Usage:
+ python firecrawl-crawl-example.py
+"""
+
+import os
+from dotenv import load_dotenv
+from firecrawl import Firecrawl
+
+# Load environment variables from .env file
+load_dotenv()
+
+
+def crawl_site(url: str, limit: int = 10):
+ """
+ Crawl a website and return all pages.
+
+ Args:
+ url: Starting URL to crawl
+ limit: Maximum number of pages to crawl
+
+ Returns:
+ CrawlResult object with data attribute containing list of Document objects
+ """
+ api_key = os.environ.get("FIRECRAWL_API_KEY")
+ if not api_key:
+ raise ValueError("FIRECRAWL_API_KEY environment variable not set")
+
+ app = Firecrawl(api_key=api_key)
+
+ print(f"Starting crawl from: {url}")
+ print(f"Limit: {limit} pages")
+
+ try:
+ # Start crawl - returns Pydantic CrawlResult object
+ result = app.crawl(
+ url=url,
+ limit=limit,
+ scrape_options={
+ "formats": ["markdown"],
+ "only_main_content": True,
+ },
+ # max_depth=2, # Optional: limit crawl depth
+ # allowed_domains=["docs.example.com"], # Optional: restrict domains
+ # exclude_paths=["/blog/*"], # Optional: exclude patterns
+ )
+
+ return result
+
+ except Exception as e:
+ print(f"Error crawling {url}: {e}")
+ raise
+
+
+def main():
+ """Main function demonstrating site crawling."""
+
+ # Example: Crawl Firecrawl documentation
+ url = "https://docs.firecrawl.dev"
+
+ # Crawl the site (limit to 5 pages for demo)
+ result = crawl_site(url, limit=5)
+
+ print("\n" + "=" * 80)
+ print("CRAWL RESULTS:")
+ print("=" * 80)
+
+ # result.data is a list of Document objects
+ if result.data:
+ print(f"\nTotal pages crawled: {len(result.data)}")
+
+ for i, page in enumerate(result.data, 1):
+ metadata = page.metadata
+ source_url = getattr(metadata, "source_url", "Unknown URL") if metadata else "Unknown URL"
+ title = getattr(metadata, "title", "No title") if metadata else "No title"
+ content_length = len(page.markdown) if page.markdown else 0
+
+ print(f"\n[{i}] {title}")
+ print(f" URL: {source_url}")
+ print(f" Content: {content_length:,} chars")
+
+ # Save each page
+ safe_filename = f"crawled_{i}.md"
+ with open(safe_filename, "w", encoding="utf-8") as f:
+ f.write(page.markdown or "")
+ print(f" Saved: {safe_filename}")
+ else:
+ print("No pages crawled")
+
+ print("\n✅ Crawl complete!")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/firecrawl-scraper/templates/firecrawl-scrape-python.py b/skills/firecrawl-scraper/templates/firecrawl-scrape-python.py
new file mode 100644
index 00000000..e35d9484
--- /dev/null
+++ b/skills/firecrawl-scraper/templates/firecrawl-scrape-python.py
@@ -0,0 +1,107 @@
+#!/usr/bin/env python3
+"""
+Firecrawl Basic Scraping Example (Python) - v4 API
+
+This template demonstrates how to scrape a single webpage using Firecrawl v4 API.
+
+Requirements:
+ pip install firecrawl-py python-dotenv
+
+Environment Variables:
+ FIRECRAWL_API_KEY - Your Firecrawl API key (get from https://www.firecrawl.dev)
+
+Usage:
+ python firecrawl-scrape-python.py
+"""
+
+import os
+from dotenv import load_dotenv
+from firecrawl import Firecrawl
+
+# Load environment variables from .env file
+load_dotenv()
+
+
+def scrape_single_page(url: str):
+ """
+ Scrape a single webpage and return markdown content.
+
+ Args:
+ url: The URL to scrape
+
+ Returns:
+ Document object with markdown, html, metadata attributes
+ """
+ # Initialize Firecrawl client
+ # NEVER hardcode API keys! Always use environment variables
+ api_key = os.environ.get("FIRECRAWL_API_KEY")
+ if not api_key:
+ raise ValueError("FIRECRAWL_API_KEY environment variable not set")
+
+ app = Firecrawl(api_key=api_key)
+
+ try:
+ # Scrape the URL - returns Pydantic Document object
+ doc = app.scrape(
+ url=url,
+ # Output formats - can include multiple
+ formats=["markdown", "html"],
+ # Only extract main content (removes nav, footer, ads)
+ # This saves credits and improves content quality
+ only_main_content=True,
+ # Remove base64 images to reduce response size
+ remove_base64_images=True,
+ # Wait time before scraping (ms) - useful for dynamic content
+ # wait_for=3000,
+ # Include screenshot
+ # formats=["markdown", "screenshot"],
+ )
+
+ return doc
+
+ except Exception as e:
+ print(f"Error scraping {url}: {e}")
+ raise
+
+
+def main():
+ """Main function demonstrating basic scraping."""
+
+ # Example URL to scrape
+ url = "https://docs.firecrawl.dev"
+
+ print(f"Scraping: {url}")
+
+ # Scrape the page
+ doc = scrape_single_page(url)
+
+ # Access different parts of the result via attributes (not dict.get())
+ markdown = doc.markdown or ""
+ html = doc.html or ""
+ metadata = doc.metadata
+
+ # Print results
+ print("\n" + "=" * 80)
+ print("MARKDOWN CONTENT:")
+ print("=" * 80)
+ print(markdown[:500] if markdown else "No markdown content") # First 500 characters
+ print("...")
+
+ print("\n" + "=" * 80)
+ print("METADATA:")
+ print("=" * 80)
+ if metadata:
+ print(f"Title: {getattr(metadata, 'title', 'N/A')}")
+ print(f"Description: {getattr(metadata, 'description', 'N/A')}")
+ print(f"Language: {getattr(metadata, 'language', 'N/A')}")
+ print(f"Source URL: {getattr(metadata, 'source_url', 'N/A')}")
+
+ # Save to file (optional)
+ output_file = "scraped_content.md"
+ with open(output_file, "w", encoding="utf-8") as f:
+ f.write(markdown)
+ print(f"\n✅ Full content saved to: {output_file}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/firecrawl-scraper/templates/firecrawl-scrape-typescript.ts b/skills/firecrawl-scraper/templates/firecrawl-scrape-typescript.ts
new file mode 100644
index 00000000..396436ef
--- /dev/null
+++ b/skills/firecrawl-scraper/templates/firecrawl-scrape-typescript.ts
@@ -0,0 +1,110 @@
+/**
+ * Firecrawl Basic Scraping Example (TypeScript - Node.js)
+ *
+ * This template demonstrates how to scrape a single webpage using Firecrawl SDK.
+ *
+ * ⚠️ NOTE: This example uses the Firecrawl SDK which requires Node.js runtime.
+ * For Cloudflare Workers, use firecrawl-worker-fetch.ts instead (direct fetch API).
+ *
+ * Requirements:
+ * npm install @mendable/firecrawl-js
+ * # or: npm install firecrawl
+ * npm install -D @types/node
+ *
+ * Environment Variables:
+ * FIRECRAWL_API_KEY - Your Firecrawl API key (get from https://www.firecrawl.dev)
+ *
+ * Usage:
+ * npx tsx firecrawl-scrape-typescript.ts
+ * # or compile first:
+ * tsc firecrawl-scrape-typescript.ts && node firecrawl-scrape-typescript.js
+ */
+
+import FirecrawlApp from '@mendable/firecrawl-js';
+import fs from 'fs/promises';
+
+/**
+ * Scrape a single webpage and return markdown content
+ */
+async function scrapeSinglePage(url: string): Promise<{
+ markdown: string;
+ html: string;
+ metadata: Record<string, any>;
+}> {
+ // Initialize Firecrawl client
+ // NEVER hardcode API keys! Always use environment variables
+ const apiKey = process.env.FIRECRAWL_API_KEY;
+ if (!apiKey) {
+ throw new Error('FIRECRAWL_API_KEY environment variable not set');
+ }
+
+ const app = new FirecrawlApp({ apiKey });
+
+ try {
+ // Scrape the URL
+ const result = await app.scrapeUrl(url, {
+ // Output formats - can include multiple
+ formats: ['markdown', 'html'],
+
+ // Only extract main content (removes nav, footer, ads)
+ // This saves credits and improves content quality
+ onlyMainContent: true,
+
+ // Wait time before scraping (ms) - useful for dynamic content
+ // waitFor: 3000,
+
+ // Remove base64 images to reduce response size
+ // removeBase64Images: true,
+
+ // Include screenshot
+ // formats: ['markdown', 'screenshot'],
+ });
+
+ return result;
+ } catch (error) {
+ console.error(`Error scraping ${url}:`, error);
+ throw error;
+ }
+}
+
+/**
+ * Main function demonstrating basic scraping
+ */
+async function main() {
+ // Example URL to scrape
+ const url = 'https://docs.firecrawl.dev';
+
+ console.log(`Scraping: ${url}`);
+
+ // Scrape the page
+ const result = await scrapeSinglePage(url);
+
+ // Access different parts of the result
+ const { markdown, html, metadata } = result;
+
+ // Print results
+ console.log('\n' + '='.repeat(80));
+ console.log('MARKDOWN CONTENT:');
+ console.log('='.repeat(80));
+ console.log(markdown.substring(0, 500)); // First 500 characters
+ console.log('...');
+
+ console.log('\n' + '='.repeat(80));
+ console.log('METADATA:');
+ console.log('='.repeat(80));
+ console.log(`Title: ${metadata.title || 'N/A'}`);
+ console.log(`Description: ${metadata.description || 'N/A'}`);
+ console.log(`Language: ${metadata.language || 'N/A'}`);
+ console.log(`Source URL: ${metadata.sourceURL || 'N/A'}`);
+
+ // Save to file (optional)
+ const outputFile = 'scraped_content.md';
+ await fs.writeFile(outputFile, markdown, 'utf-8');
+ console.log(`\n✅ Full content saved to: ${outputFile}`);
+}
+
+// Run main function
+main().catch((error) => {
+ console.error('Fatal error:', error);
+ process.exit(1);
+});
diff --git a/skills/firecrawl-scraper/templates/firecrawl-worker-fetch.ts b/skills/firecrawl-scraper/templates/firecrawl-worker-fetch.ts
new file mode 100644
index 00000000..2993d2ea
--- /dev/null
+++ b/skills/firecrawl-scraper/templates/firecrawl-worker-fetch.ts
@@ -0,0 +1,329 @@
+/**
+ * Firecrawl with Cloudflare Workers (Direct Fetch API)
+ *
+ * ⚠️ IMPORTANT: The Firecrawl SDK cannot run in Cloudflare Workers due to Node.js
+ * dependencies (axios uses Node.js http module). This template uses direct REST API
+ * calls with the fetch API, which works perfectly in Workers.
+ *
+ * Features:
+ * - Direct Firecrawl v2 API integration using fetch
+ * - Optional KV caching to reduce API calls and credits
+ * - Proper error handling and TypeScript types
+ * - Works in Cloudflare Workers runtime
+ *
+ * Environment Variables (add via wrangler secrets):
+ * FIRECRAWL_API_KEY - Your Firecrawl API key (get from https://www.firecrawl.dev)
+ *
+ * Setup:
+ * 1. Add API key: npx wrangler secret put FIRECRAWL_API_KEY
+ * 2. (Optional) Add KV binding to wrangler.jsonc:
+ * {
+ * "kv_namespaces": [
+ * { "binding": "SCRAPED_CACHE", "id": "your-kv-namespace-id" }
+ * ]
+ * }
+ * 3. Deploy: npx wrangler deploy
+ *
+ * Usage:
+ * POST https://your-worker.workers.dev
+ * Body: { "url": "https://example.com" }
+ */
+
+interface Env {
+ FIRECRAWL_API_KEY: string;
+ SCRAPED_CACHE?: KVNamespace; // Optional: for caching results
+}
+
+interface FirecrawlScrapeRequest {
+ url: string;
+ formats?: ('markdown' | 'html' | 'screenshot')[];
+ onlyMainContent?: boolean;
+ waitFor?: number;
+ removeBase64Images?: boolean;
+ actions?: Array<{
+ type: 'click' | 'wait' | 'scroll';
+ selector?: string;
+ milliseconds?: number;
+ direction?: 'up' | 'down';
+ }>;
+ headers?: Record<string, string>;
+}
+
+interface FirecrawlScrapeResponse {
+ success: boolean;
+ data: {
+ markdown?: string;
+ html?: string;
+ screenshot?: string;
+ metadata: {
+ title?: string;
+ description?: string;
+ language?: string;
+ sourceURL: string;
+ statusCode?: number;
+ };
+ };
+ error?: string;
+}
+
+interface FirecrawlCrawlRequest {
+ url: string;
+ limit?: number;
+ maxDepth?: number;
+ scrapeOptions?: Omit<FirecrawlScrapeRequest, 'url'>;
+ allowedDomains?: string[];
+ excludePaths?: string[];
+ includePaths?: string[];
+ webhook?: string;
+}
+
+interface FirecrawlCrawlResponse {
+ success: boolean;
+ id: string;
+ url: string; // Status check URL
+}
+
+/**
+ * Scrape a single URL using Firecrawl v2 API
+ */
+async function scrapeUrl(
+ url: string,
+ apiKey: string,
+ options: Omit<FirecrawlScrapeRequest, 'url'> = {}
+): Promise<FirecrawlScrapeResponse> {
+ const response = await fetch('https://api.firecrawl.dev/v2/scrape', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ url,
+ formats: options.formats || ['markdown'],
+ onlyMainContent: options.onlyMainContent ?? true,
+ waitFor: options.waitFor,
+ removeBase64Images: options.removeBase64Images ?? true,
+ actions: options.actions,
+ headers: options.headers
+ })
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(`Firecrawl API error (${response.status}): ${errorText}`);
+ }
+
+ return await response.json<FirecrawlScrapeResponse>();
+}
+
+/**
+ * Start a crawl job using Firecrawl v2 API
+ */
+async function crawlUrl(
+ apiKey: string,
+ options: FirecrawlCrawlRequest
+): Promise<FirecrawlCrawlResponse> {
+ const response = await fetch('https://api.firecrawl.dev/v2/crawl', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(options)
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(`Firecrawl API error (${response.status}): ${errorText}`);
+ }
+
+ return await response.json<FirecrawlCrawlResponse>();
+}
+
+/**
+ * Check crawl status
+ */
+async function checkCrawlStatus(
+ crawlId: string,
+ apiKey: string
+): Promise<any> {
+ const response = await fetch(`https://api.firecrawl.dev/v2/crawl/${crawlId}`, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${apiKey}`,
+ }
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(`Firecrawl API error (${response.status}): ${errorText}`);
+ }
+
+ return await response.json();
+}
+
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ // CORS headers (if needed for browser access)
+ const corsHeaders = {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
+ 'Access-Control-Allow-Headers': 'Content-Type',
+ };
+
+ // Handle CORS preflight
+ if (request.method === 'OPTIONS') {
+ return new Response(null, { headers: corsHeaders });
+ }
+
+ // Only accept POST requests
+ if (request.method !== 'POST') {
+ return Response.json(
+ { error: 'Method not allowed. Use POST with JSON body: { "url": "..." }' },
+ { status: 405, headers: corsHeaders }
+ );
+ }
+
+ try {
+ // Parse request body
+ let body: any;
+ try {
+ body = await request.json();
+ } catch (e) {
+ return Response.json(
+ { error: 'Invalid JSON in request body' },
+ { status: 400, headers: corsHeaders }
+ );
+ }
+
+ const { url, action = 'scrape' } = body;
+
+ if (!url) {
+ return Response.json(
+ { error: 'URL is required in request body' },
+ { status: 400, headers: corsHeaders }
+ );
+ }
+
+ // Check if API key is configured
+ if (!env.FIRECRAWL_API_KEY) {
+ return Response.json(
+ { error: 'FIRECRAWL_API_KEY not configured. Run: npx wrangler secret put FIRECRAWL_API_KEY' },
+ { status: 500, headers: corsHeaders }
+ );
+ }
+
+ // Handle different actions
+ if (action === 'scrape') {
+ // Check cache first (if KV is available)
+ const cacheKey = `scrape:${url}`;
+ if (env.SCRAPED_CACHE) {
+ const cached = await env.SCRAPED_CACHE.get(cacheKey, 'json');
+ if (cached) {
+ console.log(`Cache hit for ${url}`);
+ return Response.json(
+ { cached: true, data: cached },
+ { headers: corsHeaders }
+ );
+ }
+ }
+
+ // Scrape the URL
+ console.log(`Scraping ${url}...`);
+ const result = await scrapeUrl(url, env.FIRECRAWL_API_KEY, {
+ formats: body.formats || ['markdown'],
+ onlyMainContent: body.onlyMainContent ?? true,
+ waitFor: body.waitFor,
+ removeBase64Images: body.removeBase64Images ?? true,
+ actions: body.actions,
+ headers: body.headers
+ });
+
+ if (!result.success) {
+ return Response.json(
+ { error: result.error || 'Scraping failed' },
+ { status: 500, headers: corsHeaders }
+ );
+ }
+
+ // Cache result for 1 hour (if KV is available)
+ if (env.SCRAPED_CACHE) {
+ await env.SCRAPED_CACHE.put(
+ cacheKey,
+ JSON.stringify(result.data),
+ { expirationTtl: 3600 } // 1 hour
+ );
+ console.log(`Cached result for ${url}`);
+ }
+
+ return Response.json(
+ { cached: false, data: result.data },
+ { headers: corsHeaders }
+ );
+
+ } else if (action === 'crawl') {
+ // Start a crawl job
+ console.log(`Starting crawl for ${url}...`);
+ const crawlResult = await crawlUrl(env.FIRECRAWL_API_KEY, {
+ url,
+ limit: body.limit,
+ maxDepth: body.maxDepth,
+ scrapeOptions: body.scrapeOptions,
+ allowedDomains: body.allowedDomains,
+ excludePaths: body.excludePaths,
+ includePaths: body.includePaths,
+ webhook: body.webhook
+ });
+
+ return Response.json(crawlResult, { headers: corsHeaders });
+
+ } else if (action === 'crawl-status') {
+ // Check crawl status
+ const crawlId = body.crawlId;
+ if (!crawlId) {
+ return Response.json(
+ { error: 'crawlId is required for crawl-status action' },
+ { status: 400, headers: corsHeaders }
+ );
+ }
+
+ const status = await checkCrawlStatus(crawlId, env.FIRECRAWL_API_KEY);
+ return Response.json(status, { headers: corsHeaders });
+
+ } else {
+ return Response.json(
+ { error: `Unknown action: ${action}. Use 'scrape', 'crawl', or 'crawl-status'` },
+ { status: 400, headers: corsHeaders }
+ );
+ }
+
+ } catch (error) {
+ console.error('Worker error:', error);
+ return Response.json(
+ {
+ error: error instanceof Error ? error.message : 'Unknown error',
+ stack: error instanceof Error ? error.stack : undefined
+ },
+ { status: 500, headers: corsHeaders }
+ );
+ }
+ }
+};
+
+// Example usage with curl:
+/*
+# Scrape a single page
+curl -X POST https://your-worker.workers.dev \
+ -H "Content-Type: application/json" \
+ -d '{"url": "https://docs.firecrawl.dev", "action": "scrape"}'
+
+# Start a crawl
+curl -X POST https://your-worker.workers.dev \
+ -H "Content-Type: application/json" \
+ -d '{"url": "https://docs.example.com", "action": "crawl", "limit": 10}'
+
+# Check crawl status
+curl -X POST https://your-worker.workers.dev \
+ -H "Content-Type: application/json" \
+ -d '{"action": "crawl-status", "crawlId": "abc123"}'
+*/
diff --git a/templates/skill-metadata-v2.yaml b/templates/skill-metadata-v2.yaml
new file mode 100644
index 00000000..348e05c2
--- /dev/null
+++ b/templates/skill-metadata-v2.yaml
@@ -0,0 +1,74 @@
+# Skill Metadata Schema v2
+# Extended schema for deep content auditing
+#
+# This schema extends the standard Claude Code skill frontmatter
+# with metadata fields for automated content validation.
+
+---
+# REQUIRED FIELDS (standard)
+name: skill-name-lowercase-hyphenated
+description: |
+ Short description of what this skill does. First paragraph describes
+ the capability. Second paragraph lists "Use when:" scenarios.
+
+ Use when: [scenario 1], [scenario 2], troubleshooting "[error message]".
+
+# OPTIONAL FIELDS (standard)
+license: MIT
+allowed-tools:
+ - Bash
+ - Read
+ - Write
+ - Glob
+ - Grep
+
+# EXTENDED METADATA (for deep audit)
+metadata:
+ # Documentation sources for content validation
+ doc_sources:
+ # Primary documentation - REQUIRED for deep audit
+ primary: "https://docs.example.com/getting-started"
+
+ # API reference - optional
+ api: "https://docs.example.com/api-reference"
+
+ # Changelog/releases - optional but recommended
+ changelog: "https://github.com/org/repo/releases"
+
+ # Migration guides - optional
+ migration: "https://docs.example.com/migration-v2"
+
+ # Additional sources - optional
+ # Add custom keys as needed (e.g., blog, tutorials)
+
+ # Package ecosystem - REQUIRED for version validation
+ # Options: npm | pypi | github | crates | go | nuget | rubygems
+ ecosystem: npm
+
+ # Package name as it appears in the registry
+ # May differ from skill name (e.g., "@clerk/nextjs" vs "clerk-auth")
+ package_name: "@example/package"
+
+ # Alternative package names (for scoped packages, forks, etc.)
+ alt_packages:
+ - "example-package" # Non-scoped version
+ - "@other-org/example" # Fork/alternative
+
+ # Tier for audit prioritization (1 = highest priority)
+ tier: 1
+
+ # Last verified date (updated by audit scripts)
+ last_verified: "2026-01-09"
+
+ # Keywords for improved discovery
+ keywords:
+ - example
+ - api
+ - integration
+---
+
+# Skill Title
+
+## Quick Start
+
+[Skill content continues here...]