mcp-scraper 0.2.8 → 0.2.9

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 (54) hide show
  1. package/README.md +40 -3
  2. package/dist/bin/api-server.cjs +2073 -506
  3. package/dist/bin/api-server.cjs.map +1 -1
  4. package/dist/bin/api-server.js +3 -3
  5. package/dist/bin/browser-agent-stdio-server.cjs +1 -1
  6. package/dist/bin/browser-agent-stdio-server.cjs.map +1 -1
  7. package/dist/bin/browser-agent-stdio-server.js +2 -2
  8. package/dist/bin/mcp-scraper-cli.cjs +1276 -0
  9. package/dist/bin/mcp-scraper-cli.cjs.map +1 -0
  10. package/dist/bin/mcp-scraper-cli.d.cts +1 -0
  11. package/dist/bin/mcp-scraper-cli.d.ts +1 -0
  12. package/dist/bin/mcp-scraper-cli.js +476 -0
  13. package/dist/bin/mcp-scraper-cli.js.map +1 -0
  14. package/dist/bin/mcp-scraper-combined-stdio-server.cjs +3 -3
  15. package/dist/bin/mcp-scraper-combined-stdio-server.cjs.map +1 -1
  16. package/dist/bin/mcp-scraper-combined-stdio-server.js +3 -3
  17. package/dist/bin/mcp-scraper-install.cjs +4 -1
  18. package/dist/bin/mcp-scraper-install.cjs.map +1 -1
  19. package/dist/bin/mcp-scraper-install.js +4 -1
  20. package/dist/bin/mcp-scraper-install.js.map +1 -1
  21. package/dist/bin/mcp-stdio-server.cjs +3 -3
  22. package/dist/bin/mcp-stdio-server.cjs.map +1 -1
  23. package/dist/bin/mcp-stdio-server.js +2 -2
  24. package/dist/{chunk-5HMOPP76.js → chunk-5E6KJC26.js} +2 -2
  25. package/dist/{chunk-D4CJBZBY.js → chunk-7GCCOT3M.js} +372 -1
  26. package/dist/chunk-7GCCOT3M.js.map +1 -0
  27. package/dist/chunk-BJDCPCIE.js +7 -0
  28. package/dist/chunk-BJDCPCIE.js.map +1 -0
  29. package/dist/chunk-L6IS63WS.js +869 -0
  30. package/dist/chunk-L6IS63WS.js.map +1 -0
  31. package/dist/{chunk-IQOCZGJJ.js → chunk-ROS67BNV.js} +5 -5
  32. package/dist/{chunk-6NEXSNSA.js → chunk-XAY5U67D.js} +4 -4
  33. package/dist/chunk-XAY5U67D.js.map +1 -0
  34. package/dist/{db-YWCNHBLH.js → db-BVHYI57K.js} +38 -2
  35. package/dist/{server-BTTDFPSQ.js → server-BKJ7LULQ.js} +585 -266
  36. package/dist/server-BKJ7LULQ.js.map +1 -0
  37. package/dist/{worker-5O44YBF4.js → worker-TDJQ6TH3.js} +8 -8
  38. package/docs/specs/agent-ready-seo-packet-spec.md +237 -0
  39. package/docs/specs/cli-agent-wiring-spec.md +203 -0
  40. package/docs/specs/deferred-work-spec.md +12 -0
  41. package/docs/specs/local-competitive-audit-spec.md +312 -0
  42. package/docs/specs/scheduled-workflows-api-spec.md +304 -0
  43. package/docs/specs/seo-cli-growth-roadmap-spec.md +179 -0
  44. package/docs/specs/seo-workflow-runner-and-reports-spec.md +241 -0
  45. package/package.json +3 -2
  46. package/dist/chunk-6NEXSNSA.js.map +0 -1
  47. package/dist/chunk-D4CJBZBY.js.map +0 -1
  48. package/dist/chunk-I26QN7WQ.js +0 -7
  49. package/dist/chunk-I26QN7WQ.js.map +0 -1
  50. package/dist/server-BTTDFPSQ.js.map +0 -1
  51. /package/dist/{chunk-5HMOPP76.js.map → chunk-5E6KJC26.js.map} +0 -0
  52. /package/dist/{chunk-IQOCZGJJ.js.map → chunk-ROS67BNV.js.map} +0 -0
  53. /package/dist/{db-YWCNHBLH.js.map → db-BVHYI57K.js.map} +0 -0
  54. /package/dist/{worker-5O44YBF4.js.map → worker-TDJQ6TH3.js.map} +0 -0
@@ -0,0 +1,869 @@
1
+ // src/workflows/artifact-writer.ts
2
+ import { mkdir, readFile, stat, writeFile } from "fs/promises";
3
+ import { existsSync } from "fs";
4
+ import { homedir, platform } from "os";
5
+ import { dirname, join } from "path";
6
+ import { execFile } from "child_process";
7
+
8
+ // src/directory/csv.ts
9
+ function parseCsv(text) {
10
+ const rows = [];
11
+ let row = [];
12
+ let field = "";
13
+ let quoted = false;
14
+ for (let i = 0; i < text.length; i += 1) {
15
+ const ch = text[i];
16
+ const next = text[i + 1];
17
+ if (quoted) {
18
+ if (ch === '"' && next === '"') {
19
+ field += '"';
20
+ i += 1;
21
+ } else if (ch === '"') {
22
+ quoted = false;
23
+ } else {
24
+ field += ch;
25
+ }
26
+ continue;
27
+ }
28
+ if (ch === '"') {
29
+ quoted = true;
30
+ } else if (ch === ",") {
31
+ row.push(field);
32
+ field = "";
33
+ } else if (ch === "\n") {
34
+ row.push(field);
35
+ rows.push(row);
36
+ row = [];
37
+ field = "";
38
+ } else if (ch !== "\r") {
39
+ field += ch;
40
+ }
41
+ }
42
+ if (field.length > 0 || row.length > 0) {
43
+ row.push(field);
44
+ rows.push(row);
45
+ }
46
+ return rows;
47
+ }
48
+ function csvRecords(text) {
49
+ const rows = parseCsv(text).filter((row) => row.some((cell) => cell.trim() !== ""));
50
+ const header = rows[0]?.map((cell) => cell.trim()) ?? [];
51
+ return rows.slice(1).map((row) => {
52
+ const record = {};
53
+ for (let i = 0; i < header.length; i += 1) {
54
+ record[header[i]] = row[i] ?? "";
55
+ }
56
+ return record;
57
+ });
58
+ }
59
+ function csvCell(value) {
60
+ if (value === null || value === void 0) return "";
61
+ const text = String(value);
62
+ return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
63
+ }
64
+ function rowsToCsv(headers, rows) {
65
+ return [
66
+ headers.join(","),
67
+ ...rows.map((row) => headers.map((header) => csvCell(row[header])).join(","))
68
+ ].join("\n") + "\n";
69
+ }
70
+
71
+ // src/lib/slugify.ts
72
+ function slugify(s) {
73
+ return s.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
74
+ }
75
+
76
+ // src/workflows/artifact-writer.ts
77
+ function workflowOutputBaseDir(outputDir) {
78
+ return outputDir?.trim() || process.env.MCP_SCRAPER_OUTPUT_DIR?.trim() || join(homedir(), "Downloads", "mcp-scraper");
79
+ }
80
+ function timestamp() {
81
+ return (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
82
+ }
83
+ function safeSlug(value) {
84
+ return slugify(value).replace(/^-+|-+$/g, "").slice(0, 80) || "run";
85
+ }
86
+ var ArtifactWriter = class _ArtifactWriter {
87
+ constructor(workflowId, title, runId, baseDir, runDir, startedAt, input) {
88
+ this.workflowId = workflowId;
89
+ this.title = title;
90
+ this.runId = runId;
91
+ this.baseDir = baseDir;
92
+ this.runDir = runDir;
93
+ this.startedAt = startedAt;
94
+ this.input = input;
95
+ }
96
+ workflowId;
97
+ title;
98
+ runId;
99
+ baseDir;
100
+ runDir;
101
+ startedAt;
102
+ input;
103
+ artifacts = [];
104
+ static async create(workflowId, title, input, outputDir, forcedRunId) {
105
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
106
+ const runId = forcedRunId?.trim() || `${timestamp()}-${safeSlug(workflowId)}-${Math.random().toString(36).slice(2, 8)}`;
107
+ const nameSource = String(input.keyword ?? input.query ?? input.domain ?? input.state ?? workflowId);
108
+ const baseDir = workflowOutputBaseDir(outputDir);
109
+ const runDir = join(baseDir, "workflows", workflowId, `${timestamp()}-${safeSlug(nameSource)}-${safeSlug(runId).slice(0, 20)}`);
110
+ await mkdir(runDir, { recursive: true });
111
+ return new _ArtifactWriter(workflowId, title, runId, baseDir, runDir, startedAt, input);
112
+ }
113
+ async remember(kind, label, path, rows) {
114
+ const size = await stat(path).then((s) => s.size).catch(() => void 0);
115
+ this.artifacts.push({ kind, label, path, bytes: size, rows });
116
+ return path;
117
+ }
118
+ async writeJson(label, relativePath, data) {
119
+ const path = join(this.runDir, relativePath);
120
+ await mkdir(dirname(path), { recursive: true });
121
+ await writeFile(path, JSON.stringify(data, null, 2), "utf8");
122
+ return this.remember("json", label, path);
123
+ }
124
+ async writeText(label, relativePath, text, kind = "markdown") {
125
+ const path = join(this.runDir, relativePath);
126
+ await mkdir(dirname(path), { recursive: true });
127
+ await writeFile(path, text, "utf8");
128
+ return this.remember(kind, label, path);
129
+ }
130
+ async writeCsv(label, relativePath, headers, rows) {
131
+ const path = join(this.runDir, relativePath);
132
+ await mkdir(dirname(path), { recursive: true });
133
+ await writeFile(path, rowsToCsv(headers, rows), "utf8");
134
+ return this.remember("csv", label, path, rows.length);
135
+ }
136
+ async writeHtml(label, relativePath, html) {
137
+ return this.writeText(label, relativePath, html, "html_report");
138
+ }
139
+ async writeManifest(status, counts, warnings, errors) {
140
+ const manifest = {
141
+ workflow: this.workflowId,
142
+ title: this.title,
143
+ runId: this.runId,
144
+ status,
145
+ startedAt: this.startedAt,
146
+ completedAt: status === "running" ? null : (/* @__PURE__ */ new Date()).toISOString(),
147
+ input: this.input,
148
+ artifacts: this.artifacts,
149
+ warnings,
150
+ errors,
151
+ counts
152
+ };
153
+ const path = join(this.runDir, "manifest.json");
154
+ await writeFile(path, JSON.stringify(manifest, null, 2), "utf8");
155
+ await updateWorkflowIndex(manifest, path, this.baseDir);
156
+ return path;
157
+ }
158
+ };
159
+ function indexPath(baseDir = workflowOutputBaseDir()) {
160
+ return join(baseDir, "workflows", "index.json");
161
+ }
162
+ async function readIndex(baseDir) {
163
+ const path = indexPath(baseDir);
164
+ if (!existsSync(path)) return { runs: [] };
165
+ try {
166
+ return JSON.parse(await readFile(path, "utf8"));
167
+ } catch {
168
+ return { runs: [] };
169
+ }
170
+ }
171
+ async function updateWorkflowIndex(manifest, manifestPath, baseDir) {
172
+ if (manifest.status === "running") return;
173
+ const path = indexPath(baseDir);
174
+ const index = await readIndex(baseDir);
175
+ const report = manifest.artifacts.find((a) => a.kind === "html_report")?.path ?? null;
176
+ const entry = {
177
+ workflow: manifest.workflow,
178
+ runId: manifest.runId,
179
+ status: manifest.status,
180
+ startedAt: manifest.startedAt,
181
+ reportPath: report,
182
+ manifestPath,
183
+ summary: `${manifest.title} (${manifest.status})`
184
+ };
185
+ index.runs = [entry, ...index.runs.filter((r) => r.runId !== manifest.runId)].slice(0, 200);
186
+ await mkdir(dirname(path), { recursive: true });
187
+ await writeFile(path, JSON.stringify(index, null, 2), "utf8");
188
+ }
189
+ async function listWorkflowReports(outputDir) {
190
+ return (await readIndex(workflowOutputBaseDir(outputDir))).runs;
191
+ }
192
+ async function findWorkflowReport(id, outputDir) {
193
+ const runs = await listWorkflowReports(outputDir);
194
+ if (id === "last") return runs[0] ?? null;
195
+ return runs.find((run) => run.runId === id) ?? null;
196
+ }
197
+ async function openWorkflowReport(id, outputDir) {
198
+ const run = await findWorkflowReport(id, outputDir);
199
+ if (!run?.reportPath) throw new Error(`No report found for "${id}"`);
200
+ if (platform() === "darwin") {
201
+ await new Promise((resolve, reject) => {
202
+ execFile("open", [run.reportPath], (err) => err ? reject(err) : resolve());
203
+ });
204
+ }
205
+ return run.reportPath;
206
+ }
207
+
208
+ // src/workflows/registry.ts
209
+ import { z as z4 } from "zod";
210
+
211
+ // src/workflows/http-client.ts
212
+ var WorkflowHttpClient = class {
213
+ constructor(apiUrl, apiKey, fetchImpl = fetch) {
214
+ this.apiUrl = apiUrl;
215
+ this.apiKey = apiKey;
216
+ this.fetchImpl = fetchImpl;
217
+ }
218
+ apiUrl;
219
+ apiKey;
220
+ fetchImpl;
221
+ async post(path, body, timeoutMs = 18e4) {
222
+ const res = await this.fetchImpl(`${this.apiUrl.replace(/\/$/, "")}${path}`, {
223
+ method: "POST",
224
+ headers: {
225
+ "Content-Type": "application/json",
226
+ "x-api-key": this.apiKey
227
+ },
228
+ body: JSON.stringify(body),
229
+ signal: AbortSignal.timeout(timeoutMs)
230
+ });
231
+ const data = await res.json().catch(() => ({}));
232
+ if (!res.ok) {
233
+ const message = typeof data.error === "string" ? data.error : `Workflow API ${path} failed with ${res.status}`;
234
+ throw new Error(message);
235
+ }
236
+ return data;
237
+ }
238
+ };
239
+
240
+ // src/workflows/workflows/agent-packet.ts
241
+ import { z } from "zod";
242
+
243
+ // src/workflows/report-renderer.ts
244
+ function escapeHtml(value) {
245
+ return String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
246
+ }
247
+ function renderTable(table) {
248
+ const rows = table.rows.map((row) => `<tr>${table.columns.map((col) => `<td>${escapeHtml(row[col])}</td>`).join("")}</tr>`).join("\n");
249
+ return [
250
+ `<section>`,
251
+ `<h2>${escapeHtml(table.title)}</h2>`,
252
+ `<div class="table-wrap"><table>`,
253
+ `<thead><tr>${table.columns.map((col) => `<th>${escapeHtml(col)}</th>`).join("")}</tr></thead>`,
254
+ `<tbody>${rows || `<tr><td colspan="${table.columns.length}">No rows</td></tr>`}</tbody>`,
255
+ `</table></div>`,
256
+ `</section>`
257
+ ].join("\n");
258
+ }
259
+ function renderWorkflowReport(input) {
260
+ const warnings = input.warnings?.length ? `<section class="warnings"><h2>Warnings</h2><ul>${input.warnings.map((w) => `<li>${escapeHtml(w)}</li>`).join("")}</ul></section>` : "";
261
+ const sections = (input.sections ?? []).map((section) => `<section><h2>${escapeHtml(section.title)}</h2><p>${escapeHtml(section.body)}</p></section>`).join("\n");
262
+ const tables = (input.tables ?? []).map(renderTable).join("\n");
263
+ return [
264
+ "<!doctype html>",
265
+ '<html lang="en">',
266
+ "<head>",
267
+ '<meta charset="utf-8">',
268
+ '<meta name="viewport" content="width=device-width, initial-scale=1">',
269
+ `<title>${escapeHtml(input.title)}</title>`,
270
+ "<style>",
271
+ ':root{font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#172026;background:#f6f7f8}',
272
+ "body{margin:0;padding:32px}main{max-width:1180px;margin:0 auto;background:#fff;border:1px solid #d9dee3;border-radius:8px;padding:28px}",
273
+ "h1{font-size:30px;line-height:1.15;margin:0 0 8px}h2{font-size:18px;margin:28px 0 12px}p{line-height:1.55;color:#3d4952}.sub{color:#66737f;margin:0 0 20px}",
274
+ ".summary{background:#eef6f8;border-left:4px solid #12829a;padding:14px 16px;margin:20px 0}.warnings{background:#fff7e8;border-left:4px solid #c87b00;padding:12px 16px}",
275
+ ".table-wrap{overflow:auto;border:1px solid #dfe5ea;border-radius:8px}table{border-collapse:collapse;width:100%;font-size:13px}th,td{border-bottom:1px solid #edf0f2;padding:9px 10px;text-align:left;vertical-align:top}th{background:#f3f5f7;color:#31404c;position:sticky;top:0}tr:last-child td{border-bottom:0}",
276
+ "</style>",
277
+ "</head>",
278
+ "<body><main>",
279
+ `<h1>${escapeHtml(input.title)}</h1>`,
280
+ input.subtitle ? `<p class="sub">${escapeHtml(input.subtitle)}</p>` : "",
281
+ `<div class="summary">${escapeHtml(input.summary)}</div>`,
282
+ warnings,
283
+ sections,
284
+ tables,
285
+ "</main></body></html>"
286
+ ].join("\n");
287
+ }
288
+
289
+ // src/workflows/workflows/agent-packet.ts
290
+ var AgentPacketInputSchema = z.object({
291
+ keyword: z.string().min(1),
292
+ domain: z.string().optional(),
293
+ location: z.string().optional(),
294
+ maxQuestions: z.number().int().min(1).max(200).default(40),
295
+ includeSerp: z.boolean().default(true),
296
+ includePaa: z.boolean().default(true),
297
+ includeAiOverview: z.boolean().default(true),
298
+ returnPartial: z.boolean().default(true)
299
+ });
300
+ function normalizeDomain(value) {
301
+ if (!value) return null;
302
+ try {
303
+ const url = new URL(value.includes("://") ? value : `https://${value}`);
304
+ return url.hostname.replace(/^www\./, "").toLowerCase();
305
+ } catch {
306
+ return value.replace(/^https?:\/\//, "").replace(/^www\./, "").split("/")[0]?.toLowerCase() || null;
307
+ }
308
+ }
309
+ function domainFromUrl(url) {
310
+ return normalizeDomain(url) ?? "";
311
+ }
312
+ function sourceRows(input, serp, paa) {
313
+ const target = normalizeDomain(input.domain);
314
+ const rows = [];
315
+ for (const result of serp?.organicResults ?? []) {
316
+ const domain = normalizeDomain(result.domain) ?? domainFromUrl(result.url);
317
+ rows.push({
318
+ surface: "organic",
319
+ position: result.position,
320
+ title: result.title,
321
+ url: result.url,
322
+ domain,
323
+ question: "",
324
+ answer_excerpt: result.snippet ?? "",
325
+ is_target: target ? domain === target : false,
326
+ is_competitor: target ? domain !== target : true
327
+ });
328
+ }
329
+ for (const row of paa?.flat ?? []) {
330
+ const url = row.source_cite ?? "";
331
+ const domain = normalizeDomain(row.source_site ?? "") ?? (url ? domainFromUrl(url) : "");
332
+ rows.push({
333
+ surface: "paa",
334
+ position: "",
335
+ title: row.source_title ?? row.source_site ?? "",
336
+ url,
337
+ domain,
338
+ question: row.question,
339
+ answer_excerpt: (row.answer ?? "").slice(0, 240),
340
+ is_target: target ? domain === target : false,
341
+ is_competitor: target ? Boolean(domain && domain !== target) : Boolean(domain)
342
+ });
343
+ }
344
+ for (const [i, cite] of (serp?.aiOverview?.citations ?? []).entries()) {
345
+ const url = cite.href ?? "";
346
+ const domain = url ? domainFromUrl(url) : "";
347
+ rows.push({
348
+ surface: "ai_overview",
349
+ position: i + 1,
350
+ title: cite.text ?? "",
351
+ url,
352
+ domain,
353
+ question: "",
354
+ answer_excerpt: "",
355
+ is_target: target ? domain === target : false,
356
+ is_competitor: target ? Boolean(domain && domain !== target) : Boolean(domain)
357
+ });
358
+ }
359
+ return rows;
360
+ }
361
+ function competitorRows(rows, targetDomain) {
362
+ const byDomain = /* @__PURE__ */ new Map();
363
+ for (const row of rows) {
364
+ const domain = String(row.domain ?? "");
365
+ if (!domain || domain === targetDomain) continue;
366
+ const entry = byDomain.get(domain) ?? { organic: [], paa: 0, ai: 0, urls: /* @__PURE__ */ new Set() };
367
+ if (row.surface === "organic" && row.position) entry.organic.push(Number(row.position));
368
+ if (row.surface === "paa") entry.paa += 1;
369
+ if (row.surface === "ai_overview") entry.ai += 1;
370
+ if (row.url) entry.urls.add(String(row.url));
371
+ byDomain.set(domain, entry);
372
+ }
373
+ return [...byDomain.entries()].map(([domain, entry]) => ({
374
+ domain,
375
+ organic_best_position: entry.organic.length ? Math.min(...entry.organic) : "",
376
+ organic_count: entry.organic.length,
377
+ paa_mentions: entry.paa,
378
+ ai_overview_citations: entry.ai,
379
+ source_url_count: entry.urls.size
380
+ })).sort((a, b) => Number(a.organic_best_position || 999) - Number(b.organic_best_position || 999));
381
+ }
382
+ var agentPacketWorkflowDefinition = {
383
+ id: "agent-packet",
384
+ title: "Agent-Ready SEO Packet",
385
+ description: "Create an evidence folder for AI agents from live SERP/PAA/AI search surfaces.",
386
+ inputSchema: AgentPacketInputSchema,
387
+ async run(input, ctx) {
388
+ await ctx.artifacts.writeManifest("running", {}, [], []);
389
+ const warnings = [];
390
+ const errors = [];
391
+ let serp = null;
392
+ let paa = null;
393
+ if (input.includeSerp) {
394
+ try {
395
+ serp = await ctx.client.post("/harvest/sync", {
396
+ query: input.keyword,
397
+ location: input.location,
398
+ serpOnly: true,
399
+ maxQuestions: 1,
400
+ format: "json"
401
+ }, 18e4);
402
+ } catch (err) {
403
+ warnings.push(`SERP evidence unavailable: ${err instanceof Error ? err.message : String(err)}`);
404
+ }
405
+ }
406
+ if (input.includePaa) {
407
+ try {
408
+ paa = await ctx.client.post("/harvest/sync", {
409
+ query: input.keyword,
410
+ location: input.location,
411
+ maxQuestions: input.maxQuestions,
412
+ format: "json"
413
+ }, 28e4);
414
+ } catch (err) {
415
+ warnings.push(`PAA evidence unavailable: ${err instanceof Error ? err.message : String(err)}`);
416
+ }
417
+ }
418
+ if (!serp && !paa && !input.returnPartial) throw new Error("No SEO evidence was collected");
419
+ const rows = sourceRows(input, serp, paa);
420
+ const target = normalizeDomain(input.domain);
421
+ const competitors = competitorRows(rows, target);
422
+ const evidence = {
423
+ input,
424
+ serp: serp ?? { status: "skipped" },
425
+ paa: paa ?? { status: "skipped" },
426
+ target: {
427
+ domain: target,
428
+ organicPositions: rows.filter((r) => r.surface === "organic" && r.is_target).map((r) => Number(r.position)),
429
+ citedInAiOverview: rows.some((r) => r.surface === "ai_overview" && r.is_target),
430
+ citedInPaa: rows.some((r) => r.surface === "paa" && r.is_target)
431
+ },
432
+ competitors,
433
+ warnings
434
+ };
435
+ await ctx.artifacts.writeJson("Evidence JSON", "evidence.json", evidence);
436
+ await ctx.artifacts.writeCsv("Sources CSV", "sources.csv", ["surface", "position", "title", "url", "domain", "question", "answer_excerpt", "is_target", "is_competitor"], rows);
437
+ await ctx.artifacts.writeCsv("Competitors CSV", "competitors.csv", ["domain", "organic_best_position", "organic_count", "paa_mentions", "ai_overview_citations", "source_url_count"], competitors);
438
+ const brief = [
439
+ `# SEO Evidence Brief: ${input.keyword}`,
440
+ "",
441
+ `Location: ${input.location ?? "not specified"}`,
442
+ `Target domain: ${target ?? "not specified"}`,
443
+ "",
444
+ "## Evidence Summary",
445
+ `- Organic rows: ${rows.filter((r) => r.surface === "organic").length}`,
446
+ `- PAA rows: ${rows.filter((r) => r.surface === "paa").length}`,
447
+ `- AI Overview citations: ${rows.filter((r) => r.surface === "ai_overview").length}`,
448
+ `- Competitor domains: ${competitors.length}`,
449
+ "",
450
+ "## Recommended Use",
451
+ "Use the CSV files as source of truth. Tie content recommendations to evidence rows and mark unsupported ideas as assumptions."
452
+ ].join("\n");
453
+ await ctx.artifacts.writeText("Brief", "brief.md", brief);
454
+ await ctx.artifacts.writeText("Agent tasks", "tasks.md", [
455
+ "# Agent Tasks",
456
+ "",
457
+ "- [ ] Read `evidence.json` before writing recommendations.",
458
+ "- [ ] Compare the target domain against `competitors.csv`.",
459
+ "- [ ] Use `sources.csv` for citations and source-grounded page sections.",
460
+ "- [ ] Mark unsupported recommendations as assumptions."
461
+ ].join("\n"));
462
+ await ctx.artifacts.writeText("Agent instructions", "agent-instructions.md", [
463
+ "# Agent Instructions",
464
+ "",
465
+ "You are working from an MCP Scraper SEO evidence packet. Use `evidence.json` and CSV files as source of truth. Do not invent citations. If a recommendation is not supported by evidence, mark it as an assumption."
466
+ ].join("\n"));
467
+ const summary = `${rows.length} evidence rows and ${competitors.length} competitor domains collected.`;
468
+ const reportPath = await ctx.artifacts.writeHtml("HTML report", "report.html", renderWorkflowReport({
469
+ title: "Agent-Ready SEO Packet",
470
+ subtitle: `${input.keyword}${input.location ? ` \xB7 ${input.location}` : ""}`,
471
+ summary,
472
+ warnings,
473
+ tables: [
474
+ { title: "Competitor Domains", columns: ["domain", "organic_best_position", "organic_count", "paa_mentions", "ai_overview_citations", "source_url_count"], rows: competitors.slice(0, 50) },
475
+ { title: "Evidence Sources", columns: ["surface", "position", "title", "domain", "question", "is_target"], rows: rows.slice(0, 100) }
476
+ ]
477
+ }));
478
+ const status = warnings.length ? "partial" : "succeeded";
479
+ const counts = { sources: rows.length, competitors: competitors.length };
480
+ await ctx.artifacts.writeManifest(status, counts, warnings, errors);
481
+ return { title: "Agent-Ready SEO Packet", summary, status, counts, warnings, errors, reportPath };
482
+ }
483
+ };
484
+
485
+ // src/workflows/workflows/directory.ts
486
+ import { z as z2 } from "zod";
487
+ var DirectoryWorkflowCliInputSchema = z2.object({
488
+ query: z2.string().min(1),
489
+ state: z2.string().min(2).default("TN"),
490
+ minPopulation: z2.number().int().min(0).default(1e5),
491
+ maxCities: z2.number().int().min(1).max(100).default(25),
492
+ maxResultsPerCity: z2.number().int().min(1).max(50).default(20),
493
+ concurrency: z2.number().int().min(1).max(5).default(5),
494
+ proxyMode: z2.enum(["location", "configured", "none"]).default("location"),
495
+ saveCsv: z2.boolean().default(true)
496
+ });
497
+ function directoryRows(result) {
498
+ const rows = [];
499
+ for (const city of result.cities) {
500
+ if (!city.results.length) {
501
+ rows.push({
502
+ source_query: result.query,
503
+ source_location: city.location,
504
+ city: city.city,
505
+ state: city.state,
506
+ population: city.population,
507
+ result_position: null,
508
+ business_name: null,
509
+ review_stars: null,
510
+ review_count: null,
511
+ category: null,
512
+ address: null,
513
+ phone: null,
514
+ website_url: null,
515
+ place_url: null,
516
+ cid: null,
517
+ cid_decimal: null,
518
+ result_status: city.status,
519
+ error: city.error
520
+ });
521
+ continue;
522
+ }
523
+ for (const business of city.results) {
524
+ rows.push({
525
+ source_query: result.query,
526
+ source_location: city.location,
527
+ city: city.city,
528
+ state: city.state,
529
+ population: city.population,
530
+ result_position: business.position,
531
+ business_name: business.name,
532
+ review_stars: business.rating,
533
+ review_count: business.reviewCount,
534
+ category: business.category,
535
+ address: business.address,
536
+ phone: business.phone,
537
+ website_url: business.websiteUrl,
538
+ place_url: business.placeUrl,
539
+ cid: business.cid,
540
+ cid_decimal: business.cidDecimal,
541
+ result_status: city.status,
542
+ error: city.error
543
+ });
544
+ }
545
+ }
546
+ return rows;
547
+ }
548
+ var DIRECTORY_CSV_HEADERS = [
549
+ "source_query",
550
+ "source_location",
551
+ "city",
552
+ "state",
553
+ "population",
554
+ "result_position",
555
+ "business_name",
556
+ "review_stars",
557
+ "review_count",
558
+ "category",
559
+ "address",
560
+ "phone",
561
+ "website_url",
562
+ "place_url",
563
+ "cid",
564
+ "cid_decimal",
565
+ "result_status",
566
+ "error"
567
+ ];
568
+ var directoryWorkflowDefinition = {
569
+ id: "directory",
570
+ title: "Directory Workflow",
571
+ description: "Select city markets and export Google Maps business candidates.",
572
+ inputSchema: DirectoryWorkflowCliInputSchema,
573
+ async run(input, ctx) {
574
+ await ctx.artifacts.writeManifest("running", {}, [], []);
575
+ const result = await ctx.client.post("/directory/run", input, 9e5);
576
+ await ctx.artifacts.writeJson("Directory evidence", "evidence.json", result);
577
+ const rows = directoryRows(result);
578
+ await ctx.artifacts.writeCsv("Directory CSV", "exports/directory.csv", DIRECTORY_CSV_HEADERS, rows);
579
+ const cityRows = result.cities.map((city) => ({
580
+ city: city.city,
581
+ state: city.state,
582
+ population: city.population,
583
+ status: city.status,
584
+ result_count: city.resultCount,
585
+ error: city.error ?? ""
586
+ }));
587
+ const topRows = rows.filter((row) => row.business_name).slice(0, 100).map((row) => ({
588
+ city: row.city,
589
+ position: row.result_position,
590
+ business: row.business_name,
591
+ rating: row.review_stars,
592
+ reviews: row.review_count,
593
+ category: row.category,
594
+ website: row.website_url
595
+ }));
596
+ const summary = `${result.selectedCityCount} cities processed with ${result.totalResultCount} Maps results.`;
597
+ await ctx.artifacts.writeText("Summary", "summary.md", `# Directory Workflow
598
+
599
+ ${summary}
600
+ `);
601
+ const reportPath = await ctx.artifacts.writeHtml("HTML report", "report.html", renderWorkflowReport({
602
+ title: "Directory Workflow",
603
+ subtitle: `${input.query} \xB7 ${input.state}`,
604
+ summary,
605
+ warnings: result.warnings,
606
+ tables: [
607
+ { title: "Cities", columns: ["city", "state", "population", "status", "result_count", "error"], rows: cityRows },
608
+ { title: "Top Results", columns: ["city", "position", "business", "rating", "reviews", "category", "website"], rows: topRows }
609
+ ]
610
+ }));
611
+ const status = result.cities.some((city) => city.status === "failed") ? "partial" : "succeeded";
612
+ const counts = { cities: result.selectedCityCount, results: result.totalResultCount, rows: rows.length };
613
+ await ctx.artifacts.writeManifest(status, counts, result.warnings, []);
614
+ return { title: "Directory Workflow", summary, status, counts, warnings: result.warnings, errors: [], reportPath };
615
+ }
616
+ };
617
+
618
+ // src/workflows/workflows/local-competitive-audit.ts
619
+ import { z as z3 } from "zod";
620
+ var LocalCompetitiveAuditInputSchema = z3.object({
621
+ query: z3.string().min(1),
622
+ state: z3.string().min(2).default("TN"),
623
+ minPopulation: z3.number().int().min(0).default(1e5),
624
+ maxCities: z3.number().int().min(1).max(100).default(25),
625
+ maxResultsPerCity: z3.number().int().min(1).max(50).default(20),
626
+ hydrateTop: z3.number().int().min(0).max(10).default(5),
627
+ maxReviews: z3.number().int().min(0).max(500).default(50),
628
+ concurrency: z3.number().int().min(1).max(5).default(5),
629
+ proxyMode: z3.enum(["location", "configured", "none"]).default("location"),
630
+ returnPartial: z3.boolean().default(true)
631
+ });
632
+ async function mapLimit(items, limit, fn) {
633
+ const out = new Array(items.length);
634
+ let next = 0;
635
+ async function worker() {
636
+ while (next < items.length) {
637
+ const index = next;
638
+ next += 1;
639
+ out[index] = await fn(items[index], index);
640
+ }
641
+ }
642
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
643
+ return out;
644
+ }
645
+ function numberFrom(value) {
646
+ if (value === null || value === void 0 || value === "") return null;
647
+ const parsed = Number(String(value).replace(/[^\d.]/g, ""));
648
+ return Number.isFinite(parsed) ? parsed : null;
649
+ }
650
+ function median(values) {
651
+ const nums = values.filter((v) => v !== null).sort((a, b) => a - b);
652
+ if (!nums.length) return null;
653
+ return nums[Math.floor(nums.length / 2)] ?? null;
654
+ }
655
+ function termsFrom(texts) {
656
+ const stop = /* @__PURE__ */ new Set(["the", "and", "for", "with", "that", "this", "was", "were", "are", "you", "our", "they", "had", "have", "not", "but", "from", "very", "great", "good"]);
657
+ const counts = /* @__PURE__ */ new Map();
658
+ for (const text of texts) {
659
+ for (const token of text.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/)) {
660
+ if (token.length < 4 || stop.has(token)) continue;
661
+ counts.set(token, (counts.get(token) ?? 0) + 1);
662
+ }
663
+ }
664
+ return [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 8).map(([term, count]) => `${term} (${count})`).join("; ");
665
+ }
666
+ var localCompetitiveAuditWorkflowDefinition = {
667
+ id: "local-competitive-audit",
668
+ title: "Local Competitive Audit",
669
+ description: "Audit local Maps competitors, categories, review counts, and review themes across city markets.",
670
+ inputSchema: LocalCompetitiveAuditInputSchema,
671
+ async run(input, ctx) {
672
+ await ctx.artifacts.writeManifest("running", {}, [], []);
673
+ const warnings = [];
674
+ const errors = [];
675
+ const directory = await ctx.client.post("/directory/run", {
676
+ query: input.query,
677
+ state: input.state,
678
+ minPopulation: input.minPopulation,
679
+ maxCities: input.maxCities,
680
+ maxResultsPerCity: input.maxResultsPerCity,
681
+ concurrency: input.concurrency,
682
+ proxyMode: input.proxyMode,
683
+ saveCsv: true
684
+ }, 9e5);
685
+ await ctx.artifacts.writeJson("Directory raw JSON", "raw/directory-workflow.json", directory);
686
+ const baseRows = directoryRows(directory);
687
+ await ctx.artifacts.writeCsv("Base directory CSV", "exports/directory.csv", DIRECTORY_CSV_HEADERS, baseRows);
688
+ const selected = directory.cities.flatMap(
689
+ (city) => city.results.slice(0, input.hydrateTop).map((result) => ({ city, result }))
690
+ );
691
+ const seen = /* @__PURE__ */ new Set();
692
+ const deduped = selected.filter(({ city, result }) => {
693
+ const key = result.cid ?? result.placeUrl ?? `${city.location}:${result.name.toLowerCase()}`;
694
+ if (seen.has(key)) return false;
695
+ seen.add(key);
696
+ return true;
697
+ });
698
+ const hydrated = await mapLimit(deduped, 3, async ({ city, result }, index) => {
699
+ try {
700
+ const detail = await ctx.client.post("/maps/place", {
701
+ businessName: result.name,
702
+ location: city.location,
703
+ includeReviews: input.maxReviews > 0,
704
+ maxReviews: Math.max(1, input.maxReviews)
705
+ }, 18e4);
706
+ await ctx.artifacts.writeJson(`${result.name} profile`, `raw/maps-place-intel/${index + 1}-${result.name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}.json`, detail);
707
+ return { city, result, detail, error: null };
708
+ } catch (err) {
709
+ const message = err instanceof Error ? err.message : String(err);
710
+ warnings.push(`Profile hydration failed for ${result.name} (${city.location}): ${message}`);
711
+ return { city, result, detail: null, error: message };
712
+ }
713
+ });
714
+ const competitorRows2 = hydrated.map(({ city, result, detail, error }) => {
715
+ const reviews = detail?.reviews ?? [];
716
+ const ownerResponses = reviews.filter((r) => r.ownerResponse).length;
717
+ return {
718
+ city: city.city,
719
+ state: city.state,
720
+ source_location: city.location,
721
+ result_position: result.position,
722
+ business_name: result.name,
723
+ category: detail?.category ?? result.category,
724
+ review_stars: detail?.rating ?? result.rating,
725
+ review_count: detail?.reviewCount ?? result.reviewCount,
726
+ phone: result.phone,
727
+ website_url: detail?.website ?? result.websiteUrl,
728
+ place_url: result.placeUrl,
729
+ cid: result.cid,
730
+ cid_decimal: result.cidDecimal,
731
+ hydrated: detail ? "true" : "false",
732
+ reviews_status: detail?.reviewsStatus ?? "",
733
+ review_topics: (detail?.reviewTopics ?? []).map((t) => `${t.label} (${t.count})`).join("; "),
734
+ owner_response_rate: reviews.length ? (ownerResponses / reviews.length).toFixed(2) : "",
735
+ error: error ?? ""
736
+ };
737
+ });
738
+ const reviewInsightRows = hydrated.map(({ city, result, detail }) => {
739
+ const reviews = detail?.reviews ?? [];
740
+ const positive = reviews.filter((r) => Number(r.stars) >= 5 && r.text).map((r) => r.text);
741
+ const negative = reviews.filter((r) => Number(r.stars) > 0 && Number(r.stars) <= 3 && r.text).map((r) => r.text);
742
+ return {
743
+ city: city.city,
744
+ business_name: result.name,
745
+ cid: result.cid,
746
+ review_count: detail?.reviewCount ?? result.reviewCount,
747
+ average_rating: detail?.rating ?? result.rating,
748
+ topics: (detail?.reviewTopics ?? []).map((t) => `${t.label} (${t.count})`).join("; "),
749
+ praise_terms: termsFrom(positive),
750
+ complaint_terms: termsFrom(negative),
751
+ positive_sample: positive[0]?.slice(0, 280) ?? "",
752
+ negative_sample: negative[0]?.slice(0, 280) ?? ""
753
+ };
754
+ });
755
+ const citySummaryRows = directory.cities.map((city) => {
756
+ const resultReviewCounts = city.results.map((r) => numberFrom(r.reviewCount));
757
+ const resultRatings = city.results.map((r) => numberFrom(r.rating));
758
+ const topThreeReviews = city.results.slice(0, 3).map((r) => numberFrom(r.reviewCount)).filter((v) => v !== null);
759
+ const categories = /* @__PURE__ */ new Map();
760
+ for (const result of city.results) {
761
+ if (!result.category) continue;
762
+ categories.set(result.category, (categories.get(result.category) ?? 0) + 1);
763
+ }
764
+ const medReviews = median(resultReviewCounts);
765
+ const medRating = median(resultRatings);
766
+ const topThreeAvg = topThreeReviews.length ? Math.round(topThreeReviews.reduce((a, b) => a + b, 0) / topThreeReviews.length) : null;
767
+ const difficulty = Math.min(100, Math.round((topThreeAvg ?? 0) / 20 + (medRating ?? 0) * 10 + city.results.filter((r) => r.websiteUrl).length));
768
+ const opportunity = Math.max(0, 100 - difficulty);
769
+ return {
770
+ city: city.city,
771
+ state: city.state,
772
+ population: city.population,
773
+ result_count: city.resultCount,
774
+ median_review_count: medReviews ?? "",
775
+ median_rating: medRating ?? "",
776
+ top_three_average_review_count: topThreeAvg ?? "",
777
+ top_categories: [...categories.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([cat, count]) => `${cat} (${count})`).join("; "),
778
+ opportunity_score: opportunity,
779
+ difficulty_score: difficulty
780
+ };
781
+ });
782
+ await ctx.artifacts.writeCsv("Competitors CSV", "competitors.csv", ["city", "state", "source_location", "result_position", "business_name", "category", "review_stars", "review_count", "phone", "website_url", "place_url", "cid", "cid_decimal", "hydrated", "reviews_status", "review_topics", "owner_response_rate", "error"], competitorRows2);
783
+ await ctx.artifacts.writeCsv("Review insights CSV", "review-insights.csv", ["city", "business_name", "cid", "review_count", "average_rating", "topics", "praise_terms", "complaint_terms", "positive_sample", "negative_sample"], reviewInsightRows);
784
+ await ctx.artifacts.writeCsv("City summary CSV", "city-summary.csv", ["city", "state", "population", "result_count", "median_review_count", "median_rating", "top_three_average_review_count", "top_categories", "opportunity_score", "difficulty_score"], citySummaryRows);
785
+ await ctx.artifacts.writeJson("Audit evidence", "evidence.json", { input, directory, hydrated, citySummaryRows, competitorRows: competitorRows2, reviewInsightRows });
786
+ await ctx.artifacts.writeText("Agent tasks", "tasks.md", [
787
+ "# Local Competitive Audit Tasks",
788
+ "",
789
+ "- [ ] Review city opportunity and difficulty scores as heuristics, not absolute truth.",
790
+ "- [ ] Use review topics and samples as customer-language evidence.",
791
+ "- [ ] Compare target GBP category, review count, and website quality against top competitors.",
792
+ "- [ ] Identify cities with low review-count leaders and weak website coverage."
793
+ ].join("\n"));
794
+ const summary = `${directory.selectedCityCount} cities, ${directory.totalResultCount} Maps results, ${hydrated.filter((h) => h.detail).length} hydrated profiles.`;
795
+ await ctx.artifacts.writeText("Summary", "summary.md", `# Local Competitive Audit
796
+
797
+ ${summary}
798
+ `);
799
+ const reportPath = await ctx.artifacts.writeHtml("HTML report", "report.html", renderWorkflowReport({
800
+ title: "Local Competitive Audit",
801
+ subtitle: `${input.query} \xB7 ${input.state}`,
802
+ summary,
803
+ warnings,
804
+ tables: [
805
+ { title: "City Opportunity", columns: ["city", "state", "population", "result_count", "median_review_count", "median_rating", "top_three_average_review_count", "top_categories", "opportunity_score", "difficulty_score"], rows: citySummaryRows },
806
+ { title: "Hydrated Competitors", columns: ["city", "result_position", "business_name", "category", "review_stars", "review_count", "hydrated", "review_topics"], rows: competitorRows2.slice(0, 100) },
807
+ { title: "Review Insights", columns: ["city", "business_name", "topics", "praise_terms", "complaint_terms"], rows: reviewInsightRows.slice(0, 100) }
808
+ ]
809
+ }));
810
+ const status = warnings.length || directory.cities.some((city) => city.status === "failed") ? "partial" : "succeeded";
811
+ const counts = { cities: directory.selectedCityCount, mapsResults: directory.totalResultCount, hydratedProfiles: hydrated.filter((h) => h.detail).length };
812
+ await ctx.artifacts.writeManifest(status, counts, warnings, errors);
813
+ return { title: "Local Competitive Audit", summary, status, counts, warnings, errors, reportPath };
814
+ }
815
+ };
816
+
817
+ // src/workflows/registry.ts
818
+ var DEFINITIONS = [
819
+ directoryWorkflowDefinition,
820
+ agentPacketWorkflowDefinition,
821
+ localCompetitiveAuditWorkflowDefinition
822
+ ];
823
+ function listWorkflowDefinitions() {
824
+ return DEFINITIONS.map(({ id, title, description }) => ({ id, title, description }));
825
+ }
826
+ function workflowDefinition(id) {
827
+ const definition = DEFINITIONS.find((def) => def.id === id);
828
+ if (!definition) throw new Error(`Unknown workflow "${id}". Available: ${DEFINITIONS.map((def) => def.id).join(", ")}`);
829
+ return definition;
830
+ }
831
+ async function runWorkflow(id, rawInput, options = {}) {
832
+ const definition = workflowDefinition(id);
833
+ const input = definition.inputSchema.parse(rawInput);
834
+ const apiKey = options.apiKey?.trim() || process.env.MCP_SCRAPER_API_KEY?.trim();
835
+ if (!apiKey) throw new Error("MCP_SCRAPER_API_KEY is required for workflow runs. Pass --api-key or set the environment variable.");
836
+ const apiUrl = options.apiUrl?.trim() || process.env.MCP_SCRAPER_API_URL?.trim() || "https://mcpscraper.dev";
837
+ const artifacts = await ArtifactWriter.create(definition.id, definition.title, input, options.outputDir, options.runId);
838
+ const client = new WorkflowHttpClient(apiUrl, apiKey, options.fetchImpl);
839
+ try {
840
+ return await definition.run(input, {
841
+ runId: artifacts.runId,
842
+ startedAt: artifacts.startedAt,
843
+ client,
844
+ artifacts,
845
+ signal: options.signal
846
+ });
847
+ } catch (err) {
848
+ const message = err instanceof Error ? err.message : String(err);
849
+ await artifacts.writeText("Failure", "summary.md", `# ${definition.title}
850
+
851
+ ${message}
852
+ `);
853
+ await artifacts.writeManifest("failed", {}, [], [message]);
854
+ throw err;
855
+ }
856
+ }
857
+
858
+ export {
859
+ csvRecords,
860
+ rowsToCsv,
861
+ workflowOutputBaseDir,
862
+ listWorkflowReports,
863
+ findWorkflowReport,
864
+ openWorkflowReport,
865
+ listWorkflowDefinitions,
866
+ workflowDefinition,
867
+ runWorkflow
868
+ };
869
+ //# sourceMappingURL=chunk-L6IS63WS.js.map