mcp-scraper 0.2.7 → 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.
- package/README.md +44 -5
- package/dist/bin/api-server.cjs +2417 -648
- package/dist/bin/api-server.cjs.map +1 -1
- package/dist/bin/api-server.js +3 -3
- package/dist/bin/browser-agent-stdio-server.cjs +1 -1
- package/dist/bin/browser-agent-stdio-server.cjs.map +1 -1
- package/dist/bin/browser-agent-stdio-server.js +2 -2
- package/dist/bin/mcp-scraper-cli.cjs +1276 -0
- package/dist/bin/mcp-scraper-cli.cjs.map +1 -0
- package/dist/bin/mcp-scraper-cli.d.cts +1 -0
- package/dist/bin/mcp-scraper-cli.d.ts +1 -0
- package/dist/bin/mcp-scraper-cli.js +476 -0
- package/dist/bin/mcp-scraper-cli.js.map +1 -0
- package/dist/bin/mcp-scraper-combined-stdio-server.cjs +69 -14
- package/dist/bin/mcp-scraper-combined-stdio-server.cjs.map +1 -1
- package/dist/bin/mcp-scraper-combined-stdio-server.js +3 -3
- package/dist/bin/mcp-scraper-install.cjs +5 -1
- package/dist/bin/mcp-scraper-install.cjs.map +1 -1
- package/dist/bin/mcp-scraper-install.js +5 -1
- package/dist/bin/mcp-scraper-install.js.map +1 -1
- package/dist/bin/mcp-stdio-server.cjs +69 -14
- package/dist/bin/mcp-stdio-server.cjs.map +1 -1
- package/dist/bin/mcp-stdio-server.js +2 -2
- package/dist/bin/paa-harvest.cjs +42 -6
- package/dist/bin/paa-harvest.cjs.map +1 -1
- package/dist/bin/paa-harvest.js +1 -1
- package/dist/{chunk-3TF6UT2P.js → chunk-5E6KJC26.js} +2 -2
- package/dist/{chunk-D4CJBZBY.js → chunk-7GCCOT3M.js} +372 -1
- package/dist/chunk-7GCCOT3M.js.map +1 -0
- package/dist/chunk-BJDCPCIE.js +7 -0
- package/dist/chunk-BJDCPCIE.js.map +1 -0
- package/dist/{chunk-MY3S7EX7.js → chunk-CQTAKXBN.js} +43 -7
- package/dist/chunk-CQTAKXBN.js.map +1 -0
- package/dist/chunk-L6IS63WS.js +869 -0
- package/dist/chunk-L6IS63WS.js.map +1 -0
- package/dist/{chunk-IQOCZGJJ.js → chunk-ROS67BNV.js} +5 -5
- package/dist/{chunk-7SI6XIR3.js → chunk-XAY5U67D.js} +70 -15
- package/dist/chunk-XAY5U67D.js.map +1 -0
- package/dist/{db-YWCNHBLH.js → db-BVHYI57K.js} +38 -2
- package/dist/index.cjs +42 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/{server-RIKRBDOI.js → server-BKJ7LULQ.js} +818 -394
- package/dist/server-BKJ7LULQ.js.map +1 -0
- package/dist/{worker-NAKGTIF5.js → worker-TDJQ6TH3.js} +8 -8
- package/docs/mcp-tool-quality-spec.md +3 -1
- package/docs/specs/agent-ready-seo-packet-spec.md +237 -0
- package/docs/specs/cli-agent-wiring-spec.md +203 -0
- package/docs/specs/deferred-work-spec.md +12 -0
- package/docs/specs/local-competitive-audit-spec.md +312 -0
- package/docs/specs/scheduled-workflows-api-spec.md +304 -0
- package/docs/specs/seo-cli-growth-roadmap-spec.md +179 -0
- package/docs/specs/seo-workflow-runner-and-reports-spec.md +241 -0
- package/package.json +3 -2
- package/dist/chunk-7SI6XIR3.js.map +0 -1
- package/dist/chunk-D4CJBZBY.js.map +0 -1
- package/dist/chunk-IZE5UW7Y.js +0 -7
- package/dist/chunk-IZE5UW7Y.js.map +0 -1
- package/dist/chunk-MY3S7EX7.js.map +0 -1
- package/dist/server-RIKRBDOI.js.map +0 -1
- /package/dist/{chunk-3TF6UT2P.js.map → chunk-5E6KJC26.js.map} +0 -0
- /package/dist/{chunk-IQOCZGJJ.js.map → chunk-ROS67BNV.js.map} +0 -0
- /package/dist/{db-YWCNHBLH.js.map → db-BVHYI57K.js.map} +0 -0
- /package/dist/{worker-NAKGTIF5.js.map → worker-TDJQ6TH3.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/workflows/artifact-writer.ts","../src/directory/csv.ts","../src/lib/slugify.ts","../src/workflows/registry.ts","../src/workflows/http-client.ts","../src/workflows/workflows/agent-packet.ts","../src/workflows/report-renderer.ts","../src/workflows/workflows/directory.ts","../src/workflows/workflows/local-competitive-audit.ts"],"sourcesContent":["import { mkdir, readFile, stat, writeFile } from 'node:fs/promises'\nimport { existsSync } from 'node:fs'\nimport { homedir, platform } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport { execFile } from 'node:child_process'\nimport { rowsToCsv } from '../directory/csv.js'\nimport { slugify } from '../lib/slugify.js'\nimport type { WorkflowArtifact, WorkflowManifest, WorkflowStatus } from './types.js'\n\nexport function workflowOutputBaseDir(outputDir?: string): string {\n return outputDir?.trim() || process.env.MCP_SCRAPER_OUTPUT_DIR?.trim() || join(homedir(), 'Downloads', 'mcp-scraper')\n}\n\nfunction timestamp(): string {\n return new Date().toISOString().replace(/[:.]/g, '-')\n}\n\nfunction safeSlug(value: string): string {\n return slugify(value).replace(/^-+|-+$/g, '').slice(0, 80) || 'run'\n}\n\nexport class ArtifactWriter {\n readonly artifacts: WorkflowArtifact[] = []\n\n constructor(\n readonly workflowId: string,\n readonly title: string,\n readonly runId: string,\n readonly baseDir: string,\n readonly runDir: string,\n readonly startedAt: string,\n readonly input: Record<string, unknown>,\n ) {}\n\n static async create(workflowId: string, title: string, input: Record<string, unknown>, outputDir?: string, forcedRunId?: string): Promise<ArtifactWriter> {\n const startedAt = new Date().toISOString()\n const runId = forcedRunId?.trim() || `${timestamp()}-${safeSlug(workflowId)}-${Math.random().toString(36).slice(2, 8)}`\n const nameSource = String(input.keyword ?? input.query ?? input.domain ?? input.state ?? workflowId)\n const baseDir = workflowOutputBaseDir(outputDir)\n const runDir = join(baseDir, 'workflows', workflowId, `${timestamp()}-${safeSlug(nameSource)}-${safeSlug(runId).slice(0, 20)}`)\n await mkdir(runDir, { recursive: true })\n return new ArtifactWriter(workflowId, title, runId, baseDir, runDir, startedAt, input)\n }\n\n private async remember(kind: WorkflowArtifact['kind'], label: string, path: string, rows?: number): Promise<string> {\n const size = await stat(path).then(s => s.size).catch(() => undefined)\n this.artifacts.push({ kind, label, path, bytes: size, rows })\n return path\n }\n\n async writeJson(label: string, relativePath: string, data: unknown): Promise<string> {\n const path = join(this.runDir, relativePath)\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, JSON.stringify(data, null, 2), 'utf8')\n return this.remember('json', label, path)\n }\n\n async writeText(label: string, relativePath: string, text: string, kind: WorkflowArtifact['kind'] = 'markdown'): Promise<string> {\n const path = join(this.runDir, relativePath)\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, text, 'utf8')\n return this.remember(kind, label, path)\n }\n\n async writeCsv(label: string, relativePath: string, headers: string[], rows: Array<Record<string, unknown>>): Promise<string> {\n const path = join(this.runDir, relativePath)\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, rowsToCsv(headers, rows), 'utf8')\n return this.remember('csv', label, path, rows.length)\n }\n\n async writeHtml(label: string, relativePath: string, html: string): Promise<string> {\n return this.writeText(label, relativePath, html, 'html_report')\n }\n\n async writeManifest(status: WorkflowStatus, counts: Record<string, number>, warnings: string[], errors: string[]): Promise<string> {\n const manifest: WorkflowManifest = {\n workflow: this.workflowId,\n title: this.title,\n runId: this.runId,\n status,\n startedAt: this.startedAt,\n completedAt: status === 'running' ? null : new Date().toISOString(),\n input: this.input,\n artifacts: this.artifacts,\n warnings,\n errors,\n counts,\n }\n const path = join(this.runDir, 'manifest.json')\n await writeFile(path, JSON.stringify(manifest, null, 2), 'utf8')\n await updateWorkflowIndex(manifest, path, this.baseDir)\n return path\n }\n}\n\ninterface WorkflowIndexEntry {\n workflow: string\n runId: string\n status: string\n startedAt: string\n reportPath: string | null\n manifestPath: string\n summary: string\n}\n\ninterface WorkflowIndex {\n runs: WorkflowIndexEntry[]\n}\n\nfunction indexPath(baseDir = workflowOutputBaseDir()): string {\n return join(baseDir, 'workflows', 'index.json')\n}\n\nasync function readIndex(baseDir?: string): Promise<WorkflowIndex> {\n const path = indexPath(baseDir)\n if (!existsSync(path)) return { runs: [] }\n try {\n return JSON.parse(await readFile(path, 'utf8')) as WorkflowIndex\n } catch {\n return { runs: [] }\n }\n}\n\nasync function updateWorkflowIndex(manifest: WorkflowManifest, manifestPath: string, baseDir: string): Promise<void> {\n if (manifest.status === 'running') return\n const path = indexPath(baseDir)\n const index = await readIndex(baseDir)\n const report = manifest.artifacts.find(a => a.kind === 'html_report')?.path ?? null\n const entry: WorkflowIndexEntry = {\n workflow: manifest.workflow,\n runId: manifest.runId,\n status: manifest.status,\n startedAt: manifest.startedAt,\n reportPath: report,\n manifestPath,\n summary: `${manifest.title} (${manifest.status})`,\n }\n index.runs = [entry, ...index.runs.filter(r => r.runId !== manifest.runId)].slice(0, 200)\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, JSON.stringify(index, null, 2), 'utf8')\n}\n\nexport async function listWorkflowReports(outputDir?: string): Promise<WorkflowIndexEntry[]> {\n return (await readIndex(workflowOutputBaseDir(outputDir))).runs\n}\n\nexport async function findWorkflowReport(id: string, outputDir?: string): Promise<WorkflowIndexEntry | null> {\n const runs = await listWorkflowReports(outputDir)\n if (id === 'last') return runs[0] ?? null\n return runs.find(run => run.runId === id) ?? null\n}\n\nexport async function openWorkflowReport(id: string, outputDir?: string): Promise<string> {\n const run = await findWorkflowReport(id, outputDir)\n if (!run?.reportPath) throw new Error(`No report found for \"${id}\"`)\n if (platform() === 'darwin') {\n await new Promise<void>((resolve, reject) => {\n execFile('open', [run.reportPath!], (err) => err ? reject(err) : resolve())\n })\n }\n return run.reportPath\n}\n","export function parseCsv(text: string): string[][] {\n const rows: string[][] = []\n let row: string[] = []\n let field = ''\n let quoted = false\n\n for (let i = 0; i < text.length; i += 1) {\n const ch = text[i]\n const next = text[i + 1]\n\n if (quoted) {\n if (ch === '\"' && next === '\"') {\n field += '\"'\n i += 1\n } else if (ch === '\"') {\n quoted = false\n } else {\n field += ch\n }\n continue\n }\n\n if (ch === '\"') {\n quoted = true\n } else if (ch === ',') {\n row.push(field)\n field = ''\n } else if (ch === '\\n') {\n row.push(field)\n rows.push(row)\n row = []\n field = ''\n } else if (ch !== '\\r') {\n field += ch\n }\n }\n\n if (field.length > 0 || row.length > 0) {\n row.push(field)\n rows.push(row)\n }\n\n return rows\n}\n\nexport function csvRecords(text: string): Array<Record<string, string>> {\n const rows = parseCsv(text).filter(row => row.some(cell => cell.trim() !== ''))\n const header = rows[0]?.map(cell => cell.trim()) ?? []\n return rows.slice(1).map((row) => {\n const record: Record<string, string> = {}\n for (let i = 0; i < header.length; i += 1) {\n record[header[i]] = row[i] ?? ''\n }\n return record\n })\n}\n\nexport function csvCell(value: unknown): string {\n if (value === null || value === undefined) return ''\n const text = String(value)\n return /[\",\\n\\r]/.test(text) ? `\"${text.replace(/\"/g, '\"\"')}\"` : text\n}\n\nexport function rowsToCsv(headers: string[], rows: Array<Record<string, unknown>>): string {\n return [\n headers.join(','),\n ...rows.map(row => headers.map(header => csvCell(row[header])).join(',')),\n ].join('\\n') + '\\n'\n}\n","export function slugify(s: string): string {\n return s.toLowerCase().replace(/\\s+/g, '-').replace(/[^a-z0-9-]/g, '');\n}\n","import { z } from 'zod'\nimport { ArtifactWriter, findWorkflowReport, listWorkflowReports, openWorkflowReport } from './artifact-writer.js'\nimport { WorkflowHttpClient } from './http-client.js'\nimport type { WorkflowDefinition, WorkflowRunOptions, WorkflowRunSummary } from './types.js'\nimport { agentPacketWorkflowDefinition } from './workflows/agent-packet.js'\nimport { directoryWorkflowDefinition } from './workflows/directory.js'\nimport { localCompetitiveAuditWorkflowDefinition } from './workflows/local-competitive-audit.js'\n\nconst DEFINITIONS = [\n directoryWorkflowDefinition,\n agentPacketWorkflowDefinition,\n localCompetitiveAuditWorkflowDefinition,\n] satisfies WorkflowDefinition<any>[]\n\nexport function listWorkflowDefinitions(): Array<Pick<WorkflowDefinition, 'id' | 'title' | 'description'>> {\n return DEFINITIONS.map(({ id, title, description }) => ({ id, title, description }))\n}\n\nexport function workflowDefinition(id: string): WorkflowDefinition<any> {\n const definition = DEFINITIONS.find(def => def.id === id)\n if (!definition) throw new Error(`Unknown workflow \"${id}\". Available: ${DEFINITIONS.map(def => def.id).join(', ')}`)\n return definition\n}\n\nexport async function runWorkflow(id: string, rawInput: Record<string, unknown>, options: WorkflowRunOptions = {}): Promise<WorkflowRunSummary> {\n const definition = workflowDefinition(id)\n const input = definition.inputSchema.parse(rawInput)\n const apiKey = options.apiKey?.trim() || process.env.MCP_SCRAPER_API_KEY?.trim()\n if (!apiKey) throw new Error('MCP_SCRAPER_API_KEY is required for workflow runs. Pass --api-key or set the environment variable.')\n const apiUrl = options.apiUrl?.trim() || process.env.MCP_SCRAPER_API_URL?.trim() || 'https://mcpscraper.dev'\n const artifacts = await ArtifactWriter.create(definition.id, definition.title, input as Record<string, unknown>, options.outputDir, options.runId)\n const client = new WorkflowHttpClient(apiUrl, apiKey, options.fetchImpl)\n try {\n return await definition.run(input, {\n runId: artifacts.runId,\n startedAt: artifacts.startedAt,\n client,\n artifacts,\n signal: options.signal,\n })\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n await artifacts.writeText('Failure', 'summary.md', `# ${definition.title}\\n\\n${message}\\n`)\n await artifacts.writeManifest('failed', {}, [], [message])\n throw err\n }\n}\n\nexport { findWorkflowReport, listWorkflowReports, openWorkflowReport }\nexport { z }\n","import type { WorkflowApiClient } from './types.js'\n\nexport class WorkflowHttpClient implements WorkflowApiClient {\n constructor(\n private readonly apiUrl: string,\n private readonly apiKey: string,\n private readonly fetchImpl: typeof fetch = fetch,\n ) {}\n\n async post<T>(path: string, body: Record<string, unknown>, timeoutMs = 180_000): Promise<T> {\n const res = await this.fetchImpl(`${this.apiUrl.replace(/\\/$/, '')}${path}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-api-key': this.apiKey,\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(timeoutMs),\n })\n const data = await res.json().catch(() => ({}))\n if (!res.ok) {\n const message = typeof (data as { error?: unknown }).error === 'string'\n ? (data as { error: string }).error\n : `Workflow API ${path} failed with ${res.status}`\n throw new Error(message)\n }\n return data as T\n }\n}\n\n","import { z } from 'zod'\nimport { rowsToCsv } from '../../directory/csv.js'\nimport { renderWorkflowReport } from '../report-renderer.js'\nimport type { WorkflowDefinition, WorkflowRunContext, WorkflowRunSummary } from '../types.js'\n\nconst AgentPacketInputSchema = z.object({\n keyword: z.string().min(1),\n domain: z.string().optional(),\n location: z.string().optional(),\n maxQuestions: z.number().int().min(1).max(200).default(40),\n includeSerp: z.boolean().default(true),\n includePaa: z.boolean().default(true),\n includeAiOverview: z.boolean().default(true),\n returnPartial: z.boolean().default(true),\n})\n\ntype AgentPacketInput = z.infer<typeof AgentPacketInputSchema>\n\ninterface OrganicResult {\n position: number\n title: string\n url: string\n domain: string\n snippet?: string | null\n}\n\ninterface PaaRow {\n question: string\n answer?: string | null\n source_title?: string | null\n source_site?: string | null\n source_cite?: string | null\n}\n\ninterface HarvestLike {\n organicResults?: OrganicResult[]\n localPack?: Array<{ position: number; name: string; rating?: string | null; reviewCount?: string | null; websiteUrl?: string | null }>\n flat?: PaaRow[]\n aiOverview?: { detected?: boolean; text?: string | null; citations?: Array<{ text?: string; href?: string }> }\n}\n\nfunction normalizeDomain(value?: string | null): string | null {\n if (!value) return null\n try {\n const url = new URL(value.includes('://') ? value : `https://${value}`)\n return url.hostname.replace(/^www\\./, '').toLowerCase()\n } catch {\n return value.replace(/^https?:\\/\\//, '').replace(/^www\\./, '').split('/')[0]?.toLowerCase() || null\n }\n}\n\nfunction domainFromUrl(url: string): string {\n return normalizeDomain(url) ?? ''\n}\n\nfunction sourceRows(input: AgentPacketInput, serp: HarvestLike | null, paa: HarvestLike | null): Array<Record<string, unknown>> {\n const target = normalizeDomain(input.domain)\n const rows: Array<Record<string, unknown>> = []\n for (const result of serp?.organicResults ?? []) {\n const domain = normalizeDomain(result.domain) ?? domainFromUrl(result.url)\n rows.push({\n surface: 'organic',\n position: result.position,\n title: result.title,\n url: result.url,\n domain,\n question: '',\n answer_excerpt: result.snippet ?? '',\n is_target: target ? domain === target : false,\n is_competitor: target ? domain !== target : true,\n })\n }\n for (const row of paa?.flat ?? []) {\n const url = row.source_cite ?? ''\n const domain = normalizeDomain(row.source_site ?? '') ?? (url ? domainFromUrl(url) : '')\n rows.push({\n surface: 'paa',\n position: '',\n title: row.source_title ?? row.source_site ?? '',\n url,\n domain,\n question: row.question,\n answer_excerpt: (row.answer ?? '').slice(0, 240),\n is_target: target ? domain === target : false,\n is_competitor: target ? Boolean(domain && domain !== target) : Boolean(domain),\n })\n }\n for (const [i, cite] of (serp?.aiOverview?.citations ?? []).entries()) {\n const url = cite.href ?? ''\n const domain = url ? domainFromUrl(url) : ''\n rows.push({\n surface: 'ai_overview',\n position: i + 1,\n title: cite.text ?? '',\n url,\n domain,\n question: '',\n answer_excerpt: '',\n is_target: target ? domain === target : false,\n is_competitor: target ? Boolean(domain && domain !== target) : Boolean(domain),\n })\n }\n return rows\n}\n\nfunction competitorRows(rows: Array<Record<string, unknown>>, targetDomain: string | null): Array<Record<string, unknown>> {\n const byDomain = new Map<string, { organic: number[]; paa: number; ai: number; urls: Set<string> }>()\n for (const row of rows) {\n const domain = String(row.domain ?? '')\n if (!domain || domain === targetDomain) continue\n const entry = byDomain.get(domain) ?? { organic: [], paa: 0, ai: 0, urls: new Set<string>() }\n if (row.surface === 'organic' && row.position) entry.organic.push(Number(row.position))\n if (row.surface === 'paa') entry.paa += 1\n if (row.surface === 'ai_overview') entry.ai += 1\n if (row.url) entry.urls.add(String(row.url))\n byDomain.set(domain, entry)\n }\n return [...byDomain.entries()]\n .map(([domain, entry]) => ({\n domain,\n organic_best_position: entry.organic.length ? Math.min(...entry.organic) : '',\n organic_count: entry.organic.length,\n paa_mentions: entry.paa,\n ai_overview_citations: entry.ai,\n source_url_count: entry.urls.size,\n }))\n .sort((a, b) => Number(a.organic_best_position || 999) - Number(b.organic_best_position || 999))\n}\n\nexport const agentPacketWorkflowDefinition: WorkflowDefinition<AgentPacketInput> = {\n id: 'agent-packet',\n title: 'Agent-Ready SEO Packet',\n description: 'Create an evidence folder for AI agents from live SERP/PAA/AI search surfaces.',\n inputSchema: AgentPacketInputSchema,\n async run(input: AgentPacketInput, ctx: WorkflowRunContext): Promise<WorkflowRunSummary> {\n await ctx.artifacts.writeManifest('running', {}, [], [])\n const warnings: string[] = []\n const errors: string[] = []\n let serp: HarvestLike | null = null\n let paa: HarvestLike | null = null\n\n if (input.includeSerp) {\n try {\n serp = await ctx.client.post<HarvestLike>('/harvest/sync', {\n query: input.keyword,\n location: input.location,\n serpOnly: true,\n maxQuestions: 1,\n format: 'json',\n }, 180_000)\n } catch (err) {\n warnings.push(`SERP evidence unavailable: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n\n if (input.includePaa) {\n try {\n paa = await ctx.client.post<HarvestLike>('/harvest/sync', {\n query: input.keyword,\n location: input.location,\n maxQuestions: input.maxQuestions,\n format: 'json',\n }, 280_000)\n } catch (err) {\n warnings.push(`PAA evidence unavailable: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n\n if (!serp && !paa && !input.returnPartial) throw new Error('No SEO evidence was collected')\n const rows = sourceRows(input, serp, paa)\n const target = normalizeDomain(input.domain)\n const competitors = competitorRows(rows, target)\n const evidence = {\n input,\n serp: serp ?? { status: 'skipped' },\n paa: paa ?? { status: 'skipped' },\n target: {\n domain: target,\n organicPositions: rows.filter(r => r.surface === 'organic' && r.is_target).map(r => Number(r.position)),\n citedInAiOverview: rows.some(r => r.surface === 'ai_overview' && r.is_target),\n citedInPaa: rows.some(r => r.surface === 'paa' && r.is_target),\n },\n competitors,\n warnings,\n }\n\n await ctx.artifacts.writeJson('Evidence JSON', 'evidence.json', evidence)\n await ctx.artifacts.writeCsv('Sources CSV', 'sources.csv', ['surface', 'position', 'title', 'url', 'domain', 'question', 'answer_excerpt', 'is_target', 'is_competitor'], rows)\n await ctx.artifacts.writeCsv('Competitors CSV', 'competitors.csv', ['domain', 'organic_best_position', 'organic_count', 'paa_mentions', 'ai_overview_citations', 'source_url_count'], competitors)\n\n const brief = [\n `# SEO Evidence Brief: ${input.keyword}`,\n '',\n `Location: ${input.location ?? 'not specified'}`,\n `Target domain: ${target ?? 'not specified'}`,\n '',\n '## Evidence Summary',\n `- Organic rows: ${rows.filter(r => r.surface === 'organic').length}`,\n `- PAA rows: ${rows.filter(r => r.surface === 'paa').length}`,\n `- AI Overview citations: ${rows.filter(r => r.surface === 'ai_overview').length}`,\n `- Competitor domains: ${competitors.length}`,\n '',\n '## Recommended Use',\n 'Use the CSV files as source of truth. Tie content recommendations to evidence rows and mark unsupported ideas as assumptions.',\n ].join('\\n')\n await ctx.artifacts.writeText('Brief', 'brief.md', brief)\n await ctx.artifacts.writeText('Agent tasks', 'tasks.md', [\n '# Agent Tasks',\n '',\n '- [ ] Read `evidence.json` before writing recommendations.',\n '- [ ] Compare the target domain against `competitors.csv`.',\n '- [ ] Use `sources.csv` for citations and source-grounded page sections.',\n '- [ ] Mark unsupported recommendations as assumptions.',\n ].join('\\n'))\n await ctx.artifacts.writeText('Agent instructions', 'agent-instructions.md', [\n '# Agent Instructions',\n '',\n '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.',\n ].join('\\n'))\n\n const summary = `${rows.length} evidence rows and ${competitors.length} competitor domains collected.`\n const reportPath = await ctx.artifacts.writeHtml('HTML report', 'report.html', renderWorkflowReport({\n title: 'Agent-Ready SEO Packet',\n subtitle: `${input.keyword}${input.location ? ` · ${input.location}` : ''}`,\n summary,\n warnings,\n tables: [\n { title: 'Competitor Domains', columns: ['domain', 'organic_best_position', 'organic_count', 'paa_mentions', 'ai_overview_citations', 'source_url_count'], rows: competitors.slice(0, 50) },\n { title: 'Evidence Sources', columns: ['surface', 'position', 'title', 'domain', 'question', 'is_target'], rows: rows.slice(0, 100) },\n ],\n }))\n const status = warnings.length ? 'partial' : 'succeeded'\n const counts = { sources: rows.length, competitors: competitors.length }\n await ctx.artifacts.writeManifest(status, counts, warnings, errors)\n return { title: 'Agent-Ready SEO Packet', summary, status, counts, warnings, errors, reportPath }\n },\n}\n\n","export interface ReportTable {\n title: string\n columns: string[]\n rows: Array<Record<string, unknown>>\n}\n\nexport interface ReportSection {\n title: string\n body: string\n}\n\nexport interface WorkflowReportInput {\n title: string\n subtitle?: string\n summary: string\n sections?: ReportSection[]\n tables?: ReportTable[]\n warnings?: string[]\n}\n\nexport function escapeHtml(value: unknown): string {\n return String(value ?? '')\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n}\n\nfunction renderTable(table: ReportTable): string {\n const rows = table.rows.map(row => (\n `<tr>${table.columns.map(col => `<td>${escapeHtml(row[col])}</td>`).join('')}</tr>`\n )).join('\\n')\n return [\n `<section>`,\n `<h2>${escapeHtml(table.title)}</h2>`,\n `<div class=\"table-wrap\"><table>`,\n `<thead><tr>${table.columns.map(col => `<th>${escapeHtml(col)}</th>`).join('')}</tr></thead>`,\n `<tbody>${rows || `<tr><td colspan=\"${table.columns.length}\">No rows</td></tr>`}</tbody>`,\n `</table></div>`,\n `</section>`,\n ].join('\\n')\n}\n\nexport function renderWorkflowReport(input: WorkflowReportInput): string {\n const warnings = input.warnings?.length\n ? `<section class=\"warnings\"><h2>Warnings</h2><ul>${input.warnings.map(w => `<li>${escapeHtml(w)}</li>`).join('')}</ul></section>`\n : ''\n const sections = (input.sections ?? []).map(section => (\n `<section><h2>${escapeHtml(section.title)}</h2><p>${escapeHtml(section.body)}</p></section>`\n )).join('\\n')\n const tables = (input.tables ?? []).map(renderTable).join('\\n')\n\n return [\n '<!doctype html>',\n '<html lang=\"en\">',\n '<head>',\n '<meta charset=\"utf-8\">',\n '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">',\n `<title>${escapeHtml(input.title)}</title>`,\n '<style>',\n ':root{font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;color:#172026;background:#f6f7f8}',\n 'body{margin:0;padding:32px}main{max-width:1180px;margin:0 auto;background:#fff;border:1px solid #d9dee3;border-radius:8px;padding:28px}',\n '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}',\n '.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}',\n '.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}',\n '</style>',\n '</head>',\n '<body><main>',\n `<h1>${escapeHtml(input.title)}</h1>`,\n input.subtitle ? `<p class=\"sub\">${escapeHtml(input.subtitle)}</p>` : '',\n `<div class=\"summary\">${escapeHtml(input.summary)}</div>`,\n warnings,\n sections,\n tables,\n '</main></body></html>',\n ].join('\\n')\n}\n\n","import { z } from 'zod'\nimport { renderWorkflowReport } from '../report-renderer.js'\nimport type { WorkflowDefinition, WorkflowRunContext, WorkflowRunSummary } from '../types.js'\n\nconst DirectoryWorkflowCliInputSchema = z.object({\n query: z.string().min(1),\n state: z.string().min(2).default('TN'),\n minPopulation: z.number().int().min(0).default(100_000),\n maxCities: z.number().int().min(1).max(100).default(25),\n maxResultsPerCity: z.number().int().min(1).max(50).default(20),\n concurrency: z.number().int().min(1).max(5).default(5),\n proxyMode: z.enum(['location', 'configured', 'none']).default('location'),\n saveCsv: z.boolean().default(true),\n})\n\ntype DirectoryWorkflowCliInput = z.infer<typeof DirectoryWorkflowCliInputSchema>\n\ninterface DirectoryBusiness {\n position: number\n name: string\n rating: string | null\n reviewCount: string | null\n category: string | null\n address: string | null\n phone: string | null\n websiteUrl: string | null\n placeUrl: string\n cid: string | null\n cidDecimal: string | null\n}\n\ninterface DirectoryCity {\n city: string\n state: string\n location: string\n population: number\n status: 'ok' | 'empty' | 'failed'\n error: string | null\n resultCount: number\n results: DirectoryBusiness[]\n}\n\nexport interface DirectoryWorkflowApiResult {\n query: string\n state: string\n selectedCityCount: number\n totalResultCount: number\n warnings: string[]\n csvPath: string | null\n cities: DirectoryCity[]\n}\n\nexport function directoryRows(result: DirectoryWorkflowApiResult): Array<Record<string, unknown>> {\n const rows: Array<Record<string, unknown>> = []\n for (const city of result.cities) {\n if (!city.results.length) {\n rows.push({\n source_query: result.query,\n source_location: city.location,\n city: city.city,\n state: city.state,\n population: city.population,\n result_position: null,\n business_name: null,\n review_stars: null,\n review_count: null,\n category: null,\n address: null,\n phone: null,\n website_url: null,\n place_url: null,\n cid: null,\n cid_decimal: null,\n result_status: city.status,\n error: city.error,\n })\n continue\n }\n for (const business of city.results) {\n rows.push({\n source_query: result.query,\n source_location: city.location,\n city: city.city,\n state: city.state,\n population: city.population,\n result_position: business.position,\n business_name: business.name,\n review_stars: business.rating,\n review_count: business.reviewCount,\n category: business.category,\n address: business.address,\n phone: business.phone,\n website_url: business.websiteUrl,\n place_url: business.placeUrl,\n cid: business.cid,\n cid_decimal: business.cidDecimal,\n result_status: city.status,\n error: city.error,\n })\n }\n }\n return rows\n}\n\nexport const DIRECTORY_CSV_HEADERS = [\n 'source_query',\n 'source_location',\n 'city',\n 'state',\n 'population',\n 'result_position',\n 'business_name',\n 'review_stars',\n 'review_count',\n 'category',\n 'address',\n 'phone',\n 'website_url',\n 'place_url',\n 'cid',\n 'cid_decimal',\n 'result_status',\n 'error',\n]\n\nexport const directoryWorkflowDefinition: WorkflowDefinition<DirectoryWorkflowCliInput> = {\n id: 'directory',\n title: 'Directory Workflow',\n description: 'Select city markets and export Google Maps business candidates.',\n inputSchema: DirectoryWorkflowCliInputSchema,\n async run(input: DirectoryWorkflowCliInput, ctx: WorkflowRunContext): Promise<WorkflowRunSummary> {\n await ctx.artifacts.writeManifest('running', {}, [], [])\n const result = await ctx.client.post<DirectoryWorkflowApiResult>('/directory/run', input as Record<string, unknown>, 900_000)\n await ctx.artifacts.writeJson('Directory evidence', 'evidence.json', result)\n const rows = directoryRows(result)\n await ctx.artifacts.writeCsv('Directory CSV', 'exports/directory.csv', DIRECTORY_CSV_HEADERS, rows)\n\n const cityRows = result.cities.map(city => ({\n city: city.city,\n state: city.state,\n population: city.population,\n status: city.status,\n result_count: city.resultCount,\n error: city.error ?? '',\n }))\n const topRows = rows\n .filter(row => row.business_name)\n .slice(0, 100)\n .map(row => ({\n city: row.city,\n position: row.result_position,\n business: row.business_name,\n rating: row.review_stars,\n reviews: row.review_count,\n category: row.category,\n website: row.website_url,\n }))\n\n const summary = `${result.selectedCityCount} cities processed with ${result.totalResultCount} Maps results.`\n await ctx.artifacts.writeText('Summary', 'summary.md', `# Directory Workflow\\n\\n${summary}\\n`)\n const reportPath = await ctx.artifacts.writeHtml('HTML report', 'report.html', renderWorkflowReport({\n title: 'Directory Workflow',\n subtitle: `${input.query} · ${input.state}`,\n summary,\n warnings: result.warnings,\n tables: [\n { title: 'Cities', columns: ['city', 'state', 'population', 'status', 'result_count', 'error'], rows: cityRows },\n { title: 'Top Results', columns: ['city', 'position', 'business', 'rating', 'reviews', 'category', 'website'], rows: topRows },\n ],\n }))\n const status = result.cities.some(city => city.status === 'failed') ? 'partial' : 'succeeded'\n const counts = { cities: result.selectedCityCount, results: result.totalResultCount, rows: rows.length }\n await ctx.artifacts.writeManifest(status, counts, result.warnings, [])\n return { title: 'Directory Workflow', summary, status, counts, warnings: result.warnings, errors: [], reportPath }\n },\n}\n\n","import { z } from 'zod'\nimport { renderWorkflowReport } from '../report-renderer.js'\nimport type { WorkflowDefinition, WorkflowRunContext, WorkflowRunSummary } from '../types.js'\nimport { DIRECTORY_CSV_HEADERS, directoryRows, type DirectoryWorkflowApiResult } from './directory.js'\n\nconst LocalCompetitiveAuditInputSchema = z.object({\n query: z.string().min(1),\n state: z.string().min(2).default('TN'),\n minPopulation: z.number().int().min(0).default(100_000),\n maxCities: z.number().int().min(1).max(100).default(25),\n maxResultsPerCity: z.number().int().min(1).max(50).default(20),\n hydrateTop: z.number().int().min(0).max(10).default(5),\n maxReviews: z.number().int().min(0).max(500).default(50),\n concurrency: z.number().int().min(1).max(5).default(5),\n proxyMode: z.enum(['location', 'configured', 'none']).default('location'),\n returnPartial: z.boolean().default(true),\n})\n\ntype LocalCompetitiveAuditInput = z.infer<typeof LocalCompetitiveAuditInputSchema>\n\ninterface MapsPlaceIntelResult {\n name: string | null\n rating: string | null\n reviewCount: string | null\n category: string | null\n website: string | null\n reviewsStatus: string\n reviewHistogram: Array<{ stars: number; count: string }>\n reviewTopics: Array<{ label: string; count: string }>\n aboutAttributes: Array<{ section: string; attribute: string }>\n reviews: Array<{ stars: string | null; text: string | null; ownerResponse: string | null }>\n}\n\nasync function mapLimit<T, R>(items: T[], limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]> {\n const out: R[] = new Array(items.length)\n let next = 0\n async function worker(): Promise<void> {\n while (next < items.length) {\n const index = next\n next += 1\n out[index] = await fn(items[index], index)\n }\n }\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\n return out\n}\n\nfunction numberFrom(value: unknown): number | null {\n if (value === null || value === undefined || value === '') return null\n const parsed = Number(String(value).replace(/[^\\d.]/g, ''))\n return Number.isFinite(parsed) ? parsed : null\n}\n\nfunction median(values: Array<number | null>): number | null {\n const nums = values.filter((v): v is number => v !== null).sort((a, b) => a - b)\n if (!nums.length) return null\n return nums[Math.floor(nums.length / 2)] ?? null\n}\n\nfunction termsFrom(texts: string[]): string {\n const stop = new Set(['the', 'and', 'for', 'with', 'that', 'this', 'was', 'were', 'are', 'you', 'our', 'they', 'had', 'have', 'not', 'but', 'from', 'very', 'great', 'good'])\n const counts = new Map<string, number>()\n for (const text of texts) {\n for (const token of text.toLowerCase().replace(/[^a-z0-9\\s]/g, ' ').split(/\\s+/)) {\n if (token.length < 4 || stop.has(token)) continue\n counts.set(token, (counts.get(token) ?? 0) + 1)\n }\n }\n return [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 8).map(([term, count]) => `${term} (${count})`).join('; ')\n}\n\nexport const localCompetitiveAuditWorkflowDefinition: WorkflowDefinition<LocalCompetitiveAuditInput> = {\n id: 'local-competitive-audit',\n title: 'Local Competitive Audit',\n description: 'Audit local Maps competitors, categories, review counts, and review themes across city markets.',\n inputSchema: LocalCompetitiveAuditInputSchema,\n async run(input: LocalCompetitiveAuditInput, ctx: WorkflowRunContext): Promise<WorkflowRunSummary> {\n await ctx.artifacts.writeManifest('running', {}, [], [])\n const warnings: string[] = []\n const errors: string[] = []\n const directory = await ctx.client.post<DirectoryWorkflowApiResult>('/directory/run', {\n query: input.query,\n state: input.state,\n minPopulation: input.minPopulation,\n maxCities: input.maxCities,\n maxResultsPerCity: input.maxResultsPerCity,\n concurrency: input.concurrency,\n proxyMode: input.proxyMode,\n saveCsv: true,\n }, 900_000)\n\n await ctx.artifacts.writeJson('Directory raw JSON', 'raw/directory-workflow.json', directory)\n const baseRows = directoryRows(directory)\n await ctx.artifacts.writeCsv('Base directory CSV', 'exports/directory.csv', DIRECTORY_CSV_HEADERS, baseRows)\n\n const selected = directory.cities.flatMap(city =>\n city.results.slice(0, input.hydrateTop).map(result => ({ city, result })),\n )\n const seen = new Set<string>()\n const deduped = selected.filter(({ city, result }) => {\n const key = result.cid ?? result.placeUrl ?? `${city.location}:${result.name.toLowerCase()}`\n if (seen.has(key)) return false\n seen.add(key)\n return true\n })\n\n const hydrated = await mapLimit(deduped, 3, async ({ city, result }, index) => {\n try {\n const detail = await ctx.client.post<MapsPlaceIntelResult>('/maps/place', {\n businessName: result.name,\n location: city.location,\n includeReviews: input.maxReviews > 0,\n maxReviews: Math.max(1, input.maxReviews),\n }, 180_000)\n await ctx.artifacts.writeJson(`${result.name} profile`, `raw/maps-place-intel/${index + 1}-${result.name.toLowerCase().replace(/[^a-z0-9]+/g, '-')}.json`, detail)\n return { city, result, detail, error: null as string | null }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n warnings.push(`Profile hydration failed for ${result.name} (${city.location}): ${message}`)\n return { city, result, detail: null, error: message }\n }\n })\n\n const competitorRows = hydrated.map(({ city, result, detail, error }) => {\n const reviews = detail?.reviews ?? []\n const ownerResponses = reviews.filter(r => r.ownerResponse).length\n return {\n city: city.city,\n state: city.state,\n source_location: city.location,\n result_position: result.position,\n business_name: result.name,\n category: detail?.category ?? result.category,\n review_stars: detail?.rating ?? result.rating,\n review_count: detail?.reviewCount ?? result.reviewCount,\n phone: result.phone,\n website_url: detail?.website ?? result.websiteUrl,\n place_url: result.placeUrl,\n cid: result.cid,\n cid_decimal: result.cidDecimal,\n hydrated: detail ? 'true' : 'false',\n reviews_status: detail?.reviewsStatus ?? '',\n review_topics: (detail?.reviewTopics ?? []).map(t => `${t.label} (${t.count})`).join('; '),\n owner_response_rate: reviews.length ? (ownerResponses / reviews.length).toFixed(2) : '',\n error: error ?? '',\n }\n })\n\n const reviewInsightRows = hydrated.map(({ city, result, detail }) => {\n const reviews = detail?.reviews ?? []\n const positive = reviews.filter(r => Number(r.stars) >= 5 && r.text).map(r => r.text!)\n const negative = reviews.filter(r => Number(r.stars) > 0 && Number(r.stars) <= 3 && r.text).map(r => r.text!)\n return {\n city: city.city,\n business_name: result.name,\n cid: result.cid,\n review_count: detail?.reviewCount ?? result.reviewCount,\n average_rating: detail?.rating ?? result.rating,\n topics: (detail?.reviewTopics ?? []).map(t => `${t.label} (${t.count})`).join('; '),\n praise_terms: termsFrom(positive),\n complaint_terms: termsFrom(negative),\n positive_sample: positive[0]?.slice(0, 280) ?? '',\n negative_sample: negative[0]?.slice(0, 280) ?? '',\n }\n })\n\n const citySummaryRows = directory.cities.map(city => {\n const resultReviewCounts = city.results.map(r => numberFrom(r.reviewCount))\n const resultRatings = city.results.map(r => numberFrom(r.rating))\n const topThreeReviews = city.results.slice(0, 3).map(r => numberFrom(r.reviewCount)).filter((v): v is number => v !== null)\n const categories = new Map<string, number>()\n for (const result of city.results) {\n if (!result.category) continue\n categories.set(result.category, (categories.get(result.category) ?? 0) + 1)\n }\n const medReviews = median(resultReviewCounts)\n const medRating = median(resultRatings)\n const topThreeAvg = topThreeReviews.length ? Math.round(topThreeReviews.reduce((a, b) => a + b, 0) / topThreeReviews.length) : null\n const difficulty = Math.min(100, Math.round((topThreeAvg ?? 0) / 20 + (medRating ?? 0) * 10 + city.results.filter(r => r.websiteUrl).length))\n const opportunity = Math.max(0, 100 - difficulty)\n return {\n city: city.city,\n state: city.state,\n population: city.population,\n result_count: city.resultCount,\n median_review_count: medReviews ?? '',\n median_rating: medRating ?? '',\n top_three_average_review_count: topThreeAvg ?? '',\n top_categories: [...categories.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([cat, count]) => `${cat} (${count})`).join('; '),\n opportunity_score: opportunity,\n difficulty_score: difficulty,\n }\n })\n\n 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'], competitorRows)\n 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)\n 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)\n await ctx.artifacts.writeJson('Audit evidence', 'evidence.json', { input, directory, hydrated, citySummaryRows, competitorRows, reviewInsightRows })\n await ctx.artifacts.writeText('Agent tasks', 'tasks.md', [\n '# Local Competitive Audit Tasks',\n '',\n '- [ ] Review city opportunity and difficulty scores as heuristics, not absolute truth.',\n '- [ ] Use review topics and samples as customer-language evidence.',\n '- [ ] Compare target GBP category, review count, and website quality against top competitors.',\n '- [ ] Identify cities with low review-count leaders and weak website coverage.',\n ].join('\\n'))\n\n const summary = `${directory.selectedCityCount} cities, ${directory.totalResultCount} Maps results, ${hydrated.filter(h => h.detail).length} hydrated profiles.`\n await ctx.artifacts.writeText('Summary', 'summary.md', `# Local Competitive Audit\\n\\n${summary}\\n`)\n const reportPath = await ctx.artifacts.writeHtml('HTML report', 'report.html', renderWorkflowReport({\n title: 'Local Competitive Audit',\n subtitle: `${input.query} · ${input.state}`,\n summary,\n warnings,\n tables: [\n { 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 },\n { title: 'Hydrated Competitors', columns: ['city', 'result_position', 'business_name', 'category', 'review_stars', 'review_count', 'hydrated', 'review_topics'], rows: competitorRows.slice(0, 100) },\n { title: 'Review Insights', columns: ['city', 'business_name', 'topics', 'praise_terms', 'complaint_terms'], rows: reviewInsightRows.slice(0, 100) },\n ],\n }))\n\n const status = warnings.length || directory.cities.some(city => city.status === 'failed') ? 'partial' : 'succeeded'\n const counts = { cities: directory.selectedCityCount, mapsResults: directory.totalResultCount, hydratedProfiles: hydrated.filter(h => h.detail).length }\n await ctx.artifacts.writeManifest(status, counts, warnings, errors)\n return { title: 'Local Competitive Audit', summary, status, counts, warnings, errors, reportPath }\n },\n}\n\n"],"mappings":";AAAA,SAAS,OAAO,UAAU,MAAM,iBAAiB;AACjD,SAAS,kBAAkB;AAC3B,SAAS,SAAS,gBAAgB;AAClC,SAAS,SAAS,YAAY;AAC9B,SAAS,gBAAgB;;;ACJlB,SAAS,SAAS,MAA0B;AACjD,QAAM,OAAmB,CAAC;AAC1B,MAAI,M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C,OAAO,CAAC;AACzD,UAAM;AAAA,EACR;AACF;","names":["z","z","z","z","z","competitorRows"]}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
+
import {
|
|
2
|
+
finishHarvestAttempt,
|
|
3
|
+
startHarvestAttempt
|
|
4
|
+
} from "./chunk-7GCCOT3M.js";
|
|
1
5
|
import {
|
|
2
6
|
CaptchaError,
|
|
3
7
|
LocationMismatchError,
|
|
4
8
|
RequestAbortedError
|
|
5
9
|
} from "./chunk-M2S27J6Z.js";
|
|
6
|
-
import {
|
|
7
|
-
finishHarvestAttempt,
|
|
8
|
-
startHarvestAttempt
|
|
9
|
-
} from "./chunk-D4CJBZBY.js";
|
|
10
10
|
|
|
11
11
|
// src/api/rates.ts
|
|
12
12
|
var MC_COSTS = {
|
|
@@ -356,4 +356,4 @@ export {
|
|
|
356
356
|
harvestProblemResponse,
|
|
357
357
|
createHarvestAttemptRecorder
|
|
358
358
|
};
|
|
359
|
-
//# sourceMappingURL=chunk-
|
|
359
|
+
//# sourceMappingURL=chunk-ROS67BNV.js.map
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
} from "./chunk-M2S27J6Z.js";
|
|
4
4
|
import {
|
|
5
5
|
PACKAGE_VERSION
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-BJDCPCIE.js";
|
|
7
7
|
|
|
8
8
|
// src/harvest-timeout.ts
|
|
9
9
|
var VERCEL_FUNCTION_MAX_MS = 3e5;
|
|
@@ -158,12 +158,17 @@ function errorAttemptsSection(body) {
|
|
|
158
158
|
const browser = debug.browser ?? {};
|
|
159
159
|
const kernel = browser.browserRuntime ?? browser.kernel ?? {};
|
|
160
160
|
const proxyResolution = kernel.proxyResolution ?? {};
|
|
161
|
-
const network = browser.networkLocation ?? {
|
|
161
|
+
const network = browser.networkLocation ?? {
|
|
162
|
+
ip: attempt.observedIp ?? attempt.observed_ip,
|
|
163
|
+
city: attempt.observedCity ?? attempt.observed_city,
|
|
164
|
+
region: attempt.observedRegion ?? attempt.observed_region
|
|
165
|
+
};
|
|
162
166
|
const nav = browser.serpNavigation ?? {};
|
|
163
167
|
const geo = [network.ip, network.city, network.region].filter(Boolean).join(" / ") || "geo unknown";
|
|
164
|
-
const sessionId = attempt.browser_session_id ?? attempt.kernel_session_id ?? kernel.sessionId ?? "unknown";
|
|
168
|
+
const sessionId = attempt.browser_session_id ?? attempt.browserSessionIdSuffix ?? attempt.kernel_session_id ?? kernel.sessionId ?? "unknown";
|
|
165
169
|
const cleanupSucceeded = attempt.session_cleanup_succeeded ?? attempt.kernel_delete_succeeded;
|
|
166
|
-
|
|
170
|
+
const proxySource = proxyResolution.source ?? attempt.proxyResolutionSource;
|
|
171
|
+
return `- Attempt ${attempt.attempt_number ?? attempt.attemptNumber ?? "?"}: ${attempt.outcome ?? attempt.status ?? "unknown"} \xB7 session ${sessionId} \xB7 proxy ${debug.request?.proxyMode ?? kernel.proxyMode ?? attempt.proxyMode ?? "unknown"}${proxySource ? `/${proxySource}` : ""} \xB7 ${geo} \xB7 CAPTCHA ${nav.captchaDetected === true ? "yes" : nav.captchaDetected === false ? "no" : "unknown"} \xB7 cleanup ${cleanupSucceeded === true ? "yes" : cleanupSucceeded === false ? "no" : "unknown"}`;
|
|
167
172
|
});
|
|
168
173
|
return `
|
|
169
174
|
|
|
@@ -624,6 +629,29 @@ ${rows}`,
|
|
|
624
629
|
}
|
|
625
630
|
};
|
|
626
631
|
}
|
|
632
|
+
function normalizeMapsAttempts(value) {
|
|
633
|
+
const attempts = Array.isArray(value) ? value : [];
|
|
634
|
+
return attempts.map((attempt, index) => ({
|
|
635
|
+
attemptNumber: attempt.attemptNumber ?? attempt.attempt_number ?? index + 1,
|
|
636
|
+
maxAttempts: attempt.maxAttempts ?? attempt.max_attempts ?? attempts.length,
|
|
637
|
+
status: attempt.status === "ok" ? "ok" : "failed",
|
|
638
|
+
outcome: attempt.outcome ?? attempt.status ?? "unknown",
|
|
639
|
+
willRetry: attempt.willRetry ?? attempt.will_retry ?? false,
|
|
640
|
+
durationMs: attempt.durationMs ?? attempt.duration_ms ?? 0,
|
|
641
|
+
resultCount: attempt.resultCount ?? attempt.result_count ?? 0,
|
|
642
|
+
error: attempt.error ? sanitizeVendorText(attempt.error) : null,
|
|
643
|
+
proxyMode: attempt.proxyMode ?? attempt.proxy_mode ?? "location",
|
|
644
|
+
proxyResolutionSource: attempt.proxyResolutionSource ?? attempt.proxy_resolution_source ?? null,
|
|
645
|
+
proxyIdSuffix: attempt.proxyIdSuffix ?? attempt.proxy_id_suffix ?? null,
|
|
646
|
+
proxyTargetLevel: attempt.proxyTargetLevel ?? attempt.proxy_target_level ?? null,
|
|
647
|
+
proxyTargetLocation: attempt.proxyTargetLocation ?? attempt.proxy_target_location ?? null,
|
|
648
|
+
proxyTargetZip: attempt.proxyTargetZip ?? attempt.proxy_target_zip ?? null,
|
|
649
|
+
browserSessionIdSuffix: attempt.browserSessionIdSuffix ?? attempt.browser_session_id ?? null,
|
|
650
|
+
observedIp: attempt.observedIp ?? attempt.observed_ip ?? null,
|
|
651
|
+
observedCity: attempt.observedCity ?? attempt.observed_city ?? null,
|
|
652
|
+
observedRegion: attempt.observedRegion ?? attempt.observed_region ?? null
|
|
653
|
+
}));
|
|
654
|
+
}
|
|
627
655
|
function formatCreditsInfo(raw, input) {
|
|
628
656
|
const parsed = parseData(raw);
|
|
629
657
|
if ("error" in parsed) return { content: [{ type: "text", text: parsed.error }], isError: true };
|
|
@@ -696,6 +724,8 @@ function formatMapsSearch(raw, input) {
|
|
|
696
724
|
const searchQuery = d.searchQuery ?? [input.query, input.location].filter(Boolean).join(" ");
|
|
697
725
|
const requestedMax = d.requestedMaxResults ?? input.maxResults ?? 10;
|
|
698
726
|
const durationMs = d.durationMs;
|
|
727
|
+
const attempts = normalizeMapsAttempts(d.attempts);
|
|
728
|
+
const lastAttempt = attempts.at(-1);
|
|
699
729
|
const rows = results.map((r) => {
|
|
700
730
|
const rating = [r.rating, r.reviewCount ? `(${r.reviewCount})` : null].filter(Boolean).join(" ");
|
|
701
731
|
return `| ${r.position} | ${cell(r.name)} | ${cell(r.category)} | ${cell(rating)} | ${cell(r.address)} | ${r.cidDecimal ? `\`${r.cidDecimal}\`` : "\u2014"} | ${r.websiteUrl ? `[site](${r.websiteUrl})` : "\u2014"} | [maps](${r.placeUrl}) |`;
|
|
@@ -710,6 +740,7 @@ ${meta}`;
|
|
|
710
740
|
const full = [
|
|
711
741
|
`# Google Maps Search: "${searchQuery}"`,
|
|
712
742
|
`**Returned:** ${results.length} profile candidate${results.length === 1 ? "" : "s"} \xB7 **Requested max:** ${requestedMax} \xB7 **Limit:** 50`,
|
|
743
|
+
attempts.length ? `**Attempts:** ${attempts.length}/${lastAttempt?.maxAttempts ?? attempts.length} \xB7 **Proxy:** ${lastAttempt?.proxyMode ?? "unknown"}${lastAttempt?.proxyResolutionSource ? `/${lastAttempt.proxyResolutionSource}` : ""} \xB7 **Observed:** ${[lastAttempt?.observedCity, lastAttempt?.observedRegion].filter(Boolean).join(", ") || "unknown"}` : null,
|
|
713
744
|
`
|
|
714
745
|
## Results
|
|
715
746
|
| # | Name | Category | Rating | Address | CID | Website | Maps |
|
|
@@ -733,6 +764,7 @@ ${rows}`,
|
|
|
733
764
|
requestedMaxResults: requestedMax,
|
|
734
765
|
resultCount: results.length,
|
|
735
766
|
results: normalizedResults,
|
|
767
|
+
attempts,
|
|
736
768
|
durationMs: durationMs ?? 0
|
|
737
769
|
}
|
|
738
770
|
};
|
|
@@ -743,6 +775,7 @@ function formatDirectoryWorkflow(raw, input) {
|
|
|
743
775
|
const d = parsed.data;
|
|
744
776
|
const cities = (d.cities ?? []).map((city) => ({
|
|
745
777
|
...city,
|
|
778
|
+
attempts: normalizeMapsAttempts(city.attempts),
|
|
746
779
|
results: city.results.map((result) => ({
|
|
747
780
|
...result,
|
|
748
781
|
phone: result.phone ?? null,
|
|
@@ -970,7 +1003,7 @@ var HarvestPaaInputSchema = {
|
|
|
970
1003
|
gl: z.string().length(2).default("us").describe("Google country code inferred from location or user language. Examples: United States us, United Kingdom gb, Japan jp, Canada ca, Australia au."),
|
|
971
1004
|
hl: z.string().default("en").describe("Google interface/content language inferred from the user request. Use en unless the user asks for another language or locale."),
|
|
972
1005
|
device: z.enum(["desktop", "mobile"]).default("desktop").describe("SERP device context. Use desktop by default; use mobile only when the user asks for mobile rankings."),
|
|
973
|
-
proxyMode: z.enum(["location", "configured", "none"]).default("location").describe("Proxy targeting mode. Use location by default for US city/state SERPs; it creates a fresh residential proxy ID per attempt
|
|
1006
|
+
proxyMode: z.enum(["location", "configured", "none"]).default("location").describe("Proxy targeting mode. Use location by default for US city/state SERPs; it creates a fresh residential proxy ID per attempt. If Google shows a CAPTCHA/challenge, browser-service sessions briefly wait for the automatic solver first, then retry with a fresh proxy/session if the challenge does not clear. Also retries proxy tunnel failure and wrong-location evidence before returning. Use configured only for the static configured proxy. Use none only for direct-network debugging."),
|
|
974
1007
|
proxyZip: z.string().regex(/^\d{5}$/).optional().describe("Optional US ZIP override for residential location proxy targeting. Use when the user gives a specific ZIP or when city-center targeting needs to be forced. With proxyMode location this ZIP is used for each fresh proxy attempt."),
|
|
975
1008
|
debug: z.boolean().default(false).describe("Include sanitized browser/session/location diagnostics in the response. Use true when debugging localization, CAPTCHA, or proxy behavior.")
|
|
976
1009
|
};
|
|
@@ -1029,7 +1062,7 @@ var MapsSearchInputSchema = {
|
|
|
1029
1062
|
gl: z.string().length(2).default("us").describe("Google country code inferred from location."),
|
|
1030
1063
|
hl: z.string().length(2).default("en").describe("Language inferred from user request."),
|
|
1031
1064
|
maxResults: z.number().int().min(1).max(50).default(10).describe("Number of Google Maps business/profile candidates to return. Default 10. Maximum 50. Use 10 unless the user asks for more."),
|
|
1032
|
-
proxyMode: z.enum(["location", "configured", "none"]).default("location").describe("Proxy targeting mode. Use location by default for US city/state Maps searches;
|
|
1065
|
+
proxyMode: z.enum(["location", "configured", "none"]).default("location").describe("Proxy targeting mode. Use location by default for US city/state Maps searches; retryable failures create a new residential proxy ID and new browser session for up to 5 attempts. Use configured for the server proxy ID, and none only for local direct-network debugging."),
|
|
1033
1066
|
proxyZip: z.string().regex(/^\d{5}$/).optional().describe("Optional US ZIP override for residential location proxy targeting. Use when the user gives a specific ZIP or city-center ZIP."),
|
|
1034
1067
|
debug: z.boolean().default(false).describe("Include sanitized browser/proxy diagnostics when debugging Maps localization, CAPTCHA, or proxy behavior.")
|
|
1035
1068
|
};
|
|
@@ -1043,8 +1076,8 @@ var DirectoryWorkflowInputSchema = {
|
|
|
1043
1076
|
concurrency: z.number().int().min(1).max(5).default(5).describe("How many city Maps searches to run in parallel. Use 5 for broad directory batches unless debugging."),
|
|
1044
1077
|
includeZipGroups: z.boolean().default(true).describe("Attach ZIP groups from a configured US ZIPS CSV when available. Set MCP_SCRAPER_USZIPS_CSV_PATH on the API server or pass usZipsCsvPath in local/test mode."),
|
|
1045
1078
|
usZipsCsvPath: z.string().optional().describe("Local/test-only path to a US ZIPS CSV with state_abbr, zipcode, county, city columns, such as Lead Magician tools/analytics/data/uszips.csv. Deployed APIs should use MCP_SCRAPER_USZIPS_CSV_PATH instead."),
|
|
1046
|
-
saveCsv: z.boolean().default(true).describe("Save a directory-ready CSV to the MCP Scraper output directory and return its path. CSV rows include source_location, result_position, business_name, review_stars, category, address, phone, hours_status, website_url, directions_url, place_url, CID fields, population, and ZIP groups."),
|
|
1047
|
-
proxyMode: z.enum(["location", "configured", "none"]).default("location").describe("Proxy targeting mode for every city Maps search. Use location by default for US city/state batches;
|
|
1079
|
+
saveCsv: z.boolean().default(true).describe("Save a directory-ready CSV to the MCP Scraper output directory and return its path. CSV rows include source_location, result_position, business_name, review_stars, review_count, category, address, phone, hours_status, website_url, directions_url, place_url, CID fields, population, and ZIP groups."),
|
|
1080
|
+
proxyMode: z.enum(["location", "configured", "none"]).default("location").describe("Proxy targeting mode for every city Maps search. Use location by default for US city/state batches; retryable failures create a new residential proxy ID and new browser session for up to 5 attempts per city. Use configured for the server proxy ID, and none only for local direct-network debugging."),
|
|
1048
1081
|
proxyZip: z.string().regex(/^\d{5}$/).optional().describe("Optional ZIP override for proxy targeting. Normally omit it so each city can use its Lead Magician ZIP group or city/state location."),
|
|
1049
1082
|
debug: z.boolean().default(false).describe("Include sanitized browser/proxy diagnostics in each Maps browser session when supported.")
|
|
1050
1083
|
};
|
|
@@ -1067,6 +1100,26 @@ var RankTrackerBlueprintInputSchema = {
|
|
|
1067
1100
|
notes: z.string().max(4e3).optional().describe("Extra product, client, stack, or hosting requirements to include in the implementation prompt.")
|
|
1068
1101
|
};
|
|
1069
1102
|
var NullableString = z.string().nullable();
|
|
1103
|
+
var MapsSearchAttemptOutput = z.object({
|
|
1104
|
+
attemptNumber: z.number().int().min(1),
|
|
1105
|
+
maxAttempts: z.number().int().min(1),
|
|
1106
|
+
status: z.enum(["ok", "failed"]),
|
|
1107
|
+
outcome: z.string(),
|
|
1108
|
+
willRetry: z.boolean(),
|
|
1109
|
+
durationMs: z.number().int().min(0),
|
|
1110
|
+
resultCount: z.number().int().min(0),
|
|
1111
|
+
error: NullableString,
|
|
1112
|
+
proxyMode: z.enum(["location", "configured", "none"]),
|
|
1113
|
+
proxyResolutionSource: z.enum(["disabled", "location_reused", "location_created", "configured_fallback", "unavailable"]).nullable(),
|
|
1114
|
+
proxyIdSuffix: NullableString,
|
|
1115
|
+
proxyTargetLevel: z.enum(["zip", "city", "state"]).nullable(),
|
|
1116
|
+
proxyTargetLocation: NullableString,
|
|
1117
|
+
proxyTargetZip: NullableString,
|
|
1118
|
+
browserSessionIdSuffix: NullableString,
|
|
1119
|
+
observedIp: NullableString,
|
|
1120
|
+
observedCity: NullableString,
|
|
1121
|
+
observedRegion: NullableString
|
|
1122
|
+
});
|
|
1070
1123
|
var MapsSearchOutputSchema = {
|
|
1071
1124
|
query: z.string(),
|
|
1072
1125
|
location: z.string().nullable(),
|
|
@@ -1091,6 +1144,7 @@ var MapsSearchOutputSchema = {
|
|
|
1091
1144
|
directionsUrl: NullableString,
|
|
1092
1145
|
metadata: z.array(z.string())
|
|
1093
1146
|
})),
|
|
1147
|
+
attempts: z.array(MapsSearchAttemptOutput),
|
|
1094
1148
|
durationMs: z.number().int().min(0)
|
|
1095
1149
|
};
|
|
1096
1150
|
var DirectoryMapsBusinessOutput = z.object({
|
|
@@ -1137,6 +1191,7 @@ var DirectoryWorkflowOutputSchema = {
|
|
|
1137
1191
|
error: NullableString,
|
|
1138
1192
|
resultCount: z.number().int().min(0),
|
|
1139
1193
|
durationMs: z.number().int().min(0),
|
|
1194
|
+
attempts: z.array(MapsSearchAttemptOutput),
|
|
1140
1195
|
results: z.array(DirectoryMapsBusinessOutput)
|
|
1141
1196
|
})),
|
|
1142
1197
|
durationMs: z.number().int().min(0)
|
|
@@ -1353,7 +1408,7 @@ var SearchSerpInputSchema = {
|
|
|
1353
1408
|
gl: z.string().length(2).default("us").describe("Google country code inferred from location or user language."),
|
|
1354
1409
|
hl: z.string().default("en").describe("Google interface/content language inferred from user request."),
|
|
1355
1410
|
device: z.enum(["desktop", "mobile"]).default("desktop").describe("SERP device context. Use desktop by default; use mobile only when the user asks for mobile rankings."),
|
|
1356
|
-
proxyMode: z.enum(["location", "configured", "none"]).default("location").describe("Proxy targeting mode. Use location by default for US city/state SERPs; it creates a fresh residential proxy ID per attempt
|
|
1411
|
+
proxyMode: z.enum(["location", "configured", "none"]).default("location").describe("Proxy targeting mode. Use location by default for US city/state SERPs; it creates a fresh residential proxy ID per attempt. If Google shows a CAPTCHA/challenge, browser-service sessions briefly wait for the automatic solver first, then retry with a fresh proxy/session if the challenge does not clear. Also retries proxy tunnel failure and wrong-location evidence before returning. Use configured only for the static configured proxy. Use none only for direct-network debugging."),
|
|
1357
1412
|
proxyZip: z.string().regex(/^\d{5}$/).optional().describe("Optional US ZIP override for residential location proxy targeting. Use when the user gives a specific ZIP or when city-center targeting needs to be forced. With proxyMode location this ZIP is used for each fresh proxy attempt."),
|
|
1358
1413
|
debug: z.boolean().default(false).describe("Include sanitized browser/session/location diagnostics in the response. Use true when debugging localization, CAPTCHA, or proxy behavior."),
|
|
1359
1414
|
pages: z.number().int().min(1).max(2).default(1).describe("Number of result pages to fetch (1\u20132)")
|
|
@@ -1364,7 +1419,7 @@ var CaptureSerpSnapshotInputSchema = {
|
|
|
1364
1419
|
gl: z.string().length(2).default("us").describe("Google country code inferred from the requested market, e.g. us, gb, ca, au."),
|
|
1365
1420
|
hl: z.string().default("en").describe("Google interface/content language inferred from the user request."),
|
|
1366
1421
|
device: z.enum(["desktop", "mobile"]).default("desktop").describe("SERP device context. Use mobile only when the user asks for mobile rankings or mobile SERP evidence."),
|
|
1367
|
-
proxyMode: z.enum(["location", "configured", "none"]).default("location").describe("Proxy behavior for capture. Use location for localized US residential evidence; it creates a fresh proxy ID per attempt
|
|
1422
|
+
proxyMode: z.enum(["location", "configured", "none"]).default("location").describe("Proxy behavior for capture. Use location for localized US residential evidence; it creates a fresh proxy ID per attempt. If Google shows a CAPTCHA/challenge, browser-service sessions briefly wait for the automatic solver first, then retry with a fresh proxy/session if the challenge does not clear. Also retries proxy tunnel failure and wrong-location evidence before returning. Use configured only for the static residential proxy, and none only for direct-network debugging."),
|
|
1368
1423
|
proxyZip: z.string().regex(/^\d{5}$/).optional().describe("Optional US ZIP override for residential location proxy targeting when a precise city-center or ZIP proxy is needed. With proxyMode location this ZIP is used for each fresh proxy attempt."),
|
|
1369
1424
|
pages: z.number().int().min(1).max(2).default(1).describe("Number of Google result pages to capture. Use 1 normally and 2 only when the user needs deeper ranking evidence."),
|
|
1370
1425
|
debug: z.boolean().default(false).describe("Include sanitized browser, proxy, and location diagnostics. Use true when debugging localization, CAPTCHA, proxy selection, or capture reliability."),
|
|
@@ -1776,14 +1831,14 @@ function registerPaaExtractorMcpTools(server, executor, options = {}) {
|
|
|
1776
1831
|
if (savesReports) registerSavedReportResources(server);
|
|
1777
1832
|
server.registerTool("harvest_paa", {
|
|
1778
1833
|
title: "Google PAA + SERP Harvest",
|
|
1779
|
-
description: withReportNote('Best default tool for Google search research. Extracts People Also Ask questions plus answers/source URLs, organic SERP, local pack when present, entity IDs (CID/GCID/KG MID), and AI Overview. Infer the user language: split topic from location (e.g. "best hvac company in Denver CO" => query "best hvac company", location "Denver, CO", gl "us", hl "en"). For US local SERPs, leave proxyMode as location so the service uses fresh residential proxy IDs across retries
|
|
1834
|
+
description: withReportNote('Best default tool for Google search research. Extracts People Also Ask questions plus answers/source URLs, organic SERP, local pack when present, entity IDs (CID/GCID/KG MID), and AI Overview. Infer the user language: split topic from location (e.g. "best hvac company in Denver CO" => query "best hvac company", location "Denver, CO", gl "us", hl "en"). For US local SERPs, leave proxyMode as location so the service uses fresh residential proxy IDs across retries, briefly waits for browser-service automatic CAPTCHA/challenge solving when Google blocks a page, and rotates to a new proxy/session if the challenge does not clear or the market evidence is wrong. Use maxQuestions 30 normally, 100-200 for "full", "deep", "all", or comprehensive research. Deep harvests above 100 questions can run for several minutes with no interim progress \u2014 warn the user before starting one and keep maxQuestions at or below 100 unless they explicitly want a deep harvest. Credits are charged by extracted question; unused request hold is refunded.'),
|
|
1780
1835
|
inputSchema: HarvestPaaInputSchema,
|
|
1781
1836
|
outputSchema: HarvestPaaOutputSchema,
|
|
1782
1837
|
annotations: liveWebToolAnnotations("Google PAA + SERP Harvest")
|
|
1783
1838
|
}, async (input) => formatHarvestPaa(await executor.harvestPaa(input), input));
|
|
1784
1839
|
server.registerTool("search_serp", {
|
|
1785
1840
|
title: "Google SERP Lookup",
|
|
1786
|
-
description: withReportNote("Fast Google SERP lookup without PAA expansion. Use when the user asks for rankings, organic results, local pack, quick SERP, or positions. Split topic from location and infer gl/hl from the user request. For US city/state rankings, keep proxyMode as location and pass proxyZip when a city-center ZIP is known; location mode uses fresh residential proxy IDs
|
|
1841
|
+
description: withReportNote("Fast Google SERP lookup without PAA expansion. Use when the user asks for rankings, organic results, local pack, quick SERP, or positions. Split topic from location and infer gl/hl from the user request. For US city/state rankings, keep proxyMode as location and pass proxyZip when a city-center ZIP is known; location mode uses fresh residential proxy IDs, briefly waits for browser-service automatic CAPTCHA/challenge solving when Google blocks a page, and rotates to a new proxy/session if the challenge does not clear, the proxy tunnel fails, or location evidence is wrong."),
|
|
1787
1842
|
inputSchema: SearchSerpInputSchema,
|
|
1788
1843
|
outputSchema: SearchSerpOutputSchema,
|
|
1789
1844
|
annotations: liveWebToolAnnotations("Google SERP Lookup")
|
|
@@ -1851,14 +1906,14 @@ function registerPaaExtractorMcpTools(server, executor, options = {}) {
|
|
|
1851
1906
|
}, async (input) => formatMapsPlaceIntel(await executor.mapsPlaceIntel(input), input));
|
|
1852
1907
|
server.registerTool("maps_search", {
|
|
1853
1908
|
title: "Google Maps Business Search",
|
|
1854
|
-
description: withReportNote('Search Google Maps for multiple businesses/profiles by category, niche, keyword, or local market. Use this when the user asks for several Google Business Profiles, GMBs, GBPs, leads, prospects, competitors, or "more than the 3-pack." For US city/state Maps searches, keep proxyMode as location so the browser service
|
|
1909
|
+
description: withReportNote('Search Google Maps for multiple businesses/profiles by category, niche, keyword, or local market. Use this when the user asks for several Google Business Profiles, GMBs, GBPs, leads, prospects, competitors, or "more than the 3-pack." For US city/state Maps searches, keep proxyMode as location so the browser service creates a fresh residential proxy ID and browser session for the market; retryable failures rotate to a new proxy and new browser session for up to 5 attempts. Pass proxyZip only when a specific ZIP or city-center ZIP is known. Returns up to 50 candidates with names, place URLs, CIDs when available, ratings, review counts, profile metadata, and sanitized attempt telemetry. Default maxResults is 10; maximum is 50. Use maps_place_intel afterward only when a selected business needs full details and reviews.'),
|
|
1855
1910
|
inputSchema: MapsSearchInputSchema,
|
|
1856
1911
|
outputSchema: MapsSearchOutputSchema,
|
|
1857
1912
|
annotations: liveWebToolAnnotations("Google Maps Business Search")
|
|
1858
1913
|
}, async (input) => formatMapsSearch(await executor.mapsSearch(input), input));
|
|
1859
1914
|
server.registerTool("directory_workflow", {
|
|
1860
1915
|
title: "Directory Workflow: Markets + Maps",
|
|
1861
|
-
description: withReportNote('Build directory/prospecting datasets by selecting US city markets from the free Census Population Estimates city/place dataset, optionally joining configured US ZIPS/Lead Magician ZIP groups, then running Google Maps business searches for each city in parallel. Use this when the user wants "all cities over 100k population in a state", "build a directory CSV", "find markets then get Maps data", or similar location-database + Maps workflows. Set minPopulation, state, query, maxResultsPerCity, and concurrency. Use concurrency up to 5 for parallel city sessions. Keep proxyMode as location so each city
|
|
1916
|
+
description: withReportNote('Build directory/prospecting datasets by selecting US city markets from the free Census Population Estimates city/place dataset, optionally joining configured US ZIPS/Lead Magician ZIP groups, then running Google Maps business searches for each city in parallel. Use this when the user wants "all cities over 100k population in a state", "build a directory CSV", "find markets then get Maps data", or similar location-database + Maps workflows. Set minPopulation, state, query, maxResultsPerCity, and concurrency. Use concurrency up to 5 for parallel city sessions. Keep proxyMode as location so each city search creates fresh residential proxy IDs and browser sessions; retryable city failures rotate to a new proxy and new browser session for up to 5 attempts. Saved CSV rows include source_location, result_position, business_name, review_stars, review_count, category, address, phone, hours_status, website_url, directions_url, place_url, cid, cid_decimal, city population, and ZIP groups. Structured city results include sanitized attempt telemetry. Use maps_place_intel only when a selected profile needs deeper review topics, profile review count confirmation, or review cards. For local Lead Magician ZIP enrichment, set MCP_SCRAPER_USZIPS_CSV_PATH on the API server or pass usZipsCsvPath only in local/test mode.'),
|
|
1862
1917
|
inputSchema: DirectoryWorkflowInputSchema,
|
|
1863
1918
|
outputSchema: DirectoryWorkflowOutputSchema,
|
|
1864
1919
|
annotations: liveWebToolAnnotations("Directory Workflow: Markets + Maps")
|
|
@@ -2005,4 +2060,4 @@ export {
|
|
|
2005
2060
|
registerPaaExtractorMcpTools,
|
|
2006
2061
|
HttpMcpToolExecutor
|
|
2007
2062
|
};
|
|
2008
|
-
//# sourceMappingURL=chunk-
|
|
2063
|
+
//# sourceMappingURL=chunk-XAY5U67D.js.map
|