mcp-scraper 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +56 -0
  2. package/dist/bin/api-server.cjs +9256 -0
  3. package/dist/bin/api-server.cjs.map +1 -0
  4. package/dist/bin/api-server.d.cts +1 -0
  5. package/dist/bin/api-server.d.ts +1 -0
  6. package/dist/bin/api-server.js +38 -0
  7. package/dist/bin/api-server.js.map +1 -0
  8. package/dist/bin/mcp-stdio-server.cjs +840 -0
  9. package/dist/bin/mcp-stdio-server.cjs.map +1 -0
  10. package/dist/bin/mcp-stdio-server.d.cts +1 -0
  11. package/dist/bin/mcp-stdio-server.d.ts +1 -0
  12. package/dist/bin/mcp-stdio-server.js +41 -0
  13. package/dist/bin/mcp-stdio-server.js.map +1 -0
  14. package/dist/bin/paa-harvest.cjs +1438 -0
  15. package/dist/bin/paa-harvest.cjs.map +1 -0
  16. package/dist/bin/paa-harvest.d.cts +1 -0
  17. package/dist/bin/paa-harvest.d.ts +1 -0
  18. package/dist/bin/paa-harvest.js +37 -0
  19. package/dist/bin/paa-harvest.js.map +1 -0
  20. package/dist/chunk-4API3ZCT.js +1387 -0
  21. package/dist/chunk-4API3ZCT.js.map +1 -0
  22. package/dist/chunk-LXZDJJXR.js +476 -0
  23. package/dist/chunk-LXZDJJXR.js.map +1 -0
  24. package/dist/chunk-ZBP4RHNW.js +805 -0
  25. package/dist/chunk-ZBP4RHNW.js.map +1 -0
  26. package/dist/db-IOYMX64U.js +87 -0
  27. package/dist/db-IOYMX64U.js.map +1 -0
  28. package/dist/index.cjs +1689 -0
  29. package/dist/index.cjs.map +1 -0
  30. package/dist/index.d.cts +210 -0
  31. package/dist/index.d.ts +210 -0
  32. package/dist/index.js +275 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/server-63DR2HE5.js +6062 -0
  35. package/dist/server-63DR2HE5.js.map +1 -0
  36. package/dist/worker-3ECJHPRE.js +88 -0
  37. package/dist/worker-3ECJHPRE.js.map +1 -0
  38. package/package.json +76 -0
@@ -0,0 +1,805 @@
1
+ // src/mcp/paa-mcp-server.ts
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+
4
+ // src/mcp/mcp-tool-schemas.ts
5
+ import { z } from "zod";
6
+ var HarvestPaaInputSchema = {
7
+ query: z.string().min(1).describe("Search query to harvest PAA questions for"),
8
+ location: z.string().optional().describe("Location name for geo-targeted results"),
9
+ maxQuestions: z.number().int().min(1).max(100).default(30).describe("Number of PAA questions to extract (max 100)"),
10
+ gl: z.string().length(2).default("us"),
11
+ hl: z.string().default("en")
12
+ };
13
+ var ExtractUrlInputSchema = {
14
+ url: z.string().url()
15
+ };
16
+ var MapSiteUrlsInputSchema = {
17
+ url: z.string().url(),
18
+ maxUrls: z.number().int().min(1).max(500).optional()
19
+ };
20
+ var ExtractSiteInputSchema = {
21
+ url: z.string().url(),
22
+ maxPages: z.number().int().min(1).max(50).optional()
23
+ };
24
+ var YoutubeHarvestInputSchema = {
25
+ mode: z.enum(["search", "channel"]),
26
+ query: z.string().optional().describe("Required when mode is search"),
27
+ channelHandle: z.string().optional().describe("YouTube channel handle, e.g. @mkbhd"),
28
+ maxVideos: z.number().int().min(1).max(500).default(50)
29
+ };
30
+ var YoutubeTranscribeInputSchema = {
31
+ videoId: z.string().min(1).describe("YouTube video ID, e.g. dQw4w9WgXcQ")
32
+ };
33
+ var FacebookPageIntelInputSchema = {
34
+ pageId: z.string().optional(),
35
+ libraryId: z.string().optional(),
36
+ query: z.string().optional().describe("One of pageId, libraryId, or query is required"),
37
+ maxAds: z.number().int().min(1).max(200).default(50),
38
+ country: z.string().length(2).default("US")
39
+ };
40
+ var FacebookAdSearchInputSchema = {
41
+ query: z.string().min(1),
42
+ country: z.string().length(2).default("US"),
43
+ maxResults: z.number().int().min(1).max(20).default(10)
44
+ };
45
+ var FacebookAdTranscribeInputSchema = {
46
+ videoUrl: z.string().url().describe("Facebook CDN video URL from a facebook_page_intel result")
47
+ };
48
+ var MapsPlaceIntelInputSchema = {
49
+ businessName: z.string().min(1).describe("Business name to search for on Google Maps"),
50
+ location: z.string().min(1).describe('City and state, e.g. "Denver, CO"'),
51
+ gl: z.string().length(2).default("us"),
52
+ hl: z.string().length(2).default("en"),
53
+ includeReviews: z.boolean().default(false).describe("Whether to fetch individual review cards"),
54
+ maxReviews: z.number().int().min(1).max(500).default(50).describe("Max review cards to return (requires includeReviews: true)")
55
+ };
56
+ var CreditsInfoInputSchema = {
57
+ item: z.string().optional().describe('Optional tool, action, or feature to look up, e.g. "maps reviews", "extract_url", or "YouTube transcription"'),
58
+ includeLedger: z.boolean().default(false).describe("Whether to include recent credit ledger entries")
59
+ };
60
+ var SearchSerpInputSchema = {
61
+ query: z.string().min(1).describe("Search query to retrieve organic Google results for"),
62
+ location: z.string().optional().describe("Location name for geo-targeted results"),
63
+ gl: z.string().length(2).default("us"),
64
+ hl: z.string().default("en"),
65
+ pages: z.number().int().min(1).max(2).default(1).describe("Number of result pages to fetch (1\u20132)")
66
+ };
67
+
68
+ // src/mcp/mcp-response-formatter.ts
69
+ function twoBlocks(full, summary) {
70
+ return { content: [{ type: "text", text: full }, { type: "text", text: summary }] };
71
+ }
72
+ function parseData(raw) {
73
+ const first = raw.content.find((b) => b.type === "text");
74
+ const text = first?.type === "text" ? first.text : "";
75
+ try {
76
+ const parsed = JSON.parse(text || "{}");
77
+ if (parsed.error === "insufficient_balance") {
78
+ return { error: `Insufficient credits. Balance: ${parsed.balance_credits} credits. This call requires ${parsed.required_credits} credits. Top up at ${parsed.topup_url}` };
79
+ }
80
+ if (raw.isError) return { error: text || "Tool error" };
81
+ const data = parsed.result ?? parsed;
82
+ return { data };
83
+ } catch {
84
+ if (raw.isError) return { error: text || "Tool error" };
85
+ return { error: "Failed to parse tool response" };
86
+ }
87
+ }
88
+ function entityIdsSection(ids) {
89
+ if (!ids) return "";
90
+ const lines = [];
91
+ if (ids.kgIds?.length) lines.push(`- **Knowledge Graph MID:** ${ids.kgIds.join(", ")}`);
92
+ if (ids.cids?.length) lines.push(`- **CID:** ${ids.cids.join(", ")}`);
93
+ if (ids.gcids?.length) lines.push(`- **GCID:** ${ids.gcids.join(", ")}`);
94
+ return lines.length ? `
95
+ ## Entity IDs
96
+ ${lines.join("\n")}` : "";
97
+ }
98
+ function entityIdsSummaryLine(ids) {
99
+ if (!ids) return "";
100
+ const parts = [];
101
+ if (ids.kgIds?.length) parts.push(`KG MID: ${ids.kgIds[0]}`);
102
+ if (ids.cids?.length) parts.push(`CID: ${ids.cids[0]}`);
103
+ if (ids.gcids?.length) parts.push(`GCID: ${ids.gcids[0]}`);
104
+ return parts.length ? `
105
+ **Entity IDs:** ${parts.join(" \xB7 ")}` : "";
106
+ }
107
+ function truncate(s, max) {
108
+ if (!s) return "";
109
+ return s.length > max ? s.slice(0, max) + "\u2026" : s;
110
+ }
111
+ var DIRECTIVE_FULL = "> \u{1F4C4} **FULL REPORT** \u2014 render as artifact or expandable block\n\n";
112
+ var DIRECTIVE_SUMMARY = "> \u{1F4AC} **SUMMARY** \u2014 present this inline; offer the full report above as an artifact\n\n";
113
+ function formatHarvestPaa(raw, input) {
114
+ const parsed = parseData(raw);
115
+ if ("error" in parsed) return { content: [{ type: "text", text: parsed.error }], isError: true };
116
+ const d = parsed.data;
117
+ const flat = d.flat ?? [];
118
+ const organic = d.organicResults ?? [];
119
+ const entityIds = d.entityIds;
120
+ const aiOvw = d.aiOverview;
121
+ const durationMs = d.stats?.durationMs;
122
+ const paaRows = flat.map(
123
+ (r, i) => `| ${i + 1} | ${r.question} | ${truncate(r.answer, 120)} | ${r.source_site ?? ""} |`
124
+ ).join("\n");
125
+ const paaTable = flat.length ? `## People Also Ask (${flat.length} questions)
126
+ | # | Question | Answer | Source |
127
+ |---|----------|--------|--------|
128
+ ${paaRows}` : "## People Also Ask\n*No questions extracted*";
129
+ const serpRows = organic.map(
130
+ (r) => `| ${r.position} | ${r.title} | [${r.domain}](${r.url}) | ${truncate(r.snippet, 100)} |`
131
+ ).join("\n");
132
+ const serpTable = organic.length ? `
133
+ ## Organic Results (${organic.length})
134
+ | # | Title | URL | Snippet |
135
+ |---|-------|-----|----------|
136
+ ${serpRows}` : "";
137
+ const aiSection = aiOvw?.detected && aiOvw.text ? `
138
+ ## AI Overview
139
+ > ${truncate(aiOvw.text, 600)}` : "";
140
+ const statsLine = durationMs ? `
141
+ ## Stats
142
+ - Questions: ${flat.length} \xB7 Duration: ${(durationMs / 1e3).toFixed(1)}s` : "";
143
+ const tips = `
144
+ ---
145
+ \u{1F4A1} **Tips**
146
+ - Max questions: \`maxQuestions: 100\` (current: ${input.maxQuestions ?? 30})
147
+ - Organic results only: use \`search_serp\`
148
+ - Dig into a result: use \`extract_url\` on any organic URL`;
149
+ const full = `${DIRECTIVE_FULL}# PAA Report: "${input.query}"${input.location ? ` \xB7 ${input.location}` : ""}
150
+
151
+ ${paaTable}${serpTable}${entityIdsSection(entityIds)}${aiSection}${statsLine}${tips}`;
152
+ const topQ = flat.slice(0, 10).map((r, i) => `${i + 1}. ${r.question}`).join("\n");
153
+ const topO = organic.slice(0, 5).map((r) => `${r.position}. [${r.title}](${r.url}) \u2014 ${r.domain}`).join("\n");
154
+ const summary = [
155
+ `${DIRECTIVE_SUMMARY}**PAA: "${input.query}"** \u2014 ${flat.length} questions extracted`,
156
+ topQ ? `
157
+ **Top questions:**
158
+ ${topQ}` : "",
159
+ organic.length ? `
160
+ **Top organic results:**
161
+ ${topO}` : "",
162
+ entityIdsSummaryLine(entityIds),
163
+ `
164
+ \u{1F4A1} \`maxQuestions\` up to 100 \xB7Use \`extract_url\` to dig into any result`
165
+ ].filter(Boolean).join("\n");
166
+ return twoBlocks(full, summary);
167
+ }
168
+ function formatSearchSerp(raw, input) {
169
+ const parsed = parseData(raw);
170
+ if ("error" in parsed) return { content: [{ type: "text", text: parsed.error }], isError: true };
171
+ const d = parsed.data;
172
+ const organic = d.organicResults ?? [];
173
+ const localPack = d.localPack ?? [];
174
+ const entityIds = d.entityIds;
175
+ const aiOvw = d.aiOverview;
176
+ const serpRows = organic.map(
177
+ (r) => `| ${r.position} | ${r.title} | [${r.domain}](${r.url}) | ${truncate(r.snippet, 100)} |`
178
+ ).join("\n");
179
+ const serpTable = organic.length ? `## Organic Results (${organic.length})
180
+ | # | Title | URL | Snippet |
181
+ |---|-------|-----|----------|
182
+ ${serpRows}` : "## Organic Results\n*None found*";
183
+ const localRows = localPack.map(
184
+ (b) => `| ${b.position} | ${b.name} | ${b.rating ?? "\u2014"} (${b.reviewCount ?? "0"}) | ${b.websiteUrl ? `[link](${b.websiteUrl})` : "\u2014"} |`
185
+ ).join("\n");
186
+ const localSection = localPack.length ? `
187
+ ## Local Pack (${localPack.length})
188
+ | # | Name | Rating | Website |
189
+ |---|------|--------|---------|
190
+ ${localRows}` : "";
191
+ const aiSection = aiOvw?.detected && aiOvw.text ? `
192
+ ## AI Overview
193
+ > ${truncate(aiOvw.text, 600)}` : "";
194
+ const tips = `
195
+ ---
196
+ \u{1F4A1} **Tips**
197
+ - Get PAA questions: use \`harvest_paa\` for this query
198
+ - Scrape any result: use \`extract_url\`
199
+ - Business entity IDs (CID/GCID/KG MID) shown above if found`;
200
+ const full = `${DIRECTIVE_FULL}# SERP Report: "${input.query}"${input.location ? ` \xB7 ${input.location}` : ""}
201
+
202
+ ${serpTable}${localSection}${entityIdsSection(entityIds)}${aiSection}${tips}`;
203
+ const topO = organic.slice(0, 5).map((r) => `${r.position}. [${r.title}](${r.url}) \u2014 ${r.domain}`).join("\n");
204
+ const summary = [
205
+ `${DIRECTIVE_SUMMARY}**SERP: "${input.query}"** \u2014 ${organic.length} organic results`,
206
+ topO ? `
207
+ **Top results:**
208
+ ${topO}` : "",
209
+ localPack.length ? `
210
+ **Local Pack:** ${localPack.map((b) => b.name).join(", ")}` : "",
211
+ entityIdsSummaryLine(entityIds),
212
+ `
213
+ \u{1F4A1} Use \`harvest_paa\` for questions \xB7 \`extract_url\` to scrape any result`
214
+ ].filter(Boolean).join("\n");
215
+ return twoBlocks(full, summary);
216
+ }
217
+ function formatExtractUrl(raw, input) {
218
+ const parsed = parseData(raw);
219
+ if ("error" in parsed) return { content: [{ type: "text", text: parsed.error }], isError: true };
220
+ const d = parsed.data;
221
+ const url = d.url ?? input.url;
222
+ const title = d.title ?? "Untitled";
223
+ const headings = d.headings ?? [];
224
+ const kpo = d.kpo;
225
+ const bodyMd = d.bodyMarkdown ?? "";
226
+ const schema = d.schema;
227
+ const h1Lines = headings.filter((h) => h.level === 1).map((h) => `- ${h.text}`).join("\n");
228
+ const h2Lines = headings.filter((h) => h.level === 2).map((h) => ` - ${h.text}`).join("\n");
229
+ const headingSection = h1Lines || h2Lines ? `
230
+ ## Heading Structure
231
+ ${[h1Lines, h2Lines].filter(Boolean).join("\n")}` : "";
232
+ const kpoSection = kpo ? [
233
+ `
234
+ ## Entity / Schema`,
235
+ kpo.entityName ? `- **Entity:** ${kpo.entityName}` : "",
236
+ kpo.type?.length ? `- **@type:** ${kpo.type.join(", ")}` : "",
237
+ kpo.napScore !== void 0 ? `- **NAP Score:** ${kpo.napScore}/5` : "",
238
+ kpo.address ? `- **Address:** ${kpo.address}` : "",
239
+ kpo.phone ? `- **Phone:** ${kpo.phone}` : "",
240
+ kpo.email ? `- **Email:** ${kpo.email}` : "",
241
+ kpo.faqCount ? `- **FAQ items:** ${kpo.faqCount}` : "",
242
+ kpo.sameAs?.length ? `- **sameAs:** ${kpo.sameAs.slice(0, 5).join(", ")}` : "",
243
+ kpo.missingFields?.length ? `
244
+ **Missing schema fields:** ${kpo.missingFields.slice(0, 5).join(", ")}` : ""
245
+ ].filter(Boolean).join("\n") : "";
246
+ const bodySection = bodyMd ? `
247
+ ## Page Content
248
+ ${bodyMd.slice(0, 3e3)}${bodyMd.length > 3e3 ? "\n\n*(truncated)*" : ""}` : "";
249
+ const schemaCount = Array.isArray(schema) ? schema.length : 0;
250
+ const tips = `
251
+ ---
252
+ \u{1F4A1} **Tips**
253
+ - Crawl entire site: use \`extract_site\`
254
+ - Map all URLs: use \`map_site_urls\`
255
+ - ${schemaCount} JSON-LD schema block(s) detected`;
256
+ const full = `${DIRECTIVE_FULL}# URL Extract: ${url}
257
+ **${title}**
258
+ ${headingSection}${kpoSection}${bodySection}${tips}`;
259
+ const summary = [
260
+ `${DIRECTIVE_SUMMARY}**Extracted:** ${title}`,
261
+ `**URL:** ${url}`,
262
+ kpo?.entityName ? `**Entity:** ${kpo.entityName} (${kpo.type?.join(", ") ?? "unknown"})` : "",
263
+ kpo?.napScore !== void 0 ? `**NAP Score:** ${kpo.napScore}/5` : "",
264
+ headings.length ? `**${headings.length} headings**` : "",
265
+ `
266
+ \u{1F4A1} Use \`extract_site\` to crawl the full domain`
267
+ ].filter(Boolean).join("\n");
268
+ return twoBlocks(full, summary);
269
+ }
270
+ function formatMapSiteUrls(raw, input) {
271
+ const parsed = parseData(raw);
272
+ if ("error" in parsed) return { content: [{ type: "text", text: parsed.error }], isError: true };
273
+ const d = parsed.data;
274
+ const urls = d.urls ?? [];
275
+ const ok = urls.filter((u) => (u.status ?? 0) >= 200 && (u.status ?? 0) < 300);
276
+ const broken = urls.filter((u) => u.status !== null && u.status >= 400);
277
+ const redirects = urls.filter((u) => u.status !== null && u.status >= 300 && u.status < 400);
278
+ const urlRows = urls.slice(0, 200).map((u, i) => `| ${i + 1} | ${u.url} | ${u.status ?? "\u2014"} |`).join("\n");
279
+ const full = [
280
+ `${DIRECTIVE_FULL}# URL Map: ${input.url}`,
281
+ `**${d.totalFound} URLs** \xB7 ${(d.durationMs / 1e3).toFixed(1)}s${d.truncated ? " \xB7 *truncated*" : ""}`,
282
+ `
283
+ ## Summary
284
+ - \u2705 2xx: ${ok.length}
285
+ - \u{1F500} 3xx: ${redirects.length}
286
+ - \u274C 4xx+: ${broken.length}`,
287
+ `
288
+ ## URL Inventory
289
+ | # | URL | Status |
290
+ |---|-----|--------|
291
+ ${urlRows}`,
292
+ broken.length ? `
293
+ ## Broken URLs
294
+ ${broken.map((u) => `- ${u.url} (${u.status})`).join("\n")}` : "",
295
+ `
296
+ ---
297
+ \u{1F4A1} **Tips**
298
+ - Extract content from all pages: use \`extract_site\`
299
+ - Scrape a single page: use \`extract_url\``
300
+ ].filter(Boolean).join("\n");
301
+ const summary = [
302
+ `${DIRECTIVE_SUMMARY}**URL Map: ${input.url}**`,
303
+ `${d.totalFound} URLs \u2014 ${ok.length} OK \xB7 ${broken.length} broken \xB7 ${redirects.length} redirects`,
304
+ broken.length ? `
305
+ **Broken URLs:** ${broken.slice(0, 3).map((u) => u.url).join(", ")}` : "",
306
+ `
307
+ \u{1F4A1} Use \`extract_site\` to extract content from all pages`
308
+ ].filter(Boolean).join("\n");
309
+ return twoBlocks(full, summary);
310
+ }
311
+ function formatExtractSite(raw, input) {
312
+ const parsed = parseData(raw);
313
+ if ("error" in parsed) return { content: [{ type: "text", text: parsed.error }], isError: true };
314
+ const d = parsed.data;
315
+ const pages = d.pages ?? [];
316
+ const pageRows = pages.map((p, i) => {
317
+ const schemaInfo = p.kpo?.type?.join(", ") ?? (Array.isArray(p.schema) && p.schema.length ? `${p.schema.length} block(s)` : "\u2014");
318
+ return `| ${i + 1} | ${p.title ?? "Untitled"} | ${p.url} | ${schemaInfo} |`;
319
+ }).join("\n");
320
+ const full = [
321
+ `${DIRECTIVE_FULL}# Site Extract: ${input.url}`,
322
+ `**${pages.length} pages** \xB7 ${((d.durationMs ?? 0) / 1e3).toFixed(1)}s`,
323
+ `
324
+ ## Pages
325
+ | # | Title | URL | Schema |
326
+ |---|-------|-----|--------|
327
+ ${pageRows}`,
328
+ `
329
+ ---
330
+ \u{1F4A1} **Tips**
331
+ - Map URLs first: use \`map_site_urls\`
332
+ - Inspect a single page: use \`extract_url\``
333
+ ].join("\n");
334
+ const summary = [
335
+ `${DIRECTIVE_SUMMARY}**Site Extract: ${input.url}** \u2014 ${pages.length} pages`,
336
+ pages.slice(0, 5).map((p) => `- ${p.title ?? p.url}`).join("\n"),
337
+ pages.length > 5 ? `- \u2026 and ${pages.length - 5} more` : "",
338
+ `
339
+ \u{1F4A1} Use \`extract_url\` to inspect any individual page`
340
+ ].filter(Boolean).join("\n");
341
+ return twoBlocks(full, summary);
342
+ }
343
+ function formatYoutubeHarvest(raw, input) {
344
+ const parsed = parseData(raw);
345
+ if ("error" in parsed) return { content: [{ type: "text", text: parsed.error }], isError: true };
346
+ const d = parsed.data;
347
+ const videos = d.videos ?? [];
348
+ const label = input.mode === "channel" ? input.channelHandle ?? "channel" : `"${input.query ?? ""}"`;
349
+ const videoRows = videos.map(
350
+ (v, i) => `| ${i + 1} | ${truncate(v.title, 70)} | ${v.channelName} | ${v.views ?? "\u2014"} | ${v.duration ?? "\u2014"} | \`${v.videoId}\` |`
351
+ ).join("\n");
352
+ const channelSection = d.channelMeta ? `
353
+ ## Channel
354
+ - **Name:** ${d.channelMeta.title ?? "\u2014"}
355
+ - **Subscribers:** ${d.channelMeta.subscriberCount ?? "\u2014"}` : "";
356
+ const full = [
357
+ `${DIRECTIVE_FULL}# YouTube Harvest: ${label}`,
358
+ `**${videos.length} videos** \xB7 ${(d.stats.durationMs / 1e3).toFixed(1)}s`,
359
+ channelSection,
360
+ `
361
+ ## Videos
362
+ | # | Title | Channel | Views | Duration | Video ID |
363
+ |---|-------|---------|-------|----------|----------|
364
+ ${videoRows}`,
365
+ `
366
+ ---
367
+ \u{1F4A1} **Tips**
368
+ - Transcribe a video: use \`youtube_transcribe\` with the \`videoId\` above
369
+ - Switch mode: \`mode: "channel"\` with \`channelHandle\` or \`mode: "search"\` with \`query\``
370
+ ].filter(Boolean).join("\n");
371
+ const top5 = videos.slice(0, 5).map((v, i) => `${i + 1}. ${v.title} (\`${v.videoId}\`)`).join("\n");
372
+ const summary = [
373
+ `${DIRECTIVE_SUMMARY}**YouTube: ${label}** \u2014 ${videos.length} videos`,
374
+ `
375
+ **Top videos:**
376
+ ${top5}`,
377
+ `
378
+ \u{1F4A1} Transcribe any video: \`youtube_transcribe\` with its videoId`
379
+ ].join("\n");
380
+ return twoBlocks(full, summary);
381
+ }
382
+ function formatYoutubeTranscribe(raw, input) {
383
+ const parsed = parseData(raw);
384
+ if ("error" in parsed) return { content: [{ type: "text", text: parsed.error }], isError: true };
385
+ const d = parsed.data;
386
+ const text = d.text ?? "";
387
+ const chunks = d.chunks ?? [];
388
+ const durSec = d.durationMs ? (d.durationMs / 1e3).toFixed(0) : "\u2014";
389
+ const chunkRows = chunks.slice(0, 50).map((c) => {
390
+ const sec = Math.floor(c.startMs / 1e3);
391
+ const mm = String(Math.floor(sec / 60)).padStart(2, "0");
392
+ const ss = String(sec % 60).padStart(2, "0");
393
+ return `| ${mm}:${ss} | ${truncate(c.text, 120)} |`;
394
+ }).join("\n");
395
+ const full = [
396
+ `${DIRECTIVE_FULL}# YouTube Transcript: \`${input.videoId}\``,
397
+ `**Duration:** ${durSec}s \xB7 **${text.split(" ").length} words**`,
398
+ `
399
+ ## Full Transcript
400
+ ${text}`,
401
+ chunks.length ? `
402
+ ## Timestamped Chunks
403
+ | Time | Text |
404
+ |------|------|
405
+ ${chunkRows}` : "",
406
+ `
407
+ ---
408
+ \u{1F4A1} Harvest more from this channel: use \`youtube_harvest\` with \`mode: "channel"\``
409
+ ].filter(Boolean).join("\n");
410
+ const summary = [
411
+ `${DIRECTIVE_SUMMARY}**YouTube Transcript: \`${input.videoId}\`** \u2014 ${text.split(" ").length} words \xB7 ${durSec}s`,
412
+ `
413
+ **Preview:**
414
+ > ${truncate(text, 300)}`,
415
+ `
416
+ \u{1F4A1} Full transcript in artifact above`
417
+ ].join("\n");
418
+ return twoBlocks(full, summary);
419
+ }
420
+ function formatFacebookPageIntel(raw, input) {
421
+ const parsed = parseData(raw);
422
+ if ("error" in parsed) return { content: [{ type: "text", text: parsed.error }], isError: true };
423
+ const d = parsed.data;
424
+ const advertiser = d.advertiserName ?? input.query ?? input.pageId ?? input.libraryId ?? "Advertiser";
425
+ const ads = d.ads ?? [];
426
+ const s = d.summary ?? { totalAds: 0, activeCount: 0, videoCount: 0, imageCount: 0 };
427
+ const adBlocks = ads.map((ad, i) => [
428
+ `### Ad ${i + 1}${ad.libraryId ? ` \xB7 \`${ad.libraryId}\`` : ""} \u2014 ${ad.status ?? "\u2014"} \xB7 ${ad.creativeType ?? "\u2014"} \xB7 ${ad.startDate ?? "\u2014"}`,
429
+ ad.headline ? `**Headline:** ${ad.headline}` : "",
430
+ ad.primaryText ? `**Copy:** ${truncate(ad.primaryText, 200)}` : "",
431
+ ad.cta ? `**CTA:** ${ad.cta}` : "",
432
+ ad.videoUrl ? `**Video URL:** \`${ad.videoUrl}\`` : "",
433
+ ad.variations ? `**Variations:** ${ad.variations}` : ""
434
+ ].filter(Boolean).join("\n")).join("\n\n---\n\n");
435
+ const full = [
436
+ `${DIRECTIVE_FULL}# Facebook Ad Intel: ${advertiser}`,
437
+ `**${s.totalAds} ads** \xB7 ${s.activeCount} active \xB7 ${s.videoCount} video \xB7 ${s.imageCount} image`,
438
+ `
439
+ ${adBlocks}`,
440
+ `
441
+ ---
442
+ \u{1F4A1} **Tips**
443
+ - Transcribe video ads: use \`facebook_ad_transcribe\` with the \`videoUrl\` above
444
+ - Find other advertisers: use \`facebook_ad_search\``
445
+ ].filter(Boolean).join("\n");
446
+ const activeAds = ads.filter((a) => a.status?.toLowerCase() === "active").slice(0, 5);
447
+ const adSummary = activeAds.map((a, i) => `${i + 1}. ${truncate(a.headline ?? a.primaryText, 80)} (${a.creativeType ?? "\u2014"})`).join("\n");
448
+ const videoCount = ads.filter((a) => a.videoUrl).length;
449
+ const summary = [
450
+ `${DIRECTIVE_SUMMARY}**Facebook Ads: ${advertiser}** \u2014 ${s.totalAds} ads (${s.activeCount} active)`,
451
+ adSummary ? `
452
+ **Active ads:**
453
+ ${adSummary}` : "",
454
+ `**Creative mix:** ${s.videoCount} video \xB7 ${s.imageCount} image`,
455
+ videoCount ? `
456
+ \u{1F4A1} ${videoCount} video ads \u2014 transcribe with \`facebook_ad_transcribe\` using the videoUrl` : ""
457
+ ].filter(Boolean).join("\n");
458
+ return twoBlocks(full, summary);
459
+ }
460
+ function formatFacebookAdSearch(raw, input) {
461
+ const parsed = parseData(raw);
462
+ if ("error" in parsed) return { content: [{ type: "text", text: parsed.error }], isError: true };
463
+ const d = parsed.data;
464
+ const advertisers = d.results ?? d.advertisers ?? [];
465
+ const rows = advertisers.map(
466
+ (a, i) => `| ${i + 1} | ${a.name} | ${a.adCount ?? "\u2014"} | \`${a.libraryId ?? "\u2014"}\` |`
467
+ ).join("\n");
468
+ const full = [
469
+ `${DIRECTIVE_FULL}# Facebook Ad Library Search: "${input.query}"`,
470
+ `**${advertisers.length} advertisers found**`,
471
+ `
472
+ ## Advertisers
473
+ | # | Name | Ad Count | Library ID |
474
+ |---|------|----------|------------|
475
+ ${rows}`,
476
+ `
477
+ ---
478
+ \u{1F4A1} **Tips**
479
+ - Scan all ads: use \`facebook_page_intel\` with \`libraryId\`
480
+ - Or pass the advertiser name as \`query\` in \`facebook_page_intel\``
481
+ ].join("\n");
482
+ const summary = [
483
+ `${DIRECTIVE_SUMMARY}**Facebook Ad Search: "${input.query}"** \u2014 ${advertisers.length} advertisers`,
484
+ advertisers.slice(0, 5).map(
485
+ (a, i) => `${i + 1}. ${a.name}${a.adCount ? ` (${a.adCount} ads)` : ""} \u2014 \`${a.libraryId ?? "\u2014"}\``
486
+ ).join("\n"),
487
+ `
488
+ \u{1F4A1} Scan ads with \`facebook_page_intel\` using \`libraryId\``
489
+ ].filter(Boolean).join("\n");
490
+ return twoBlocks(full, summary);
491
+ }
492
+ function formatCreditsInfo(raw, input) {
493
+ const parsed = parseData(raw);
494
+ if ("error" in parsed) return { content: [{ type: "text", text: parsed.error }], isError: true };
495
+ const d = parsed.data;
496
+ const balance = d.balance_credits;
497
+ const costs = d.costs ?? [];
498
+ const matched = d.matched_cost;
499
+ const ledger = d.ledger ?? [];
500
+ const costRows = costs.map((c) => {
501
+ const notes = c.notes ? ` ${c.notes}` : "";
502
+ return `| ${c.label} | ${c.credits} | ${c.unit}${notes} |`;
503
+ }).join("\n");
504
+ const ledgerRows = ledger.map((row) => {
505
+ const credits = row.amount_mc / 1e3;
506
+ return `| ${row.created_at} | ${row.operation} | ${credits} | ${row.description ?? ""} |`;
507
+ }).join("\n");
508
+ const matchedSection = matched ? `
509
+ ## Matched Cost
510
+ **${matched.label}:** ${matched.credits} credits ${matched.unit}${matched.notes ? `
511
+
512
+ ${matched.notes}` : ""}` : input.item ? `
513
+ ## Matched Cost
514
+ No exact cost match found for "${input.item}". See the full cost table below.` : "";
515
+ const full = [
516
+ `${DIRECTIVE_FULL}# Credits`,
517
+ `**Balance:** ${balance ?? "unknown"} credits`,
518
+ matchedSection,
519
+ costs.length ? `
520
+ ## Cost Table
521
+ | Item | Credits | Unit |
522
+ |------|---------|------|
523
+ ${costRows}` : "",
524
+ ledger.length ? `
525
+ ## Recent Ledger
526
+ | Date | Operation | Credits | Description |
527
+ |------|-----------|---------|-------------|
528
+ ${ledgerRows}` : ""
529
+ ].filter(Boolean).join("\n");
530
+ const summary = [
531
+ `${DIRECTIVE_SUMMARY}**Credit balance:** ${balance ?? "unknown"} credits`,
532
+ matched ? `
533
+ **${matched.label}:** ${matched.credits} credits ${matched.unit}` : null,
534
+ input.includeLedger && ledger.length ? `
535
+ Recent ledger entries included in the full report.` : null
536
+ ].filter(Boolean).join("\n");
537
+ return twoBlocks(full, summary);
538
+ }
539
+ function formatMapsPlaceIntel(raw, input) {
540
+ const parsed = parseData(raw);
541
+ if ("error" in parsed) return { content: [{ type: "text", text: parsed.error }], isError: true };
542
+ const d = parsed.data;
543
+ const name = d.name ?? input.businessName;
544
+ const rating = d.rating;
545
+ const reviewCount = d.reviewCount;
546
+ const category = d.category;
547
+ const address = d.address;
548
+ const phone = d.phoneDisplay;
549
+ const website = d.website;
550
+ const hoursSummary = d.hoursSummary;
551
+ const plusCode = d.plusCode;
552
+ const bookingUrl = d.bookingUrl;
553
+ const kgmid = d.kgmid;
554
+ const cidDecimal = d.cidDecimal;
555
+ const cidUrl = d.cidUrl;
556
+ const lat = d.lat;
557
+ const lng = d.lng;
558
+ const durationMs = d.durationMs;
559
+ const histogram = d.reviewHistogram ?? [];
560
+ const topics = d.reviewTopics ?? [];
561
+ const about = d.aboutAttributes ?? [];
562
+ const reviews = d.reviews ?? [];
563
+ const hoursTable = d.hoursTable ?? [];
564
+ const ratingLine = [rating, reviewCount ? `(${reviewCount} reviews)` : null].filter(Boolean).join(" ");
565
+ const basicLines = [
566
+ address ? `- **Address:** ${address}` : null,
567
+ phone ? `- **Phone:** ${phone}` : null,
568
+ website ? `- **Website:** ${website}` : null,
569
+ hoursSummary ? `- **Hours:** ${hoursSummary}` : null,
570
+ plusCode ? `- **Plus Code:** ${plusCode}` : null,
571
+ bookingUrl ? `- **Book:** ${bookingUrl}` : null
572
+ ].filter(Boolean).join("\n");
573
+ const hoursSection = hoursTable.length ? `
574
+ ## Hours
575
+ | Day | Hours |
576
+ |-----|-------|
577
+ ${hoursTable.map((r) => `| ${r.day} | ${r.hours} |`).join("\n")}` : "";
578
+ const histSection = histogram.length ? `
579
+ ## Rating Distribution
580
+ | Stars | Count |
581
+ |-------|-------|
582
+ ${histogram.map((r) => `| ${"\u2605".repeat(r.stars)}${"\u2606".repeat(5 - r.stars)} | ${r.count} |`).join("\n")}` : "";
583
+ const topicsSection = topics.length ? `
584
+ ## Review Topics
585
+ ${topics.map((t) => `- **${t.label}:** ${t.count} mentions`).join("\n")}` : "";
586
+ const aboutBySection = {};
587
+ for (const a of about) {
588
+ if (!aboutBySection[a.section]) aboutBySection[a.section] = [];
589
+ aboutBySection[a.section].push(a.attribute);
590
+ }
591
+ const aboutSection = Object.keys(aboutBySection).length ? `
592
+ ## About
593
+ ${Object.entries(aboutBySection).map(([s, attrs]) => `**${s}**
594
+ ${attrs.map((a) => `- ${a}`).join("\n")}`).join("\n\n")}` : "";
595
+ const entitySection = [
596
+ kgmid ? `- **KGMID:** \`${kgmid}\`` : null,
597
+ cidDecimal ? `- **CID:** \`${cidDecimal}\`` : null,
598
+ cidUrl ? `- **Maps CID URL:** ${cidUrl}` : null,
599
+ lat != null && lng != null ? `- **Coordinates:** ${lat}, ${lng}` : null
600
+ ].filter(Boolean).join("\n");
601
+ const reviewsSection = reviews.length ? `
602
+ ## Reviews (${reviews.length})
603
+ ${reviews.map((r, i) => {
604
+ const starsN = parseInt(r.stars ?? "0");
605
+ const stars = "\u2605".repeat(starsN) + "\u2606".repeat(5 - starsN);
606
+ return `### ${i + 1}. ${r.author ?? "Anonymous"} \u2014 ${stars}
607
+ *${r.date ?? ""}*
608
+
609
+ ${r.text ?? ""}`;
610
+ }).join("\n\n")}` : "";
611
+ const full = [
612
+ `${DIRECTIVE_FULL}# ${name}`,
613
+ category ? `*${category}*` : null,
614
+ ratingLine ? `
615
+ **Rating:** ${ratingLine}` : null,
616
+ basicLines ? `
617
+ ${basicLines}` : null,
618
+ hoursSection,
619
+ histSection,
620
+ topicsSection,
621
+ aboutSection,
622
+ entitySection ? `
623
+ ## Entity IDs
624
+ ${entitySection}` : null,
625
+ reviewsSection,
626
+ durationMs != null ? `
627
+ ---
628
+ *Extracted in ${(durationMs / 1e3).toFixed(1)}s*` : null
629
+ ].filter(Boolean).join("\n");
630
+ const summary = [
631
+ `${DIRECTIVE_SUMMARY}**${name}** \u2014 ${category ?? "Business"} \xB7 ${ratingLine || "No rating"}`,
632
+ address ? `\u{1F4CD} ${address}` : null,
633
+ phone ? `\u{1F4DE} ${phone}` : null,
634
+ hoursSummary ? `\u{1F550} ${hoursSummary}` : null,
635
+ website ? `\u{1F310} ${website}` : null,
636
+ reviews.length ? `
637
+ \u{1F4AC} ${reviews.length} reviews fetched \u2014 full list in artifact above` : null
638
+ ].filter(Boolean).join("\n");
639
+ return twoBlocks(full, summary);
640
+ }
641
+ function formatFacebookAdTranscribe(raw, input) {
642
+ const parsed = parseData(raw);
643
+ if ("error" in parsed) return { content: [{ type: "text", text: parsed.error }], isError: true };
644
+ const d = parsed.data;
645
+ const text = d.text ?? "";
646
+ const chunks = d.chunks ?? [];
647
+ const durSec = d.durationMs ? (d.durationMs / 1e3).toFixed(0) : "\u2014";
648
+ const chunkRows = chunks.slice(0, 50).map((c) => {
649
+ const sec = Math.floor(c.startMs / 1e3);
650
+ const mm = String(Math.floor(sec / 60)).padStart(2, "0");
651
+ const ss = String(sec % 60).padStart(2, "0");
652
+ return `| ${mm}:${ss} | ${truncate(c.text, 120)} |`;
653
+ }).join("\n");
654
+ const full = [
655
+ `${DIRECTIVE_FULL}# Facebook Ad Transcript`,
656
+ `**Duration:** ${durSec}s \xB7 **${text.split(" ").length} words**`,
657
+ `
658
+ ## Full Transcript
659
+ ${text}`,
660
+ chunks.length ? `
661
+ ## Timestamped Chunks
662
+ | Time | Text |
663
+ |------|------|
664
+ ${chunkRows}` : "",
665
+ `
666
+ ---
667
+ \u{1F4A1} Get more ads from this advertiser: use \`facebook_page_intel\``
668
+ ].filter(Boolean).join("\n");
669
+ const summary = [
670
+ `${DIRECTIVE_SUMMARY}**Facebook Ad Transcript** \u2014 ${text.split(" ").length} words \xB7 ${durSec}s`,
671
+ `
672
+ **Preview:**
673
+ > ${truncate(text, 300)}`,
674
+ `
675
+ \u{1F4A1} Full transcript in artifact above`
676
+ ].join("\n");
677
+ return twoBlocks(full, summary);
678
+ }
679
+
680
+ // src/mcp/paa-mcp-server.ts
681
+ function buildPaaExtractorMcpServer(executor) {
682
+ const server = new McpServer({ name: "paa-extractor", version: "1.0.0" });
683
+ server.registerTool("harvest_paa", {
684
+ description: "Extract PAA (People Also Ask) questions from Google Search. Returns full question list with answers, organic SERP, entity IDs (CID/GCID/KG MID), and AI Overview. Use maxQuestions to control volume (up to 40).",
685
+ inputSchema: HarvestPaaInputSchema
686
+ }, async (input) => formatHarvestPaa(await executor.harvestPaa(input), input));
687
+ server.registerTool("search_serp", {
688
+ description: "Fetch organic Google search results. Returns ranked URLs, titles, snippets, local pack, entity IDs (CID/GCID/KG MID), and AI Overview. Use when you need SERP positions without PAA expansion.",
689
+ inputSchema: SearchSerpInputSchema
690
+ }, async (input) => formatSearchSerp(await executor.searchSerp(input), input));
691
+ server.registerTool("extract_url", {
692
+ description: "Extract structured data from a single URL: page content as Markdown, heading structure, JSON-LD schema, entity details, NAP score, and missing schema fields. Use for SEO audits and entity validation.",
693
+ inputSchema: ExtractUrlInputSchema
694
+ }, async (input) => formatExtractUrl(await executor.extractUrl(input), input));
695
+ server.registerTool("map_site_urls", {
696
+ description: "Spider a website to build a complete URL inventory with HTTP status codes. Identifies broken links and redirect chains. Use before extract_site to understand site scope.",
697
+ inputSchema: MapSiteUrlsInputSchema
698
+ }, async (input) => formatMapSiteUrls(await executor.mapSiteUrls(input), input));
699
+ server.registerTool("extract_site", {
700
+ description: "Run multi-page extraction across an entire website. Returns schema, entity data, headings, and content from each page. Use map_site_urls first to check scope.",
701
+ inputSchema: ExtractSiteInputSchema
702
+ }, async (input) => formatExtractSite(await executor.extractSite(input), input));
703
+ server.registerTool("youtube_harvest", {
704
+ description: 'Harvest YouTube video metadata by search query or channel handle. Returns titles, view counts, durations, and videoIds. Use mode "search" for keyword results or "channel" for a specific creator.',
705
+ inputSchema: YoutubeHarvestInputSchema
706
+ }, async (input) => formatYoutubeHarvest(await executor.youtubeHarvest(input), input));
707
+ server.registerTool("youtube_transcribe", {
708
+ description: "Fetch and transcribe captions from a YouTube video. Returns full transcript, timestamped chunks, and word count. Pass a videoId from youtube_harvest results.",
709
+ inputSchema: YoutubeTranscribeInputSchema
710
+ }, async (input) => formatYoutubeTranscribe(await executor.youtubeTranscribe(input), input));
711
+ server.registerTool("facebook_page_intel", {
712
+ description: "Harvest all ads from a Facebook advertiser. Returns ad copy, headlines, CTAs, creative type, status, and video URLs ready for transcription. Accepts pageId, libraryId, or a brand name as query.",
713
+ inputSchema: FacebookPageIntelInputSchema
714
+ }, async (input) => formatFacebookPageIntel(await executor.facebookPageIntel(input), input));
715
+ server.registerTool("facebook_ad_search", {
716
+ description: "Search Facebook Ad Library by keyword. Returns advertisers with ad counts and library IDs. Use to discover competitors, then pass libraryId to facebook_page_intel to get their full ad list.",
717
+ inputSchema: FacebookAdSearchInputSchema
718
+ }, async (input) => formatFacebookAdSearch(await executor.facebookAdSearch(input), input));
719
+ server.registerTool("facebook_ad_transcribe", {
720
+ description: "Transcribe audio from a Facebook ad video. Returns full transcript and timestamped chunks. Use the videoUrl value from facebook_page_intel results.",
721
+ inputSchema: FacebookAdTranscribeInputSchema
722
+ }, async (input) => formatFacebookAdTranscribe(await executor.facebookAdTranscribe(input), input));
723
+ server.registerTool("maps_place_intel", {
724
+ description: "Extract Google Maps business intelligence for a named business: rating, review count, category, address, phone, website, hours, booking URL, review histogram, review topics, about attributes, and optional review cards. Pass includeReviews: true and maxReviews to fetch individual review text.",
725
+ inputSchema: MapsPlaceIntelInputSchema
726
+ }, async (input) => formatMapsPlaceIntel(await executor.mapsPlaceIntel(input), input));
727
+ server.registerTool("credits_info", {
728
+ description: "Answer questions about MCP Scraper credits: current credit balance, what a specific tool/action costs, the full cost table, and optionally recent credit ledger entries. Does not expose payment methods or credit card information.",
729
+ inputSchema: CreditsInfoInputSchema
730
+ }, async (input) => formatCreditsInfo(await executor.creditsInfo(input), input));
731
+ return server;
732
+ }
733
+
734
+ // src/mcp/http-mcp-tool-executor.ts
735
+ var HttpMcpToolExecutor = class {
736
+ baseUrl;
737
+ apiKey;
738
+ constructor(baseUrl, apiKey) {
739
+ this.baseUrl = baseUrl.replace(/\/$/, "");
740
+ this.apiKey = apiKey;
741
+ }
742
+ async call(path, body) {
743
+ try {
744
+ const res = await fetch(`${this.baseUrl}${path}`, {
745
+ method: "POST",
746
+ headers: {
747
+ "Content-Type": "application/json",
748
+ "x-api-key": this.apiKey
749
+ },
750
+ body: JSON.stringify(body),
751
+ signal: AbortSignal.timeout(29e4)
752
+ });
753
+ const data = await res.json();
754
+ if (!res.ok) {
755
+ return { content: [{ type: "text", text: JSON.stringify(data) }], isError: true };
756
+ }
757
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
758
+ } catch (err) {
759
+ const msg = err instanceof Error ? err.message : String(err);
760
+ return { content: [{ type: "text", text: msg }], isError: true };
761
+ }
762
+ }
763
+ harvestPaa(input) {
764
+ return this.call("/harvest/sync", input);
765
+ }
766
+ searchSerp(input) {
767
+ return this.call("/harvest/sync", { ...input, serpOnly: true });
768
+ }
769
+ extractUrl(input) {
770
+ return this.call("/extract-url", input);
771
+ }
772
+ mapSiteUrls(input) {
773
+ return this.call("/map-urls", input);
774
+ }
775
+ extractSite(input) {
776
+ return this.call("/extract-site", input);
777
+ }
778
+ youtubeHarvest(input) {
779
+ return this.call("/youtube/harvest", input);
780
+ }
781
+ youtubeTranscribe(input) {
782
+ return this.call("/youtube/transcribe", input);
783
+ }
784
+ facebookPageIntel(input) {
785
+ return this.call("/facebook/page-intel", input);
786
+ }
787
+ facebookAdSearch(input) {
788
+ return this.call("/facebook/search", input);
789
+ }
790
+ facebookAdTranscribe(input) {
791
+ return this.call("/facebook/transcribe", input);
792
+ }
793
+ mapsPlaceIntel(input) {
794
+ return this.call("/maps/place", input);
795
+ }
796
+ creditsInfo(input) {
797
+ return this.call("/billing/credits", input);
798
+ }
799
+ };
800
+
801
+ export {
802
+ buildPaaExtractorMcpServer,
803
+ HttpMcpToolExecutor
804
+ };
805
+ //# sourceMappingURL=chunk-ZBP4RHNW.js.map