mcp-scraper 0.3.11 → 0.3.12
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 +2 -2
- package/dist/bin/api-server.cjs +86 -22
- package/dist/bin/api-server.cjs.map +1 -1
- package/dist/bin/api-server.js +2 -2
- package/dist/bin/browser-agent-stdio-server.cjs +198 -27
- package/dist/bin/browser-agent-stdio-server.cjs.map +1 -1
- package/dist/bin/browser-agent-stdio-server.js +3 -2
- package/dist/bin/browser-agent-stdio-server.js.map +1 -1
- package/dist/bin/mcp-scraper-cli.cjs +1 -1
- package/dist/bin/mcp-scraper-cli.cjs.map +1 -1
- package/dist/bin/mcp-scraper-cli.js +1 -1
- package/dist/bin/mcp-scraper-combined-stdio-server.cjs +254 -56
- package/dist/bin/mcp-scraper-combined-stdio-server.cjs.map +1 -1
- package/dist/bin/mcp-scraper-combined-stdio-server.js +4 -3
- package/dist/bin/mcp-scraper-combined-stdio-server.js.map +1 -1
- package/dist/bin/mcp-scraper-install.cjs +1 -1
- package/dist/bin/mcp-scraper-install.cjs.map +1 -1
- package/dist/bin/mcp-scraper-install.js +1 -1
- package/dist/bin/mcp-stdio-server.cjs +38 -11
- 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 +21 -1
- package/dist/bin/paa-harvest.cjs.map +1 -1
- package/dist/bin/paa-harvest.js +1 -1
- package/dist/chunk-3YGKXXUG.js +133 -0
- package/dist/chunk-3YGKXXUG.js.map +1 -0
- package/dist/{chunk-UWSG3C5J.js → chunk-4OPKIDON.js} +22 -2
- package/dist/chunk-4OPKIDON.js.map +1 -0
- package/dist/{chunk-VMH7SRWY.js → chunk-7R7VBQRV.js} +39 -12
- package/dist/chunk-7R7VBQRV.js.map +1 -0
- package/dist/{chunk-L27GJQV7.js → chunk-BW3DGFNQ.js} +28 -5
- package/dist/chunk-BW3DGFNQ.js.map +1 -0
- package/dist/chunk-FB5ZJGFN.js +7 -0
- package/dist/chunk-FB5ZJGFN.js.map +1 -0
- package/dist/index.cjs +21 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/{server-3SA5Q4OF.js → server-CUPDJLWM.js} +42 -151
- package/dist/server-CUPDJLWM.js.map +1 -0
- package/dist/{worker-56IXWOQU.js → worker-FG7ZWEGA.js} +2 -2
- package/docs/mcp-tool-craft-lint.generated.md +1 -1
- package/docs/mcp-tool-manifest.generated.json +1 -1
- package/package.json +1 -1
- package/dist/chunk-L27GJQV7.js.map +0 -1
- package/dist/chunk-RRE7WVHQ.js +0 -7
- package/dist/chunk-RRE7WVHQ.js.map +0 -1
- package/dist/chunk-UWSG3C5J.js.map +0 -1
- package/dist/chunk-VMH7SRWY.js.map +0 -1
- package/dist/server-3SA5Q4OF.js.map +0 -1
- /package/dist/{worker-56IXWOQU.js.map → worker-FG7ZWEGA.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../bin/mcp-stdio-server.ts","../../src/harvest-timeout.ts","../../src/mcp/http-mcp-tool-executor.ts","../../src/mcp/paa-mcp-server.ts","../../src/version.ts","../../src/mcp/mcp-response-formatter.ts","../../src/errors.ts","../../src/mcp/workflow-catalog.ts","../../src/mcp/mcp-tool-schemas.ts","../../src/schemas.ts","../../src/mcp/rank-tracker-blueprint.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { readFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { HttpMcpToolExecutor } from '../src/mcp/http-mcp-tool-executor.js'\nimport { buildPaaExtractorMcpServer } from '../src/mcp/paa-mcp-server.js'\n\nfunction readApiKeyFile(): string | undefined {\n const explicitPath = process.env.MCP_SCRAPER_KEY_PATH?.trim()\n const paths = [explicitPath, join(homedir(), '.mcp-scraper-key')].filter(Boolean) as string[]\n for (const path of paths) {\n try {\n const value = readFileSync(path, 'utf8').trim()\n if (value) return value\n } catch {}\n }\n return undefined\n}\n\nconst apiKey = (\n process.env.MCP_SCRAPER_API_KEY ??\n process.env.MCP_SCRAPER_KEY ??\n process.env.MCP_API_KEY ??\n readApiKeyFile()\n)?.trim()\nif (!apiKey) {\n process.stderr.write('MCP_SCRAPER_API_KEY env var or ~/.mcp-scraper-key is required\\n')\n process.exit(1)\n}\n\nconst baseUrl = process.env.MCP_SCRAPER_BASE_URL?.trim() || process.env.MCP_BASE_URL?.trim() || 'https://mcpscraper.dev'\nconst executor = new HttpMcpToolExecutor(baseUrl, apiKey)\nconst server = buildPaaExtractorMcpServer(executor)\nconst transport = new StdioServerTransport()\n\nasync function main() {\n await server.connect(transport)\n}\n\nmain().catch((err) => {\n process.stderr.write(`${err instanceof Error ? err.message : String(err)}\\n`)\n process.exit(1)\n})\n","export const VERCEL_FUNCTION_MAX_MS = 300_000\n\nexport const CLIENT_OVER_SERVER_MARGIN_MS = 15_000\n\nexport interface HarvestTimeoutBudget {\n serverMs: number\n clientMs: number\n}\n\nexport function harvestTimeoutBudget(maxQuestions: number, serpOnly = false): HarvestTimeoutBudget {\n const requested = Number.isFinite(maxQuestions) && maxQuestions > 0 ? Math.trunc(maxQuestions) : 30\n let serverMs: number\n if (serpOnly || requested <= 50) serverMs = 110_000\n else if (requested <= 100) serverMs = 180_000\n else if (requested <= 150) serverMs = 240_000\n else serverMs = 280_000\n const clientMs = Math.min(serverMs + CLIENT_OVER_SERVER_MARGIN_MS, VERCEL_FUNCTION_MAX_MS - 5_000)\n return { serverMs, clientMs }\n}\n","import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'\nimport type { IMcpToolExecutor, ISerpIntelligenceToolExecutor } from './IMcpToolExecutor.js'\nimport { harvestTimeoutBudget } from '../harvest-timeout.js'\nimport type {\n HarvestPaaInput,\n SearchSerpInput,\n ExtractUrlInput,\n MapSiteUrlsInput,\n ExtractSiteInput,\n YoutubeHarvestInput,\n YoutubeTranscribeInput,\n FacebookPageIntelInput,\n FacebookAdSearchInput,\n FacebookAdTranscribeInput,\n FacebookVideoTranscribeInput,\n InstagramProfileContentInput,\n InstagramMediaDownloadInput,\n MapsPlaceIntelInput,\n MapsSearchInput,\n DirectoryWorkflowInput,\n CreditsInfoInput,\n WorkflowListInput,\n WorkflowRunInput,\n WorkflowStepInput,\n WorkflowStatusInput,\n WorkflowArtifactReadInput,\n CaptureSerpSnapshotInput,\n CaptureSerpPageSnapshotsInput,\n} from './mcp-tool-schemas.js'\n\nfunction youtubeVideoIdFromUrl(url: string | undefined): string | null {\n if (!url) return null\n try {\n const parsed = new URL(url)\n const host = parsed.hostname.replace(/^www\\./, '').replace(/^m\\./, '')\n if (host === 'youtu.be') {\n const id = parsed.pathname.split('/').filter(Boolean)[0]\n return id || null\n }\n if (host === 'youtube.com' || host === 'music.youtube.com') {\n const watchId = parsed.searchParams.get('v')\n if (watchId) return watchId\n const parts = parsed.pathname.split('/').filter(Boolean)\n const markerIndex = parts.findIndex(part => ['shorts', 'embed', 'live'].includes(part))\n if (markerIndex >= 0 && parts[markerIndex + 1]) return parts[markerIndex + 1]\n }\n } catch {\n return null\n }\n return null\n}\n\nexport class HttpMcpToolExecutor implements IMcpToolExecutor, ISerpIntelligenceToolExecutor {\n private readonly baseUrl: string\n private readonly apiKey: string\n private readonly timeoutMs: number\n private readonly httpTimeoutOverrideMs: number | null\n private readonly serpIntelligenceTimeoutMs: number\n\n constructor(baseUrl: string, apiKey: string) {\n this.baseUrl = baseUrl.replace(/\\/$/, '')\n this.apiKey = apiKey\n const rawOverride = process.env.MCP_SCRAPER_HTTP_TIMEOUT_MS\n const parsedOverride = rawOverride === undefined ? NaN : Number(rawOverride)\n this.httpTimeoutOverrideMs = Number.isFinite(parsedOverride) && parsedOverride > 0 ? parsedOverride : null\n this.timeoutMs = this.httpTimeoutOverrideMs ?? 110_000\n const configuredSerpIntelligenceTimeoutMs = Number(process.env.MCP_SCRAPER_SERP_INTELLIGENCE_HTTP_TIMEOUT_MS ?? this.timeoutMs)\n this.serpIntelligenceTimeoutMs = Number.isFinite(configuredSerpIntelligenceTimeoutMs) && configuredSerpIntelligenceTimeoutMs > 0\n ? configuredSerpIntelligenceTimeoutMs\n : this.timeoutMs\n }\n\n private async call(path: string, body: Record<string, unknown>, timeoutMs = this.timeoutMs): Promise<CallToolResult> {\n try {\n const res = await fetch(`${this.baseUrl}${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()\n if (!res.ok) {\n return { content: [{ type: 'text', text: JSON.stringify(data) }], isError: true }\n }\n return { content: [{ type: 'text', text: JSON.stringify(data) }] }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n if (err instanceof DOMException && err.name === 'TimeoutError') {\n return {\n content: [{\n type: 'text',\n text: JSON.stringify({\n error: 'mcp_request_timeout',\n error_type: 'timeout',\n retryable: true,\n path,\n timeoutMs,\n message: `MCP Scraper request exceeded ${Math.round(timeoutMs / 1000)}s and was cancelled. Retry with fewer results or use the async API for deep harvests.`,\n }),\n }],\n isError: true,\n }\n }\n return { content: [{ type: 'text', text: msg }], isError: true }\n }\n }\n\n private async getJson(path: string, timeoutMs = this.timeoutMs): Promise<CallToolResult> {\n try {\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: 'GET',\n headers: {\n 'x-api-key': this.apiKey,\n },\n signal: AbortSignal.timeout(timeoutMs),\n })\n const data = await res.json()\n if (!res.ok) {\n return { content: [{ type: 'text', text: JSON.stringify(data) }], isError: true }\n }\n return { content: [{ type: 'text', text: JSON.stringify(data) }] }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n return { content: [{ type: 'text', text: msg }], isError: true }\n }\n }\n\n private async getTextArtifact(path: string, maxBytes: number, timeoutMs = this.timeoutMs): Promise<CallToolResult> {\n try {\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: 'GET',\n headers: {\n 'x-api-key': this.apiKey,\n },\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!res.ok) {\n const data = await res.json().catch(async () => ({ error: await res.text().catch(() => `HTTP ${res.status}`) }))\n return { content: [{ type: 'text', text: JSON.stringify(data) }], isError: true }\n }\n const bytes = Buffer.from(await res.arrayBuffer())\n const sliced = bytes.subarray(0, Math.min(maxBytes, bytes.length))\n return {\n content: [{\n type: 'text',\n text: JSON.stringify({\n contentType: res.headers.get('content-type') ?? 'application/octet-stream',\n bytes: bytes.length,\n truncated: sliced.length < bytes.length,\n maxBytes,\n text: sliced.toString('utf8'),\n }),\n }],\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n return { content: [{ type: 'text', text: msg }], isError: true }\n }\n }\n\n harvestPaa(input: HarvestPaaInput): Promise<CallToolResult> {\n const timeoutMs = this.httpTimeoutOverrideMs ?? harvestTimeoutBudget(input.maxQuestions ?? 30).clientMs\n return this.call('/harvest/sync', input as Record<string, unknown>, timeoutMs)\n }\n\n searchSerp(input: SearchSerpInput): Promise<CallToolResult> {\n const timeoutMs = this.httpTimeoutOverrideMs ?? harvestTimeoutBudget(0, true).clientMs\n return this.call('/harvest/sync', { ...input, serpOnly: true } as Record<string, unknown>, timeoutMs)\n }\n\n extractUrl(input: ExtractUrlInput): Promise<CallToolResult> {\n return this.call('/extract-url', input as Record<string, unknown>)\n }\n\n mapSiteUrls(input: MapSiteUrlsInput): Promise<CallToolResult> {\n return this.call('/map-urls', input as Record<string, unknown>)\n }\n\n extractSite(input: ExtractSiteInput): Promise<CallToolResult> {\n return this.call('/extract-site', input as Record<string, unknown>)\n }\n\n youtubeHarvest(input: YoutubeHarvestInput): Promise<CallToolResult> {\n return this.call('/youtube/harvest', input as Record<string, unknown>)\n }\n\n youtubeTranscribe(input: YoutubeTranscribeInput): Promise<CallToolResult> {\n const videoId = input.videoId?.trim() || youtubeVideoIdFromUrl(input.url)\n if (!videoId) {\n return Promise.resolve({\n content: [{\n type: 'text',\n text: JSON.stringify({\n error_code: 'youtube_video_id_required',\n error: 'Pass videoId from youtube_harvest or a YouTube url that contains a video id.',\n retryable: false,\n }),\n }],\n isError: true,\n })\n }\n return this.call('/youtube/transcribe', { videoId })\n }\n\n facebookPageIntel(input: FacebookPageIntelInput): Promise<CallToolResult> {\n return this.call('/facebook/page-intel', input as Record<string, unknown>)\n }\n\n facebookAdSearch(input: FacebookAdSearchInput): Promise<CallToolResult> {\n return this.call('/facebook/search', input as Record<string, unknown>)\n }\n\n facebookAdTranscribe(input: FacebookAdTranscribeInput): Promise<CallToolResult> {\n return this.call('/facebook/transcribe', input as Record<string, unknown>)\n }\n\n facebookVideoTranscribe(input: FacebookVideoTranscribeInput): Promise<CallToolResult> {\n return this.call('/facebook/video-transcribe', input as Record<string, unknown>, this.httpTimeoutOverrideMs ?? 240_000)\n }\n\n instagramProfileContent(input: InstagramProfileContentInput): Promise<CallToolResult> {\n return this.call('/instagram/profile-content', input as Record<string, unknown>, this.httpTimeoutOverrideMs ?? 240_000)\n }\n\n instagramMediaDownload(input: InstagramMediaDownloadInput): Promise<CallToolResult> {\n return this.call('/instagram/media-download', input as Record<string, unknown>, this.httpTimeoutOverrideMs ?? 300_000)\n }\n\n mapsPlaceIntel(input: MapsPlaceIntelInput): Promise<CallToolResult> {\n return this.call('/maps/place', input as Record<string, unknown>)\n }\n\n mapsSearch(input: MapsSearchInput): Promise<CallToolResult> {\n return this.call('/maps/search', input as Record<string, unknown>)\n }\n\n directoryWorkflow(input: DirectoryWorkflowInput): Promise<CallToolResult> {\n const cityCount = typeof input.maxCities === 'number' ? input.maxCities : 25\n const concurrency = typeof input.concurrency === 'number' && input.concurrency > 0 ? input.concurrency : 5\n const timeoutMs = this.httpTimeoutOverrideMs ?? Math.min(900_000, Math.max(180_000, Math.ceil(cityCount / concurrency) * 120_000))\n return this.call('/directory/run', input as Record<string, unknown>, timeoutMs)\n }\n\n workflowList(_input: WorkflowListInput): Promise<CallToolResult> {\n return this.getJson('/workflows/definitions')\n }\n\n workflowRun(input: WorkflowRunInput): Promise<CallToolResult> {\n const timeoutMs = this.httpTimeoutOverrideMs ?? Number(process.env.MCP_SCRAPER_WORKFLOW_TIMEOUT_MS ?? 900_000)\n return this.call('/workflows/run', {\n workflowId: input.workflowId,\n input: input.input ?? {},\n webhookUrl: input.webhookUrl,\n }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 900_000)\n }\n\n workflowStep(input: WorkflowStepInput): Promise<CallToolResult> {\n const timeoutMs = this.httpTimeoutOverrideMs ?? Number(process.env.MCP_SCRAPER_WORKFLOW_TIMEOUT_MS ?? 900_000)\n return this.call(`/workflows/runs/${encodeURIComponent(input.runId)}/step`, {}, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 900_000)\n }\n\n workflowStatus(input: WorkflowStatusInput): Promise<CallToolResult> {\n return this.getJson(`/workflows/runs/${encodeURIComponent(input.runId)}`)\n }\n\n workflowArtifactRead(input: WorkflowArtifactReadInput): Promise<CallToolResult> {\n return this.getTextArtifact(\n `/workflows/runs/${encodeURIComponent(input.runId)}/artifacts/${encodeURIComponent(input.artifactId)}`,\n input.maxBytes ?? 200_000,\n )\n }\n\n creditsInfo(input: CreditsInfoInput): Promise<CallToolResult> {\n return this.call('/billing/credits', input as Record<string, unknown>)\n }\n\n captureSerpSnapshot(input: CaptureSerpSnapshotInput): Promise<CallToolResult> {\n return this.call('/serp-intelligence/capture', input as Record<string, unknown>, this.serpIntelligenceTimeoutMs)\n }\n\n captureSerpPageSnapshots(input: CaptureSerpPageSnapshotsInput): Promise<CallToolResult> {\n return this.call('/serp-intelligence/page-snapshots', input as Record<string, unknown>, this.serpIntelligenceTimeoutMs)\n }\n\n}\n","import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { readdirSync, readFileSync, statSync } from 'node:fs'\nimport { basename, join } from 'node:path'\nimport type { IMcpToolExecutor } from './IMcpToolExecutor.js'\nimport { PACKAGE_VERSION } from '../version.js'\nimport { outputBaseDir } from './mcp-response-formatter.js'\nimport {\n HarvestPaaInputSchema,\n SearchSerpInputSchema,\n ExtractUrlInputSchema,\n HarvestPaaOutputSchema,\n SearchSerpOutputSchema,\n ExtractUrlOutputSchema,\n ExtractSiteOutputSchema,\n MapsPlaceIntelOutputSchema,\n CreditsInfoOutputSchema,\n MapSiteUrlsInputSchema,\n MapSiteUrlsOutputSchema,\n ExtractSiteInputSchema,\n YoutubeHarvestInputSchema,\n YoutubeHarvestOutputSchema,\n YoutubeTranscribeInputSchema,\n YoutubeTranscribeOutputSchema,\n FacebookPageIntelInputSchema,\n FacebookPageIntelOutputSchema,\n FacebookAdSearchInputSchema,\n FacebookAdSearchOutputSchema,\n FacebookAdTranscribeInputSchema,\n FacebookAdTranscribeOutputSchema,\n FacebookVideoTranscribeInputSchema,\n FacebookVideoTranscribeOutputSchema,\n InstagramProfileContentInputSchema,\n InstagramProfileContentOutputSchema,\n InstagramMediaDownloadInputSchema,\n InstagramMediaDownloadOutputSchema,\n MapsPlaceIntelInputSchema,\n MapsSearchInputSchema,\n MapsSearchOutputSchema,\n DirectoryWorkflowInputSchema,\n DirectoryWorkflowOutputSchema,\n WorkflowListInputSchema,\n WorkflowListOutputSchema,\n WorkflowSuggestInputSchema,\n WorkflowSuggestOutputSchema,\n WorkflowRunInputSchema,\n WorkflowRunOutputSchema,\n WorkflowStepInputSchema,\n WorkflowStepOutputSchema,\n WorkflowStatusInputSchema,\n WorkflowStatusOutputSchema,\n WorkflowArtifactReadInputSchema,\n WorkflowArtifactReadOutputSchema,\n RankTrackerBlueprintInputSchema,\n RankTrackerBlueprintOutputSchema,\n CreditsInfoInputSchema,\n} from './mcp-tool-schemas.js'\nimport { buildRankTrackerBlueprint } from './rank-tracker-blueprint.js'\nimport {\n formatHarvestPaa,\n formatSearchSerp,\n formatExtractUrl,\n formatMapSiteUrls,\n formatExtractSite,\n formatYoutubeHarvest,\n formatYoutubeTranscribe,\n formatFacebookPageIntel,\n formatFacebookAdSearch,\n formatFacebookAdTranscribe,\n formatFacebookVideoTranscribe,\n formatInstagramProfileContent,\n formatInstagramMediaDownload,\n formatMapsPlaceIntel,\n formatMapsSearch,\n formatDirectoryWorkflow,\n formatWorkflowList,\n formatWorkflowSuggest,\n formatWorkflowRun,\n formatWorkflowStep,\n formatWorkflowStatus,\n formatWorkflowArtifactRead,\n formatCreditsInfo,\n} from './mcp-response-formatter.js'\n\nexport interface BuildMcpServerOptions {\n savesReportsLocally?: boolean\n}\n\nexport function liveWebToolAnnotations(title: string) {\n return {\n title,\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n }\n}\n\nfunction localPlanningToolAnnotations(title: string) {\n return {\n title,\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n }\n}\n\nfunction listSavedReports(): Array<{ filename: string; mtimeMs: number }> {\n try {\n const dir = outputBaseDir()\n return readdirSync(dir)\n .filter(f => f.endsWith('.md'))\n .map(f => ({ filename: f, mtimeMs: statSync(join(dir, f)).mtimeMs }))\n .sort((a, b) => b.mtimeMs - a.mtimeMs)\n .slice(0, 100)\n } catch {\n return []\n }\n}\n\nfunction registerSavedReportResources(server: McpServer): void {\n server.registerResource(\n 'saved-report',\n new ResourceTemplate('report://{filename}', {\n list: () => ({\n resources: listSavedReports().map(r => ({\n uri: `report://${encodeURIComponent(r.filename)}`,\n name: r.filename,\n mimeType: 'text/markdown',\n })),\n }),\n }),\n {\n title: 'Saved MCP Scraper Reports',\n description: 'Markdown research reports saved by previous MCP Scraper tool calls. Read a report to reuse prior research without re-scraping or spending credits.',\n mimeType: 'text/markdown',\n },\n async (uri, variables) => {\n const requested = Array.isArray(variables.filename) ? variables.filename[0] : variables.filename\n const filename = basename(decodeURIComponent(String(requested ?? '')))\n if (!filename.endsWith('.md')) throw new Error('Only saved .md reports can be read')\n const text = readFileSync(join(outputBaseDir(), filename), 'utf8')\n return { contents: [{ uri: uri.href, mimeType: 'text/markdown', text }] }\n },\n )\n}\n\nexport function buildPaaExtractorMcpServer(\n executor: IMcpToolExecutor,\n options: BuildMcpServerOptions = {},\n): McpServer {\n const server = new McpServer({ name: 'mcp-scraper', version: PACKAGE_VERSION })\n registerPaaExtractorMcpTools(server, executor, options)\n return server\n}\n\nexport function registerPaaExtractorMcpTools(\n server: McpServer,\n executor: IMcpToolExecutor,\n options: BuildMcpServerOptions = {},\n): void {\n const savesReports = options.savesReportsLocally !== false\n const reportNote = savesReports\n ? ' Saves a full Markdown report to disk.'\n : ' Reports are returned inline; no files are saved on this hosted endpoint.'\n const withReportNote = (description: string) => `${description}${reportNote}`\n\n if (savesReports) registerSavedReportResources(server)\n\n server.registerTool('harvest_paa', {\n title: 'Google PAA + SERP Harvest',\n 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\"). Omit proxyMode for normal use; the service defaults to the configured browser-service proxy without city/ZIP targeting for the highest general success rate. Use proxyMode location only when the user explicitly needs city/ZIP-targeted residential proxy evidence. 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 — 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.'),\n inputSchema: HarvestPaaInputSchema,\n outputSchema: HarvestPaaOutputSchema,\n annotations: liveWebToolAnnotations('Google PAA + SERP Harvest'),\n }, async (input) => formatHarvestPaa(await executor.harvestPaa(input), input))\n\n server.registerTool('search_serp', {\n title: 'Google SERP Lookup',\n 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. Omit proxyMode for normal use; the service defaults to the configured browser-service proxy without city/ZIP targeting. Use proxyMode location and proxyZip only when the user explicitly needs city/ZIP-targeted residential proxy evidence.'),\n inputSchema: SearchSerpInputSchema,\n outputSchema: SearchSerpOutputSchema,\n annotations: liveWebToolAnnotations('Google SERP Lookup'),\n }, async (input) => formatSearchSerp(await executor.searchSerp(input), input))\n\n server.registerTool('extract_url', {\n title: 'Single URL Extract',\n description: withReportNote('Extract structured data from one public URL when the user provides one page, asks to inspect/scrape a page, or needs page content, schema, headings, metadata, screenshots, branding, or media assets. Returns structured page fields plus artifact handles for saved reports/screenshots/media when requested. Use map_site_urls before extracting a site inventory; use extract_site for multi-page crawling.'),\n inputSchema: ExtractUrlInputSchema,\n outputSchema: ExtractUrlOutputSchema,\n annotations: liveWebToolAnnotations('Single URL Extract'),\n }, async (input) => formatExtractUrl(await executor.extractUrl(input), input))\n\n server.registerTool('map_site_urls', {\n title: 'Site URL Map',\n description: withReportNote('Map/crawl a public website when the user asks for a sitemap, URL inventory, broken-link scan, redirect scan, or crawl planning. Returns internal URLs with HTTP status and truncation metadata. Use this before extract_site when choosing pages for an audit; use extract_url for one known page.'),\n inputSchema: MapSiteUrlsInputSchema,\n outputSchema: MapSiteUrlsOutputSchema,\n annotations: liveWebToolAnnotations('Site URL Map'),\n }, async (input) => formatMapSiteUrls(await executor.mapSiteUrls(input), input))\n\n server.registerTool('extract_site', {\n title: 'Multi-Page Site Extract',\n description: withReportNote('Run multi-page extraction across a public website when the user asks for a website audit, competitor audit, full-site content crawl, schema inventory, or page metadata review. Returns per-page titles, H1s, metadata, headings, schema/entity data, canonical URLs, and content. Use map_site_urls first when URL selection matters; use extract_url for one page.'),\n inputSchema: ExtractSiteInputSchema,\n outputSchema: ExtractSiteOutputSchema,\n annotations: liveWebToolAnnotations('Multi-Page Site Extract'),\n }, async (input) => formatExtractSite(await executor.extractSite(input), input))\n\n server.registerTool('youtube_harvest', {\n title: 'YouTube Video Harvest',\n description: withReportNote('Harvest YouTube video metadata when the user wants to find videos by topic, inspect a channel library, compare video angles, or get videoIds for later transcription. Use mode \"search\" for keyword/topic requests and mode \"channel\" for @handles, channel IDs, or channel URLs. Returns titles, views, durations, URLs, and videoIds for follow-up transcription. Use youtube_transcribe after selecting one video.'),\n inputSchema: YoutubeHarvestInputSchema,\n outputSchema: YoutubeHarvestOutputSchema,\n annotations: liveWebToolAnnotations('YouTube Video Harvest'),\n }, async (input) => formatYoutubeHarvest(await executor.youtubeHarvest(input), input))\n\n server.registerTool('youtube_transcribe', {\n title: 'YouTube Transcription',\n description: withReportNote('Fetch and transcribe captions from a YouTube video. Use this when the user asks what was said in a YouTube video, wants claims/offers/lessons extracted from a video, or provides a YouTube URL for transcript work. Returns full transcript, timestamped chunks, word count, and resolvedInputs. Pass videoId from youtube_harvest results, or pass url when the user pasted a YouTube URL. Use youtube_harvest first when you need to discover videos by topic/channel.'),\n inputSchema: YoutubeTranscribeInputSchema,\n outputSchema: YoutubeTranscribeOutputSchema,\n annotations: liveWebToolAnnotations('YouTube Transcription'),\n }, async (input) => formatYoutubeTranscribe(await executor.youtubeTranscribe(input), input))\n\n server.registerTool('facebook_page_intel', {\n title: 'Facebook Advertiser Ad Intel',\n description: withReportNote('Harvest ads from a Facebook advertiser when the user wants current ad copy, creative angles, CTAs, video URLs, or competitive ad intelligence for one brand/page. Returns ad copy, headlines, CTAs, creative type, status, landing URLs, and direct ad video URLs ready for facebook_ad_transcribe. Accepts pageId, libraryId, or a brand/advertiser name as query. Use facebook_ad_search first when the advertiser handle is unknown. For normal public Facebook reels/posts/watch/share URLs, use facebook_video_transcribe instead.'),\n inputSchema: FacebookPageIntelInputSchema,\n outputSchema: FacebookPageIntelOutputSchema,\n annotations: liveWebToolAnnotations('Facebook Advertiser Ad Intel'),\n }, async (input) => formatFacebookPageIntel(await executor.facebookPageIntel(input), input))\n\n server.registerTool('facebook_ad_search', {\n title: 'Facebook Ad Library Search',\n description: withReportNote('Search Facebook Ad Library when the user wants to find advertisers by brand, competitor, niche, or keyword. Returns advertisers with ad counts and library IDs. Use this to discover competitor/page handles, then pass libraryId or pageId to facebook_page_intel for ad details.'),\n inputSchema: FacebookAdSearchInputSchema,\n outputSchema: FacebookAdSearchOutputSchema,\n annotations: liveWebToolAnnotations('Facebook Ad Library Search'),\n }, async (input) => formatFacebookAdSearch(await executor.facebookAdSearch(input), input))\n\n server.registerTool('facebook_ad_transcribe', {\n title: 'Facebook Ad Transcription',\n description: 'Transcribe audio from a Facebook ad video CDN URL. Use this when facebook_page_intel returned a direct videoUrl and the user asks what the ad says, what claims it makes, or wants ad-message extraction. Returns full transcript, timestamped chunks, word count, and resolvedInputs. Use only with the direct videoUrl value from facebook_page_intel results; do not pass public Facebook post/reel/share URLs. Use facebook_video_transcribe for organic Facebook URLs, and facebook_page_intel first when you only have a brand/page/ad library handle.',\n inputSchema: FacebookAdTranscribeInputSchema,\n outputSchema: FacebookAdTranscribeOutputSchema,\n annotations: liveWebToolAnnotations('Facebook Ad Transcription'),\n }, async (input) => formatFacebookAdTranscribe(await executor.facebookAdTranscribe(input), input))\n\n server.registerTool('facebook_video_transcribe', {\n title: 'Facebook Organic Video Transcription',\n description: withReportNote('Transcribe audio from an organic Facebook reel, video, watch, post, or share URL, including fb.watch links. Use this when the user pastes a normal Facebook video page URL and wants the transcript or downloadable MP4. Renders the Facebook page in a browser, selects the best matching public Facebook CDN MP4 URL from page state, then returns sourceUrl, resolved pageUrl, videoId, ownerName, selectedQuality, bitrate, videoDurationSec, extracted MP4 URL, full transcript, and timestamped chunks.'),\n inputSchema: FacebookVideoTranscribeInputSchema,\n outputSchema: FacebookVideoTranscribeOutputSchema,\n annotations: liveWebToolAnnotations('Facebook Organic Video Transcription'),\n }, async (input) => formatFacebookVideoTranscribe(await executor.facebookVideoTranscribe(input), input))\n\n server.registerTool('instagram_profile_content', {\n title: 'Instagram Profile Content Discovery',\n description: withReportNote('Discover Instagram profile grid content links for a handle or profile URL. Use this when the user wants a person or brand account content inventory before selecting posts/reels to download. Returns profile stats, collected post/reel/tv URLs, shortcodes, type counts, browser details, pagination attempts, stop reason, and limitations.'),\n inputSchema: InstagramProfileContentInputSchema,\n outputSchema: InstagramProfileContentOutputSchema,\n annotations: liveWebToolAnnotations('Instagram Profile Content Discovery'),\n }, async (input) => formatInstagramProfileContent(await executor.instagramProfileContent(input), input))\n\n server.registerTool('instagram_media_download', {\n title: 'Instagram Post/Reel Media Download',\n description: withReportNote('Extract and download media from one Instagram post, reel, or tv URL. Use after instagram_profile_content or when the user gives a specific Instagram URL and wants the image, caption/text, reel audio/video tracks, optional muxed MP4, or optional transcript. Reels commonly expose separate video-only and audio-only MP4 tracks; this tool selects the best video and audio tracks and attempts muxing when ffmpeg is available.'),\n inputSchema: InstagramMediaDownloadInputSchema,\n outputSchema: InstagramMediaDownloadOutputSchema,\n annotations: liveWebToolAnnotations('Instagram Post/Reel Media Download'),\n }, async (input) => formatInstagramMediaDownload(await executor.instagramMediaDownload(input), input))\n\n server.registerTool('maps_place_intel', {\n title: 'Google Maps Business Profile Details',\n description: withReportNote('Extract Google Maps business intelligence for one known/named business: rating, review count, category, address, phone, website, hours, booking URL, review histogram, review topics, about attributes, entity IDs, and optional review cards. Do not use this for category searches, local market prospect lists, or requests for multiple GMB/GBP profiles; use maps_search first for those. Split business name from location (e.g. \"Elite Roofing Denver CO\" => businessName \"Elite Roofing\", location \"Denver, CO\"). Pass includeReviews true when the user asks for reviews/customer pain.'),\n inputSchema: MapsPlaceIntelInputSchema,\n outputSchema: MapsPlaceIntelOutputSchema,\n annotations: liveWebToolAnnotations('Google Maps Business Profile Details'),\n }, async (input) => formatMapsPlaceIntel(await executor.mapsPlaceIntel(input), input))\n\n server.registerTool('maps_search', {\n title: 'Google Maps Business Search',\n 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.\" Maps is the default location-targeted surface: omit proxyMode for normal Maps use so the service creates residential proxy evidence for the requested market and rotates on retryable failures. Pass proxyZip only when a specific ZIP or city-center ZIP is known. Use proxyMode configured only when you explicitly do not want city/ZIP proxy targeting. 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.'),\n inputSchema: MapsSearchInputSchema,\n outputSchema: MapsSearchOutputSchema,\n annotations: liveWebToolAnnotations('Google Maps Business Search'),\n }, async (input) => formatMapsSearch(await executor.mapsSearch(input), input))\n\n server.registerTool('directory_workflow', {\n title: 'Directory Workflow: Markets + Maps',\n 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. Maps workflows default to location-targeted proxying so each city can use city/state or ZIP-group residential proxy evidence; use proxyMode configured only when you explicitly do not want city/ZIP proxy targeting. 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.'),\n inputSchema: DirectoryWorkflowInputSchema,\n outputSchema: DirectoryWorkflowOutputSchema,\n annotations: liveWebToolAnnotations('Directory Workflow: Markets + Maps'),\n }, async (input) => formatDirectoryWorkflow(await executor.directoryWorkflow(input), input))\n\n server.registerTool('workflow_list', {\n title: 'Workflow Catalog',\n description: 'List MCP Scraper higher-level workflows and AI-facing recipes. Use this when the user asks what MCP Scraper can do beyond single tools, or asks for market analysis, ICP research, forum/review acquisition, full brand design briefings, CRO audits, competitive positioning, content gap briefs, or AI search visibility audits. Returns runnable workflow ids plus recipe guidance for the best tool chain.',\n inputSchema: WorkflowListInputSchema,\n outputSchema: WorkflowListOutputSchema,\n annotations: localPlanningToolAnnotations('Workflow Catalog'),\n }, async (input) => formatWorkflowList(await executor.workflowList(input), input))\n\n server.registerTool('workflow_suggest', {\n title: 'Workflow Intent Router',\n description: 'Route a high-level business or research goal to the right MCP Scraper workflow/tool chain. Use before running work when the user says things like \"do market analysis\", \"research my ICP\", \"acquire forum and review language\", \"build a brand design brief\", \"run a CRO audit\", \"compare competitors\", \"make a content gap brief\", or \"audit AI search visibility\". This tool does not spend credits; it tells the AI exactly which workflow/tool chain to run next.',\n inputSchema: WorkflowSuggestInputSchema,\n outputSchema: WorkflowSuggestOutputSchema,\n annotations: localPlanningToolAnnotations('Workflow Intent Router'),\n }, async (input) => formatWorkflowSuggest(input))\n\n server.registerTool('workflow_run', {\n title: 'Run Workflow',\n description: withReportNote('Start a higher-level MCP Scraper workflow. Use after workflow_suggest or workflow_list. Runnable workflow ids: directory, agent-packet, local-competitive-audit, map-comparison, serp-comparison, paa-expansion-brief, ai-overview-language. This is the main MCP tool for market analysis, ICP evidence packets, local competitive audits, Maps/SERP comparisons, content gap briefs, and AI Overview language guidance. Stepwise workflows (e.g. agent-packet) run ONE leg per call and return runId, the step output, and nextStep — when nextStep is present, call workflow_step with the runId to run the next leg, and keep calling it until done is true. This keeps each call short instead of one long blocking run, so report each step result to the user as it arrives.'),\n inputSchema: WorkflowRunInputSchema,\n outputSchema: WorkflowRunOutputSchema,\n annotations: liveWebToolAnnotations('Run Workflow'),\n }, async (input) => formatWorkflowRun(await executor.workflowRun(input), input))\n\n server.registerTool('workflow_step', {\n title: 'Advance Workflow Step',\n description: withReportNote('Run the next leg of a stepwise MCP Scraper workflow started with workflow_run. Pass the runId. Each call executes exactly one logical step (typically one live harvest), persists that step\\'s artifacts, and returns the step output plus nextStep. Keep calling workflow_step with the same runId until done is true, reporting each step result to the user as it lands. Use this instead of waiting on one long workflow call — it avoids client timeouts on long multi-step jobs.'),\n inputSchema: WorkflowStepInputSchema,\n outputSchema: WorkflowStepOutputSchema,\n annotations: liveWebToolAnnotations('Advance Workflow Step'),\n }, async (input) => formatWorkflowStep(await executor.workflowStep(input), input))\n\n server.registerTool('workflow_status', {\n title: 'Workflow Status',\n description: 'Fetch a hosted workflow run by id and list its current status and artifacts. Use when a workflow may still be running, when the model needs to re-open a run, inspect artifact ids, recover from a long workflow, or decide whether to call workflow_step or workflow_artifact_read next. Use only a runId returned by workflow_run/workflow_step/workflow_status; do not construct one yourself.',\n inputSchema: WorkflowStatusInputSchema,\n outputSchema: WorkflowStatusOutputSchema,\n annotations: liveWebToolAnnotations('Workflow Status'),\n }, async (input) => formatWorkflowStatus(await executor.workflowStatus(input), input))\n\n server.registerTool('workflow_artifact_read', {\n title: 'Read Workflow Artifact',\n description: 'Read a workflow artifact back into MCP context by run id and artifact id. Use this before writing final deliverables so the answer is grounded in generated evidence.json, CSVs, Markdown briefs, reports, and task files instead of memory. Use workflow_status first when artifact ids are unknown. Use only artifactId values returned by workflow_run/workflow_step/workflow_status; do not construct one yourself. Use maxBytes to limit large CSV/JSON artifacts.',\n inputSchema: WorkflowArtifactReadInputSchema,\n outputSchema: WorkflowArtifactReadOutputSchema,\n annotations: liveWebToolAnnotations('Read Workflow Artifact'),\n }, async (input) => formatWorkflowArtifactRead(await executor.workflowArtifactRead(input), input))\n\n server.registerTool('rank_tracker_blueprint', {\n title: 'Rank Tracker Blueprint Builder',\n description: 'Generate a build-ready database, cron/heartbeat, ingestion, metrics, and AI implementation prompt for a rank tracker powered by MCP Scraper. Supports Maps rankings through directory_workflow/maps_search, organic rankings through search_serp, AI Overview citation tracking, and People Also Ask source presence tracking. This tool is local planning only; it does not call the web or spend credits.',\n inputSchema: RankTrackerBlueprintInputSchema,\n outputSchema: RankTrackerBlueprintOutputSchema,\n annotations: localPlanningToolAnnotations('Rank Tracker Blueprint Builder'),\n }, async (input) => buildRankTrackerBlueprint(input))\n\n server.registerTool('credits_info', {\n title: 'MCP Scraper Credits & Costs',\n description: 'Answer questions about MCP Scraper credits, usage limits, and concurrency upgrades: current credit balance, what a specific tool/action costs, the full cost table, current concurrency limit, the extra-slot price, billing URL, and the terminal checkout command. Does not expose payment methods or credit card information.',\n inputSchema: CreditsInfoInputSchema,\n outputSchema: CreditsInfoOutputSchema,\n annotations: {\n title: 'MCP Scraper Credits & Costs',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n }, async (input) => formatCreditsInfo(await executor.creditsInfo(input), input))\n\n}\n","export const PACKAGE_VERSION = '0.3.11'\n","import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { sanitizeVendorName } from '../errors.js'\nimport { WORKFLOW_RECIPES, suggestWorkflowRecipes, type WorkflowRecipe } from './workflow-catalog.js'\n\nlet reportSavingEnabled = true\n\nexport function configureReportSaving(enabled: boolean): void {\n reportSavingEnabled = enabled\n}\n\nfunction sanitizeVendorText(text: string): string {\n return sanitizeVendorName(\n text\n .replace(/kernel_session_id/gi, 'browser_session_id')\n .replace(/kernel_delete_succeeded/gi, 'session_cleanup_succeeded')\n .replace(/kernel_delete_started/gi, 'session_cleanup_started')\n .replace(/kernel_delete_error/gi, 'session_cleanup_error')\n .replace(/kernelSessionId/g, 'browserSessionId')\n .replace(/kernelProxyId/g, 'proxyId')\n .replace(/KERNEL_API_KEY/g, 'BROWSER_SERVICE_API_KEY')\n .replace(/\"kernel\"\\s*:/gi, '\"browserRuntime\":'),\n )\n}\n\nfunction slugifyReportName(input: string): string {\n return input\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 80) || 'mcp-scraper-report'\n}\n\nfunction reportTitle(full: string): string {\n const title = full.split('\\n').find(line => line.startsWith('# '))\n return title?.replace(/^#\\s+/, '').trim() || 'MCP Scraper Report'\n}\n\nexport function outputBaseDir(): string {\n return process.env.MCP_SCRAPER_OUTPUT_DIR?.trim() || join(homedir(), 'Downloads', 'mcp-scraper')\n}\n\nfunction saveFullReport(full: string): string | null {\n if (!reportSavingEnabled || process.env.MCP_SCRAPER_SAVE_REPORTS === 'false') return null\n const outDir = outputBaseDir()\n try {\n mkdirSync(outDir, { recursive: true })\n const stamp = new Date().toISOString().replace(/[:.]/g, '-')\n const file = join(outDir, `${stamp}-${slugifyReportName(reportTitle(full))}.md`)\n writeFileSync(file, full, 'utf8')\n return file\n } catch {\n return null\n }\n}\n\nfunction persistScreenshotLocally(base64: string, url: string): string | null {\n if (!reportSavingEnabled || process.env.MCP_SCRAPER_SAVE_REPORTS === 'false') return null\n try {\n const dir = join(outputBaseDir(), 'screenshots')\n mkdirSync(dir, { recursive: true })\n const stamp = new Date().toISOString().replace(/[:.]/g, '-')\n const slug = url.replace(/^https?:\\/\\//, '').replace(/[^a-z0-9]+/gi, '-').replace(/^-+|-+$/g, '').slice(0, 60)\n const filePath = join(dir, `${stamp}-${slug}.png`)\n writeFileSync(filePath, Buffer.from(base64, 'base64'))\n return filePath\n } catch {\n return null\n }\n}\n\nfunction oneBlock(content: string): CallToolResult {\n const filePath = saveFullReport(content)\n const text = filePath ? `${content}\\n\\n📄 Saved: \\`${filePath}\\`` : content\n return { content: [{ type: 'text', text }] }\n}\n\nexport function passthrough(raw: CallToolResult): CallToolResult {\n return raw\n}\n\nfunction workflowRecipeTable(recipes: WorkflowRecipe[]): string {\n if (!recipes.length) return ''\n return [\n '| Recipe | Best workflow | What it produces |',\n '|---|---|---|',\n ...recipes.map(recipe => `| ${cell(recipe.title)} | ${recipe.primaryWorkflowId ? `\\`${recipe.primaryWorkflowId}\\`` : 'tool chain'} | ${cell(recipe.produces.slice(0, 4).join(', '))} |`),\n ].join('\\n')\n}\n\nfunction checkInsufficientBalance(raw: CallToolResult): CallToolResult | null {\n const first = raw.content.find(b => b.type === 'text')\n const text = first?.type === 'text' ? first.text : ''\n try {\n const body = JSON.parse(text || '{}') as Record<string, unknown>\n if (body.error === 'insufficient_balance') {\n return {\n isError: true,\n content: [{\n type: 'text',\n text: `Insufficient credits. Balance: ${body.balance_credits} credits. This call requires ${body.required_credits} credits. Top up at ${body.topup_url}`,\n }],\n }\n }\n } catch { }\n return null\n}\n\nfunction formatStructuredError(body: Record<string, unknown>, fallback: string): string {\n if (body.error === 'insufficient_balance') {\n return `Insufficient credits. Balance: ${body.balance_credits} credits. This call requires ${body.required_credits} credits. Top up at ${body.topup_url}`\n }\n if (body.error === 'mcp_request_timeout') {\n return typeof body.message === 'string' ? body.message : 'MCP Scraper request timed out and was cancelled.'\n }\n if (typeof body.error_code === 'string') {\n const message = typeof body.error === 'string'\n ? body.error\n : typeof body.message === 'string'\n ? body.message\n : fallback\n const retryable = body.retryable === true ? ' Retryable: yes.' : ''\n return `${body.error_code}: ${message}${retryable}${errorAttemptsSection(body)}`\n }\n if (typeof body.error === 'string') return body.error\n return fallback || 'Tool error'\n}\n\nfunction parseData(raw: CallToolResult): { data: Record<string, unknown> } | { error: string } {\n const first = raw.content.find(b => b.type === 'text')\n const text = first?.type === 'text' ? first.text : ''\n try {\n const parsed = JSON.parse(text || '{}') as Record<string, unknown>\n if (raw.isError || parsed.error || parsed.error_code) return { error: sanitizeVendorText(formatStructuredError(parsed, text)) }\n const data = (parsed.result as Record<string, unknown>) ?? parsed\n return { data }\n } catch {\n if (raw.isError) return { error: sanitizeVendorText(text || 'Tool error') }\n return { error: 'Failed to parse tool response' }\n }\n}\n\nfunction entityIdsSection(ids?: { kgIds?: string[]; cids?: string[]; gcids?: string[] }): string {\n if (!ids) return ''\n const lines: string[] = []\n if (ids.kgIds?.length) lines.push(`- **Knowledge Graph MID:** ${ids.kgIds.join(', ')}`)\n if (ids.cids?.length) lines.push(`- **CID:** ${ids.cids.join(', ')}`)\n if (ids.gcids?.length) lines.push(`- **GCID:** ${ids.gcids.join(', ')}`)\n return lines.length ? `\\n## Entity IDs\\n${lines.join('\\n')}` : ''\n}\n\nfunction truncate(s: string | null | undefined, max: number): string {\n if (!s) return ''\n return s.length > max ? s.slice(0, max) + '…' : s\n}\n\nexport function cell(s: string | null | undefined): string {\n return String(s ?? '')\n .replace(/\\r?\\n+/g, ' ')\n .replace(/\\|/g, '\\\\|')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\nfunction debugSection(debug: any): string {\n if (!debug || typeof debug !== 'object') return ''\n const request = debug.request ?? {}\n const browser = debug.browser ?? {}\n const kernel = browser.browserRuntime ?? browser.kernel ?? {}\n const network = browser.networkLocation ?? {}\n const nav = browser.serpNavigation ?? {}\n const proxyResolution = kernel.proxyResolution ?? {}\n const locationEvidence = debug.locationEvidence\n const candidates = Array.isArray(locationEvidence?.candidates)\n ? locationEvidence.candidates.slice(0, 4).map((c: any) => `${c.city}, ${c.regionCode} (${c.count})`).join(', ')\n : ''\n const lines = [\n '\\n## Debug',\n `- Proxy mode: ${request.proxyMode ?? kernel.proxyMode ?? 'unknown'} · requested proxy: ${kernel.requestedProxyIdPresent === true ? `yes (${kernel.requestedProxyIdSuffix ?? 'redacted'})` : 'no'}`,\n `- Proxy resolution: ${proxyResolution.source ?? 'unknown'}${proxyResolution.target ? ` · ${proxyResolution.target.level ?? 'city'} ${proxyResolution.target.city}, ${proxyResolution.target.state}` : ''}${proxyResolution.error ? ` · ${truncate(proxyResolution.error, 180)}` : ''}`,\n `- Browser session: ${kernel.sessionId ?? 'unknown'} · retrieved proxy: ${kernel.retrievedProxyIdPresent === true ? `yes (${kernel.retrievedProxyIdSuffix ?? 'redacted'})` : kernel.retrievedProxyIdPresent === false ? 'no' : 'unknown'}`,\n `- Browser IP geo: ${[network.ip, network.city, network.region, network.country].filter(Boolean).join(' · ') || network.error || 'unknown'}`,\n `- Google URL: ${truncate(nav.requestedUrl, 240) || 'unknown'}`,\n `- Final URL: ${truncate(nav.finalUrl, 240) || 'unknown'} · CAPTCHA: ${nav.captchaDetected === true ? 'yes' : nav.captchaDetected === false ? 'no' : 'unknown'} · redirected: ${nav.redirected === true ? 'yes' : nav.redirected === false ? 'no' : 'unknown'}`,\n ]\n if (locationEvidence) {\n lines.push(`- Location evidence: ${locationEvidence.status}${locationEvidence.expected ? ` · expected ${locationEvidence.expected.city}${locationEvidence.expected.regionCode ? `, ${locationEvidence.expected.regionCode}` : ''}` : ''}${candidates ? ` · candidates ${candidates}` : ''}`)\n }\n return sanitizeVendorText(lines.join('\\n'))\n}\n\nfunction errorAttemptsSection(body: Record<string, unknown>): string {\n const attempts = Array.isArray(body.attempts) ? body.attempts as Array<Record<string, any>> : []\n if (attempts.length === 0) return ''\n const lines = attempts.slice(0, 5).map((attempt) => {\n const debug = attempt.debug ?? {}\n const browser = debug.browser ?? {}\n const kernel = browser.browserRuntime ?? browser.kernel ?? {}\n const proxyResolution = kernel.proxyResolution ?? {}\n const network = browser.networkLocation ?? {\n ip: attempt.observedIp ?? attempt.observed_ip,\n city: attempt.observedCity ?? attempt.observed_city,\n region: attempt.observedRegion ?? attempt.observed_region,\n }\n const nav = browser.serpNavigation ?? {}\n const geo = [network.ip, network.city, network.region].filter(Boolean).join(' / ') || 'geo unknown'\n const sessionId = attempt.browser_session_id ?? attempt.browserSessionIdSuffix ?? attempt.kernel_session_id ?? kernel.sessionId ?? 'unknown'\n const cleanupSucceeded = attempt.session_cleanup_succeeded ?? attempt.kernel_delete_succeeded\n const proxySource = proxyResolution.source ?? attempt.proxyResolutionSource\n return `- Attempt ${attempt.attempt_number ?? attempt.attemptNumber ?? '?'}: ${attempt.outcome ?? attempt.status ?? 'unknown'} · session ${sessionId} · proxy ${debug.request?.proxyMode ?? kernel.proxyMode ?? attempt.proxyMode ?? 'unknown'}${proxySource ? `/${proxySource}` : ''} · ${geo} · CAPTCHA ${nav.captchaDetected === true ? 'yes' : nav.captchaDetected === false ? 'no' : 'unknown'} · cleanup ${cleanupSucceeded === true ? 'yes' : cleanupSucceeded === false ? 'no' : 'unknown'}`\n })\n return `\\n\\nAttempts:\\n${lines.join('\\n')}`\n}\n\ninterface FlatRow { question: string; answer?: string; source_site?: string; source_title?: string }\ninterface OrganicResult { position: number; title: string; url: string; domain: string; snippet?: string | null }\ninterface AIOverview { detected: boolean; text?: string | null }\ninterface HarvestDiagnostics { completionStatus?: string; debug?: unknown }\n\nexport function formatHarvestPaa(\n raw: CallToolResult,\n input: { query: string; maxQuestions?: number; location?: string },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data\n\n const flat = (d.flat as FlatRow[]) ?? []\n const organic = (d.organicResults as OrganicResult[]) ?? []\n const entityIds = d.entityIds as { kgIds?: string[]; cids?: string[]; gcids?: string[] } | undefined\n const aiOvw = d.aiOverview as AIOverview | undefined\n const diagnostics = d.diagnostics as HarvestDiagnostics | undefined\n const durationMs = (d.stats as { durationMs?: number } | undefined)?.durationMs\n\n const paaRows = flat.map((r, i) =>\n `| ${i + 1} | ${cell(r.question)} | ${cell(truncate(r.answer, 120))} | ${cell(r.source_title || r.source_site || '')} |`,\n ).join('\\n')\n\n const paaTable = flat.length\n ? `## People Also Ask (${flat.length} questions)\\n| # | Question | Answer | Source |\\n|---|----------|--------|--------|\\n${paaRows}`\n : '## People Also Ask\\n*Google did not return a People Also Ask block for this query/location. SERP data was extracted successfully when available.*'\n\n const serpRows = organic.map(r =>\n `| ${r.position} | ${cell(r.title)} | [${cell(r.domain)}](${r.url}) | ${cell(truncate(r.snippet, 100))} |`,\n ).join('\\n')\n\n const serpTable = organic.length\n ? `\\n## Organic Results (${organic.length})\\n| # | Title | URL | Snippet |\\n|---|-------|-----|----------|\\n${serpRows}`\n : ''\n\n const aiSection = aiOvw?.detected && aiOvw.text\n ? `\\n## AI Overview\\n> ${truncate(aiOvw.text, 600)}`\n : ''\n\n const statsLine = durationMs\n ? `\\n## Stats\\n- Status: ${diagnostics?.completionStatus ?? (flat.length ? 'paa_found' : 'no_paa')} · Questions: ${flat.length} · Duration: ${(durationMs / 1000).toFixed(1)}s`\n : ''\n\n const tips = `\\n---\\n💡 **Tips**\\n- Max questions: \\`maxQuestions: 200\\` (current: ${input.maxQuestions ?? 30})\\n- Organic results only: use \\`search_serp\\`\\n- Dig into a result: use \\`extract_url\\` on any organic URL`\n\n const full = `# PAA Report: \"${input.query}\"${input.location ? ` · ${input.location}` : ''}\\n\\n${paaTable}${serpTable}${entityIdsSection(entityIds)}${aiSection}${statsLine}${debugSection(diagnostics?.debug)}${tips}`\n\n return {\n ...oneBlock(full),\n structuredContent: {\n query: input.query,\n location: input.location ?? null,\n questionCount: flat.length,\n completionStatus: diagnostics?.completionStatus ?? null,\n questions: flat.map(r => ({\n question: String(r.question ?? ''),\n answer: r.answer ?? null,\n sourceTitle: r.source_title ?? null,\n sourceSite: r.source_site ?? null,\n })),\n organicResults: organic.map(r => ({\n position: Number(r.position) || 0,\n title: String(r.title ?? ''),\n url: String(r.url ?? ''),\n domain: String(r.domain ?? ''),\n snippet: r.snippet ?? null,\n })),\n aiOverview: aiOvw ? { detected: aiOvw.detected === true, text: aiOvw.text ?? null } : null,\n entityIds: entityIds\n ? { kgIds: entityIds.kgIds ?? [], cids: entityIds.cids ?? [], gcids: entityIds.gcids ?? [] }\n : null,\n durationMs: durationMs ?? null,\n },\n }\n}\n\ninterface LocalBusiness { position: number; name: string; rating?: string | null; reviewCount?: string | null; websiteUrl?: string | null }\n\nexport function formatSearchSerp(\n raw: CallToolResult,\n input: { query: string; location?: string },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data\n\n const organic = (d.organicResults as OrganicResult[]) ?? []\n const localPack = (d.localPack as LocalBusiness[]) ?? []\n const entityIds = d.entityIds as { kgIds?: string[]; cids?: string[]; gcids?: string[] } | undefined\n const aiOvw = d.aiOverview as AIOverview | undefined\n const diagnostics = d.diagnostics as HarvestDiagnostics | undefined\n\n const serpRows = organic.map(r =>\n `| ${r.position} | ${cell(r.title)} | [${cell(r.domain)}](${r.url}) | ${cell(truncate(r.snippet, 100))} |`,\n ).join('\\n')\n\n const serpTable = organic.length\n ? `## Organic Results (${organic.length})\\n| # | Title | URL | Snippet |\\n|---|-------|-----|----------|\\n${serpRows}`\n : '## Organic Results\\n*None found*'\n\n const localRows = localPack.map(b =>\n `| ${b.position} | ${cell(b.name)} | ${b.rating ?? '—'} (${b.reviewCount ?? '0'}) | ${b.websiteUrl ? `[link](${b.websiteUrl})` : '—'} |`,\n ).join('\\n')\n\n const localSection = localPack.length\n ? `\\n## Local Pack (${localPack.length})\\n| # | Name | Rating | Website |\\n|---|------|--------|---------|\\n${localRows}`\n : ''\n\n const aiSection = aiOvw?.detected && aiOvw.text\n ? `\\n## AI Overview\\n> ${truncate(aiOvw.text, 600)}`\n : ''\n\n const tips = `\\n---\\n💡 **Tips**\\n- Get PAA questions: use \\`harvest_paa\\` for this query\\n- Scrape any result: use \\`extract_url\\`\\n- Business entity IDs (CID/GCID/KG MID) shown above if found`\n\n const full = `# SERP Report: \"${input.query}\"${input.location ? ` · ${input.location}` : ''}\\n\\n${serpTable}${localSection}${entityIdsSection(entityIds)}${aiSection}${debugSection(diagnostics?.debug)}${tips}`\n\n return {\n ...oneBlock(full),\n structuredContent: {\n query: input.query,\n location: input.location ?? null,\n organicResults: organic.map(r => ({\n position: Number(r.position) || 0,\n title: String(r.title ?? ''),\n url: String(r.url ?? ''),\n domain: String(r.domain ?? ''),\n snippet: r.snippet ?? null,\n })),\n localPack: localPack.map(b => ({\n position: Number(b.position) || 0,\n name: String(b.name ?? ''),\n rating: b.rating ?? null,\n reviewCount: b.reviewCount ?? null,\n websiteUrl: b.websiteUrl ?? null,\n })),\n aiOverview: aiOvw ? { detected: aiOvw.detected === true, text: aiOvw.text ?? null } : null,\n entityIds: entityIds\n ? { kgIds: entityIds.kgIds ?? [], cids: entityIds.cids ?? [], gcids: entityIds.gcids ?? [] }\n : null,\n },\n }\n}\n\ninterface Heading { level: number; text: string }\ninterface KpoResult {\n entityName?: string | null; type?: string[]; napScore?: number\n address?: string | null; phone?: string | null; email?: string | null\n sameAs?: string[]; missingFields?: string[]; faqCount?: number\n}\n\nexport function formatExtractUrl(raw: CallToolResult, input: { url: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data\n\n const url = (d.url as string) ?? input.url\n const title = (d.title as string | null) ?? 'Untitled'\n const headings = (d.headings as Heading[]) ?? []\n const kpo = d.kpo as KpoResult | undefined\n const bodyMd = (d.bodyMarkdown as string | null) ?? ''\n const schema = d.schema as unknown[]\n const screenshotMeta = d.screenshot as { base64: string; sizeBytes: number; device: string } | null | undefined\n const screenshotPath = screenshotMeta?.base64 ? persistScreenshotLocally(screenshotMeta.base64, url) : null\n const branding = d.branding as { colorScheme: string | null; colors: Record<string, string | null>; fonts: Record<string, string | null>; assets: Record<string, string | null> } | null | undefined\n const media = d.media as { outputDir: string | null; assets: unknown[]; filteredCount: number; totalFound: number } | null | undefined\n\n const h1Lines = headings.filter(h => h.level === 1).map(h => `- ${h.text}`).join('\\n')\n const h2Lines = headings.filter(h => h.level === 2).map(h => ` - ${h.text}`).join('\\n')\n const headingSection = (h1Lines || h2Lines)\n ? `\\n## Heading Structure\\n${[h1Lines, h2Lines].filter(Boolean).join('\\n')}`\n : ''\n\n const kpoSection = kpo ? [\n `\\n## Entity / Schema`,\n kpo.entityName ? `- **Entity:** ${kpo.entityName}` : '',\n kpo.type?.length ? `- **@type:** ${kpo.type.join(', ')}` : '',\n kpo.napScore !== undefined ? `- **NAP Score:** ${kpo.napScore}/5` : '',\n kpo.address ? `- **Address:** ${kpo.address}` : '',\n kpo.phone ? `- **Phone:** ${kpo.phone}` : '',\n kpo.email ? `- **Email:** ${kpo.email}` : '',\n kpo.faqCount ? `- **FAQ items:** ${kpo.faqCount}` : '',\n kpo.sameAs?.length ? `- **sameAs:** ${kpo.sameAs.slice(0, 5).join(', ')}` : '',\n kpo.missingFields?.length ? `\\n**Missing schema fields:** ${kpo.missingFields.slice(0, 5).join(', ')}` : '',\n ].filter(Boolean).join('\\n') : ''\n\n const bodySection = bodyMd\n ? `\\n## Page Content\\n${bodyMd.slice(0, 3000)}${bodyMd.length > 3000 ? '\\n\\n*(truncated)*' : ''}`\n : ''\n\n const screenshotSection = screenshotMeta\n ? `\\n## Screenshot\\n- **File:** ${screenshotPath ?? '(returned inline only — disk write unavailable in this environment)'}\\n- **Size:** ${(screenshotMeta.sizeBytes / 1024).toFixed(1)} KB\\n- **Device:** ${screenshotMeta.device}`\n : ''\n\n const brandingSection = branding\n ? [\n `\\n## Branding`,\n branding.colorScheme ? `- **Color scheme:** ${branding.colorScheme}` : '',\n `- **Colors:**${Object.entries(branding.colors ?? {}).filter(([,v]) => v).map(([k,v]) => ` ${k}=${v}`).join(',') || ' (none extracted)'}`,\n `- **Fonts:**${Object.entries(branding.fonts ?? {}).filter(([,v]) => v).map(([k,v]) => ` ${k}=${v}`).join(',') || ' (none extracted)'}`,\n branding.assets?.logo ? `- **Logo:** ${branding.assets.logo}` : '',\n branding.assets?.favicon ? `- **Favicon:** ${branding.assets.favicon}` : '',\n ].filter(Boolean).join('\\n')\n : ''\n\n const mediaSection = media\n ? [\n `\\n## Media Assets`,\n `- **Found:** ${media.totalFound} total, ${media.filteredCount} filtered (ads/noise), ${media.assets.length} downloaded`,\n media.outputDir ? `- **Saved to:** ${media.outputDir}` : '',\n ].filter(Boolean).join('\\n')\n : ''\n\n const schemaCount = Array.isArray(schema) ? schema.length : 0\n const tips = `\\n---\\n💡 **Tips**\\n- Crawl entire site: use \\`extract_site\\`\\n- Map all URLs: use \\`map_site_urls\\`\\n- ${schemaCount} JSON-LD schema block(s) detected`\n\n const full = `# URL Extract: ${url}\\n**${title}**\\n${headingSection}${kpoSection}${brandingSection}${bodySection}${screenshotSection}${mediaSection}${tips}`\n\n const textResult = oneBlock(full)\n const structuredContent = {\n url,\n title: (d.title as string | null) ?? null,\n headings: headings.map(h => ({ level: Number(h.level) || 0, text: String(h.text ?? '') })),\n schemaBlockCount: schemaCount,\n entityName: kpo?.entityName ?? null,\n entityTypes: kpo?.type ?? [],\n napScore: kpo?.napScore ?? null,\n missingSchemaFields: kpo?.missingFields ?? [],\n screenshotSaved: screenshotPath ?? null,\n branding: branding ?? null,\n mediaAssets: media?.assets ?? null,\n }\n\n if (screenshotMeta?.base64) {\n return {\n content: [\n ...(textResult.content),\n { type: 'image', data: screenshotMeta.base64, mimeType: 'image/png' },\n ],\n structuredContent,\n }\n }\n\n return { ...textResult, structuredContent }\n}\n\ninterface DiscoveredUrl { url: string; status: number | null }\ninterface SpiderResult { startUrl: string; urls: DiscoveredUrl[]; totalFound: number; durationMs: number; truncated: boolean }\n\nexport function formatMapSiteUrls(raw: CallToolResult, input: { url: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as SpiderResult\n\n const urls = d.urls ?? []\n const ok = urls.filter(u => (u.status ?? 0) >= 200 && (u.status ?? 0) < 300)\n const broken = urls.filter(u => u.status !== null && u.status >= 400)\n const redirects = urls.filter(u => u.status !== null && u.status >= 300 && u.status < 400)\n\n const urlRows = urls.slice(0, 200).map((u, i) => `| ${i + 1} | ${u.url} | ${u.status ?? '—'} |`).join('\\n')\n\n const full = [\n `# URL Map: ${input.url}`,\n `**${d.totalFound} URLs** · ${(d.durationMs / 1000).toFixed(1)}s${d.truncated ? ' · *truncated*' : ''}`,\n `\\n## Summary\\n- ✅ 2xx: ${ok.length}\\n- 🔀 3xx: ${redirects.length}\\n- ❌ 4xx+: ${broken.length}`,\n `\\n## URL Inventory\\n| # | URL | Status |\\n|---|-----|--------|\\n${urlRows}`,\n broken.length ? `\\n## Broken URLs\\n${broken.map(u => `- ${u.url} (${u.status})`).join('\\n')}` : '',\n `\\n---\\n💡 **Tips**\\n- Extract content from all pages: use \\`extract_site\\`\\n- Scrape a single page: use \\`extract_url\\``,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n startUrl: d.startUrl ?? input.url,\n totalFound: d.totalFound ?? urls.length,\n truncated: d.truncated === true,\n okCount: ok.length,\n redirectCount: redirects.length,\n brokenCount: broken.length,\n urls: urls.map(u => ({ url: u.url, status: u.status ?? null })),\n durationMs: d.durationMs ?? 0,\n },\n }\n}\n\ninterface SitePageResult { url: string; title?: string | null; kpo?: KpoResult; schema?: unknown[] }\ninterface ExtractSiteResult { pages: SitePageResult[]; durationMs?: number }\n\nexport function formatExtractSite(raw: CallToolResult, input: { url: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as ExtractSiteResult\n\n const pages = d.pages ?? []\n\n const pageRows = pages.map((p, i) => {\n const schemaInfo = p.kpo?.type?.join(', ') ?? (Array.isArray(p.schema) && p.schema.length ? `${p.schema.length} block(s)` : '—')\n return `| ${i + 1} | ${cell(p.title ?? 'Untitled')} | ${p.url} | ${schemaInfo} |`\n }).join('\\n')\n\n const full = [\n `# Site Extract: ${input.url}`,\n `**${pages.length} pages** · ${(((d.durationMs ?? 0)) / 1000).toFixed(1)}s`,\n `\\n## Pages\\n| # | Title | URL | Schema |\\n|---|-------|-----|--------|\\n${pageRows}`,\n `\\n---\\n💡 **Tips**\\n- Map URLs first: use \\`map_site_urls\\`\\n- Inspect a single page: use \\`extract_url\\``,\n ].join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n url: input.url,\n pageCount: pages.length,\n pages: pages.map(p => ({\n url: String(p.url ?? ''),\n title: p.title ?? null,\n schemaTypes: p.kpo?.type ?? [],\n })),\n durationMs: d.durationMs ?? 0,\n },\n }\n}\n\ninterface YTVideo { videoId: string; title: string; channelName: string; views?: string | null; duration?: string | null; url: string }\ninterface YTHarvestResult { videos: YTVideo[]; channelMeta?: { title?: string; subscriberCount?: string | null } | null; stats: { durationMs: number } }\n\nexport function formatYoutubeHarvest(\n raw: CallToolResult,\n input: { mode: string; query?: string; channelHandle?: string },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as YTHarvestResult\n\n const videos = d.videos ?? []\n const label = input.mode === 'channel' ? (input.channelHandle ?? 'channel') : `\"${input.query ?? ''}\"`\n\n const videoRows = videos.map((v, i) =>\n `| ${i + 1} | ${cell(truncate(v.title, 70))} | ${cell(v.channelName)} | ${v.views ?? '—'} | ${v.duration ?? '—'} | \\`${v.videoId}\\` |`,\n ).join('\\n')\n\n const channelSection = d.channelMeta\n ? `\\n## Channel\\n- **Name:** ${d.channelMeta.title ?? '—'}\\n- **Subscribers:** ${d.channelMeta.subscriberCount ?? '—'}`\n : ''\n\n const full = [\n `# YouTube Harvest: ${label}`,\n `**${videos.length} videos** · ${(d.stats.durationMs / 1000).toFixed(1)}s`,\n channelSection,\n `\\n## Videos\\n| # | Title | Channel | Views | Duration | Video ID |\\n|---|-------|---------|-------|----------|----------|\\n${videoRows}`,\n `\\n---\\n💡 **Tips**\\n- Transcribe a video: use \\`youtube_transcribe\\` with the \\`videoId\\` above\\n- Switch mode: \\`mode: \"channel\"\\` with \\`channelHandle\\` or \\`mode: \"search\"\\` with \\`query\\``,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n mode: input.mode,\n videoCount: videos.length,\n channel: d.channelMeta\n ? { title: d.channelMeta.title ?? null, subscriberCount: d.channelMeta.subscriberCount ?? null }\n : null,\n videos: videos.map(v => ({\n videoId: String(v.videoId ?? ''),\n title: String(v.title ?? ''),\n channelName: v.channelName ?? null,\n views: v.views ?? null,\n duration: v.duration ?? null,\n url: v.url ?? null,\n })),\n },\n }\n}\n\ninterface TranscriptChunk { timestamp: [number, number]; text: string }\ninterface TranscriptResult { videoId?: string | null; text: string; chunks?: TranscriptChunk[]; durationMs?: number }\n\nfunction structuredTranscriptChunks(chunks: TranscriptChunk[]): Array<{ startSec: number; endSec: number; text: string }> {\n return chunks.map(c => ({\n startSec: Number.isFinite(c.timestamp?.[0]) ? c.timestamp[0] : 0,\n endSec: Number.isFinite(c.timestamp?.[1]) ? c.timestamp[1] : 0,\n text: c.text,\n }))\n}\n\nfunction wordCount(text: string): number {\n return text.trim() ? text.trim().split(/\\s+/).length : 0\n}\n\nexport function formatYoutubeTranscribe(raw: CallToolResult, input: { videoId?: string; url?: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as TranscriptResult\n\n const text = d.text ?? ''\n const chunks = d.chunks ?? []\n const videoId = d.videoId ?? input.videoId ?? null\n const durSec = d.durationMs ? (d.durationMs / 1000).toFixed(0) : '—'\n const words = wordCount(text)\n\n const chunkRows = chunks.slice(0, 50).map(c => {\n const sec = Number.isFinite(c.timestamp[0]) ? Math.floor(c.timestamp[0]) : 0\n const mm = String(Math.floor(sec / 60)).padStart(2, '0')\n const ss = String(sec % 60).padStart(2, '0')\n return `| ${mm}:${ss} | ${cell(truncate(c.text, 120))} |`\n }).join('\\n')\n\n const full = [\n `# YouTube Transcript: \\`${videoId ?? input.url ?? 'video'}\\``,\n `**Duration:** ${durSec}s · **${words} words**`,\n `\\n## Full Transcript\\n${text}`,\n chunks.length ? `\\n## Timestamped Chunks\\n| Time | Text |\\n|------|------|\\n${chunkRows}` : '',\n `\\n---\\n💡 Harvest more from this channel: use \\`youtube_harvest\\` with \\`mode: \"channel\"\\``,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n videoId,\n url: videoId ? `https://www.youtube.com/watch?v=${videoId}` : input.url ?? null,\n wordCount: words,\n chunkCount: chunks.length,\n durationMs: typeof d.durationMs === 'number' ? d.durationMs : null,\n transcriptText: text,\n chunks: structuredTranscriptChunks(chunks),\n resolvedInputs: {\n videoId,\n url: input.url ?? null,\n },\n },\n }\n}\n\ninterface FbAd {\n libraryId?: string; status?: string; creativeType?: string\n headline?: string | null; primaryText?: string | null; cta?: string | null\n startDate?: string | null; started?: string | null\n landingUrl?: string | null; domain?: string | null\n videoUrl?: string | null; videoSrc?: string | null\n imageUrl?: string | null; imageSrc?: string | null; videoPoster?: string | null\n variations?: number; clusterCount?: number | null\n}\ninterface FbPageResult {\n advertiserName?: string | null\n summary: { totalAds: number; activeCount: number; videoCount: number; imageCount: number }\n ads: FbAd[]\n}\n\nexport function formatFacebookPageIntel(\n raw: CallToolResult,\n input: { pageId?: string; libraryId?: string; query?: string },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as FbPageResult\n\n const advertiser = d.advertiserName ?? input.query ?? input.pageId ?? input.libraryId ?? 'Advertiser'\n const ads = d.ads ?? []\n const s = d.summary ?? { totalAds: 0, activeCount: 0, videoCount: 0, imageCount: 0 }\n\n const adBlocks = ads.map((ad, i) => [\n `### Ad ${i + 1}${ad.libraryId ? ` · \\`${ad.libraryId}\\`` : ''} — ${ad.status ?? '—'} · ${ad.creativeType ?? '—'} · ${ad.startDate ?? ad.started ?? '—'}`,\n ad.headline ? `**Headline:** ${ad.headline}` : '',\n ad.primaryText ? `**Copy:** ${truncate(ad.primaryText, 200)}` : '',\n ad.cta ? `**CTA:** ${ad.cta}` : '',\n ad.landingUrl ? `**Landing URL:** ${ad.landingUrl}` : '',\n (ad.videoUrl ?? ad.videoSrc) ? `**Video URL:** \\`${ad.videoUrl ?? ad.videoSrc}\\`` : '',\n (ad.variations ?? ad.clusterCount) ? `**Variations:** ${ad.variations ?? ad.clusterCount}` : '',\n ].filter(Boolean).join('\\n')).join('\\n\\n---\\n\\n')\n\n const full = [\n `# Facebook Ad Intel: ${advertiser}`,\n `**${s.totalAds} ads** · ${s.activeCount} active · ${s.videoCount} video · ${s.imageCount} image`,\n `\\n${adBlocks}`,\n `\\n---\\n💡 **Tips**\\n- Transcribe video ads: use \\`facebook_ad_transcribe\\` with the direct \\`videoUrl\\` above\\n- Transcribe organic Facebook reels/posts: use \\`facebook_video_transcribe\\` with the public Facebook URL\\n- Find other advertisers: use \\`facebook_ad_search\\``,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n advertiserName: d.advertiserName ?? null,\n totalAds: s.totalAds ?? 0,\n activeCount: s.activeCount ?? 0,\n videoCount: s.videoCount ?? 0,\n imageCount: s.imageCount ?? 0,\n ads: ads.map(ad => ({\n libraryId: ad.libraryId ?? null,\n status: ad.status ?? null,\n creativeType: ad.creativeType ?? null,\n primaryText: ad.primaryText ?? null,\n headline: ad.headline ?? null,\n cta: ad.cta ?? null,\n startDate: ad.startDate ?? ad.started ?? null,\n landingUrl: ad.landingUrl ?? null,\n domain: ad.domain ?? null,\n videoUrl: ad.videoUrl ?? ad.videoSrc ?? null,\n imageUrl: ad.imageUrl ?? ad.imageSrc ?? null,\n videoPoster: ad.videoPoster ?? null,\n variations: typeof ad.variations === 'number'\n ? ad.variations\n : typeof ad.clusterCount === 'number'\n ? ad.clusterCount\n : null,\n })),\n },\n }\n}\n\ninterface FbAdvertiserResult { name?: string; pageName?: string; pageId?: string; pageUrl?: string; adCount?: number; libraryId?: string; sampleLibraryId?: string }\ninterface FbSearchResult { results?: FbAdvertiserResult[]; advertisers?: FbAdvertiserResult[] }\n\nexport function formatFacebookAdSearch(raw: CallToolResult, input: { query: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as FbSearchResult\n\n const advertisers = d.results ?? d.advertisers ?? []\n\n const rows = advertisers.map((a, i) =>\n `| ${i + 1} | ${cell(a.pageName ?? a.name)} | ${a.adCount ?? '—'} | \\`${a.sampleLibraryId ?? a.libraryId ?? '—'}\\` |`,\n ).join('\\n')\n\n const full = [\n `# Facebook Ad Library Search: \"${input.query}\"`,\n `**${advertisers.length} advertisers found**`,\n `\\n## Advertisers\\n| # | Name | Ad Count | Library ID |\\n|---|------|----------|------------|\\n${rows}`,\n `\\n---\\n💡 **Tips**\\n- Scan all ads: use \\`facebook_page_intel\\` with \\`libraryId\\`\\n- Or pass the advertiser name as \\`query\\` in \\`facebook_page_intel\\``,\n ].join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n query: input.query,\n advertiserCount: advertisers.length,\n advertisers: advertisers.map(a => ({\n name: a.pageName ?? a.name ?? null,\n pageId: a.pageId ?? null,\n pageUrl: a.pageUrl ?? null,\n adCount: typeof a.adCount === 'number' ? a.adCount : null,\n libraryId: a.sampleLibraryId ?? a.libraryId ?? null,\n sampleLibraryId: a.sampleLibraryId ?? null,\n })),\n },\n }\n}\n\ninterface MapsReviewCard { author: string | null; stars: string | null; date: string | null; text: string | null }\ntype ReviewsStatus = 'collected' | 'none_exist' | 'unavailable' | 'not_requested'\ninterface MapsHistogramEntry { stars: number; count: string }\ninterface MapsTopicEntry { label: string; count: string }\ninterface MapsAboutEntry { section: string; attribute: string }\ninterface MapsSearchBusiness {\n position: number\n name: string\n placeUrl: string\n cid: string | null\n cidDecimal: string | null\n rating: string | null\n reviewCount: string | null\n category: string | null\n address: string | null\n phone: string | null\n hoursStatus: string | null\n websiteUrl: string | null\n directionsUrl: string | null\n metadata: string[]\n}\ninterface MapsSearchAttempt {\n attemptNumber?: number\n attempt_number?: number\n maxAttempts?: number\n max_attempts?: number\n status?: 'ok' | 'failed'\n outcome?: string\n willRetry?: boolean\n will_retry?: boolean\n durationMs?: number\n duration_ms?: number\n resultCount?: number\n result_count?: number\n error?: string | null\n proxyMode?: 'location' | 'configured' | 'none'\n proxy_mode?: 'location' | 'configured' | 'none'\n proxyResolutionSource?: string | null\n proxy_resolution_source?: string | null\n proxyIdSuffix?: string | null\n proxy_id_suffix?: string | null\n proxyTargetLevel?: 'zip' | 'city' | 'state' | null\n proxy_target_level?: 'zip' | 'city' | 'state' | null\n proxyTargetLocation?: string | null\n proxy_target_location?: string | null\n proxyTargetZip?: string | null\n proxy_target_zip?: string | null\n browserSessionIdSuffix?: string | null\n browser_session_id?: string | null\n observedIp?: string | null\n observed_ip?: string | null\n observedCity?: string | null\n observed_city?: string | null\n observedRegion?: string | null\n observed_region?: string | null\n}\ninterface DirectoryWorkflowCity {\n city: string\n state: string\n location: string\n cityKey: string\n censusName: string\n population: number\n populationYear: number\n zips: string[]\n counties: string[]\n status: 'ok' | 'empty' | 'failed'\n error: string | null\n resultCount: number\n durationMs: number\n attempts?: MapsSearchAttempt[]\n results: MapsSearchBusiness[]\n}\ninterface CreditCostEntry { key: string; label: string; credits: number; unit: string; notes?: string }\ninterface CreditLedgerEntry { amount_mc: number; operation: string; description: string | null; created_at: string }\n\nfunction normalizeMapsAttempts(value: unknown): Array<{\n attemptNumber: number\n maxAttempts: number\n status: 'ok' | 'failed'\n outcome: string\n willRetry: boolean\n durationMs: number\n resultCount: number\n error: string | null\n proxyMode: 'location' | 'configured' | 'none'\n proxyResolutionSource: string | null\n proxyIdSuffix: string | null\n proxyTargetLevel: 'zip' | 'city' | 'state' | null\n proxyTargetLocation: string | null\n proxyTargetZip: string | null\n browserSessionIdSuffix: string | null\n observedIp: string | null\n observedCity: string | null\n observedRegion: string | null\n}> {\n const attempts = Array.isArray(value) ? value as MapsSearchAttempt[] : []\n return attempts.map((attempt, index) => ({\n attemptNumber: attempt.attemptNumber ?? attempt.attempt_number ?? index + 1,\n maxAttempts: attempt.maxAttempts ?? attempt.max_attempts ?? attempts.length,\n status: attempt.status === 'ok' ? 'ok' : 'failed',\n outcome: attempt.outcome ?? attempt.status ?? 'unknown',\n willRetry: attempt.willRetry ?? attempt.will_retry ?? false,\n durationMs: attempt.durationMs ?? attempt.duration_ms ?? 0,\n resultCount: attempt.resultCount ?? attempt.result_count ?? 0,\n error: attempt.error ? sanitizeVendorText(attempt.error) : null,\n proxyMode: attempt.proxyMode ?? attempt.proxy_mode ?? 'location',\n proxyResolutionSource: attempt.proxyResolutionSource ?? attempt.proxy_resolution_source ?? null,\n proxyIdSuffix: attempt.proxyIdSuffix ?? attempt.proxy_id_suffix ?? null,\n proxyTargetLevel: attempt.proxyTargetLevel ?? attempt.proxy_target_level ?? null,\n proxyTargetLocation: attempt.proxyTargetLocation ?? attempt.proxy_target_location ?? null,\n proxyTargetZip: attempt.proxyTargetZip ?? attempt.proxy_target_zip ?? null,\n browserSessionIdSuffix: attempt.browserSessionIdSuffix ?? attempt.browser_session_id ?? null,\n observedIp: attempt.observedIp ?? attempt.observed_ip ?? null,\n observedCity: attempt.observedCity ?? attempt.observed_city ?? null,\n observedRegion: attempt.observedRegion ?? attempt.observed_region ?? null,\n }))\n}\n\nfunction workflowArtifactsFrom(run: Record<string, unknown> | undefined): Array<Record<string, unknown>> {\n return Array.isArray(run?.artifacts) ? run.artifacts as Array<Record<string, unknown>> : []\n}\n\nfunction workflowArtifactRows(artifacts: Array<Record<string, unknown>>): string {\n if (!artifacts.length) return ''\n return [\n '| Artifact | Type | ID | Rows/Bytes |',\n '|---|---|---|---|',\n ...artifacts.map(artifact => {\n const rows = artifact.rows_count ?? artifact.rows ?? ''\n const bytes = artifact.bytes ?? ''\n const size = [rows ? `${rows} rows` : '', bytes ? `${bytes} bytes` : ''].filter(Boolean).join(' / ')\n return `| ${cell(String(artifact.label ?? artifact.path ?? 'artifact'))} | ${cell(String(artifact.kind ?? artifact.content_type ?? 'file'))} | \\`${String(artifact.id ?? '')}\\` | ${cell(size || '—')} |`\n }),\n ].join('\\n')\n}\n\nexport function formatWorkflowList(raw: CallToolResult, input: { includeRecipes?: boolean }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const workflows = Array.isArray(parsed.data.workflows) ? parsed.data.workflows as Array<Record<string, unknown>> : []\n const workflowRows = [\n '| Workflow ID | Title | Use |',\n '|---|---|---|',\n ...workflows.map(workflow => `| \\`${String(workflow.id ?? '')}\\` | ${cell(String(workflow.title ?? ''))} | ${cell(String(workflow.description ?? ''))} |`),\n ].join('\\n')\n const recipes = input.includeRecipes === false ? [] : WORKFLOW_RECIPES\n const full = [\n '# MCP Scraper Workflows',\n 'Use `workflow_suggest` when the user describes a high-level job. Use `workflow_run` when the workflow id and input are known. Use `workflow_status` and `workflow_artifact_read` to inspect completed runs and pull evidence back into context.',\n workflows.length ? `\\n## Runnable Workflows\\n${workflowRows}` : '',\n recipes.length ? `\\n## High-Level Recipes\\n${workflowRecipeTable(recipes)}` : '',\n recipes.length ? '\\nThese recipes cover market analysis, ICP research, forum and review acquisition, brand design briefings, CRO audits, competitive positioning, content gaps, and AI search visibility audits.' : '',\n ].filter(Boolean).join('\\n')\n return {\n ...oneBlock(full),\n structuredContent: {\n workflows: workflows.map(workflow => ({\n id: String(workflow.id ?? ''),\n title: String(workflow.title ?? ''),\n description: String(workflow.description ?? ''),\n })),\n recipes,\n },\n }\n}\n\nexport function formatWorkflowSuggest(input: { goal: string; maxSuggestions?: number }): CallToolResult {\n const suggestions = suggestWorkflowRecipes(input.goal, input.maxSuggestions ?? 3)\n const full = [\n `# Workflow Suggestions`,\n `**Goal:** ${input.goal}`,\n '',\n workflowRecipeTable(suggestions),\n '',\n '## How To Execute',\n '1. Pick the closest recipe.',\n '2. If it has a `primaryWorkflowId`, call `workflow_run` with that id and the required inputs.',\n '3. After the run completes, use `workflow_artifact_read` on the most relevant CSV/JSON/Markdown artifacts before writing the final answer.',\n ].join('\\n')\n return {\n ...oneBlock(full),\n structuredContent: {\n goal: input.goal,\n suggestions,\n },\n }\n}\n\nfunction workflowStepLines(data: Record<string, unknown>): string[] {\n const step = data.step as Record<string, unknown> | undefined\n const nextStep = data.nextStep as Record<string, unknown> | null | undefined\n const done = data.done === true\n const lines: string[] = []\n if (step) {\n const index = Number(step.index ?? 0)\n const totalSteps = step.totalSteps != null ? Number(step.totalSteps) : undefined\n const stepLabel = totalSteps ? `${index + 1}/${totalSteps}` : `${index + 1}`\n lines.push(`\\n## Step ${stepLabel}: ${step.title ?? step.id ?? ''}`)\n const output = step.output as Record<string, unknown> | undefined\n if (output && Object.keys(output).length) {\n lines.push(Object.entries(output).map(([k, v]) => `- ${k}: ${typeof v === 'object' ? JSON.stringify(v) : String(v)}`).join('\\n'))\n }\n const warnings = Array.isArray(step.warnings) ? step.warnings as string[] : []\n if (warnings.length) lines.push(`\\n**Warnings:**\\n${warnings.map(w => `- ${w}`).join('\\n')}`)\n }\n if (done) {\n lines.push('\\n**Done.** All steps complete.')\n } else if (nextStep && typeof nextStep === 'object') {\n lines.push(`\\n**Next step:** \\`${nextStep.id ?? nextStep.index}\\` — call \\`workflow_step\\` with this run id to continue.`)\n }\n return lines\n}\n\nexport function formatWorkflowRun(raw: CallToolResult, input: { workflowId: string; input?: Record<string, unknown> }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const run = parsed.data.run as Record<string, unknown> | undefined\n const summary = parsed.data.summary as Record<string, unknown> | undefined\n const artifacts = workflowArtifactsFrom(run)\n const runId = String(run?.id ?? '')\n const status = String(run?.status ?? summary?.status ?? 'unknown')\n const full = [\n `# Workflow Run: ${input.workflowId}`,\n `**Run ID:** \\`${runId || 'unknown'}\\``,\n `**Status:** ${status}`,\n summary?.title ? `**Title:** ${summary.title}` : '',\n ...workflowStepLines(parsed.data),\n summary?.summary ? `\\n## Summary\\n${summary.summary}` : '',\n artifacts.length ? `\\n## Artifacts\\n${workflowArtifactRows(artifacts)}` : '',\n artifacts.length ? '\\nUse `workflow_artifact_read` with the run id and artifact id to pull CSV, JSON, Markdown, or report content into context.' : '',\n ].filter(Boolean).join('\\n')\n return {\n ...oneBlock(full),\n structuredContent: {\n workflowId: input.workflowId,\n input: input.input ?? {},\n run,\n summary,\n step: parsed.data.step,\n nextStep: parsed.data.nextStep ?? null,\n done: parsed.data.done === true,\n artifacts,\n },\n }\n}\n\nexport function formatWorkflowStep(raw: CallToolResult, input: { runId: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const run = parsed.data.run as Record<string, unknown> | undefined\n const summary = parsed.data.summary as Record<string, unknown> | undefined\n const artifacts = workflowArtifactsFrom(run)\n const done = parsed.data.done === true\n const full = [\n `# Workflow Step`,\n `**Run ID:** \\`${input.runId}\\``,\n `**Status:** ${run?.status ?? (done ? 'done' : 'running')}`,\n ...workflowStepLines(parsed.data),\n done && summary?.summary ? `\\n## Summary\\n${summary.summary}` : '',\n artifacts.length ? `\\n## Artifacts\\n${workflowArtifactRows(artifacts)}` : '',\n done && artifacts.length ? '\\nUse `workflow_artifact_read` with the run id and artifact id to pull CSV, JSON, Markdown, or report content into context.' : '',\n ].filter(Boolean).join('\\n')\n return {\n ...oneBlock(full),\n structuredContent: {\n runId: input.runId,\n run,\n summary: summary ?? null,\n step: parsed.data.step,\n nextStep: parsed.data.nextStep ?? null,\n done,\n artifacts,\n },\n }\n}\n\nexport function formatWorkflowStatus(raw: CallToolResult, input: { runId: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const run = parsed.data.run as Record<string, unknown> | undefined\n const artifacts = workflowArtifactsFrom(run)\n const full = [\n `# Workflow Status`,\n `**Run ID:** \\`${input.runId}\\``,\n `**Workflow:** ${run?.workflow_id ?? 'unknown'}`,\n `**Status:** ${run?.status ?? 'unknown'}`,\n run?.error_message ? `\\n## Error\\n${run.error_message}` : '',\n artifacts.length ? `\\n## Artifacts\\n${workflowArtifactRows(artifacts)}` : '',\n ].filter(Boolean).join('\\n')\n return {\n ...oneBlock(full),\n structuredContent: {\n run,\n artifacts,\n },\n }\n}\n\nexport function formatWorkflowArtifactRead(raw: CallToolResult, input: { runId: string; artifactId: string; maxBytes?: number }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const text = typeof parsed.data.text === 'string' ? parsed.data.text : ''\n const contentType = String(parsed.data.contentType ?? 'text/plain')\n const bytes = Number(parsed.data.bytes ?? 0)\n const truncated = parsed.data.truncated === true\n const full = [\n `# Workflow Artifact`,\n `**Run ID:** \\`${input.runId}\\``,\n `**Artifact ID:** \\`${input.artifactId}\\``,\n `**Content-Type:** ${contentType}`,\n `**Bytes:** ${bytes}${truncated ? ` (truncated to ${input.maxBytes ?? 200000})` : ''}`,\n '',\n '```',\n text,\n '```',\n ].join('\\n')\n return {\n ...oneBlock(full),\n structuredContent: {\n runId: input.runId,\n artifactId: input.artifactId,\n contentType,\n bytes,\n truncated,\n text,\n },\n }\n}\n\nexport function formatCreditsInfo(raw: CallToolResult, input: { item?: string; includeLedger?: boolean }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as Record<string, unknown>\n\n const balance = d.balance_credits as number | undefined\n const costs = (d.costs as CreditCostEntry[] | undefined) ?? []\n const matched = d.matched_cost as CreditCostEntry | null\n const ledger = (d.ledger as CreditLedgerEntry[] | undefined) ?? []\n const concurrencyRaw = d.concurrency as Record<string, unknown> | undefined\n const upgradeRaw = concurrencyRaw?.upgrade as Record<string, unknown> | undefined\n\n const costRows = costs.map(c => {\n const notes = c.notes ? ` ${c.notes}` : ''\n return `| ${c.label} | ${c.credits} | ${c.unit}${notes} |`\n }).join('\\n')\n\n const ledgerRows = ledger.map(row => {\n const credits = row.amount_mc / 1000\n return `| ${row.created_at} | ${row.operation} | ${credits} | ${row.description ?? ''} |`\n }).join('\\n')\n\n const matchedSection = matched\n ? `\\n## Matched Cost\\n**${matched.label}:** ${matched.credits} credits ${matched.unit}${matched.notes ? `\\n\\n${matched.notes}` : ''}`\n : input.item\n ? `\\n## Matched Cost\\nNo exact cost match found for \"${input.item}\". See the full cost table below.`\n : ''\n\n const concurrencySection = concurrencyRaw\n ? [\n `\\n## Concurrency`,\n `**Current limit:** ${concurrencyRaw.current_limit ?? 'unknown'} concurrent operation${concurrencyRaw.current_limit === 1 ? '' : 's'}`,\n `**Extra slots:** ${concurrencyRaw.current_extra_slots ?? 'unknown'}`,\n `**Extra concurrency slot:** ${upgradeRaw?.price_label ?? '$5/month'}`,\n `**Upgrade in terminal:** \\`${upgradeRaw?.terminal_command ?? 'npx -y -p mcp-scraper@latest mcp-scraper-cli billing concurrency checkout'}\\``,\n `**Billing URL:** ${upgradeRaw?.billing_url ?? 'https://mcpscraper.dev/billing'}`,\n ].join('\\n')\n : ''\n\n const full = [\n `# Credits`,\n `**Balance:** ${balance ?? 'unknown'} credits`,\n matchedSection,\n concurrencySection,\n costs.length ? `\\n## Cost Table\\n| Item | Credits | Unit |\\n|------|---------|------|\\n${costRows}` : '',\n ledger.length ? `\\n## Recent Ledger\\n| Date | Operation | Credits | Description |\\n|------|-----------|---------|-------------|\\n${ledgerRows}` : '',\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n balanceCredits: typeof balance === 'number' ? balance : null,\n matchedCost: matched\n ? { label: matched.label, credits: matched.credits, unit: matched.unit, notes: matched.notes ?? null }\n : null,\n costs: costs.map(c => ({\n key: c.key,\n label: c.label,\n credits: c.credits,\n unit: c.unit,\n notes: c.notes ?? null,\n })),\n ledger: ledger.map(row => ({\n createdAt: String(row.created_at ?? ''),\n operation: String(row.operation ?? ''),\n credits: row.amount_mc / 1000,\n description: row.description ?? null,\n })),\n concurrency: concurrencyRaw && upgradeRaw\n ? {\n currentExtraSlots: Number(concurrencyRaw.current_extra_slots ?? 0),\n currentLimit: Number(concurrencyRaw.current_limit ?? 1),\n hasSubscription: concurrencyRaw.has_subscription === true,\n upgrade: {\n product: String(upgradeRaw.product ?? 'Extra concurrency slot'),\n priceLabel: String(upgradeRaw.price_label ?? '$5/month'),\n unitAmountUsd: Number(upgradeRaw.unit_amount_usd ?? 5),\n currency: String(upgradeRaw.currency ?? 'usd'),\n interval: String(upgradeRaw.interval ?? 'month'),\n billingUrl: String(upgradeRaw.billing_url ?? 'https://mcpscraper.dev/billing'),\n terminalCommand: String(upgradeRaw.terminal_command ?? 'npx -y -p mcp-scraper@latest mcp-scraper-cli billing concurrency checkout'),\n terminalCommandWithApiKeyEnv: String(upgradeRaw.terminal_command_with_api_key_env ?? 'MCP_SCRAPER_API_KEY=sk_live_your_key npx -y -p mcp-scraper@latest mcp-scraper-cli billing concurrency checkout'),\n },\n }\n : null,\n },\n }\n}\n\nexport function formatMapsSearch(\n raw: CallToolResult,\n input: { query: string; location?: string; maxResults?: number },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as Record<string, unknown>\n const results = (d.results as MapsSearchBusiness[]) ?? []\n const normalizedResults = results.map(result => ({\n ...result,\n phone: result.phone ?? null,\n hoursStatus: result.hoursStatus ?? null,\n }))\n const searchQuery = (d.searchQuery as string | undefined) ?? [input.query, input.location].filter(Boolean).join(' ')\n const requestedMax = (d.requestedMaxResults as number | undefined) ?? input.maxResults ?? 10\n const durationMs = d.durationMs as number | undefined\n const attempts = normalizeMapsAttempts(d.attempts)\n const lastAttempt = attempts.at(-1)\n\n const rows = results.map((r) => {\n const rating = [r.rating, r.reviewCount ? `(${r.reviewCount})` : null].filter(Boolean).join(' ')\n return `| ${r.position} | ${cell(r.name)} | ${cell(r.category)} | ${cell(rating)} | ${cell(r.address)} | ${r.cidDecimal ? `\\`${r.cidDecimal}\\`` : '—'} | ${r.websiteUrl ? `[site](${r.websiteUrl})` : '—'} | [maps](${r.placeUrl}) |`\n }).join('\\n')\n\n const metadataSection = results.length\n ? `\\n## Candidate Metadata\\n${results.map(r => {\n const meta = r.metadata?.length ? r.metadata.slice(0, 8).map(m => ` - ${m}`).join('\\n') : ' - none'\n return `### ${r.position}. ${r.name}\\n${meta}`\n }).join('\\n\\n')}`\n : ''\n\n const full = [\n `# Google Maps Search: \"${searchQuery}\"`,\n `**Returned:** ${results.length} profile candidate${results.length === 1 ? '' : 's'} · **Requested max:** ${requestedMax} · **Limit:** 50`,\n attempts.length ? `**Attempts:** ${attempts.length}/${lastAttempt?.maxAttempts ?? attempts.length} · **Proxy:** ${lastAttempt?.proxyMode ?? 'unknown'}${lastAttempt?.proxyResolutionSource ? `/${lastAttempt.proxyResolutionSource}` : ''} · **Observed:** ${[lastAttempt?.observedCity, lastAttempt?.observedRegion].filter(Boolean).join(', ') || 'unknown'}` : null,\n `\\n## Results\\n| # | Name | Category | Rating | Address | CID | Website | Maps |\\n|---|------|----------|--------|---------|-----|---------|------|\\n${rows}`,\n metadataSection,\n `\\n---\\n💡 **Next step:** use \\`maps_place_intel\\` with a selected business name and location to hydrate full hours, phone, review topics, and optional review cards.`,\n durationMs != null ? `\\n*Extracted in ${(durationMs / 1000).toFixed(1)}s*` : null,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n query: d.query,\n location: d.location ?? null,\n searchQuery: d.searchQuery,\n searchUrl: d.searchUrl,\n extractedAt: d.extractedAt,\n requestedMaxResults: requestedMax,\n resultCount: results.length,\n results: normalizedResults,\n attempts,\n durationMs: durationMs ?? 0,\n },\n }\n}\n\nexport function formatDirectoryWorkflow(\n raw: CallToolResult,\n input: { query: string; state?: string; minPopulation?: number; maxResultsPerCity?: number },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as Record<string, unknown>\n const cities = ((d.cities as DirectoryWorkflowCity[]) ?? []).map(city => ({\n ...city,\n attempts: normalizeMapsAttempts(city.attempts),\n results: city.results.map(result => ({\n ...result,\n phone: result.phone ?? null,\n hoursStatus: result.hoursStatus ?? null,\n })),\n }))\n const warnings = (d.warnings as string[] | undefined) ?? []\n const csvPath = (d.csvPath as string | null | undefined) ?? null\n const totalResultCount = (d.totalResultCount as number | undefined) ?? cities.reduce((sum, city) => sum + city.resultCount, 0)\n const durationMs = d.durationMs as number | undefined\n\n const marketRows = cities.map((city) => {\n const zips = city.zips?.length ? city.zips.slice(0, 8).join(' ') + (city.zips.length > 8 ? ` +${city.zips.length - 8}` : '') : '—'\n return `| ${cell(city.city)} | ${city.population.toLocaleString()} | ${city.zips?.length ?? 0} | ${city.resultCount} | ${city.status} | ${cell(zips)} |`\n }).join('\\n')\n\n const businessRows = cities\n .flatMap(city => city.results.slice(0, 3).map(result => ({ city, result })))\n .map(({ city, result }) => {\n const rating = [result.rating, result.reviewCount ? `(${result.reviewCount})` : null].filter(Boolean).join(' ')\n return `| ${cell(city.city)} | ${result.position} | ${cell(result.name)} | ${cell(result.category)} | ${cell(rating)} | ${result.websiteUrl ? `[site](${result.websiteUrl})` : '—'} | [maps](${result.placeUrl}) |`\n }).join('\\n')\n\n const warningText = warnings.length ? `\\n## Warnings\\n${warnings.map(w => `- ${w}`).join('\\n')}` : ''\n const csvText = csvPath ? `\\n**CSV:** \\`${csvPath}\\`` : ''\n const full = [\n `# Directory Workflow: ${input.query}`,\n `**Markets:** ${cities.length} · **Maps results:** ${totalResultCount} · **State:** ${d.state ?? input.state ?? 'US'} · **Population threshold:** ${d.minPopulation ?? input.minPopulation ?? 100000}`,\n csvText,\n `\\n## Markets\\n| City | Population | ZIPs | Maps Results | Status | ZIP Sample |\\n|---|---:|---:|---:|---|---|\\n${marketRows}`,\n businessRows ? `\\n## Top Candidates By City\\n| City | # | Name | Category | Rating | Website | Maps |\\n|---|---:|---|---|---|---|---|\\n${businessRows}` : null,\n warningText,\n `\\n## Sources\\n- Population: ${d.censusSourceUrl ?? 'Census Population Estimates Program'}\\n- ZIP groups: ${d.usZipsSourcePath ?? 'not configured'}`,\n durationMs != null ? `\\n*Completed in ${(durationMs / 1000).toFixed(1)}s*` : null,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n query: d.query,\n state: d.state,\n minPopulation: d.minPopulation,\n populationYear: d.populationYear,\n maxResultsPerCity: d.maxResultsPerCity,\n concurrency: d.concurrency,\n censusSourceUrl: d.censusSourceUrl,\n usZipsSourcePath: d.usZipsSourcePath ?? null,\n warnings,\n extractedAt: d.extractedAt,\n selectedCityCount: d.selectedCityCount,\n totalResultCount,\n csvPath,\n cities,\n durationMs: durationMs ?? 0,\n },\n }\n}\n\nexport function formatMapsPlaceIntel(\n raw: CallToolResult,\n input: { businessName: string; location: string; includeReviews?: boolean },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as Record<string, unknown>\n\n const name = (d.name as string | null) ?? input.businessName\n const rating = d.rating as string | null\n const reviewCount = d.reviewCount as string | null\n const category = d.category as string | null\n const address = d.address as string | null\n const phone = d.phoneDisplay as string | null\n const website = d.website as string | null\n const hoursSummary = d.hoursSummary as string | null\n const plusCode = d.plusCode as string | null\n const bookingUrl = d.bookingUrl as string | null\n const kgmid = d.kgmid as string | null\n const cidDecimal = d.cidDecimal as string | null\n const cidUrl = d.cidUrl as string | null\n const lat = d.lat as number | null\n const lng = d.lng as number | null\n const durationMs = d.durationMs as number | null\n\n const histogram = (d.reviewHistogram as MapsHistogramEntry[]) ?? []\n const topics = (d.reviewTopics as MapsTopicEntry[]) ?? []\n const about = (d.aboutAttributes as MapsAboutEntry[]) ?? []\n const reviews = (d.reviews as MapsReviewCard[]) ?? []\n const reviewsStatus = (d.reviewsStatus as ReviewsStatus | undefined) ?? 'not_requested'\n\n const hoursTable = (d.hoursTable as Array<{ day: string; hours: string }>) ?? []\n\n const ratingLine = [rating, reviewCount ? `(${reviewCount} reviews)` : null].filter(Boolean).join(' ')\n\n const basicLines = [\n address ? `- **Address:** ${address}` : null,\n phone ? `- **Phone:** ${phone}` : null,\n website ? `- **Website:** ${website}` : null,\n hoursSummary ? `- **Hours:** ${hoursSummary}` : null,\n plusCode ? `- **Plus Code:** ${plusCode}` : null,\n bookingUrl ? `- **Book:** ${bookingUrl}` : null,\n ].filter(Boolean).join('\\n')\n\n const hoursSection = hoursTable.length\n ? `\\n## Hours\\n| Day | Hours |\\n|-----|-------|\\n${hoursTable.map(r => `| ${r.day} | ${r.hours} |`).join('\\n')}`\n : ''\n\n const histSection = histogram.length\n ? `\\n## Rating Distribution\\n| Stars | Count |\\n|-------|-------|\\n${histogram.map(r => `| ${'★'.repeat(r.stars)}${'☆'.repeat(5 - r.stars)} | ${r.count} |`).join('\\n')}`\n : ''\n\n const topicsSection = topics.length\n ? `\\n## Review Topics\\n${topics.map(t => `- **${t.label}:** ${t.count} mentions`).join('\\n')}`\n : ''\n\n const aboutBySection: Record<string, string[]> = {}\n for (const a of about) {\n if (!aboutBySection[a.section]) aboutBySection[a.section] = []\n aboutBySection[a.section].push(a.attribute)\n }\n const aboutSection = Object.keys(aboutBySection).length\n ? `\\n## About\\n${Object.entries(aboutBySection).map(([s, attrs]) => `**${s}**\\n${attrs.map(a => `- ${a}`).join('\\n')}`).join('\\n\\n')}`\n : ''\n\n const entitySection = [\n kgmid ? `- **KGMID:** \\`${kgmid}\\`` : null,\n cidDecimal ? `- **CID:** \\`${cidDecimal}\\`` : null,\n cidUrl ? `- **Maps CID URL:** ${cidUrl}` : null,\n lat != null && lng != null ? `- **Coordinates:** ${lat}, ${lng}` : null,\n ].filter(Boolean).join('\\n')\n\n const reviewsSection = (() => {\n if (reviewsStatus === 'not_requested') return ''\n if (reviewsStatus === 'unavailable') return '\\n## Reviews\\n> Reviews could not be retrieved this run — retry with `includeReviews: true`.'\n if (reviewsStatus === 'none_exist') return '\\n## Reviews\\n*This business has no reviews on Google Maps.*'\n if (reviews.length === 0) return '\\n## Reviews\\n*0 reviews collected.*'\n return `\\n## Reviews (${reviews.length})\\n${reviews.map((r, i) => {\n const starsN = parseInt(r.stars ?? '0')\n const stars = '★'.repeat(starsN) + '☆'.repeat(5 - starsN)\n return `### ${i + 1}. ${r.author ?? 'Anonymous'} — ${stars}\\n*${r.date ?? ''}*\\n\\n${r.text ?? ''}`\n }).join('\\n\\n')}`\n })()\n\n const full = [\n `# ${name}`,\n category ? `*${category}*` : null,\n ratingLine ? `\\n**Rating:** ${ratingLine}` : null,\n basicLines ? `\\n${basicLines}` : null,\n hoursSection,\n histSection,\n topicsSection,\n aboutSection,\n entitySection ? `\\n## Entity IDs\\n${entitySection}` : null,\n reviewsSection,\n durationMs != null ? `\\n---\\n*Extracted in ${(durationMs / 1000).toFixed(1)}s*` : null,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n name,\n rating: rating ?? null,\n reviewCount: reviewCount ?? null,\n category: category ?? null,\n address: address ?? null,\n phone: phone ?? null,\n website: website ?? null,\n hoursSummary: hoursSummary ?? null,\n bookingUrl: bookingUrl ?? null,\n kgmid: kgmid ?? null,\n cidDecimal: cidDecimal ?? null,\n cidUrl: cidUrl ?? null,\n lat: lat ?? null,\n lng: lng ?? null,\n reviewsStatus,\n reviewsCollected: reviews.length,\n reviewTopics: topics.map(t => ({ label: String(t.label ?? ''), count: String(t.count ?? '') })),\n },\n }\n}\n\nexport function formatFacebookAdTranscribe(raw: CallToolResult, input: { videoUrl: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as TranscriptResult\n\n const text = d.text ?? ''\n const chunks = d.chunks ?? []\n const durSec = d.durationMs ? (d.durationMs / 1000).toFixed(0) : '—'\n const words = wordCount(text)\n\n const chunkRows = chunks.slice(0, 50).map(c => {\n const sec = Number.isFinite(c.timestamp[0]) ? Math.floor(c.timestamp[0]) : 0\n const mm = String(Math.floor(sec / 60)).padStart(2, '0')\n const ss = String(sec % 60).padStart(2, '0')\n return `| ${mm}:${ss} | ${cell(truncate(c.text, 120))} |`\n }).join('\\n')\n\n const full = [\n `# Facebook Ad Transcript`,\n `**Duration:** ${durSec}s · **${words} words**`,\n `\\n## Full Transcript\\n${text}`,\n chunks.length ? `\\n## Timestamped Chunks\\n| Time | Text |\\n|------|------|\\n${chunkRows}` : '',\n `\\n---\\n💡 Get more ads from this advertiser: use \\`facebook_page_intel\\`. For public Facebook reel/post URLs, use \\`facebook_video_transcribe\\`.`,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n videoUrl: input.videoUrl,\n wordCount: words,\n chunkCount: chunks.length,\n durationMs: typeof d.durationMs === 'number' ? d.durationMs : null,\n transcriptText: text,\n chunks: structuredTranscriptChunks(chunks),\n resolvedInputs: {\n videoUrl: input.videoUrl,\n },\n },\n }\n}\n\ninterface FacebookVideoTranscriptResult extends TranscriptResult {\n sourceUrl?: string\n pageUrl?: string\n videoId?: string | null\n ownerName?: string | null\n selectedQuality?: string\n bitrate?: number | null\n videoDurationSec?: number | null\n videoUrl?: string\n}\n\nexport function formatFacebookVideoTranscribe(raw: CallToolResult, input: { url: string; quality?: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as FacebookVideoTranscriptResult\n\n const text = d.text ?? ''\n const chunks = d.chunks ?? []\n const wordCount = text.trim() ? text.trim().split(/\\s+/).length : 0\n const durSec = d.durationMs ? (d.durationMs / 1000).toFixed(0) : '—'\n const videoDuration = typeof d.videoDurationSec === 'number' ? `${Math.round(d.videoDurationSec)}s` : '—'\n const label = d.videoId ? `Facebook Organic Video \\`${d.videoId}\\`` : 'Facebook Organic Video'\n\n const chunkRows = chunks.slice(0, 50).map(c => {\n const sec = Number.isFinite(c.timestamp[0]) ? Math.floor(c.timestamp[0]) : 0\n const mm = String(Math.floor(sec / 60)).padStart(2, '0')\n const ss = String(sec % 60).padStart(2, '0')\n return `| ${mm}:${ss} | ${cell(truncate(c.text, 120))} |`\n }).join('\\n')\n\n const full = [\n `# ${label} Transcript`,\n d.ownerName ? `**Owner:** ${d.ownerName}` : '',\n `**Video duration:** ${videoDuration} · **Transcribed in:** ${durSec}s · **${wordCount} words**`,\n d.pageUrl ? `**Page URL:** ${d.pageUrl}` : `**Page URL:** ${input.url}`,\n d.videoUrl ? `**Extracted MP4:** \\`${d.videoUrl}\\`` : '',\n `\\n## Full Transcript\\n${text}`,\n chunks.length ? `\\n## Timestamped Chunks\\n| Time | Text |\\n|------|------|\\n${chunkRows}` : '',\n `\\n---\\n💡 Use \\`videoUrl\\` as the extracted MP4 for download or follow-up processing. Use \\`facebook_ad_transcribe\\` only for Ad Library videoUrl values.`,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n sourceUrl: d.sourceUrl ?? input.url,\n pageUrl: d.pageUrl ?? input.url,\n videoId: d.videoId ?? null,\n ownerName: d.ownerName ?? null,\n selectedQuality: d.selectedQuality ?? input.quality ?? 'best',\n bitrate: typeof d.bitrate === 'number' ? d.bitrate : null,\n videoDurationSec: typeof d.videoDurationSec === 'number' ? d.videoDurationSec : null,\n videoUrl: d.videoUrl ?? '',\n wordCount,\n chunkCount: chunks.length,\n transcriptText: text,\n chunks: chunks.map(c => ({\n startSec: Number.isFinite(c.timestamp[0]) ? c.timestamp[0] : 0,\n endSec: Number.isFinite(c.timestamp[1]) ? c.timestamp[1] : 0,\n text: c.text,\n })),\n },\n }\n}\n\ninterface InstagramProfileItem {\n url: string\n type: 'post' | 'reel' | 'tv'\n shortcode: string\n anchorText?: string | null\n firstSeenStage?: string\n}\n\ninterface InstagramMediaTrack {\n url: string\n streamType: 'video' | 'audio' | 'unknown'\n bitrate?: number | null\n durationSec?: number | null\n vencodeTag?: string | null\n width?: number | null\n height?: number | null\n}\n\ninterface InstagramDownload {\n kind: 'text' | 'image' | 'video' | 'audio' | 'muxed_video'\n url: string | null\n savedPath: string | null\n sizeBytes: number | null\n mimeType: string | null\n error: string | null\n}\n\ninterface StructuredInstagramBrowser {\n mode: 'hosted'\n requestedMode: 'hosted'\n profileName: string | null\n profileSource: 'hosted'\n profileDirConfigured: boolean\n executablePathConfigured: boolean\n}\n\ninterface StructuredInstagramPagination {\n maxItems: number\n maxScrolls: number\n attemptedScrolls: number\n stableScrolls: number\n stableScrollLimit: number\n scrollDelayMs: number\n reachedMaxItems: boolean\n reachedReportedPostCount: boolean\n finalScrollHeight: number | null\n stoppedReason: 'max_items' | 'reported_post_count' | 'stable_scrolls' | 'max_scrolls' | 'no_scrolls'\n stages: Array<{\n stage: string\n itemCount: number\n addedCount: number\n scrollY: number | null\n scrollHeight: number | null\n }>\n}\n\nfunction structuredInstagramBrowser(raw: unknown): StructuredInstagramBrowser {\n const browser = raw && typeof raw === 'object' ? raw as Record<string, unknown> : {}\n return {\n mode: 'hosted',\n requestedMode: 'hosted',\n profileName: typeof browser.profileName === 'string' ? browser.profileName : null,\n profileSource: 'hosted',\n profileDirConfigured: false,\n executablePathConfigured: false,\n }\n}\n\nfunction structuredInstagramPagination(raw: unknown, input: { maxItems?: number; maxScrolls?: number; scrollDelayMs?: number; stableScrollLimit?: number }): StructuredInstagramPagination {\n const pagination = raw && typeof raw === 'object' ? raw as Record<string, unknown> : {}\n const stages = Array.isArray(pagination.stages) ? pagination.stages : []\n const stoppedReason = (typeof pagination.stoppedReason === 'string'\n && ['max_items', 'reported_post_count', 'stable_scrolls', 'max_scrolls', 'no_scrolls'].includes(pagination.stoppedReason)\n ? pagination.stoppedReason\n : 'no_scrolls') as StructuredInstagramPagination['stoppedReason']\n return {\n maxItems: typeof pagination.maxItems === 'number' ? pagination.maxItems : Number(input.maxItems ?? 50),\n maxScrolls: typeof pagination.maxScrolls === 'number' ? pagination.maxScrolls : Number(input.maxScrolls ?? 10),\n attemptedScrolls: typeof pagination.attemptedScrolls === 'number' ? pagination.attemptedScrolls : 0,\n stableScrolls: typeof pagination.stableScrolls === 'number' ? pagination.stableScrolls : 0,\n stableScrollLimit: typeof pagination.stableScrollLimit === 'number' ? pagination.stableScrollLimit : Number(input.stableScrollLimit ?? 4),\n scrollDelayMs: typeof pagination.scrollDelayMs === 'number' ? pagination.scrollDelayMs : Number(input.scrollDelayMs ?? 1200),\n reachedMaxItems: pagination.reachedMaxItems === true,\n reachedReportedPostCount: pagination.reachedReportedPostCount === true,\n finalScrollHeight: typeof pagination.finalScrollHeight === 'number' ? pagination.finalScrollHeight : null,\n stoppedReason,\n stages: stages.map((stage) => {\n const row = stage && typeof stage === 'object' ? stage as Record<string, unknown> : {}\n return {\n stage: String(row.stage ?? ''),\n itemCount: typeof row.itemCount === 'number' ? row.itemCount : 0,\n addedCount: typeof row.addedCount === 'number' ? row.addedCount : 0,\n scrollY: typeof row.scrollY === 'number' ? row.scrollY : null,\n scrollHeight: typeof row.scrollHeight === 'number' ? row.scrollHeight : null,\n }\n }),\n }\n}\n\nexport function formatInstagramProfileContent(\n raw: CallToolResult,\n input: { handle?: string; url?: string; maxItems?: number; maxScrolls?: number; scrollDelayMs?: number; stableScrollLimit?: number },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data\n const items = (Array.isArray(d.items) ? d.items : []) as InstagramProfileItem[]\n const typeCounts = d.typeCounts as Record<string, number> | undefined\n const limitations = Array.isArray(d.limitations) ? d.limitations.map(String) : []\n const browser = structuredInstagramBrowser(d.browser)\n const pagination = structuredInstagramPagination(d.pagination, input)\n const itemRows = items.slice(0, 100).map((item, i) =>\n `| ${i + 1} | ${item.type} | \\`${item.shortcode}\\` | ${item.url} | ${cell(item.firstSeenStage ?? '')} |`,\n ).join('\\n')\n const browserLabel = 'hosted browser'\n\n const full = [\n `# Instagram Profile Content: ${d.handle ?? input.handle ?? input.url ?? 'profile'}`,\n `**Collected:** ${items.length} items · posts ${typeCounts?.post ?? 0} · reels ${typeCounts?.reel ?? 0} · tv ${typeCounts?.tv ?? 0}`,\n `**Browser:** ${browserLabel}`,\n `**Pagination:** ${pagination.attemptedScrolls} scrolls · stopped: ${pagination.stoppedReason}`,\n d.reportedPostCountText ? `**Profile count:** ${d.reportedPostCountText}` : '',\n d.followerCountText ? `**Followers:** ${d.followerCountText}` : '',\n `\\n## Content Links\\n| # | Type | Shortcode | URL | First Seen |\\n|---|------|-----------|-----|------------|\\n${itemRows || '| — | — | — | — | — |'}`,\n limitations.length ? `\\n## Limits\\n${limitations.map(l => `- ${l}`).join('\\n')}` : '',\n `\\n---\\n💡 Use \\`instagram_media_download\\` with one of these URLs to download text, image, reel tracks, and optional transcript.`,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n handle: String(d.handle ?? input.handle ?? ''),\n profileUrl: String(d.profileUrl ?? input.url ?? ''),\n pageUrl: String(d.pageUrl ?? d.profileUrl ?? input.url ?? ''),\n browser,\n profileName: typeof d.profileName === 'string' ? d.profileName : null,\n reportedPostCount: typeof d.reportedPostCount === 'number' ? d.reportedPostCount : null,\n reportedPostCountText: typeof d.reportedPostCountText === 'string' ? d.reportedPostCountText : null,\n followerCountText: typeof d.followerCountText === 'string' ? d.followerCountText : null,\n followingCountText: typeof d.followingCountText === 'string' ? d.followingCountText : null,\n collectedContentCount: items.length,\n typeCounts: {\n post: Number(typeCounts?.post ?? 0),\n reel: Number(typeCounts?.reel ?? 0),\n tv: Number(typeCounts?.tv ?? 0),\n },\n pagination,\n limited: d.limited === true,\n limitations,\n items: items.map(item => ({\n url: String(item.url ?? ''),\n type: item.type,\n shortcode: String(item.shortcode ?? ''),\n anchorText: item.anchorText ?? null,\n firstSeenStage: String(item.firstSeenStage ?? ''),\n })),\n },\n }\n}\n\nfunction structuredInstagramTrack(track: InstagramMediaTrack | null | undefined): Record<string, unknown> | null {\n if (!track) return null\n return {\n url: String(track.url ?? ''),\n streamType: track.streamType ?? 'unknown',\n bitrate: typeof track.bitrate === 'number' ? track.bitrate : null,\n durationSec: typeof track.durationSec === 'number' ? track.durationSec : null,\n vencodeTag: track.vencodeTag ?? null,\n width: typeof track.width === 'number' ? track.width : null,\n height: typeof track.height === 'number' ? track.height : null,\n }\n}\n\nexport function formatInstagramMediaDownload(\n raw: CallToolResult,\n input: { url: string; includeTranscript?: boolean },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data\n const tracks = (Array.isArray(d.tracks) ? d.tracks : []) as InstagramMediaTrack[]\n const downloads = (Array.isArray(d.downloads) ? d.downloads : []) as InstagramDownload[]\n const warnings = Array.isArray(d.warnings) ? d.warnings.map(String) : []\n const limitations = Array.isArray(d.limitations) ? d.limitations.map(String) : []\n const transcript = d.transcript as TranscriptResult | null | undefined\n const transcriptText = transcript?.text ?? ''\n const chunks = transcript?.chunks ?? []\n const browser = structuredInstagramBrowser(d.browser)\n const browserLabel = 'hosted browser'\n\n const downloadRows = downloads.map((download, i) => {\n const status = download.error ? `error: ${cell(download.error)}` : `${download.sizeBytes ?? 0} bytes`\n return `| ${i + 1} | ${download.kind} | ${download.savedPath ? `\\`${download.savedPath}\\`` : '—'} | ${status} |`\n }).join('\\n')\n const trackRows = tracks.slice(0, 20).map((track, i) =>\n `| ${i + 1} | ${track.streamType} | ${track.bitrate ?? '—'} | ${track.durationSec ?? '—'} | ${cell(track.vencodeTag ?? '')} |`,\n ).join('\\n')\n\n const full = [\n `# Instagram Media Download`,\n `**URL:** ${d.pageUrl ?? input.url}`,\n `**Browser:** ${browserLabel}`,\n d.ownerName ? `**Owner:** ${d.ownerName}` : '',\n d.shortcode ? `**Shortcode:** \\`${d.shortcode}\\`` : '',\n d.caption ? `\\n## Caption\\n${truncate(String(d.caption), 1200)}` : '',\n d.imageUrl ? `\\n## Image\\n${d.imageUrl}` : '',\n tracks.length ? `\\n## Media Tracks\\n| # | Type | Bitrate | Duration | Tag |\\n|---|------|---------|----------|-----|\\n${trackRows}` : '\\n## Media Tracks\\n*None captured.*',\n downloads.length ? `\\n## Downloads\\n| # | Kind | File | Status |\\n|---|------|------|--------|\\n${downloadRows}` : '',\n d.outputDir ? `\\n**Output directory:** \\`${d.outputDir}\\`` : '',\n transcript ? `\\n## Transcript\\n**${wordCount(transcriptText)} words** · ${chunks.length} chunks\\n\\n${transcriptText}` : '',\n warnings.length ? `\\n## Warnings\\n${warnings.map(w => `- ${w}`).join('\\n')}` : '',\n limitations.length ? `\\n## Limits\\n${limitations.map(l => `- ${l}`).join('\\n')}` : '',\n `\\n---\\n💡 Reels may expose separate video-only and audio-only MP4 tracks. Use the muxed file when present; otherwise use the selected video/audio track URLs or saved files.`,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n sourceUrl: String(d.sourceUrl ?? input.url),\n pageUrl: String(d.pageUrl ?? input.url),\n browser,\n type: d.type === 'post' || d.type === 'reel' || d.type === 'tv' ? d.type : null,\n shortcode: typeof d.shortcode === 'string' ? d.shortcode : null,\n ownerName: typeof d.ownerName === 'string' ? d.ownerName : null,\n caption: typeof d.caption === 'string' ? d.caption : null,\n imageUrl: typeof d.imageUrl === 'string' ? d.imageUrl : null,\n trackCount: tracks.length,\n selectedVideoTrack: structuredInstagramTrack(d.selectedVideoTrack as InstagramMediaTrack | null | undefined),\n selectedAudioTrack: structuredInstagramTrack(d.selectedAudioTrack as InstagramMediaTrack | null | undefined),\n downloads: downloads.map(download => ({\n kind: download.kind,\n url: download.url ?? null,\n savedPath: download.savedPath ?? null,\n sizeBytes: typeof download.sizeBytes === 'number' ? download.sizeBytes : null,\n mimeType: download.mimeType ?? null,\n error: download.error ?? null,\n })),\n outputDir: typeof d.outputDir === 'string' ? d.outputDir : null,\n warnings,\n limitations,\n transcript: transcript ? {\n wordCount: wordCount(transcriptText),\n chunkCount: chunks.length,\n durationMs: typeof transcript.durationMs === 'number' ? transcript.durationMs : null,\n transcriptText,\n chunks: structuredTranscriptChunks(chunks),\n } : null,\n },\n }\n}\n\nexport function formatCaptureSerpSnapshot(\n raw: CallToolResult,\n input: Record<string, unknown>,\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data\n const providerPayload = d\n const organic = Array.isArray(d.organicResults) ? d.organicResults : Array.isArray(d.organic) ? d.organic : []\n const localPack = Array.isArray(d.localPack) ? d.localPack : []\n const artifacts = Array.isArray(d.artifacts) ? d.artifacts as Array<Record<string, unknown>> : []\n const status = String(d.status ?? d.captureStatus ?? 'captured')\n const query = typeof d.query === 'string' ? d.query : typeof input.query === 'string' ? input.query : null\n const location = typeof d.location === 'string' ? d.location : typeof input.location === 'string' ? input.location : null\n const capturedAt = typeof d.capturedAt === 'string'\n ? d.capturedAt\n : typeof d.extractedAt === 'string'\n ? d.extractedAt\n : null\n const resultCount = organic.length + localPack.length\n\n const full = [\n `# SERP Intelligence Snapshot: ${query ?? 'query'}`,\n `**Status:** ${status}`,\n location ? `**Location:** ${location}` : '',\n `**Result count:** ${resultCount}`,\n artifacts.length ? `**Artifacts:** ${artifacts.length}` : '',\n '',\n 'Use `capture_serp_page_snapshots` when you need page-level evidence for ranking URLs.',\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n schemaVersion: 'serp-intelligence.capture.v1',\n status,\n query,\n location,\n capturedAt,\n resultCount,\n snapshotId: typeof d.snapshotId === 'string'\n ? d.snapshotId\n : typeof d.snapshot_id === 'string'\n ? d.snapshot_id\n : typeof d.id === 'string'\n ? d.id\n : null,\n resolvedInputs: {\n query: input.query ?? null,\n location: input.location ?? null,\n gl: input.gl ?? null,\n hl: input.hl ?? null,\n device: input.device ?? null,\n proxyMode: input.proxyMode ?? null,\n proxyZip: input.proxyZip ?? null,\n pages: input.pages ?? null,\n },\n artifacts,\n diagnostics: d.diagnostics && typeof d.diagnostics === 'object' ? d.diagnostics as Record<string, unknown> : null,\n providerPayload,\n },\n }\n}\n\nexport function formatCaptureSerpPageSnapshots(\n raw: CallToolResult,\n input: Record<string, unknown>,\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data\n const captures = Array.isArray(d.captures)\n ? d.captures as Array<Record<string, unknown>>\n : Array.isArray(d.results)\n ? d.results as Array<Record<string, unknown>>\n : []\n const failedCount = captures.filter(c => c.status === 'failed' || c.error).length\n const status = String(d.status ?? (failedCount ? 'partial' : 'captured'))\n\n const rows = captures.slice(0, 25).map((capture, i) => {\n const url = typeof capture.url === 'string' ? capture.url : ''\n const sourceKind = typeof capture.sourceKind === 'string' ? capture.sourceKind : typeof capture.source_kind === 'string' ? capture.source_kind : 'configured_target'\n return `| ${i + 1} | ${cell(url)} | ${cell(sourceKind)} | ${cell(String(capture.status ?? (capture.error ? 'failed' : 'ok')))} |`\n }).join('\\n')\n\n const full = [\n '# SERP Intelligence Page Snapshots',\n `**Status:** ${status}`,\n `**Captured:** ${captures.length}`,\n `**Failed:** ${failedCount}`,\n captures.length ? `\\n| # | URL | Source | Status |\\n|---|-----|--------|--------|\\n${rows}` : '',\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n schemaVersion: 'serp-intelligence.page-snapshots.v1',\n status,\n count: captures.length,\n failedCount,\n captures,\n resolvedInputs: {\n urls: input.urls ?? null,\n targets: input.targets ?? null,\n maxConcurrency: input.maxConcurrency ?? null,\n timeoutMs: input.timeoutMs ?? null,\n debug: input.debug ?? null,\n },\n diagnostics: d.diagnostics && typeof d.diagnostics === 'object' ? d.diagnostics as Record<string, unknown> : null,\n providerPayload: d,\n },\n }\n}\n","export const RECAPTCHA_INSTRUCTIONS = 'Google returned a CAPTCHA. Run with --headless=false to re-warm the browser profile, then retry.'\n\nexport function sanitizeVendorName(message: string): string {\n return message\n .replace(/kernel\\.sh\\s+sessions?/gi, 'sessions')\n .replace(/kernel\\.sh\\s+session/gi, 'this session')\n .replace(/kernel\\.sh/gi, 'the service')\n .replace(/kernel\\s+sessions?/gi, 'sessions')\n .replace(/kernel\\s+session/gi, 'this session')\n .replace(/\\bkernel\\b/gi, 'the service')\n .replace(/ +/g, ' ')\n .trim()\n}\n\nexport class CaptchaError extends Error {\n readonly name = 'CaptchaError'\n constructor(public readonly instructions: string) {\n super(`CAPTCHA detected. ${instructions}`)\n }\n}\n\nexport class ExtractionError extends Error {\n readonly name = 'ExtractionError'\n constructor(message: string, public readonly cause?: unknown) {\n super(message)\n }\n}\n\nexport class RequestAbortedError extends Error {\n readonly name = 'RequestAbortedError'\n constructor(message = 'Request aborted before harvest completed') {\n super(message)\n }\n}\n\nexport class LocationMismatchError extends Error {\n readonly name = 'LocationMismatchError'\n constructor(message = 'Google returned results for a different location than requested') {\n super(message)\n }\n}\n","export type WorkflowRecipe = {\n id: string\n title: string\n description: string\n primaryWorkflowId: string | null\n recommendedTools: string[]\n requiredInputs: string[]\n optionalInputs: string[]\n produces: string[]\n runHint: string\n}\n\nexport const WORKFLOW_RECIPES: WorkflowRecipe[] = [\n {\n id: 'market_analysis',\n title: 'Market Analysis',\n description: 'Compare a niche across a city, state, or market set using Google Maps competitors, SERP evidence, review counts, categories, and opportunity signals.',\n primaryWorkflowId: 'local-competitive-audit',\n recommendedTools: ['workflow_run', 'directory_workflow', 'maps_search', 'maps_place_intel', 'search_serp', 'harvest_paa'],\n requiredInputs: ['query', 'state or location'],\n optionalInputs: ['domain', 'minPopulation', 'maxCities', 'maxResultsPerCity', 'hydrateTop', 'maxReviews'],\n produces: ['city summary', 'competitor CSV', 'review insight CSV', 'market difficulty/opportunity notes', 'HTML report'],\n runHint: 'Use workflow_run with workflowId local-competitive-audit for state-wide market batches, or map-comparison for one city/location comparison.',\n },\n {\n id: 'icp_research',\n title: 'ICP Research',\n description: 'Build an evidence packet for ideal-customer-profile research from real search demand, PAA language, competing pages, AI Overview citations, and source domains.',\n primaryWorkflowId: 'agent-packet',\n recommendedTools: ['workflow_run', 'harvest_paa', 'search_serp', 'extract_url', 'youtube_harvest', 'facebook_ad_search'],\n requiredInputs: ['keyword or audience problem'],\n optionalInputs: ['domain', 'location', 'maxQuestions'],\n produces: ['evidence JSON', 'sources CSV', 'competitor CSV', 'brief markdown', 'agent task list'],\n runHint: 'Use workflow_run with workflowId agent-packet. Treat keyword as the buyer problem, job-to-be-done, niche, or service category.',\n },\n {\n id: 'forum_review_research',\n title: 'Forum And Review Research',\n description: 'Acquire customer language from Google PAA, forum/Perspectives SERP surfaces, Google Maps reviews, review topics, Facebook ads, and video transcripts.',\n primaryWorkflowId: 'local-competitive-audit',\n recommendedTools: ['workflow_run', 'harvest_paa', 'maps_search', 'maps_place_intel', 'facebook_page_intel', 'facebook_video_transcribe', 'youtube_transcribe'],\n requiredInputs: ['query', 'state or location'],\n optionalInputs: ['maxReviews', 'maxQuestions', 'competitors', 'facebookUrl', 'youtubeVideoId'],\n produces: ['review insight CSV', 'PAA/source language', 'competitor review topics', 'transcripts where supplied', 'pain/theme summary'],\n runHint: 'Use local-competitive-audit for review acquisition, then harvest_paa for forum/Perspectives language and transcript tools for supplied videos.',\n },\n {\n id: 'brand_design_brief',\n title: 'Brand Design Brief',\n description: 'Create a design briefing grounded in a brand site, competitor pages, SERP language, audience pains, visual assets, colors, fonts, screenshots, and positioning evidence.',\n primaryWorkflowId: 'serp-comparison',\n recommendedTools: ['workflow_run', 'extract_url', 'extract_site', 'capture_serp_page_snapshots', 'search_serp', 'harvest_paa', 'browser_open'],\n requiredInputs: ['url or domain', 'keyword or market category'],\n optionalInputs: ['competitorUrls', 'location', 'extractTop'],\n produces: ['page comparison CSV', 'content gaps', 'branding/asset evidence', 'SERP positioning evidence', 'designer-ready brief'],\n runHint: 'Use workflow_run with workflowId serp-comparison for market/page evidence, then extract_url with extractBranding:true for brand assets and colors.',\n },\n {\n id: 'cro_audit',\n title: 'CRO Audit',\n description: 'Audit conversion clarity using page extraction, screenshots, browser DOM inspection, competitor SERP/page comparisons, forms/buttons, proof, offer, trust, and friction evidence.',\n primaryWorkflowId: 'serp-comparison',\n recommendedTools: ['workflow_run', 'extract_url', 'extract_site', 'capture_serp_page_snapshots', 'browser_open', 'browser_screenshot', 'browser_locate'],\n requiredInputs: ['url'],\n optionalInputs: ['keyword', 'domain', 'location', 'competitorUrls'],\n produces: ['page extraction', 'SERP/page comparison', 'screenshot evidence', 'friction checklist', 'CRO recommendations'],\n runHint: 'Use workflow_run with workflowId serp-comparison when a keyword/domain is known; use extract_url and browser tools for page-level CRO evidence.',\n },\n {\n id: 'competitive_positioning_brief',\n title: 'Competitive Positioning Brief',\n description: 'Compare competitors across SERP, PAA, AI Overview citations, page headings, Facebook ads, YouTube angles, Maps proof, and website claims.',\n primaryWorkflowId: 'serp-comparison',\n recommendedTools: ['workflow_run', 'facebook_ad_search', 'facebook_page_intel', 'youtube_harvest', 'youtube_transcribe', 'maps_search', 'extract_url'],\n requiredInputs: ['keyword or query', 'domain or url'],\n optionalInputs: ['location', 'extractTop', 'competitorUrls', 'brandNames'],\n produces: ['SERP comparison', 'content gap CSV', 'AI Overview citation table', 'competitor message map', 'positioning brief'],\n runHint: 'Use workflow_run with workflowId serp-comparison, then enrich with Facebook, YouTube, and Maps tools when the user asks for campaign or offer positioning.',\n },\n {\n id: 'content_gap_brief',\n title: 'Content Gap Brief',\n description: 'Turn live SERP, page extraction, PAA questions, AI Overview citations, and source-domain evidence into a writer-ready content brief.',\n primaryWorkflowId: 'serp-comparison',\n recommendedTools: ['workflow_run', 'paa-expansion-brief', 'harvest_paa', 'extract_url'],\n requiredInputs: ['keyword'],\n optionalInputs: ['domain', 'url', 'location', 'maxQuestions', 'extractTop'],\n produces: ['content gaps', 'page comparison CSV', 'PAA questions CSV', 'section map', 'writer brief'],\n runHint: 'Use workflow_run with workflowId serp-comparison for competitor gaps or paa-expansion-brief when the user mainly wants a section map from PAA data.',\n },\n {\n id: 'ai_search_visibility_audit',\n title: 'AI Search Visibility Audit',\n description: 'Audit whether a brand/domain appears in AI Overview citations, PAA sources, organic results, local pack, and source pages, then produce language guidance.',\n primaryWorkflowId: 'ai-overview-language',\n recommendedTools: ['workflow_run', 'search_serp', 'harvest_paa', 'extract_url', 'capture_serp_snapshot'],\n requiredInputs: ['keyword', 'domain or url'],\n optionalInputs: ['location', 'maxQuestions', 'extractTop'],\n produces: ['AI Overview citations CSV', 'claim patterns', 'language guidance', 'citation hooks', 'visibility gaps'],\n runHint: 'Use workflow_run with workflowId ai-overview-language. Use serp-comparison when the user also wants ranking-page gaps.',\n },\n]\n\nfunction normalize(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()\n}\n\nexport function suggestWorkflowRecipes(goal: string, limit = 3): WorkflowRecipe[] {\n const normalized = normalize(goal)\n const scored = WORKFLOW_RECIPES.map(recipe => {\n const haystack = normalize([\n recipe.id,\n recipe.title,\n recipe.description,\n recipe.requiredInputs.join(' '),\n recipe.optionalInputs.join(' '),\n recipe.produces.join(' '),\n ].join(' '))\n let score = 0\n for (const token of normalized.split(/\\s+/).filter(Boolean)) {\n if (haystack.includes(token)) score += 1\n }\n if (haystack.includes(normalized)) score += 5\n return { recipe, score }\n })\n return scored\n .sort((a, b) => b.score - a.score || a.recipe.title.localeCompare(b.recipe.title))\n .slice(0, Math.max(1, limit))\n .map(item => item.recipe)\n}\n","import { z } from 'zod'\nimport { DEFAULT_MAPS_PROXY_MODE, DEFAULT_PROXY_MODE } from '../schemas.js'\n\nexport const HarvestPaaInputSchema = {\n query: z.string().min(1).describe('Core search topic only. If the user says \"best hvac company in Denver CO\", use query=\"best hvac company\" and location=\"Denver, CO\". Do not include the location in query when it can be separated.'),\n location: z.string().optional().describe('City, region, or country for geo-targeted results, inferred from the user request when present, e.g. \"Denver, CO\", \"Tokyo, Japan\", \"London, UK\".'),\n maxQuestions: z.number().int().min(1).max(200).default(30).describe('Number of PAA questions to extract. Default 30. Maximum 200. Use 10 for quick probes, 30 for normal research, 100-200 when the user asks for everything/full/deep research. Larger harvests get a longer server time budget (151-200 questions → up to 280s). Credits are charged by extracted question; unused request hold is refunded.'),\n 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.'),\n 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.'),\n 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.'),\n proxyMode: z.enum(['location', 'configured', 'none']).default(DEFAULT_PROXY_MODE).describe('Proxy targeting mode. Default configured uses the service proxy without city/ZIP targeting for the highest general success rate. Use location only when the user explicitly needs city/ZIP-targeted residential proxy evidence. Use none only for direct-network debugging.'),\n proxyZip: z.string().regex(/^\\d{5}$/).optional().describe('Optional US ZIP override for residential location proxy targeting. Use only with proxyMode location when the user gives a specific ZIP or city-center targeting needs to be forced.'),\n debug: z.boolean().default(false).describe('Include sanitized browser/session/location diagnostics in the response. Use true when debugging localization, CAPTCHA, or proxy behavior.'),\n}\nexport type HarvestPaaInput = z.infer<ReturnType<typeof z.object<typeof HarvestPaaInputSchema>>>\n\nexport const ExtractUrlInputSchema = {\n url: z.string().url().describe('Public http/https URL to extract. Use this when the user provides one specific page URL.'),\n screenshot: z.boolean().default(false).describe('Also capture a full-page screenshot of the URL. Saved to ~/Downloads/mcp-scraper/screenshots/ and returned inline. Use when the user asks to see or capture the page visually.'),\n screenshotDevice: z.enum(['desktop', 'mobile']).default('desktop').describe('Viewport for screenshot. desktop = 1440×900. mobile = 390×844. Default desktop.'),\n extractBranding: z.boolean().default(false).describe('Extract brand colors, fonts, logo, and favicon using a rendered browser session. Returns colorScheme (light/dark), colors (primary/accent/background/text/heading as hex), fonts (heading/body family names), and assets (logo URL, favicon URL). Use when the user asks about brand colors, site theme, or brand assets.'),\n downloadMedia: z.boolean().default(false).describe('Extract and download all page media (images, video, audio) to ~/Downloads/mcp-scraper/media/. Ad networks, tracking pixels, and noise URLs are filtered automatically. Use when the user asks to download or harvest assets from a page.'),\n mediaTypes: z.array(z.enum(['image', 'video', 'audio'])).default(['image', 'video', 'audio']).describe('Which media types to download. Default all three.'),\n allowLocal: z.boolean().default(false).describe('Allow localhost and private-network URLs. For local development only.'),\n}\nexport type ExtractUrlInput = z.infer<ReturnType<typeof z.object<typeof ExtractUrlInputSchema>>>\n\nexport const MapSiteUrlsInputSchema = {\n url: z.string().url().describe('Public website URL or domain to crawl for internal URLs. Use before extract_site when the user asks to audit/map/crawl a site.'),\n maxUrls: z.number().int().min(1).max(500).optional().describe('Maximum URLs to discover. Use 100 for normal maps, higher when the user asks for a full inventory.'),\n}\nexport type MapSiteUrlsInput = z.infer<ReturnType<typeof z.object<typeof MapSiteUrlsInputSchema>>>\n\nexport const ExtractSiteInputSchema = {\n url: z.string().url().describe('Public website URL or domain to extract across multiple pages. Use when the user asks for a site audit, website crawl, or full-site content/schema extraction.'),\n maxPages: z.number().int().min(1).max(50).optional().describe('Maximum pages to extract. Use 50 when the user asks for full results or a complete crawl within MCP limits.'),\n}\nexport type ExtractSiteInput = z.infer<ReturnType<typeof z.object<typeof ExtractSiteInputSchema>>>\n\nexport const YoutubeHarvestInputSchema = {\n mode: z.enum(['search', 'channel']).describe('Use search for topic/keyword requests. Use channel when the user provides @handle, channel ID, or channel URL.'),\n query: z.string().optional().describe('Required when mode is search. The YouTube search topic in the user’s words.'),\n channelHandle: z.string().optional().describe('YouTube channel handle, channel ID, or URL. Examples: @mkbhd, UC..., https://youtube.com/@mkbhd.'),\n maxVideos: z.number().int().min(1).max(500).default(50).describe('Number of videos to return. Default 50, maximum 500. Use 10-25 for quick topic discovery, 50 for normal channel/search harvests, and larger values only when the user asks for full channel/history because large responses consume more context.'),\n}\nexport type YoutubeHarvestInput = z.infer<ReturnType<typeof z.object<typeof YoutubeHarvestInputSchema>>>\n\nexport const YoutubeTranscribeInputSchema = {\n videoId: z.string().min(1).optional().describe('YouTube video ID, e.g. dQw4w9WgXcQ. Use only an ID returned by youtube_harvest or visible in a YouTube URL; do not invent one.'),\n url: z.string().url().optional().describe('Full YouTube URL, e.g. https://www.youtube.com/watch?v=dQw4w9WgXcQ or https://youtu.be/dQw4w9WgXcQ. Use this when the user pasted a URL instead of an ID. Provide videoId or url.'),\n}\nexport type YoutubeTranscribeInput = z.infer<ReturnType<typeof z.object<typeof YoutubeTranscribeInputSchema>>>\n\nexport const FacebookPageIntelInputSchema = {\n pageId: z.string().optional().describe('Facebook advertiser/page ID. Use only a pageId returned by facebook_ad_search/facebook_page_intel or copied from Facebook Ad Library; do not construct one yourself.'),\n libraryId: z.string().optional().describe('Facebook Ad Library archive ID for a known ad or advertiser sample. Use a libraryId returned by facebook_ad_search, or a libraryId/adArchiveId visible in Ad Library.'),\n query: z.string().optional().describe('Advertiser or brand name when pageId/libraryId is not known. One of pageId, libraryId, or query is required.'),\n maxAds: z.number().int().min(1).max(200).default(50).describe('Maximum ads to inspect. Default 50, maximum 200. Prefer 25-50 for focused advertiser scans; use 100-200 only when the user asks for a broad ad archive sweep.'),\n country: z.string().length(2).default('US').describe('Two-letter Ad Library country code. Default US. Examples: US, CA, GB, AU. Infer from the user request when they name a country.'),\n}\nexport type FacebookPageIntelInput = z.infer<ReturnType<typeof z.object<typeof FacebookPageIntelInputSchema>>>\n\nexport const FacebookAdSearchInputSchema = {\n query: z.string().min(1).describe('Advertiser, brand, competitor, niche, or keyword to search in Facebook Ad Library.'),\n country: z.string().length(2).default('US').describe('Two-letter Ad Library country code. Default US. Examples: US, CA, GB, AU.'),\n maxResults: z.number().int().min(1).max(20).default(10).describe('Maximum advertisers to return. Default 10, maximum 20. Prefer tighter search terms over maxing this out.'),\n}\nexport type FacebookAdSearchInput = z.infer<ReturnType<typeof z.object<typeof FacebookAdSearchInputSchema>>>\n\nexport const FacebookAdTranscribeInputSchema = {\n videoUrl: z.string().url().describe('Direct Facebook CDN video URL from a facebook_page_intel ad result. Do not pass a public Facebook reel/post/share URL here; use facebook_video_transcribe for organic Facebook URLs.'),\n}\nexport type FacebookAdTranscribeInput = z.infer<ReturnType<typeof z.object<typeof FacebookAdTranscribeInputSchema>>>\n\nexport const FacebookVideoTranscribeInputSchema = {\n url: z.string().url().describe('Organic Facebook reel, video, watch, post, or share URL from facebook.com, m.facebook.com, or fb.watch. The tool renders the page, extracts the best matching public Facebook CDN MP4 URL, then transcribes it. Use this when the user pastes a normal Facebook video page URL and asks for the transcript or downloadable MP4.'),\n quality: z.enum(['best', 'hd', 'sd']).default('best').describe('Preferred progressive MP4 quality. Use best by default; hd prefers the highest HD progressive URL; sd forces the SD URL.'),\n}\nexport type FacebookVideoTranscribeInput = z.infer<ReturnType<typeof z.object<typeof FacebookVideoTranscribeInputSchema>>>\n\nexport const InstagramProfileContentInputSchema = {\n handle: z.string().min(1).optional().describe('Instagram handle, with or without @. Provide handle or url.'),\n url: z.string().url().optional().describe('Instagram profile URL, e.g. https://www.instagram.com/nasaartemis/. Provide handle or url.'),\n maxItems: z.number().int().min(1).max(500).default(50).describe('Maximum profile grid post/reel/tv URLs to collect. Default 50, maximum 500. Use higher values only when the user asks for a fuller archive.'),\n maxScrolls: z.number().int().min(0).max(100).default(10).describe('Maximum pagination scroll attempts. Default 10, maximum 100. Increase for long profiles when Instagram continues loading more grid links.'),\n scrollDelayMs: z.number().int().min(250).max(5000).default(1200).describe('Delay after each pagination scroll before collecting newly loaded links. Default 1200ms. Increase to 2000-3000ms when Instagram loads slowly.'),\n stableScrollLimit: z.number().int().min(1).max(10).default(4).describe('Stop after this many consecutive scrolls with no new links or scroll progress. Default 4.'),\n}\nexport type InstagramProfileContentInput = z.infer<ReturnType<typeof z.object<typeof InstagramProfileContentInputSchema>>>\n\nexport const InstagramMediaDownloadInputSchema = {\n url: z.string().url().describe('Instagram post, reel, or tv URL, e.g. https://www.instagram.com/reel/SHORTCODE/. The tool renders the page, extracts text, image metadata, and Instagram CDN media tracks.'),\n mediaTypes: z.array(z.enum(['image', 'video', 'audio'])).default(['image', 'video', 'audio']).describe('Which media types to download when downloadMedia is true. Reels commonly expose separate video-only and audio-only MP4 tracks.'),\n downloadMedia: z.boolean().default(true).describe('Download extracted text/media files to the MCP Scraper output directory when the API server can write files. Always returns extracted media URLs even when false.'),\n downloadAllTracks: z.boolean().default(false).describe('Download every captured Instagram MP4 track instead of only the selected best video and audio tracks. Use false by default to avoid duplicate bitrates.'),\n includeTranscript: z.boolean().default(false).describe('Transcribe the selected audio track when available. This adds transcription cost and may take longer.'),\n mux: z.boolean().default(true).describe('When video and audio tracks are downloaded separately, try to mux them into a single MP4 if ffmpeg is available. Returns separate tracks when muxing is unavailable.'),\n}\nexport type InstagramMediaDownloadInput = z.infer<ReturnType<typeof z.object<typeof InstagramMediaDownloadInputSchema>>>\n\nexport const MapsPlaceIntelInputSchema = {\n businessName: z.string().min(1).describe('Business name only. If user says \"Elite Roofing Denver CO\", use businessName=\"Elite Roofing\" and location=\"Denver, CO\".'),\n location: z.string().min(1).describe('City/region/country where the business should be searched, e.g. \"Denver, CO\". Infer from the user request when possible.'),\n gl: z.string().length(2).default('us').describe('Google country code inferred from location.'),\n hl: z.string().length(2).default('en').describe('Language inferred from user request.'),\n includeReviews: z.boolean().default(false).describe('Whether to fetch individual review cards. Use true when the user asks for reviews, customer pain, complaints, praise, themes, or review evidence.'),\n maxReviews: z.number().int().min(1).max(500).default(50).describe('Max review cards to return when includeReviews is true. Default 50, maximum 500. Use 50 for normal review analysis and larger values only for deep review mining.'),\n}\nexport type MapsPlaceIntelInput = z.infer<ReturnType<typeof z.object<typeof MapsPlaceIntelInputSchema>>>\n\nexport const MapsSearchInputSchema = {\n query: z.string().min(1).describe('Business category, niche, keyword, or search term. If the user says \"roofers in Denver CO\", use query=\"roofers\" and location=\"Denver, CO\". Do not put the location here when it can be separated.'),\n location: z.string().optional().describe('City, region, country, or service area for the Maps search, e.g. \"Denver, CO\". Infer from the user request when present.'),\n gl: z.string().length(2).default('us').describe('Google country code inferred from location.'),\n hl: z.string().length(2).default('en').describe('Language inferred from user request.'),\n 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.'),\n proxyMode: z.enum(['location', 'configured', 'none']).default(DEFAULT_MAPS_PROXY_MODE).describe('Proxy targeting mode. Maps defaults to location so local market searches get city/state residential proxy targeting and rotation. Use configured to force the service proxy without city/ZIP targeting, and none only for local direct-network debugging.'),\n 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.'),\n debug: z.boolean().default(false).describe('Include sanitized browser/proxy diagnostics when debugging Maps localization, CAPTCHA, or proxy behavior.'),\n}\nexport type MapsSearchInput = z.infer<ReturnType<typeof z.object<typeof MapsSearchInputSchema>>>\n\nexport const DirectoryWorkflowInputSchema = {\n query: z.string().min(1).describe('Business category, niche, or keyword to search on Google Maps for every selected market, e.g. roofers, dentists, med spas. Do not include the city here.'),\n state: z.string().min(2).default('TN').describe('US state abbreviation or state name used to select Census places, e.g. TN or Tennessee.'),\n minPopulation: z.number().int().min(0).default(100000).describe('Minimum Census place population for market selection. Use 100000 for \"cities above 100k population\".'),\n populationYear: z.number().int().min(2020).max(2025).default(2025).describe('Census population estimate year from the 2020-2025 Population Estimates Program city/place dataset.'),\n maxCities: z.number().int().min(1).max(100).default(25).describe('Maximum number of markets to process after sorting by population descending.'),\n maxResultsPerCity: z.number().int().min(1).max(50).default(50).describe('Google Maps business/profile candidates to collect for each city. Maximum 50.'),\n 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.'),\n 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.'),\n 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.'),\n 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.'),\n proxyMode: z.enum(['location', 'configured', 'none']).default(DEFAULT_MAPS_PROXY_MODE).describe('Proxy targeting mode for every city Maps search. Maps workflows default to location so each city can use city/state or ZIP-group residential proxy targeting. Use configured to force the service proxy without city/ZIP targeting, and none only for local direct-network debugging.'),\n proxyZip: z.string().regex(/^\\d{5}$/).optional().describe('Optional ZIP override for proxy targeting. Normally omit it so each city can use its ZIP group or city/state location.'),\n debug: z.boolean().default(false).describe('Include sanitized browser/proxy diagnostics in each Maps browser session when supported.'),\n}\nexport type DirectoryWorkflowInput = z.infer<ReturnType<typeof z.object<typeof DirectoryWorkflowInputSchema>>>\n\nexport const RankTrackerModeSchema = z.enum(['maps', 'organic', 'ai_overview', 'paa'])\nexport type RankTrackerMode = z.infer<typeof RankTrackerModeSchema>\n\nexport const RankTrackerBlueprintInputSchema = {\n projectName: z.string().min(1).optional().describe('Optional name for the rank tracker project, client, or campaign.'),\n targetDomain: z.string().min(1).optional().describe('Primary domain to track in organic results, AI Overview citations, and PAA sources, e.g. example.com.'),\n targetBusinessName: z.string().min(1).optional().describe('Primary Google Business Profile or brand/business name to match in Maps results. Required for reliable Maps rank tracking.'),\n trackingModes: z.array(RankTrackerModeSchema).min(1).max(4).default(['maps', 'organic', 'ai_overview', 'paa']).describe('Rank tracker surfaces to build. maps uses directory_workflow/maps_search. organic uses search_serp. ai_overview uses search_serp/harvest_paa. paa uses harvest_paa source presence.'),\n keywords: z.array(z.string().min(1)).max(200).default([]).describe('Seed keywords or service queries to track. Leave empty when the downstream AI should create the keyword table from user input.'),\n locations: z.array(z.string().min(1)).max(100).default([]).describe('Markets, cities, ZIPs, or service areas to track. Use city/state strings like Denver, CO for localized SERP and Maps checks.'),\n competitors: z.array(z.string().min(1)).max(100).default([]).describe('Optional competitor domains or business names to persist as comparison targets.'),\n database: z.enum(['postgres', 'neon', 'supabase', 'sqlite', 'mysql']).default('postgres').describe('Database family the downstream AI should target when generating migrations.'),\n scheduleCadence: z.enum(['daily', 'weekly', 'monthly', 'custom']).default('weekly').describe('Default recurring rank check cadence for the generated cron/heartbeat plan.'),\n customCron: z.string().min(1).optional().describe('Cron expression to use when scheduleCadence is custom.'),\n timezone: z.string().min(1).default('UTC').describe('IANA timezone for scheduled rank checks, e.g. America/Denver.'),\n includeCron: z.boolean().default(true).describe('Include a cron or heartbeat worker plan. Keep true for production rank trackers.'),\n includeDashboard: z.boolean().default(true).describe('Include dashboard/reporting requirements in the generated prompt.'),\n includeAlerts: z.boolean().default(true).describe('Include alert rules for rank movement and SERP feature gains/losses.'),\n notes: z.string().max(4000).optional().describe('Extra product, client, stack, or hosting requirements to include in the implementation prompt.'),\n}\nexport type RankTrackerBlueprintInput = z.infer<ReturnType<typeof z.object<typeof RankTrackerBlueprintInputSchema>>>\n\nconst NullableString = z.string().nullable()\n\nconst MapsSearchAttemptOutput = z.object({\n attemptNumber: z.number().int().min(1),\n maxAttempts: z.number().int().min(1),\n status: z.enum(['ok', 'failed']),\n outcome: z.string(),\n willRetry: z.boolean(),\n durationMs: z.number().int().min(0),\n resultCount: z.number().int().min(0),\n error: NullableString,\n proxyMode: z.enum(['location', 'configured', 'none']),\n proxyResolutionSource: z.enum(['disabled', 'location_reused', 'location_created', 'configured_fallback', 'unavailable']).nullable(),\n proxyIdSuffix: NullableString,\n proxyTargetLevel: z.enum(['zip', 'city', 'state']).nullable(),\n proxyTargetLocation: NullableString,\n proxyTargetZip: NullableString,\n browserSessionIdSuffix: NullableString,\n observedIp: NullableString,\n observedCity: NullableString,\n observedRegion: NullableString,\n})\n\nexport const MapsSearchOutputSchema = {\n query: z.string(),\n location: z.string().nullable(),\n searchQuery: z.string(),\n searchUrl: z.string().url(),\n extractedAt: z.string(),\n requestedMaxResults: z.number().int().min(1).max(50),\n resultCount: z.number().int().min(0).max(50),\n results: z.array(z.object({\n position: z.number().int().min(1),\n name: z.string(),\n placeUrl: z.string().url(),\n cid: NullableString,\n cidDecimal: NullableString,\n rating: NullableString,\n reviewCount: NullableString,\n category: NullableString,\n address: NullableString,\n phone: NullableString,\n hoursStatus: NullableString,\n websiteUrl: NullableString,\n directionsUrl: NullableString,\n metadata: z.array(z.string()),\n })),\n attempts: z.array(MapsSearchAttemptOutput),\n durationMs: z.number().int().min(0),\n}\n\nconst DirectoryMapsBusinessOutput = z.object({\n position: z.number().int().min(1),\n name: z.string(),\n placeUrl: z.string().url(),\n cid: NullableString,\n cidDecimal: NullableString,\n rating: NullableString,\n reviewCount: NullableString,\n category: NullableString,\n address: NullableString,\n phone: NullableString,\n hoursStatus: NullableString,\n websiteUrl: NullableString,\n directionsUrl: NullableString,\n metadata: z.array(z.string()),\n})\n\nexport const DirectoryWorkflowOutputSchema = {\n query: z.string(),\n state: z.string(),\n minPopulation: z.number().int().min(0),\n populationYear: z.number().int().min(2020).max(2025),\n maxResultsPerCity: z.number().int().min(1).max(50),\n concurrency: z.number().int().min(1).max(5),\n censusSourceUrl: z.string().url(),\n usZipsSourcePath: NullableString,\n warnings: z.array(z.string()),\n extractedAt: z.string(),\n selectedCityCount: z.number().int().min(0),\n totalResultCount: z.number().int().min(0),\n csvPath: NullableString,\n cities: z.array(z.object({\n city: z.string(),\n state: z.string(),\n location: z.string(),\n cityKey: z.string(),\n censusName: z.string(),\n population: z.number().int().min(0),\n populationYear: z.number().int().min(2020).max(2025),\n zips: z.array(z.string()),\n counties: z.array(z.string()),\n status: z.enum(['ok', 'empty', 'failed']),\n error: NullableString,\n resultCount: z.number().int().min(0),\n durationMs: z.number().int().min(0),\n attempts: z.array(MapsSearchAttemptOutput),\n results: z.array(DirectoryMapsBusinessOutput),\n })),\n durationMs: z.number().int().min(0),\n}\n\nconst RankTrackerToolPlanOutput = z.object({\n tool: z.string(),\n purpose: z.string(),\n})\n\nconst RankTrackerTableOutput = z.object({\n name: z.string(),\n purpose: z.string(),\n keyColumns: z.array(z.string()),\n})\n\nconst RankTrackerCronJobOutput = z.object({\n name: z.string(),\n purpose: z.string(),\n modes: z.array(RankTrackerModeSchema),\n recommendedTools: z.array(z.string()),\n})\n\nexport const RankTrackerBlueprintOutputSchema = {\n projectName: z.string(),\n targetDomain: NullableString,\n targetBusinessName: NullableString,\n trackingModes: z.array(RankTrackerModeSchema),\n database: z.string(),\n recommendedTools: z.array(RankTrackerToolPlanOutput),\n tables: z.array(RankTrackerTableOutput),\n cron: z.object({\n enabled: z.boolean(),\n cadence: z.string(),\n expression: z.string(),\n timezone: z.string(),\n jobs: z.array(RankTrackerCronJobOutput),\n }),\n metrics: z.array(z.string()),\n implementationPrompt: z.string(),\n}\n\nconst OrganicResultOutput = z.object({\n position: z.number().int(),\n title: z.string(),\n url: z.string(),\n domain: z.string(),\n snippet: NullableString,\n})\n\nconst AiOverviewOutput = z.object({\n detected: z.boolean(),\n text: NullableString,\n}).nullable()\n\nconst EntityIdsOutput = z.object({\n kgIds: z.array(z.string()),\n cids: z.array(z.string()),\n gcids: z.array(z.string()),\n}).nullable()\n\nexport const HarvestPaaOutputSchema = {\n query: z.string(),\n location: NullableString,\n questionCount: z.number().int().min(0),\n completionStatus: NullableString,\n questions: z.array(z.object({\n question: z.string(),\n answer: NullableString,\n sourceTitle: NullableString,\n sourceSite: NullableString,\n })),\n organicResults: z.array(OrganicResultOutput),\n aiOverview: AiOverviewOutput,\n entityIds: EntityIdsOutput,\n durationMs: z.number().min(0).nullable(),\n}\n\nexport const SearchSerpOutputSchema = {\n query: z.string(),\n location: NullableString,\n organicResults: z.array(OrganicResultOutput),\n localPack: z.array(z.object({\n position: z.number().int(),\n name: z.string(),\n rating: NullableString,\n reviewCount: NullableString,\n websiteUrl: NullableString,\n })),\n aiOverview: AiOverviewOutput,\n entityIds: EntityIdsOutput,\n}\n\nexport const ExtractUrlOutputSchema = {\n url: z.string(),\n title: NullableString,\n headings: z.array(z.object({\n level: z.number().int(),\n text: z.string(),\n })),\n schemaBlockCount: z.number().int().min(0),\n entityName: NullableString,\n entityTypes: z.array(z.string()),\n napScore: z.number().nullable(),\n missingSchemaFields: z.array(z.string()),\n screenshotSaved: NullableString,\n}\n\nexport const ExtractSiteOutputSchema = {\n url: z.string(),\n pageCount: z.number().int().min(0),\n pages: z.array(z.object({\n url: z.string(),\n title: NullableString,\n schemaTypes: z.array(z.string()),\n })),\n durationMs: z.number().min(0),\n}\n\nexport const MapsPlaceIntelOutputSchema = {\n name: z.string(),\n rating: NullableString,\n reviewCount: NullableString,\n category: NullableString,\n address: NullableString,\n phone: NullableString,\n website: NullableString,\n hoursSummary: NullableString,\n bookingUrl: NullableString,\n kgmid: NullableString,\n cidDecimal: NullableString,\n cidUrl: NullableString,\n lat: z.number().nullable(),\n lng: z.number().nullable(),\n reviewsStatus: z.string(),\n reviewsCollected: z.number().int().min(0),\n reviewTopics: z.array(z.object({\n label: z.string(),\n count: z.string(),\n })),\n}\n\nexport const CreditsInfoOutputSchema = {\n balanceCredits: z.number().nullable(),\n matchedCost: z.object({\n label: z.string(),\n credits: z.number(),\n unit: z.string(),\n notes: NullableString,\n }).nullable(),\n costs: z.array(z.object({\n key: z.string(),\n label: z.string(),\n credits: z.number(),\n unit: z.string(),\n notes: NullableString,\n })),\n ledger: z.array(z.object({\n createdAt: z.string(),\n operation: z.string(),\n credits: z.number(),\n description: NullableString,\n })),\n concurrency: z.object({\n currentExtraSlots: z.number().int().min(0),\n currentLimit: z.number().int().min(1),\n hasSubscription: z.boolean(),\n upgrade: z.object({\n product: z.string(),\n priceLabel: z.string(),\n unitAmountUsd: z.number(),\n currency: z.string(),\n interval: z.string(),\n billingUrl: z.string().url(),\n terminalCommand: z.string(),\n terminalCommandWithApiKeyEnv: z.string(),\n }),\n }).nullable(),\n}\n\nexport const MapSiteUrlsOutputSchema = {\n startUrl: z.string(),\n totalFound: z.number().int().min(0),\n truncated: z.boolean(),\n okCount: z.number().int().min(0),\n redirectCount: z.number().int().min(0),\n brokenCount: z.number().int().min(0),\n urls: z.array(z.object({\n url: z.string(),\n status: z.number().int().nullable(),\n })),\n durationMs: z.number().min(0),\n}\n\nexport const YoutubeHarvestOutputSchema = {\n mode: z.string(),\n videoCount: z.number().int().min(0),\n channel: z.object({\n title: NullableString,\n subscriberCount: NullableString,\n }).nullable(),\n videos: z.array(z.object({\n videoId: z.string(),\n title: z.string(),\n channelName: NullableString,\n views: NullableString,\n duration: NullableString,\n url: NullableString,\n })),\n}\n\nexport const FacebookAdSearchOutputSchema = {\n query: z.string(),\n advertiserCount: z.number().int().min(0),\n advertisers: z.array(z.object({\n name: NullableString,\n pageId: NullableString,\n pageUrl: NullableString,\n adCount: z.number().int().nullable(),\n libraryId: NullableString,\n sampleLibraryId: NullableString,\n })),\n}\n\nexport const FacebookPageIntelOutputSchema = {\n advertiserName: NullableString,\n totalAds: z.number().int().min(0),\n activeCount: z.number().int().min(0),\n videoCount: z.number().int().min(0),\n imageCount: z.number().int().min(0),\n ads: z.array(z.object({\n libraryId: NullableString,\n status: NullableString,\n creativeType: NullableString,\n primaryText: NullableString,\n headline: NullableString,\n cta: NullableString,\n startDate: NullableString,\n landingUrl: NullableString,\n domain: NullableString,\n videoUrl: NullableString,\n imageUrl: NullableString,\n videoPoster: NullableString,\n variations: z.number().int().nullable(),\n })),\n}\n\nexport const FacebookVideoTranscribeOutputSchema = {\n sourceUrl: z.string().url(),\n pageUrl: z.string().url(),\n videoId: NullableString,\n ownerName: NullableString,\n selectedQuality: z.string(),\n bitrate: z.number().int().nullable(),\n videoDurationSec: z.number().nullable(),\n videoUrl: z.string().url(),\n wordCount: z.number().int().min(0),\n chunkCount: z.number().int().min(0),\n transcriptText: z.string(),\n chunks: z.array(z.object({\n startSec: z.number(),\n endSec: z.number(),\n text: z.string(),\n })),\n}\n\nconst TranscriptChunkOutput = z.object({\n startSec: z.number(),\n endSec: z.number(),\n text: z.string(),\n})\n\nconst InstagramBrowserOutput = z.object({\n mode: z.literal('hosted'),\n requestedMode: z.literal('hosted'),\n profileName: NullableString,\n profileSource: z.literal('hosted'),\n profileDirConfigured: z.boolean(),\n executablePathConfigured: z.boolean(),\n})\n\nconst InstagramPaginationOutput = z.object({\n maxItems: z.number().int().min(1).max(500),\n maxScrolls: z.number().int().min(0).max(100),\n attemptedScrolls: z.number().int().min(0),\n stableScrolls: z.number().int().min(0),\n stableScrollLimit: z.number().int().min(1).max(10),\n scrollDelayMs: z.number().int().min(250).max(5000),\n reachedMaxItems: z.boolean(),\n reachedReportedPostCount: z.boolean(),\n finalScrollHeight: z.number().int().nullable(),\n stoppedReason: z.enum(['max_items', 'reported_post_count', 'stable_scrolls', 'max_scrolls', 'no_scrolls']),\n stages: z.array(z.object({\n stage: z.string(),\n itemCount: z.number().int().min(0),\n addedCount: z.number().int().min(0),\n scrollY: z.number().nullable(),\n scrollHeight: z.number().nullable(),\n })),\n})\n\nexport const InstagramProfileContentOutputSchema = {\n handle: z.string(),\n profileUrl: z.string().url(),\n pageUrl: z.string().url(),\n browser: InstagramBrowserOutput,\n profileName: NullableString,\n reportedPostCount: z.number().int().nullable(),\n reportedPostCountText: NullableString,\n followerCountText: NullableString,\n followingCountText: NullableString,\n collectedContentCount: z.number().int().min(0),\n typeCounts: z.object({\n post: z.number().int().min(0),\n reel: z.number().int().min(0),\n tv: z.number().int().min(0),\n }),\n pagination: InstagramPaginationOutput,\n limited: z.boolean(),\n limitations: z.array(z.string()),\n items: z.array(z.object({\n url: z.string().url(),\n type: z.enum(['post', 'reel', 'tv']),\n shortcode: z.string(),\n anchorText: NullableString,\n firstSeenStage: z.string(),\n })),\n}\n\nconst InstagramMediaTrackOutput = z.object({\n url: z.string().url(),\n streamType: z.enum(['video', 'audio', 'unknown']),\n bitrate: z.number().int().nullable(),\n durationSec: z.number().nullable(),\n vencodeTag: NullableString,\n width: z.number().int().nullable(),\n height: z.number().int().nullable(),\n})\n\nconst InstagramDownloadOutput = z.object({\n kind: z.enum(['text', 'image', 'video', 'audio', 'muxed_video']),\n url: z.string().url().nullable(),\n savedPath: NullableString,\n sizeBytes: z.number().int().nullable(),\n mimeType: NullableString,\n error: NullableString,\n})\n\nexport const InstagramMediaDownloadOutputSchema = {\n sourceUrl: z.string().url(),\n pageUrl: z.string().url(),\n browser: InstagramBrowserOutput,\n type: z.enum(['post', 'reel', 'tv']).nullable(),\n shortcode: NullableString,\n ownerName: NullableString,\n caption: NullableString,\n imageUrl: z.string().url().nullable(),\n trackCount: z.number().int().min(0),\n selectedVideoTrack: InstagramMediaTrackOutput.nullable(),\n selectedAudioTrack: InstagramMediaTrackOutput.nullable(),\n downloads: z.array(InstagramDownloadOutput),\n outputDir: NullableString,\n warnings: z.array(z.string()),\n limitations: z.array(z.string()),\n transcript: z.object({\n wordCount: z.number().int().min(0),\n chunkCount: z.number().int().min(0),\n durationMs: z.number().nullable(),\n transcriptText: z.string(),\n chunks: z.array(TranscriptChunkOutput),\n }).nullable(),\n}\n\nexport const YoutubeTranscribeOutputSchema = {\n videoId: NullableString,\n url: NullableString,\n wordCount: z.number().int().min(0),\n chunkCount: z.number().int().min(0),\n durationMs: z.number().nullable(),\n transcriptText: z.string(),\n chunks: z.array(TranscriptChunkOutput),\n resolvedInputs: z.object({\n videoId: NullableString,\n url: NullableString,\n }),\n}\n\nexport const FacebookAdTranscribeOutputSchema = {\n videoUrl: z.string().url(),\n wordCount: z.number().int().min(0),\n chunkCount: z.number().int().min(0),\n durationMs: z.number().nullable(),\n transcriptText: z.string(),\n chunks: z.array(TranscriptChunkOutput),\n resolvedInputs: z.object({\n videoUrl: z.string().url(),\n }),\n}\n\nexport const CaptureSerpSnapshotOutputSchema = {\n schemaVersion: z.literal('serp-intelligence.capture.v1'),\n status: z.string(),\n query: NullableString,\n location: NullableString,\n capturedAt: NullableString,\n resultCount: z.number().int().min(0).nullable(),\n snapshotId: NullableString,\n resolvedInputs: z.record(z.unknown()),\n artifacts: z.array(z.record(z.unknown())),\n diagnostics: z.record(z.unknown()).nullable(),\n providerPayload: z.record(z.unknown()),\n}\n\nexport const CaptureSerpPageSnapshotsOutputSchema = {\n schemaVersion: z.literal('serp-intelligence.page-snapshots.v1'),\n status: z.string(),\n count: z.number().int().min(0),\n failedCount: z.number().int().min(0),\n captures: z.array(z.record(z.unknown())),\n resolvedInputs: z.record(z.unknown()),\n diagnostics: z.record(z.unknown()).nullable(),\n providerPayload: z.record(z.unknown()),\n}\n\nexport const CreditsInfoInputSchema = {\n item: z.string().optional().describe('Optional tool, action, or feature to look up, e.g. \"maps reviews\", \"extract_url\", \"YouTube transcription\", or \"concurrency\"'),\n includeLedger: z.boolean().default(false).describe('Whether to include recent credit ledger entries'),\n}\nexport type CreditsInfoInput = z.infer<ReturnType<typeof z.object<typeof CreditsInfoInputSchema>>>\n\nexport const WorkflowIdSchema = z.enum([\n 'directory',\n 'agent-packet',\n 'local-competitive-audit',\n 'map-comparison',\n 'serp-comparison',\n 'paa-expansion-brief',\n 'ai-overview-language',\n])\nexport type WorkflowId = z.infer<typeof WorkflowIdSchema>\n\nexport const WorkflowListInputSchema = {\n includeRecipes: z.boolean().default(true).describe('Include high-level AI-facing recipes such as market analysis, ICP research, forum/review research, brand design briefings, CRO audits, positioning briefs, content gaps, and AI search visibility audits.'),\n}\nexport type WorkflowListInput = z.infer<ReturnType<typeof z.object<typeof WorkflowListInputSchema>>>\n\nexport const WorkflowSuggestInputSchema = {\n goal: z.string().min(1).describe('The user goal or job to route, e.g. \"market analysis for roofers in Tennessee\", \"ICP research for med spas\", \"CRO audit for this URL\", or \"brand design briefing\".'),\n query: z.string().optional().describe('Business category, niche, or Maps query when known.'),\n keyword: z.string().optional().describe('Search keyword, audience problem, or content topic when known.'),\n domain: z.string().optional().describe('Target domain or brand domain when known.'),\n url: z.string().url().optional().describe('Target URL when the workflow should inspect a specific page.'),\n location: z.string().optional().describe('City/region/country for localized research, e.g. Denver, CO.'),\n state: z.string().optional().describe('US state abbreviation or name for state-wide market research.'),\n maxSuggestions: z.number().int().min(1).max(8).default(3).describe('Number of matching workflow recipes to return.'),\n}\nexport type WorkflowSuggestInput = z.infer<ReturnType<typeof z.object<typeof WorkflowSuggestInputSchema>>>\n\nexport const WorkflowRunInputSchema = {\n workflowId: WorkflowIdSchema.describe('Workflow to run: directory, agent-packet, local-competitive-audit, map-comparison, serp-comparison, paa-expansion-brief, ai-overview-language. Use only these values; call workflow_list or workflow_suggest first when unsure.'),\n input: z.record(z.unknown()).default({}).describe('Workflow-specific input object. Examples: agent-packet uses {keyword, domain?, location?, maxQuestions?}; local-competitive-audit uses {query, state, minPopulation?, maxCities?, maxResultsPerCity?, hydrateTop?, maxReviews?}; serp-comparison uses {keyword, domain?, url?, location?, extractTop?}.'),\n webhookUrl: z.string().url().optional().describe('Optional HTTPS webhook to receive the completed hosted workflow run event.'),\n}\nexport type WorkflowRunInput = z.infer<ReturnType<typeof z.object<typeof WorkflowRunInputSchema>>>\n\nexport const WorkflowStepInputSchema = {\n runId: z.string().min(1).describe('Workflow run id returned by workflow_run, workflow_step, or workflow_status. Use only a returned runId; do not construct one yourself. Advances the run by exactly one step (one logical leg, e.g. one live harvest).'),\n}\nexport type WorkflowStepInput = z.infer<ReturnType<typeof z.object<typeof WorkflowStepInputSchema>>>\n\nexport const WorkflowStatusInputSchema = {\n runId: z.string().min(1).describe('Workflow run id returned by workflow_run, workflow_step, or workflow_status. Use only a returned runId; do not construct one yourself.'),\n}\nexport type WorkflowStatusInput = z.infer<ReturnType<typeof z.object<typeof WorkflowStatusInputSchema>>>\n\nexport const WorkflowArtifactReadInputSchema = {\n runId: z.string().min(1).describe('Workflow run id returned by workflow_run, workflow_step, or workflow_status. Use only a returned runId; do not construct one yourself.'),\n artifactId: z.string().min(1).describe('Artifact id from the run artifact list returned by workflow_run, workflow_step, or workflow_status. Use only a returned artifactId; do not construct one yourself.'),\n maxBytes: z.number().int().min(1_000).max(1_000_000).default(200_000).describe('Maximum bytes of artifact text to return inline. Use lower values for large CSV/JSON artifacts; call again with the downloadUrl if needed outside MCP.'),\n}\nexport type WorkflowArtifactReadInput = z.infer<ReturnType<typeof z.object<typeof WorkflowArtifactReadInputSchema>>>\n\nconst WorkflowRecipeOutput = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string(),\n primaryWorkflowId: z.string().nullable(),\n recommendedTools: z.array(z.string()),\n requiredInputs: z.array(z.string()),\n optionalInputs: z.array(z.string()),\n produces: z.array(z.string()),\n runHint: z.string(),\n})\n\nconst WorkflowDefinitionOutput = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string(),\n})\n\nconst WorkflowArtifactOutput = z.record(z.unknown())\n\nexport const WorkflowListOutputSchema = {\n workflows: z.array(WorkflowDefinitionOutput),\n recipes: z.array(WorkflowRecipeOutput),\n}\n\nexport const WorkflowSuggestOutputSchema = {\n goal: z.string(),\n suggestions: z.array(WorkflowRecipeOutput),\n}\n\nexport const WorkflowRunOutputSchema = {\n workflowId: z.string(),\n input: z.record(z.unknown()),\n run: z.record(z.unknown()).optional(),\n summary: z.record(z.unknown()).optional(),\n step: z.record(z.unknown()).optional(),\n nextStep: z.record(z.unknown()).nullable().optional(),\n done: z.boolean().optional(),\n artifacts: z.array(WorkflowArtifactOutput),\n}\n\nexport const WorkflowStepOutputSchema = {\n runId: z.string(),\n run: z.record(z.unknown()).optional(),\n summary: z.record(z.unknown()).nullable().optional(),\n step: z.record(z.unknown()).optional(),\n nextStep: z.record(z.unknown()).nullable().optional(),\n done: z.boolean(),\n artifacts: z.array(WorkflowArtifactOutput),\n}\n\nexport const WorkflowStatusOutputSchema = {\n run: z.record(z.unknown()).optional(),\n artifacts: z.array(WorkflowArtifactOutput),\n}\n\nexport const WorkflowArtifactReadOutputSchema = {\n runId: z.string(),\n artifactId: z.string(),\n contentType: z.string(),\n bytes: z.number().int().min(0),\n truncated: z.boolean(),\n text: z.string(),\n}\n\nexport const SearchSerpInputSchema = {\n query: z.string().min(1).describe('Core search topic only. Separate location when possible. If user says \"best dentist in Brooklyn NY serp\", use query=\"best dentist\" and location=\"Brooklyn, NY\".'),\n location: z.string().optional().describe('City, region, or country for geo-targeted results, inferred from user request when present.'),\n gl: z.string().length(2).default('us').describe('Google country code inferred from location or user language.'),\n hl: z.string().default('en').describe('Google interface/content language inferred from user request.'),\n 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.'),\n proxyMode: z.enum(['location', 'configured', 'none']).default(DEFAULT_PROXY_MODE).describe('Proxy targeting mode. Default configured uses the service proxy without city/ZIP targeting for the highest general SERP success rate. Use location only when the user explicitly needs city/ZIP-targeted residential proxy evidence. Use none only for direct-network debugging.'),\n proxyZip: z.string().regex(/^\\d{5}$/).optional().describe('Optional US ZIP override for residential location proxy targeting. Use only with proxyMode location when the user gives a specific ZIP or city-center targeting needs to be forced.'),\n debug: z.boolean().default(false).describe('Include sanitized browser/session/location diagnostics in the response. Use true when debugging localization, CAPTCHA, or proxy behavior.'),\n pages: z.number().int().min(1).max(2).default(1).describe('Number of result pages to fetch (1–2)'),\n}\nexport type SearchSerpInput = z.infer<ReturnType<typeof z.object<typeof SearchSerpInputSchema>>>\n\nexport const CaptureSerpSnapshotInputSchema = {\n query: z.string().min(1).describe('Core search query to capture as a structured SERP Intelligence snapshot. Separate the place into location when the user gives a city, region, country, or ZIP.'),\n location: z.string().optional().describe('City, region, country, or service area used for localized Google results. MCP Scraper records location evidence; UULE alone is not proof of localization.'),\n gl: z.string().length(2).default('us').describe('Google country code inferred from the requested market, e.g. us, gb, ca, au.'),\n hl: z.string().default('en').describe('Google interface/content language inferred from the user request.'),\n 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.'),\n proxyMode: z.enum(['location', 'configured', 'none']).default(DEFAULT_PROXY_MODE).describe('Proxy behavior for capture. Default configured uses the service proxy without city/ZIP targeting for the highest general capture success rate. Use location only when the user explicitly needs city/ZIP-targeted residential proxy evidence. Use none only for direct-network debugging.'),\n proxyZip: z.string().regex(/^\\d{5}$/).optional().describe('Optional US ZIP override for residential location proxy targeting. Use only with proxyMode location when a precise city-center or ZIP proxy is needed.'),\n 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.'),\n debug: z.boolean().default(false).describe('Include sanitized browser, proxy, and location diagnostics. Use true when debugging localization, CAPTCHA, proxy selection, or capture reliability.'),\n includePageSnapshots: z.boolean().default(false).describe('Also capture ranking-page snapshots for selected SERP URLs through the same product capture path.'),\n pageSnapshotLimit: z.number().int().min(0).max(10).default(0).describe('Maximum ranking-page snapshots to capture when includePageSnapshots is true. Use 0 when only SERP evidence is needed.'),\n}\nexport type CaptureSerpSnapshotInput = z.infer<ReturnType<typeof z.object<typeof CaptureSerpSnapshotInputSchema>>>\n\nexport const ScreenshotInputSchema = {\n url: z.string().url().describe('URL to capture as a full-page screenshot. Use http or https. Pass allowLocal: true to capture localhost or private-network URLs during development.'),\n device: z.enum(['desktop', 'mobile']).default('desktop').describe('Viewport profile. desktop = 1440×900. mobile = 390×844. Use desktop by default; use mobile when the user asks for a mobile view.'),\n allowLocal: z.boolean().default(false).describe('Allow localhost and private-network URLs (127.x, 192.168.x, 10.x, etc.). For local development only — not for production use.'),\n}\nexport type ScreenshotInput = z.infer<ReturnType<typeof z.object<typeof ScreenshotInputSchema>>>\n\nexport const CaptureSerpPageSnapshotsInputSchema = {\n urls: z.array(z.string().url()).min(1).max(25).describe('Public HTTP/HTTPS URLs to capture as SERP Intelligence page snapshots. Do not pass localhost, private IPs, file URLs, or internal admin URLs.'),\n targets: z.array(z.object({\n url: z.string().url().describe('Public HTTP/HTTPS URL to capture.'),\n sourceKind: z.enum(['organic', 'ai_citation', 'local_pack_website', 'configured_target', 'site_subject']).default('configured_target').describe('Why this page is being captured for SERP Intelligence evidence.'),\n sourcePosition: z.number().int().min(1).optional().describe('Ranking or citation position when the page came from SERP evidence.'),\n }).strict()).min(1).max(25).optional().describe('Structured page snapshot targets. Use this instead of urls when source kind or position should be preserved.'),\n maxConcurrency: z.number().int().min(1).max(5).default(2).describe('Parallel page captures. Use 2 normally; higher values can increase proxy/browser pressure.'),\n timeoutMs: z.number().int().min(1_000).max(60_000).default(15_000).describe('Per-page capture timeout in milliseconds. Increase for slow pages; timeout artifacts are returned as structured capture failures.'),\n debug: z.boolean().default(false).describe('Include sanitized browser/proxy diagnostics for page snapshot debugging. Use true for capture, network, or proxy troubleshooting.'),\n}\nexport type CaptureSerpPageSnapshotsInput = z.infer<ReturnType<typeof z.object<typeof CaptureSerpPageSnapshotsInputSchema>>>\n","import { z } from 'zod'\n\nexport const DEFAULT_PROXY_MODE = 'configured' as const\nexport const DEFAULT_MAPS_PROXY_MODE = 'location' as const\n\nexport const HarvestOptionsSchema = z.object({\n query: z.string().min(1),\n location: z.string().optional(),\n gl: z.string().length(2).default('us'),\n hl: z.string().length(2).default('en'),\n device: z.enum(['desktop', 'mobile']).default('desktop'),\n proxyMode: z.enum(['location', 'configured', 'none']).default(DEFAULT_PROXY_MODE),\n proxyZip: z.string().regex(/^\\d{5}$/).optional(),\n debug: z.boolean().default(false),\n depth: z.number().int().min(1).max(30).default(3),\n maxQuestions: z.number().int().min(1).max(1000).default(100),\n headless: z.boolean().default(false),\n profileDir: z.string().optional(),\n proxy: z.string().url().optional(),\n kernelApiKey: z.string().optional(),\n kernelProxyId: z.string().optional(),\n kernelProxyResolution: z.unknown().optional(),\n outputDir: z.string().default('./paa-output'),\n format: z.enum(['json', 'csv', 'both']).default('both'),\n serpOnly: z.boolean().default(false),\n pages: z.number().int().min(1).max(2).default(1),\n})\n\nexport const MapsPlaceOptionsSchema = z.object({\n businessName: z.string().min(1),\n location: z.string().min(1),\n gl: z.string().length(2).default('us'),\n hl: z.string().length(2).default('en'),\n includeReviews: z.boolean().default(false),\n maxReviews: z.number().int().min(1).max(500).default(50),\n kernelApiKey: z.string().optional(),\n kernelProxyId: z.string().optional(),\n headless: z.boolean().default(true),\n})\n\nexport const MapsSearchOptionsSchema = z.object({\n query: z.string().min(1),\n location: z.string().optional(),\n gl: z.string().length(2).default('us'),\n hl: z.string().length(2).default('en'),\n maxResults: z.number().int().min(1).max(50).default(10),\n proxyMode: z.enum(['location', 'configured', 'none']).default(DEFAULT_MAPS_PROXY_MODE),\n proxyZip: z.string().regex(/^\\d{5}$/).optional(),\n debug: z.boolean().default(false),\n kernelApiKey: z.string().optional(),\n kernelProxyId: z.string().optional(),\n kernelProxyResolution: z.unknown().optional(),\n headless: z.boolean().default(true),\n})\n\nexport const RawPAAItemSchema = z.object({\n question: z.string().min(1),\n answer: z.string().optional(),\n sourceTitle: z.string().optional(),\n sourceSite: z.string().optional(),\n sourceCite: z.string().optional(),\n})\n\nexport const RawMapsOverviewSchema = z.object({\n name: z.string().nullable(),\n rating: z.string().nullable(),\n reviewCount: z.string().nullable(),\n category: z.string().nullable(),\n address: z.string().nullable(),\n hoursSummary: z.string().nullable(),\n phone: z.string().nullable(),\n phoneDisplay: z.string().nullable(),\n website: z.string().nullable(),\n plusCode: z.string().nullable(),\n bookingUrl: z.string().nullable(),\n})\n\nexport const RawMapsHoursRowSchema = z.object({\n day: z.string(),\n hours: z.string(),\n})\n\nexport const RawMapsReviewStatsSchema = z.object({\n reviewHistogram: z.array(z.object({\n stars: z.number(),\n count: z.string(),\n })),\n reviewTopics: z.array(z.object({\n label: z.string(),\n count: z.string(),\n })),\n})\n\nexport const RawMapsReviewCardSchema = z.object({\n reviewId: z.string(),\n author: z.string().nullable(),\n stars: z.string().nullable(),\n date: z.string().nullable(),\n text: z.string().nullable(),\n ownerResponse: z.string().nullable(),\n})\n\nexport const RawMapsAboutAttributeSchema = z.object({\n section: z.string(),\n attribute: z.string(),\n})\n","import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'\nimport type { RankTrackerBlueprintInput, RankTrackerMode } from './mcp-tool-schemas.js'\n\ntype ToolPlan = {\n tool: string\n purpose: string\n}\n\ntype TablePlan = {\n name: string\n purpose: string\n keyColumns: string[]\n}\n\ntype CronJobPlan = {\n name: string\n purpose: string\n modes: RankTrackerMode[]\n recommendedTools: string[]\n}\n\ntype RankTrackerBlueprint = {\n projectName: string\n targetDomain: string | null\n targetBusinessName: string | null\n trackingModes: RankTrackerMode[]\n database: string\n recommendedTools: ToolPlan[]\n tables: TablePlan[]\n cron: {\n enabled: boolean\n cadence: string\n expression: string\n timezone: string\n jobs: CronJobPlan[]\n }\n metrics: string[]\n implementationPrompt: string\n}\n\nconst DEFAULT_MODES: RankTrackerMode[] = ['maps', 'organic', 'ai_overview', 'paa']\n\nfunction normalizeDomain(value?: string): string | null {\n const trimmed = value?.trim()\n if (!trimmed) return null\n try {\n const url = new URL(trimmed.includes('://') ? trimmed : `https://${trimmed}`)\n return url.hostname.replace(/^www\\./, '').toLowerCase()\n } catch {\n return trimmed.replace(/^https?:\\/\\//, '').replace(/^www\\./, '').split('/')[0]?.toLowerCase() || trimmed\n }\n}\n\nfunction uniqueModes(input?: RankTrackerMode[]): RankTrackerMode[] {\n const modes = input?.length ? input : DEFAULT_MODES\n return [...new Set(modes)]\n}\n\nfunction cronExpression(cadence: RankTrackerBlueprintInput['scheduleCadence'], customCron?: string): string {\n if (cadence === 'daily') return '15 6 * * *'\n if (cadence === 'monthly') return '15 6 1 * *'\n if (cadence === 'custom') return customCron?.trim() || 'CUSTOM_CRON_EXPRESSION_REQUIRED'\n return '15 6 * * 1'\n}\n\nfunction includes(modes: RankTrackerMode[], mode: RankTrackerMode): boolean {\n return modes.includes(mode)\n}\n\nfunction buildToolPlan(modes: RankTrackerMode[]): ToolPlan[] {\n const plans: ToolPlan[] = []\n const push = (tool: string, purpose: string) => {\n if (!plans.some((plan) => plan.tool === tool)) plans.push({ tool, purpose })\n }\n\n push('credits_info', 'Check account balance and rates before scheduling recurring rank checks.')\n\n if (includes(modes, 'maps')) {\n push('directory_workflow', 'Seed or refresh city-by-city Maps datasets when building local market coverage.')\n push('maps_search', 'Run recurring Google Maps category checks for each keyword and location.')\n push('maps_place_intel', 'Hydrate selected target or competitor GBP details when profile-level evidence is needed.')\n }\n if (includes(modes, 'organic')) {\n push('search_serp', 'Capture localized organic rankings, local pack data, and AI Overview status without PAA expansion.')\n }\n if (includes(modes, 'ai_overview')) {\n push('search_serp', 'Capture quick AI Overview detection and organic context for each tracked query.')\n push('harvest_paa', 'Use when AI Overview text, PAA context, or source-level evidence needs deeper capture.')\n }\n if (includes(modes, 'paa')) {\n push('harvest_paa', 'Capture People Also Ask questions, answers, and source sites for PAA presence tracking.')\n }\n\n return plans\n}\n\nfunction buildTables(modes: RankTrackerMode[], includeDashboard: boolean, includeAlerts: boolean, hasCompetitors: boolean): TablePlan[] {\n const tables: TablePlan[] = [\n {\n name: 'rank_tracker_projects',\n purpose: 'One row per client, campaign, or tracked property.',\n keyColumns: ['id', 'name', 'target_domain', 'target_business_name', 'database_mode', 'timezone', 'created_at'],\n },\n {\n name: 'rank_tracker_targets',\n purpose: 'Normalized target identities and match rules for domains, URLs, business names, CIDs, and competitors.',\n keyColumns: ['id', 'project_id', 'kind', 'value', 'display_name', 'match_rules_json', 'active'],\n },\n {\n name: 'rank_tracker_keywords',\n purpose: 'Tracked keywords or service queries, separated from location so calls can localize correctly.',\n keyColumns: ['id', 'project_id', 'keyword', 'intent', 'tags_json', 'active'],\n },\n {\n name: 'rank_tracker_locations',\n purpose: 'Markets, cities, ZIPs, country/language settings, and proxy targeting hints.',\n keyColumns: ['id', 'project_id', 'label', 'gl', 'hl', 'proxy_zip', 'device', 'active'],\n },\n {\n name: 'rank_tracker_runs',\n purpose: 'Heartbeat table for every scheduled or manual rank check batch.',\n keyColumns: ['id', 'project_id', 'scheduled_for', 'started_at', 'completed_at', 'status', 'idempotency_key', 'error_message'],\n },\n ]\n\n if (includes(modes, 'organic')) {\n tables.push({\n name: 'rank_tracker_organic_results',\n purpose: 'SERP organic result rows from search_serp, including target-domain matches and competitor rows.',\n keyColumns: ['id', 'run_id', 'keyword_id', 'location_id', 'device', 'position', 'title', 'url', 'domain', 'is_target'],\n })\n }\n\n if (includes(modes, 'maps')) {\n tables.push({\n name: 'rank_tracker_maps_results',\n purpose: 'Google Maps result rows from maps_search and directory_workflow, including GBP identity fields.',\n keyColumns: ['id', 'run_id', 'keyword_id', 'location_id', 'position', 'business_name', 'place_url', 'cid', 'website_url', 'rating', 'review_count', 'is_target'],\n })\n tables.push({\n name: 'rank_tracker_market_seeds',\n purpose: 'Directory workflow city, population, ZIP-group, and market seed records used to build local tracking coverage.',\n keyColumns: ['id', 'project_id', 'query', 'city', 'state', 'population', 'zip_group_json', 'last_seeded_run_id'],\n })\n }\n\n if (includes(modes, 'ai_overview')) {\n tables.push({\n name: 'rank_tracker_ai_overviews',\n purpose: 'AI Overview detection, text snapshot, citation domains, and target citation status per query/location.',\n keyColumns: ['id', 'run_id', 'keyword_id', 'location_id', 'detected', 'target_cited', 'cited_domains_json', 'overview_text'],\n })\n }\n\n if (includes(modes, 'paa')) {\n tables.push({\n name: 'rank_tracker_paa_sources',\n purpose: 'People Also Ask questions, answers, and source sites, with target source presence flags.',\n keyColumns: ['id', 'run_id', 'keyword_id', 'location_id', 'question', 'answer', 'source_title', 'source_site', 'target_present'],\n })\n }\n\n if (hasCompetitors) {\n tables.push({\n name: 'rank_tracker_competitor_snapshots',\n purpose: 'Per-run competitor visibility summaries across organic, Maps, AI Overview, and PAA surfaces.',\n keyColumns: ['id', 'run_id', 'target_id', 'surface', 'best_position', 'presence_count', 'share_of_surface'],\n })\n }\n\n if (includeDashboard) {\n tables.push({\n name: 'rank_tracker_daily_metrics',\n purpose: 'Rollup table for dashboard charts, trend lines, and share-of-visibility summaries.',\n keyColumns: ['id', 'project_id', 'metric_date', 'keyword_id', 'location_id', 'surface', 'metric_name', 'metric_value'],\n })\n }\n\n if (includeAlerts) {\n tables.push({\n name: 'rank_tracker_alert_events',\n purpose: 'Deduplicated gain/loss events for rank movement, Maps top 3, AI Overview citations, and PAA source presence.',\n keyColumns: ['id', 'project_id', 'run_id', 'surface', 'severity', 'event_key', 'message', 'created_at', 'acknowledged_at'],\n })\n }\n\n return tables\n}\n\nfunction buildCronJobs(modes: RankTrackerMode[], includeDashboard: boolean, includeAlerts: boolean): CronJobPlan[] {\n const jobs: CronJobPlan[] = [\n {\n name: 'rank-tracker-dispatch',\n purpose: 'Find due keyword/location/mode combinations, create a rank_tracker_runs row, and enqueue idempotent work items.',\n modes,\n recommendedTools: ['credits_info'],\n },\n ]\n\n if (includes(modes, 'maps')) {\n jobs.push({\n name: 'maps-rank-check',\n purpose: 'Run maps_search per keyword/location and optionally directory_workflow for market seed refreshes.',\n modes: ['maps'],\n recommendedTools: ['maps_search', 'directory_workflow', 'maps_place_intel'],\n })\n }\n\n if (includes(modes, 'organic') || includes(modes, 'ai_overview')) {\n jobs.push({\n name: 'serp-rank-check',\n purpose: 'Run search_serp per keyword/location/device and persist organic ranks, local pack, and AI Overview status.',\n modes: modes.filter((mode) => mode === 'organic' || mode === 'ai_overview'),\n recommendedTools: ['search_serp'],\n })\n }\n\n if (includes(modes, 'paa') || includes(modes, 'ai_overview')) {\n jobs.push({\n name: 'paa-ai-evidence-check',\n purpose: 'Run harvest_paa for PAA source presence and deeper AI Overview/PAA evidence where needed.',\n modes: modes.filter((mode) => mode === 'paa' || mode === 'ai_overview'),\n recommendedTools: ['harvest_paa'],\n })\n }\n\n if (includeDashboard) {\n jobs.push({\n name: 'rank-tracker-rollups',\n purpose: 'Aggregate raw rows into daily metrics for charts, comparison tables, and trend lines.',\n modes,\n recommendedTools: [],\n })\n }\n\n if (includeAlerts) {\n jobs.push({\n name: 'rank-tracker-alerts',\n purpose: 'Compare latest run against prior snapshots and emit deduplicated visibility gain/loss events.',\n modes,\n recommendedTools: [],\n })\n }\n\n return jobs\n}\n\nfunction buildMetrics(modes: RankTrackerMode[], includeDashboard: boolean, includeAlerts: boolean): string[] {\n const metrics: string[] = ['run_success_rate', 'last_successful_run_at', 'stale_keyword_location_count']\n\n if (includes(modes, 'maps')) {\n metrics.push('maps_best_position', 'maps_top_3_presence', 'maps_target_found', 'maps_competitor_count_above_target')\n }\n if (includes(modes, 'organic')) {\n metrics.push('organic_best_position', 'organic_top_3_presence', 'organic_top_10_presence', 'organic_best_url')\n }\n if (includes(modes, 'ai_overview')) {\n metrics.push('ai_overview_detected', 'target_ai_overview_cited', 'ai_overview_citation_domain_count')\n }\n if (includes(modes, 'paa')) {\n metrics.push('paa_question_count', 'target_paa_source_count', 'paa_presence_rate', 'paa_source_domains')\n }\n if (includeDashboard) metrics.push('share_of_visibility', 'position_delta_7d', 'position_delta_30d')\n if (includeAlerts) metrics.push('visibility_gain_events', 'visibility_loss_events')\n\n return metrics\n}\n\nfunction listOrPlaceholder(values: string[] | undefined, fallback: string): string {\n const clean = values?.map((value) => value.trim()).filter(Boolean) ?? []\n if (!clean.length) return fallback\n return clean.map((value) => `- ${value}`).join('\\n')\n}\n\nfunction buildPrompt(\n input: RankTrackerBlueprintInput,\n modes: RankTrackerMode[],\n tools: ToolPlan[],\n tables: TablePlan[],\n jobs: CronJobPlan[],\n metrics: string[],\n expression: string,\n targetDomain: string | null,\n targetBusinessName: string | null,\n): string {\n const keywords = listOrPlaceholder(input.keywords, '- TODO: add tracked keywords')\n const locations = listOrPlaceholder(input.locations, '- TODO: add tracked markets/locations')\n const competitors = listOrPlaceholder(input.competitors, '- Optional: add competitor domains or GBP names')\n const notes = input.notes?.trim() || 'No extra implementation notes.'\n\n return [\n 'You are building a production rank tracker powered by MCP Scraper. Create the database migrations, scheduled worker, ingestion functions, and dashboard/query layer described below.',\n '',\n `Project: ${input.projectName || 'MCP Scraper Rank Tracker'}`,\n `Target domain: ${targetDomain || 'TODO_TARGET_DOMAIN'}`,\n `Target business/GBP name: ${targetBusinessName || 'TODO_TARGET_BUSINESS_NAME'}`,\n `Database target: ${input.database || 'postgres'}`,\n `Tracking modes: ${modes.join(', ')}`,\n '',\n 'Seed keywords:',\n keywords,\n '',\n 'Seed locations:',\n locations,\n '',\n 'Competitors:',\n competitors,\n '',\n 'MCP Scraper calls to use:',\n tools.map((tool) => `- ${tool.tool}: ${tool.purpose}`).join('\\n'),\n '',\n 'Database tables to create:',\n tables.map((table) => `- ${table.name}: ${table.keyColumns.join(', ')}`).join('\\n'),\n '',\n 'Scheduler and heartbeat requirements:',\n `- Use cron expression \"${expression}\" in timezone \"${input.timezone || 'UTC'}\" unless the user changes cadence.`,\n '- Every scheduled batch must insert or update rank_tracker_runs before calling MCP tools.',\n '- Use idempotency_key = project_id + keyword_id + location_id + mode + device + scheduled_date.',\n '- Mark runs as running, succeeded, failed, or skipped; persist error_message on failures.',\n '- Run MCP calls sequentially by default because accounts have one concurrency slot unless the user bought more.',\n '- Retry retryable upstream failures with backoff, but do not duplicate rows for the same idempotency key.',\n '',\n 'Mode-specific ingestion rules:',\n '- maps: Use directory_workflow to seed/refresh market coverage and maps_search for recurring keyword/location rank checks. Match the target by targetBusinessName, website domain, CID, and place URL when available.',\n '- organic: Use search_serp and persist every organic result row. Compute the best targetDomain position and best ranking URL per keyword/location/device.',\n '- ai_overview: Use search_serp for quick detection and harvest_paa when deeper text/source evidence is needed. Track detected, overview_text, cited domains, and whether targetDomain is cited.',\n '- paa: Use harvest_paa and persist each question/source pair. Track whether sourceSite or answer/source evidence matches targetDomain, then compute PAA presence rate.',\n '',\n 'Metrics to expose:',\n metrics.map((metric) => `- ${metric}`).join('\\n'),\n '',\n 'Alert requirements:',\n input.includeAlerts\n ? '- Emit deduplicated alert_events when target gains/loses Maps top 3, organic top 10, AI Overview citation, or PAA source presence.'\n : '- Alerts are out of scope for this build unless the user asks for them.',\n '',\n 'Dashboard requirements:',\n input.includeDashboard\n ? '- Build views for latest position by keyword/location, trend deltas, competitors above target, AI Overview citations, and PAA source wins/losses.'\n : '- Dashboard is out of scope for this build unless the user asks for it.',\n '',\n 'Extra notes:',\n notes,\n ].join('\\n')\n}\n\nexport function buildRankTrackerBlueprint(input: RankTrackerBlueprintInput): CallToolResult {\n const trackingModes = uniqueModes(input.trackingModes)\n const targetDomain = normalizeDomain(input.targetDomain)\n const targetBusinessName = input.targetBusinessName?.trim() || null\n const projectName = input.projectName?.trim() || 'MCP Scraper Rank Tracker'\n const database = input.database || 'postgres'\n const expression = cronExpression(input.scheduleCadence || 'weekly', input.customCron)\n const tools = buildToolPlan(trackingModes)\n const tables = buildTables(trackingModes, input.includeDashboard !== false, input.includeAlerts !== false, Boolean(input.competitors?.length))\n const jobs = input.includeCron === false ? [] : buildCronJobs(trackingModes, input.includeDashboard !== false, input.includeAlerts !== false)\n const metrics = buildMetrics(trackingModes, input.includeDashboard !== false, input.includeAlerts !== false)\n const implementationPrompt = buildPrompt(input, trackingModes, tools, tables, jobs, metrics, expression, targetDomain, targetBusinessName)\n\n const blueprint: RankTrackerBlueprint = {\n projectName,\n targetDomain,\n targetBusinessName,\n trackingModes,\n database,\n recommendedTools: tools,\n tables,\n cron: {\n enabled: input.includeCron !== false,\n cadence: input.scheduleCadence || 'weekly',\n expression: input.includeCron === false ? 'disabled' : expression,\n timezone: input.timezone || 'UTC',\n jobs,\n },\n metrics,\n implementationPrompt,\n }\n\n const text = [\n `# ${projectName}`,\n '',\n 'Rank tracker build blueprint generated from MCP Scraper tool capabilities.',\n '',\n '## Modes',\n trackingModes.map((mode) => `- ${mode}`).join('\\n'),\n '',\n '## Recommended MCP Tools',\n tools.map((tool) => `- \\`${tool.tool}\\` - ${tool.purpose}`).join('\\n'),\n '',\n '## Database Tables',\n tables.map((table) => `- \\`${table.name}\\` - ${table.purpose}`).join('\\n'),\n '',\n '## Cron / Heartbeat',\n blueprint.cron.enabled\n ? `- Cadence: ${blueprint.cron.cadence}\\n- Cron: \\`${blueprint.cron.expression}\\`\\n- Timezone: ${blueprint.cron.timezone}\\n- Jobs: ${jobs.map((job) => job.name).join(', ')}`\n : '- Disabled by input. Still create rank_tracker_runs for manual runs.',\n '',\n '## Implementation Prompt',\n '```text',\n implementationPrompt,\n '```',\n ].join('\\n')\n\n return {\n content: [{ type: 'text', text }],\n structuredContent: blueprint,\n }\n}\n"],"mappings":";;;;AACA,IAAAA,kBAA6B;AAC7B,IAAAC,kBAAwB;AACxB,IAAAC,oBAAqB;AACrB,mBAAqC;;;ACJ9B,IAAM,yBAAyB;AAE/B,IAAM,+BAA+B;AAOrC,SAAS,qBAAqB,cAAsB,WAAW,OAA6B;AACjG,QAAM,YAAY,OAAO,SAAS,YAAY,KAAK,eAAe,IAAI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AQ,OAAO,MAAM,iEAAiE;AACtF,UAAQ,KAAK,CAAC;AAChB;AAEA,IAAM,UAAU,QAAQ,IAAI,sBAAsB,KAAK,KAAK,QAAQ,IAAI,cAAc,KAAK,KAAK;AAChG,IAAM,WAAW,IAAI,oBAAoB,SAAS,MAAM;AACxD,IAAM,SAAS,2BAA2B,QAAQ;AAClD,IAAM,YAAY,IAAI,kCAAqB;AAE3C,eAAe,OAAO;AACpB,QAAM,OAAO,QAAQ,SAAS;AAChC;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,OAAO,MAAM,GAAG,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,CAAI;AAC5E,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["import_node_fs","import_node_os","import_node_path","baseUrl","apiKey","import_node_fs","import_node_path","wordCount","import_zod","server","executor"]}
|
|
1
|
+
{"version":3,"sources":["../../bin/mcp-stdio-server.ts","../../src/harvest-timeout.ts","../../src/mcp/http-mcp-tool-executor.ts","../../src/mcp/paa-mcp-server.ts","../../src/version.ts","../../src/mcp/mcp-response-formatter.ts","../../src/errors.ts","../../src/mcp/workflow-catalog.ts","../../src/mcp/mcp-tool-schemas.ts","../../src/schemas.ts","../../src/mcp/rank-tracker-blueprint.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { readFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { HttpMcpToolExecutor } from '../src/mcp/http-mcp-tool-executor.js'\nimport { buildPaaExtractorMcpServer } from '../src/mcp/paa-mcp-server.js'\n\nfunction readApiKeyFile(): string | undefined {\n const explicitPath = process.env.MCP_SCRAPER_KEY_PATH?.trim()\n const paths = [explicitPath, join(homedir(), '.mcp-scraper-key')].filter(Boolean) as string[]\n for (const path of paths) {\n try {\n const value = readFileSync(path, 'utf8').trim()\n if (value) return value\n } catch {}\n }\n return undefined\n}\n\nconst apiKey = (\n process.env.MCP_SCRAPER_API_KEY ??\n process.env.MCP_SCRAPER_KEY ??\n process.env.MCP_API_KEY ??\n readApiKeyFile()\n)?.trim()\nif (!apiKey) {\n process.stderr.write('MCP_SCRAPER_API_KEY env var or ~/.mcp-scraper-key is required\\n')\n process.exit(1)\n}\n\nconst baseUrl = process.env.MCP_SCRAPER_BASE_URL?.trim() || process.env.MCP_BASE_URL?.trim() || 'https://mcpscraper.dev'\nconst executor = new HttpMcpToolExecutor(baseUrl, apiKey)\nconst server = buildPaaExtractorMcpServer(executor)\nconst transport = new StdioServerTransport()\n\nasync function main() {\n await server.connect(transport)\n}\n\nmain().catch((err) => {\n process.stderr.write(`${err instanceof Error ? err.message : String(err)}\\n`)\n process.exit(1)\n})\n","export const VERCEL_FUNCTION_MAX_MS = 300_000\n\nexport const CLIENT_OVER_SERVER_MARGIN_MS = 15_000\n\nexport interface HarvestTimeoutBudget {\n serverMs: number\n clientMs: number\n}\n\nexport function harvestTimeoutBudget(maxQuestions: number, serpOnly = false): HarvestTimeoutBudget {\n const requested = Number.isFinite(maxQuestions) && maxQuestions > 0 ? Math.trunc(maxQuestions) : 30\n let serverMs: number\n if (serpOnly || requested <= 50) serverMs = 110_000\n else if (requested <= 100) serverMs = 180_000\n else if (requested <= 150) serverMs = 240_000\n else serverMs = 280_000\n const clientMs = Math.min(serverMs + CLIENT_OVER_SERVER_MARGIN_MS, VERCEL_FUNCTION_MAX_MS - 5_000)\n return { serverMs, clientMs }\n}\n","import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'\nimport type { IMcpToolExecutor, ISerpIntelligenceToolExecutor } from './IMcpToolExecutor.js'\nimport { harvestTimeoutBudget } from '../harvest-timeout.js'\nimport type {\n HarvestPaaInput,\n SearchSerpInput,\n ExtractUrlInput,\n MapSiteUrlsInput,\n ExtractSiteInput,\n YoutubeHarvestInput,\n YoutubeTranscribeInput,\n FacebookPageIntelInput,\n FacebookAdSearchInput,\n FacebookAdTranscribeInput,\n FacebookVideoTranscribeInput,\n InstagramProfileContentInput,\n InstagramMediaDownloadInput,\n MapsPlaceIntelInput,\n MapsSearchInput,\n DirectoryWorkflowInput,\n CreditsInfoInput,\n WorkflowListInput,\n WorkflowRunInput,\n WorkflowStepInput,\n WorkflowStatusInput,\n WorkflowArtifactReadInput,\n CaptureSerpSnapshotInput,\n CaptureSerpPageSnapshotsInput,\n} from './mcp-tool-schemas.js'\n\nfunction youtubeVideoIdFromUrl(url: string | undefined): string | null {\n if (!url) return null\n try {\n const parsed = new URL(url)\n const host = parsed.hostname.replace(/^www\\./, '').replace(/^m\\./, '')\n if (host === 'youtu.be') {\n const id = parsed.pathname.split('/').filter(Boolean)[0]\n return id || null\n }\n if (host === 'youtube.com' || host === 'music.youtube.com') {\n const watchId = parsed.searchParams.get('v')\n if (watchId) return watchId\n const parts = parsed.pathname.split('/').filter(Boolean)\n const markerIndex = parts.findIndex(part => ['shorts', 'embed', 'live'].includes(part))\n if (markerIndex >= 0 && parts[markerIndex + 1]) return parts[markerIndex + 1]\n }\n } catch {\n return null\n }\n return null\n}\n\nasync function readResponseData(res: Response): Promise<unknown> {\n const text = await res.text()\n if (!text.trim()) return null\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n}\n\nfunction httpErrorPayload(path: string, res: Response, data: unknown): Record<string, unknown> {\n const objectData = data && typeof data === 'object' && !Array.isArray(data)\n ? data as Record<string, unknown>\n : null\n const bodyMessage = objectData\n ? objectData.message ?? objectData.error ?? objectData.error_code\n : data\n return {\n ...(objectData ?? { body: data }),\n error: objectData?.error ?? objectData?.error_code ?? 'mcp_http_error',\n error_type: 'http',\n retryable: res.status === 429 || res.status >= 500,\n status: res.status,\n statusText: res.statusText,\n path,\n message: typeof bodyMessage === 'string' && bodyMessage.trim()\n ? bodyMessage\n : `MCP Scraper HTTP ${res.status}${res.statusText ? ` ${res.statusText}` : ''} for ${path}`,\n }\n}\n\nexport class HttpMcpToolExecutor implements IMcpToolExecutor, ISerpIntelligenceToolExecutor {\n private readonly baseUrl: string\n private readonly apiKey: string\n private readonly timeoutMs: number\n private readonly httpTimeoutOverrideMs: number | null\n private readonly serpIntelligenceTimeoutMs: number\n\n constructor(baseUrl: string, apiKey: string) {\n this.baseUrl = baseUrl.replace(/\\/$/, '')\n this.apiKey = apiKey\n const rawOverride = process.env.MCP_SCRAPER_HTTP_TIMEOUT_MS\n const parsedOverride = rawOverride === undefined ? NaN : Number(rawOverride)\n this.httpTimeoutOverrideMs = Number.isFinite(parsedOverride) && parsedOverride > 0 ? parsedOverride : null\n this.timeoutMs = this.httpTimeoutOverrideMs ?? 110_000\n const configuredSerpIntelligenceTimeoutMs = Number(process.env.MCP_SCRAPER_SERP_INTELLIGENCE_HTTP_TIMEOUT_MS ?? this.timeoutMs)\n this.serpIntelligenceTimeoutMs = Number.isFinite(configuredSerpIntelligenceTimeoutMs) && configuredSerpIntelligenceTimeoutMs > 0\n ? configuredSerpIntelligenceTimeoutMs\n : this.timeoutMs\n }\n\n private async call(path: string, body: Record<string, unknown>, timeoutMs = this.timeoutMs): Promise<CallToolResult> {\n try {\n const res = await fetch(`${this.baseUrl}${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 readResponseData(res)\n if (!res.ok) {\n return { content: [{ type: 'text', text: JSON.stringify(httpErrorPayload(path, res, data)) }], isError: true }\n }\n return { content: [{ type: 'text', text: JSON.stringify(data) }] }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n if (err instanceof DOMException && err.name === 'TimeoutError') {\n return {\n content: [{\n type: 'text',\n text: JSON.stringify({\n error: 'mcp_request_timeout',\n error_type: 'timeout',\n retryable: true,\n path,\n timeoutMs,\n message: `MCP Scraper request exceeded ${Math.round(timeoutMs / 1000)}s and was cancelled. Retry with fewer results or use the async API for deep harvests.`,\n }),\n }],\n isError: true,\n }\n }\n return { content: [{ type: 'text', text: msg }], isError: true }\n }\n }\n\n private async getJson(path: string, timeoutMs = this.timeoutMs): Promise<CallToolResult> {\n try {\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: 'GET',\n headers: {\n 'x-api-key': this.apiKey,\n },\n signal: AbortSignal.timeout(timeoutMs),\n })\n const data = await readResponseData(res)\n if (!res.ok) {\n return { content: [{ type: 'text', text: JSON.stringify(httpErrorPayload(path, res, data)) }], isError: true }\n }\n return { content: [{ type: 'text', text: JSON.stringify(data) }] }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n return { content: [{ type: 'text', text: msg }], isError: true }\n }\n }\n\n private async getTextArtifact(path: string, maxBytes: number, timeoutMs = this.timeoutMs): Promise<CallToolResult> {\n try {\n const res = await fetch(`${this.baseUrl}${path}`, {\n method: 'GET',\n headers: {\n 'x-api-key': this.apiKey,\n },\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!res.ok) {\n const data = await res.json().catch(async () => ({ error: await res.text().catch(() => `HTTP ${res.status}`) }))\n return { content: [{ type: 'text', text: JSON.stringify(data) }], isError: true }\n }\n const bytes = Buffer.from(await res.arrayBuffer())\n const sliced = bytes.subarray(0, Math.min(maxBytes, bytes.length))\n return {\n content: [{\n type: 'text',\n text: JSON.stringify({\n contentType: res.headers.get('content-type') ?? 'application/octet-stream',\n bytes: bytes.length,\n truncated: sliced.length < bytes.length,\n maxBytes,\n text: sliced.toString('utf8'),\n }),\n }],\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n return { content: [{ type: 'text', text: msg }], isError: true }\n }\n }\n\n harvestPaa(input: HarvestPaaInput): Promise<CallToolResult> {\n const timeoutMs = this.httpTimeoutOverrideMs ?? harvestTimeoutBudget(input.maxQuestions ?? 30).clientMs\n return this.call('/harvest/sync', input as Record<string, unknown>, timeoutMs)\n }\n\n searchSerp(input: SearchSerpInput): Promise<CallToolResult> {\n const timeoutMs = this.httpTimeoutOverrideMs ?? harvestTimeoutBudget(0, true).clientMs\n return this.call('/harvest/sync', { ...input, serpOnly: true } as Record<string, unknown>, timeoutMs)\n }\n\n extractUrl(input: ExtractUrlInput): Promise<CallToolResult> {\n return this.call('/extract-url', input as Record<string, unknown>)\n }\n\n mapSiteUrls(input: MapSiteUrlsInput): Promise<CallToolResult> {\n return this.call('/map-urls', input as Record<string, unknown>)\n }\n\n extractSite(input: ExtractSiteInput): Promise<CallToolResult> {\n return this.call('/extract-site', input as Record<string, unknown>)\n }\n\n youtubeHarvest(input: YoutubeHarvestInput): Promise<CallToolResult> {\n return this.call('/youtube/harvest', input as Record<string, unknown>)\n }\n\n youtubeTranscribe(input: YoutubeTranscribeInput): Promise<CallToolResult> {\n const videoId = input.videoId?.trim() || youtubeVideoIdFromUrl(input.url)\n if (!videoId) {\n return Promise.resolve({\n content: [{\n type: 'text',\n text: JSON.stringify({\n error_code: 'youtube_video_id_required',\n error: 'Pass videoId from youtube_harvest or a YouTube url that contains a video id.',\n retryable: false,\n }),\n }],\n isError: true,\n })\n }\n return this.call('/youtube/transcribe', { videoId })\n }\n\n facebookPageIntel(input: FacebookPageIntelInput): Promise<CallToolResult> {\n return this.call('/facebook/page-intel', input as Record<string, unknown>)\n }\n\n facebookAdSearch(input: FacebookAdSearchInput): Promise<CallToolResult> {\n return this.call('/facebook/search', input as Record<string, unknown>)\n }\n\n facebookAdTranscribe(input: FacebookAdTranscribeInput): Promise<CallToolResult> {\n return this.call('/facebook/transcribe', input as Record<string, unknown>)\n }\n\n facebookVideoTranscribe(input: FacebookVideoTranscribeInput): Promise<CallToolResult> {\n return this.call('/facebook/video-transcribe', input as Record<string, unknown>, this.httpTimeoutOverrideMs ?? 240_000)\n }\n\n instagramProfileContent(input: InstagramProfileContentInput): Promise<CallToolResult> {\n return this.call('/instagram/profile-content', input as Record<string, unknown>, this.httpTimeoutOverrideMs ?? 240_000)\n }\n\n instagramMediaDownload(input: InstagramMediaDownloadInput): Promise<CallToolResult> {\n return this.call('/instagram/media-download', input as Record<string, unknown>, this.httpTimeoutOverrideMs ?? 300_000)\n }\n\n mapsPlaceIntel(input: MapsPlaceIntelInput): Promise<CallToolResult> {\n return this.call('/maps/place', input as Record<string, unknown>)\n }\n\n mapsSearch(input: MapsSearchInput): Promise<CallToolResult> {\n return this.call('/maps/search', input as Record<string, unknown>)\n }\n\n directoryWorkflow(input: DirectoryWorkflowInput): Promise<CallToolResult> {\n const cityCount = typeof input.maxCities === 'number' ? input.maxCities : 25\n const concurrency = typeof input.concurrency === 'number' && input.concurrency > 0 ? input.concurrency : 5\n const timeoutMs = this.httpTimeoutOverrideMs ?? Math.min(900_000, Math.max(180_000, Math.ceil(cityCount / concurrency) * 120_000))\n return this.call('/directory/run', input as Record<string, unknown>, timeoutMs)\n }\n\n workflowList(_input: WorkflowListInput): Promise<CallToolResult> {\n return this.getJson('/workflows/definitions')\n }\n\n workflowRun(input: WorkflowRunInput): Promise<CallToolResult> {\n const timeoutMs = this.httpTimeoutOverrideMs ?? Number(process.env.MCP_SCRAPER_WORKFLOW_TIMEOUT_MS ?? 900_000)\n return this.call('/workflows/run', {\n workflowId: input.workflowId,\n input: input.input ?? {},\n webhookUrl: input.webhookUrl,\n }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 900_000)\n }\n\n workflowStep(input: WorkflowStepInput): Promise<CallToolResult> {\n const timeoutMs = this.httpTimeoutOverrideMs ?? Number(process.env.MCP_SCRAPER_WORKFLOW_TIMEOUT_MS ?? 900_000)\n return this.call(`/workflows/runs/${encodeURIComponent(input.runId)}/step`, {}, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 900_000)\n }\n\n workflowStatus(input: WorkflowStatusInput): Promise<CallToolResult> {\n return this.getJson(`/workflows/runs/${encodeURIComponent(input.runId)}`)\n }\n\n workflowArtifactRead(input: WorkflowArtifactReadInput): Promise<CallToolResult> {\n return this.getTextArtifact(\n `/workflows/runs/${encodeURIComponent(input.runId)}/artifacts/${encodeURIComponent(input.artifactId)}`,\n input.maxBytes ?? 200_000,\n )\n }\n\n creditsInfo(input: CreditsInfoInput): Promise<CallToolResult> {\n return this.call('/billing/credits', input as Record<string, unknown>)\n }\n\n captureSerpSnapshot(input: CaptureSerpSnapshotInput): Promise<CallToolResult> {\n return this.call('/serp-intelligence/capture', input as Record<string, unknown>, this.serpIntelligenceTimeoutMs)\n }\n\n captureSerpPageSnapshots(input: CaptureSerpPageSnapshotsInput): Promise<CallToolResult> {\n return this.call('/serp-intelligence/page-snapshots', input as Record<string, unknown>, this.serpIntelligenceTimeoutMs)\n }\n\n}\n","import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { readdirSync, readFileSync, statSync } from 'node:fs'\nimport { basename, join } from 'node:path'\nimport type { IMcpToolExecutor } from './IMcpToolExecutor.js'\nimport { PACKAGE_VERSION } from '../version.js'\nimport { outputBaseDir } from './mcp-response-formatter.js'\nimport {\n HarvestPaaInputSchema,\n SearchSerpInputSchema,\n ExtractUrlInputSchema,\n HarvestPaaOutputSchema,\n SearchSerpOutputSchema,\n ExtractUrlOutputSchema,\n ExtractSiteOutputSchema,\n MapsPlaceIntelOutputSchema,\n CreditsInfoOutputSchema,\n MapSiteUrlsInputSchema,\n MapSiteUrlsOutputSchema,\n ExtractSiteInputSchema,\n YoutubeHarvestInputSchema,\n YoutubeHarvestOutputSchema,\n YoutubeTranscribeInputSchema,\n YoutubeTranscribeOutputSchema,\n FacebookPageIntelInputSchema,\n FacebookPageIntelOutputSchema,\n FacebookAdSearchInputSchema,\n FacebookAdSearchOutputSchema,\n FacebookAdTranscribeInputSchema,\n FacebookAdTranscribeOutputSchema,\n FacebookVideoTranscribeInputSchema,\n FacebookVideoTranscribeOutputSchema,\n InstagramProfileContentInputSchema,\n InstagramProfileContentOutputSchema,\n InstagramMediaDownloadInputSchema,\n InstagramMediaDownloadOutputSchema,\n MapsPlaceIntelInputSchema,\n MapsSearchInputSchema,\n MapsSearchOutputSchema,\n DirectoryWorkflowInputSchema,\n DirectoryWorkflowOutputSchema,\n WorkflowListInputSchema,\n WorkflowListOutputSchema,\n WorkflowSuggestInputSchema,\n WorkflowSuggestOutputSchema,\n WorkflowRunInputSchema,\n WorkflowRunOutputSchema,\n WorkflowStepInputSchema,\n WorkflowStepOutputSchema,\n WorkflowStatusInputSchema,\n WorkflowStatusOutputSchema,\n WorkflowArtifactReadInputSchema,\n WorkflowArtifactReadOutputSchema,\n RankTrackerBlueprintInputSchema,\n RankTrackerBlueprintOutputSchema,\n CreditsInfoInputSchema,\n} from './mcp-tool-schemas.js'\nimport { buildRankTrackerBlueprint } from './rank-tracker-blueprint.js'\nimport {\n formatHarvestPaa,\n formatSearchSerp,\n formatExtractUrl,\n formatMapSiteUrls,\n formatExtractSite,\n formatYoutubeHarvest,\n formatYoutubeTranscribe,\n formatFacebookPageIntel,\n formatFacebookAdSearch,\n formatFacebookAdTranscribe,\n formatFacebookVideoTranscribe,\n formatInstagramProfileContent,\n formatInstagramMediaDownload,\n formatMapsPlaceIntel,\n formatMapsSearch,\n formatDirectoryWorkflow,\n formatWorkflowList,\n formatWorkflowSuggest,\n formatWorkflowRun,\n formatWorkflowStep,\n formatWorkflowStatus,\n formatWorkflowArtifactRead,\n formatCreditsInfo,\n} from './mcp-response-formatter.js'\n\nexport interface BuildMcpServerOptions {\n savesReportsLocally?: boolean\n}\n\nexport function liveWebToolAnnotations(title: string) {\n return {\n title,\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n }\n}\n\nfunction localPlanningToolAnnotations(title: string) {\n return {\n title,\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n }\n}\n\nfunction listSavedReports(): Array<{ filename: string; mtimeMs: number }> {\n try {\n const dir = outputBaseDir()\n return readdirSync(dir)\n .filter(f => f.endsWith('.md'))\n .map(f => ({ filename: f, mtimeMs: statSync(join(dir, f)).mtimeMs }))\n .sort((a, b) => b.mtimeMs - a.mtimeMs)\n .slice(0, 100)\n } catch {\n return []\n }\n}\n\nfunction registerSavedReportResources(server: McpServer): void {\n server.registerResource(\n 'saved-report',\n new ResourceTemplate('report://{filename}', {\n list: () => ({\n resources: listSavedReports().map(r => ({\n uri: `report://${encodeURIComponent(r.filename)}`,\n name: r.filename,\n mimeType: 'text/markdown',\n })),\n }),\n }),\n {\n title: 'Saved MCP Scraper Reports',\n description: 'Markdown research reports saved by previous MCP Scraper tool calls. Read a report to reuse prior research without re-scraping or spending credits.',\n mimeType: 'text/markdown',\n },\n async (uri, variables) => {\n const requested = Array.isArray(variables.filename) ? variables.filename[0] : variables.filename\n const filename = basename(decodeURIComponent(String(requested ?? '')))\n if (!filename.endsWith('.md')) throw new Error('Only saved .md reports can be read')\n const text = readFileSync(join(outputBaseDir(), filename), 'utf8')\n return { contents: [{ uri: uri.href, mimeType: 'text/markdown', text }] }\n },\n )\n}\n\nexport function buildPaaExtractorMcpServer(\n executor: IMcpToolExecutor,\n options: BuildMcpServerOptions = {},\n): McpServer {\n const server = new McpServer({ name: 'mcp-scraper', version: PACKAGE_VERSION })\n registerPaaExtractorMcpTools(server, executor, options)\n return server\n}\n\nexport function registerPaaExtractorMcpTools(\n server: McpServer,\n executor: IMcpToolExecutor,\n options: BuildMcpServerOptions = {},\n): void {\n const savesReports = options.savesReportsLocally !== false\n const reportNote = savesReports\n ? ' Saves a full Markdown report to disk.'\n : ' Reports are returned inline; no files are saved on this hosted endpoint.'\n const withReportNote = (description: string) => `${description}${reportNote}`\n\n if (savesReports) registerSavedReportResources(server)\n\n server.registerTool('harvest_paa', {\n title: 'Google PAA + SERP Harvest',\n 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\"). Omit proxyMode for normal use; the service defaults to the configured browser-service proxy without city/ZIP targeting for the highest general success rate. Use proxyMode location only when the user explicitly needs city/ZIP-targeted residential proxy evidence. 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 — 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.'),\n inputSchema: HarvestPaaInputSchema,\n outputSchema: HarvestPaaOutputSchema,\n annotations: liveWebToolAnnotations('Google PAA + SERP Harvest'),\n }, async (input) => formatHarvestPaa(await executor.harvestPaa(input), input))\n\n server.registerTool('search_serp', {\n title: 'Google SERP Lookup',\n 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. Omit proxyMode for normal use; the service defaults to the configured browser-service proxy without city/ZIP targeting. Use proxyMode location and proxyZip only when the user explicitly needs city/ZIP-targeted residential proxy evidence.'),\n inputSchema: SearchSerpInputSchema,\n outputSchema: SearchSerpOutputSchema,\n annotations: liveWebToolAnnotations('Google SERP Lookup'),\n }, async (input) => formatSearchSerp(await executor.searchSerp(input), input))\n\n server.registerTool('extract_url', {\n title: 'Single URL Extract',\n description: withReportNote('Extract structured data from one public URL when the user provides one page, asks to inspect/scrape a page, or needs page content, schema, headings, metadata, screenshots, branding, or media assets. Returns structured page fields plus artifact handles for saved reports/screenshots/media when requested. Use map_site_urls before extracting a site inventory; use extract_site for multi-page crawling.'),\n inputSchema: ExtractUrlInputSchema,\n outputSchema: ExtractUrlOutputSchema,\n annotations: liveWebToolAnnotations('Single URL Extract'),\n }, async (input) => formatExtractUrl(await executor.extractUrl(input), input))\n\n server.registerTool('map_site_urls', {\n title: 'Site URL Map',\n description: withReportNote('Map/crawl a public website when the user asks for a sitemap, URL inventory, broken-link scan, redirect scan, or crawl planning. Returns internal URLs with HTTP status and truncation metadata. Use this before extract_site when choosing pages for an audit; use extract_url for one known page.'),\n inputSchema: MapSiteUrlsInputSchema,\n outputSchema: MapSiteUrlsOutputSchema,\n annotations: liveWebToolAnnotations('Site URL Map'),\n }, async (input) => formatMapSiteUrls(await executor.mapSiteUrls(input), input))\n\n server.registerTool('extract_site', {\n title: 'Multi-Page Site Extract',\n description: withReportNote('Run multi-page extraction across a public website when the user asks for a website audit, competitor audit, full-site content crawl, schema inventory, or page metadata review. Returns per-page titles, H1s, metadata, headings, schema/entity data, canonical URLs, and content. Use map_site_urls first when URL selection matters; use extract_url for one page.'),\n inputSchema: ExtractSiteInputSchema,\n outputSchema: ExtractSiteOutputSchema,\n annotations: liveWebToolAnnotations('Multi-Page Site Extract'),\n }, async (input) => formatExtractSite(await executor.extractSite(input), input))\n\n server.registerTool('youtube_harvest', {\n title: 'YouTube Video Harvest',\n description: withReportNote('Harvest YouTube video metadata when the user wants to find videos by topic, inspect a channel library, compare video angles, or get videoIds for later transcription. Use mode \"search\" for keyword/topic requests and mode \"channel\" for @handles, channel IDs, or channel URLs. Returns titles, views, durations, URLs, and videoIds for follow-up transcription. Use youtube_transcribe after selecting one video.'),\n inputSchema: YoutubeHarvestInputSchema,\n outputSchema: YoutubeHarvestOutputSchema,\n annotations: liveWebToolAnnotations('YouTube Video Harvest'),\n }, async (input) => formatYoutubeHarvest(await executor.youtubeHarvest(input), input))\n\n server.registerTool('youtube_transcribe', {\n title: 'YouTube Transcription',\n description: withReportNote('Fetch and transcribe captions from a YouTube video. Use this when the user asks what was said in a YouTube video, wants claims/offers/lessons extracted from a video, or provides a YouTube URL for transcript work. Returns full transcript, timestamped chunks, word count, and resolvedInputs. Pass videoId from youtube_harvest results, or pass url when the user pasted a YouTube URL. Use youtube_harvest first when you need to discover videos by topic/channel.'),\n inputSchema: YoutubeTranscribeInputSchema,\n outputSchema: YoutubeTranscribeOutputSchema,\n annotations: liveWebToolAnnotations('YouTube Transcription'),\n }, async (input) => formatYoutubeTranscribe(await executor.youtubeTranscribe(input), input))\n\n server.registerTool('facebook_page_intel', {\n title: 'Facebook Advertiser Ad Intel',\n description: withReportNote('Harvest ads from a Facebook advertiser when the user wants current ad copy, creative angles, CTAs, video URLs, or competitive ad intelligence for one brand/page. Returns ad copy, headlines, CTAs, creative type, status, landing URLs, and direct ad video URLs ready for facebook_ad_transcribe. Accepts pageId, libraryId, or a brand/advertiser name as query. Use facebook_ad_search first when the advertiser handle is unknown. For normal public Facebook reels/posts/watch/share URLs, use facebook_video_transcribe instead.'),\n inputSchema: FacebookPageIntelInputSchema,\n outputSchema: FacebookPageIntelOutputSchema,\n annotations: liveWebToolAnnotations('Facebook Advertiser Ad Intel'),\n }, async (input) => formatFacebookPageIntel(await executor.facebookPageIntel(input), input))\n\n server.registerTool('facebook_ad_search', {\n title: 'Facebook Ad Library Search',\n description: withReportNote('Search Facebook Ad Library when the user wants to find advertisers by brand, competitor, niche, or keyword. Returns advertisers with ad counts and library IDs. Use this to discover competitor/page handles, then pass libraryId or pageId to facebook_page_intel for ad details.'),\n inputSchema: FacebookAdSearchInputSchema,\n outputSchema: FacebookAdSearchOutputSchema,\n annotations: liveWebToolAnnotations('Facebook Ad Library Search'),\n }, async (input) => formatFacebookAdSearch(await executor.facebookAdSearch(input), input))\n\n server.registerTool('facebook_ad_transcribe', {\n title: 'Facebook Ad Transcription',\n description: 'Transcribe audio from a Facebook ad video CDN URL. Use this when facebook_page_intel returned a direct videoUrl and the user asks what the ad says, what claims it makes, or wants ad-message extraction. Returns full transcript, timestamped chunks, word count, and resolvedInputs. Use only with the direct videoUrl value from facebook_page_intel results; do not pass public Facebook post/reel/share URLs. Use facebook_video_transcribe for organic Facebook URLs, and facebook_page_intel first when you only have a brand/page/ad library handle.',\n inputSchema: FacebookAdTranscribeInputSchema,\n outputSchema: FacebookAdTranscribeOutputSchema,\n annotations: liveWebToolAnnotations('Facebook Ad Transcription'),\n }, async (input) => formatFacebookAdTranscribe(await executor.facebookAdTranscribe(input), input))\n\n server.registerTool('facebook_video_transcribe', {\n title: 'Facebook Organic Video Transcription',\n description: withReportNote('Transcribe audio from an organic Facebook reel, video, watch, post, or share URL, including fb.watch links. Use this when the user pastes a normal Facebook video page URL and wants the transcript or downloadable MP4. Renders the Facebook page in a browser, selects the best matching public Facebook CDN MP4 URL from page state, then returns sourceUrl, resolved pageUrl, videoId, ownerName, selectedQuality, bitrate, videoDurationSec, extracted MP4 URL, full transcript, and timestamped chunks.'),\n inputSchema: FacebookVideoTranscribeInputSchema,\n outputSchema: FacebookVideoTranscribeOutputSchema,\n annotations: liveWebToolAnnotations('Facebook Organic Video Transcription'),\n }, async (input) => formatFacebookVideoTranscribe(await executor.facebookVideoTranscribe(input), input))\n\n server.registerTool('instagram_profile_content', {\n title: 'Instagram Profile Content Discovery',\n description: withReportNote('Discover Instagram profile grid content links for a handle or profile URL. Use this when the user wants a person or brand account content inventory before selecting posts/reels to download. Returns profile stats, collected post/reel/tv URLs, shortcodes, type counts, browser details, pagination attempts, stop reason, and limitations.'),\n inputSchema: InstagramProfileContentInputSchema,\n outputSchema: InstagramProfileContentOutputSchema,\n annotations: liveWebToolAnnotations('Instagram Profile Content Discovery'),\n }, async (input) => formatInstagramProfileContent(await executor.instagramProfileContent(input), input))\n\n server.registerTool('instagram_media_download', {\n title: 'Instagram Post/Reel Media Download',\n description: withReportNote('Extract and download media from one Instagram post, reel, or tv URL. Use after instagram_profile_content or when the user gives a specific Instagram URL and wants the image, caption/text, reel audio/video tracks, optional muxed MP4, or optional transcript. Reels commonly expose separate video-only and audio-only MP4 tracks; this tool selects the best video and audio tracks and attempts muxing when ffmpeg is available.'),\n inputSchema: InstagramMediaDownloadInputSchema,\n outputSchema: InstagramMediaDownloadOutputSchema,\n annotations: liveWebToolAnnotations('Instagram Post/Reel Media Download'),\n }, async (input) => formatInstagramMediaDownload(await executor.instagramMediaDownload(input), input))\n\n server.registerTool('maps_place_intel', {\n title: 'Google Maps Business Profile Details',\n description: withReportNote('Extract Google Maps business intelligence for one known/named business: rating, review count, category, address, phone, website, hours, booking URL, review histogram, review topics, about attributes, entity IDs, and optional review cards. Do not use this for category searches, local market prospect lists, or requests for multiple GMB/GBP profiles; use maps_search first for those. Split business name from location (e.g. \"Elite Roofing Denver CO\" => businessName \"Elite Roofing\", location \"Denver, CO\"). Pass includeReviews true when the user asks for reviews/customer pain.'),\n inputSchema: MapsPlaceIntelInputSchema,\n outputSchema: MapsPlaceIntelOutputSchema,\n annotations: liveWebToolAnnotations('Google Maps Business Profile Details'),\n }, async (input) => formatMapsPlaceIntel(await executor.mapsPlaceIntel(input), input))\n\n server.registerTool('maps_search', {\n title: 'Google Maps Business Search',\n 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.\" Maps is the default location-targeted surface: omit proxyMode for normal Maps use so the service creates residential proxy evidence for the requested market and rotates on retryable failures. Pass proxyZip only when a specific ZIP or city-center ZIP is known. Use proxyMode configured only when you explicitly do not want city/ZIP proxy targeting. 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.'),\n inputSchema: MapsSearchInputSchema,\n outputSchema: MapsSearchOutputSchema,\n annotations: liveWebToolAnnotations('Google Maps Business Search'),\n }, async (input) => formatMapsSearch(await executor.mapsSearch(input), input))\n\n server.registerTool('directory_workflow', {\n title: 'Directory Workflow: Markets + Maps',\n 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. Maps workflows default to location-targeted proxying so each city can use city/state or ZIP-group residential proxy evidence; use proxyMode configured only when you explicitly do not want city/ZIP proxy targeting. 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.'),\n inputSchema: DirectoryWorkflowInputSchema,\n outputSchema: DirectoryWorkflowOutputSchema,\n annotations: liveWebToolAnnotations('Directory Workflow: Markets + Maps'),\n }, async (input) => formatDirectoryWorkflow(await executor.directoryWorkflow(input), input))\n\n server.registerTool('workflow_list', {\n title: 'Workflow Catalog',\n description: 'List MCP Scraper higher-level workflows and AI-facing recipes. Use this when the user asks what MCP Scraper can do beyond single tools, or asks for market analysis, ICP research, forum/review acquisition, full brand design briefings, CRO audits, competitive positioning, content gap briefs, or AI search visibility audits. Returns runnable workflow ids plus recipe guidance for the best tool chain.',\n inputSchema: WorkflowListInputSchema,\n outputSchema: WorkflowListOutputSchema,\n annotations: localPlanningToolAnnotations('Workflow Catalog'),\n }, async (input) => formatWorkflowList(await executor.workflowList(input), input))\n\n server.registerTool('workflow_suggest', {\n title: 'Workflow Intent Router',\n description: 'Route a high-level business or research goal to the right MCP Scraper workflow/tool chain. Use before running work when the user says things like \"do market analysis\", \"research my ICP\", \"acquire forum and review language\", \"build a brand design brief\", \"run a CRO audit\", \"compare competitors\", \"make a content gap brief\", or \"audit AI search visibility\". This tool does not spend credits; it tells the AI exactly which workflow/tool chain to run next.',\n inputSchema: WorkflowSuggestInputSchema,\n outputSchema: WorkflowSuggestOutputSchema,\n annotations: localPlanningToolAnnotations('Workflow Intent Router'),\n }, async (input) => formatWorkflowSuggest(input))\n\n server.registerTool('workflow_run', {\n title: 'Run Workflow',\n description: withReportNote('Start a higher-level MCP Scraper workflow. Use after workflow_suggest or workflow_list. Runnable workflow ids: directory, agent-packet, local-competitive-audit, map-comparison, serp-comparison, paa-expansion-brief, ai-overview-language. This is the main MCP tool for market analysis, ICP evidence packets, local competitive audits, Maps/SERP comparisons, content gap briefs, and AI Overview language guidance. Stepwise workflows (e.g. agent-packet) run ONE leg per call and return runId, the step output, and nextStep — when nextStep is present, call workflow_step with the runId to run the next leg, and keep calling it until done is true. This keeps each call short instead of one long blocking run, so report each step result to the user as it arrives.'),\n inputSchema: WorkflowRunInputSchema,\n outputSchema: WorkflowRunOutputSchema,\n annotations: liveWebToolAnnotations('Run Workflow'),\n }, async (input) => formatWorkflowRun(await executor.workflowRun(input), input))\n\n server.registerTool('workflow_step', {\n title: 'Advance Workflow Step',\n description: withReportNote('Run the next leg of a stepwise MCP Scraper workflow started with workflow_run. Pass the runId. Each call executes exactly one logical step (typically one live harvest), persists that step\\'s artifacts, and returns the step output plus nextStep. Keep calling workflow_step with the same runId until done is true, reporting each step result to the user as it lands. Use this instead of waiting on one long workflow call — it avoids client timeouts on long multi-step jobs.'),\n inputSchema: WorkflowStepInputSchema,\n outputSchema: WorkflowStepOutputSchema,\n annotations: liveWebToolAnnotations('Advance Workflow Step'),\n }, async (input) => formatWorkflowStep(await executor.workflowStep(input), input))\n\n server.registerTool('workflow_status', {\n title: 'Workflow Status',\n description: 'Fetch a hosted workflow run by id and list its current status and artifacts. Use when a workflow may still be running, when the model needs to re-open a run, inspect artifact ids, recover from a long workflow, or decide whether to call workflow_step or workflow_artifact_read next. Use only a runId returned by workflow_run/workflow_step/workflow_status; do not construct one yourself.',\n inputSchema: WorkflowStatusInputSchema,\n outputSchema: WorkflowStatusOutputSchema,\n annotations: liveWebToolAnnotations('Workflow Status'),\n }, async (input) => formatWorkflowStatus(await executor.workflowStatus(input), input))\n\n server.registerTool('workflow_artifact_read', {\n title: 'Read Workflow Artifact',\n description: 'Read a workflow artifact back into MCP context by run id and artifact id. Use this before writing final deliverables so the answer is grounded in generated evidence.json, CSVs, Markdown briefs, reports, and task files instead of memory. Use workflow_status first when artifact ids are unknown. Use only artifactId values returned by workflow_run/workflow_step/workflow_status; do not construct one yourself. Use maxBytes to limit large CSV/JSON artifacts.',\n inputSchema: WorkflowArtifactReadInputSchema,\n outputSchema: WorkflowArtifactReadOutputSchema,\n annotations: liveWebToolAnnotations('Read Workflow Artifact'),\n }, async (input) => formatWorkflowArtifactRead(await executor.workflowArtifactRead(input), input))\n\n server.registerTool('rank_tracker_blueprint', {\n title: 'Rank Tracker Blueprint Builder',\n description: 'Generate a build-ready database, cron/heartbeat, ingestion, metrics, and AI implementation prompt for a rank tracker powered by MCP Scraper. Supports Maps rankings through directory_workflow/maps_search, organic rankings through search_serp, AI Overview citation tracking, and People Also Ask source presence tracking. This tool is local planning only; it does not call the web or spend credits.',\n inputSchema: RankTrackerBlueprintInputSchema,\n outputSchema: RankTrackerBlueprintOutputSchema,\n annotations: localPlanningToolAnnotations('Rank Tracker Blueprint Builder'),\n }, async (input) => buildRankTrackerBlueprint(input))\n\n server.registerTool('credits_info', {\n title: 'MCP Scraper Credits & Costs',\n description: 'Answer questions about MCP Scraper credits, usage limits, and concurrency upgrades: current credit balance, what a specific tool/action costs, the full cost table, current concurrency limit, the extra-slot price, billing URL, and the terminal checkout command. Does not expose payment methods or credit card information.',\n inputSchema: CreditsInfoInputSchema,\n outputSchema: CreditsInfoOutputSchema,\n annotations: {\n title: 'MCP Scraper Credits & Costs',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n }, async (input) => formatCreditsInfo(await executor.creditsInfo(input), input))\n\n}\n","export const PACKAGE_VERSION = '0.3.12'\n","import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { sanitizeVendorName } from '../errors.js'\nimport { WORKFLOW_RECIPES, suggestWorkflowRecipes, type WorkflowRecipe } from './workflow-catalog.js'\n\nlet reportSavingEnabled = true\n\nexport function configureReportSaving(enabled: boolean): void {\n reportSavingEnabled = enabled\n}\n\nfunction sanitizeVendorText(text: string): string {\n return sanitizeVendorName(\n text\n .replace(/kernel_session_id/gi, 'browser_session_id')\n .replace(/kernel_delete_succeeded/gi, 'session_cleanup_succeeded')\n .replace(/kernel_delete_started/gi, 'session_cleanup_started')\n .replace(/kernel_delete_error/gi, 'session_cleanup_error')\n .replace(/kernelSessionId/g, 'browserSessionId')\n .replace(/kernelProxyId/g, 'proxyId')\n .replace(/KERNEL_API_KEY/g, 'BROWSER_SERVICE_API_KEY')\n .replace(/\"kernel\"\\s*:/gi, '\"browserRuntime\":'),\n )\n}\n\nfunction slugifyReportName(input: string): string {\n return input\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 80) || 'mcp-scraper-report'\n}\n\nfunction reportTitle(full: string): string {\n const title = full.split('\\n').find(line => line.startsWith('# '))\n return title?.replace(/^#\\s+/, '').trim() || 'MCP Scraper Report'\n}\n\nexport function outputBaseDir(): string {\n return process.env.MCP_SCRAPER_OUTPUT_DIR?.trim() || join(homedir(), 'Downloads', 'mcp-scraper')\n}\n\nfunction saveFullReport(full: string): string | null {\n if (!reportSavingEnabled || process.env.MCP_SCRAPER_SAVE_REPORTS === 'false') return null\n const outDir = outputBaseDir()\n try {\n mkdirSync(outDir, { recursive: true })\n const stamp = new Date().toISOString().replace(/[:.]/g, '-')\n const file = join(outDir, `${stamp}-${slugifyReportName(reportTitle(full))}.md`)\n writeFileSync(file, full, 'utf8')\n return file\n } catch {\n return null\n }\n}\n\nfunction persistScreenshotLocally(base64: string, url: string): string | null {\n if (!reportSavingEnabled || process.env.MCP_SCRAPER_SAVE_REPORTS === 'false') return null\n try {\n const dir = join(outputBaseDir(), 'screenshots')\n mkdirSync(dir, { recursive: true })\n const stamp = new Date().toISOString().replace(/[:.]/g, '-')\n const slug = url.replace(/^https?:\\/\\//, '').replace(/[^a-z0-9]+/gi, '-').replace(/^-+|-+$/g, '').slice(0, 60)\n const filePath = join(dir, `${stamp}-${slug}.png`)\n writeFileSync(filePath, Buffer.from(base64, 'base64'))\n return filePath\n } catch {\n return null\n }\n}\n\nfunction oneBlock(content: string): CallToolResult {\n const filePath = saveFullReport(content)\n const text = filePath ? `${content}\\n\\n📄 Saved: \\`${filePath}\\`` : content\n return { content: [{ type: 'text', text }] }\n}\n\nexport function passthrough(raw: CallToolResult): CallToolResult {\n return raw\n}\n\nfunction workflowRecipeTable(recipes: WorkflowRecipe[]): string {\n if (!recipes.length) return ''\n return [\n '| Recipe | Best workflow | What it produces |',\n '|---|---|---|',\n ...recipes.map(recipe => `| ${cell(recipe.title)} | ${recipe.primaryWorkflowId ? `\\`${recipe.primaryWorkflowId}\\`` : 'tool chain'} | ${cell(recipe.produces.slice(0, 4).join(', '))} |`),\n ].join('\\n')\n}\n\nfunction checkInsufficientBalance(raw: CallToolResult): CallToolResult | null {\n const first = raw.content.find(b => b.type === 'text')\n const text = first?.type === 'text' ? first.text : ''\n try {\n const body = JSON.parse(text || '{}') as Record<string, unknown>\n if (body.error === 'insufficient_balance') {\n return {\n isError: true,\n content: [{\n type: 'text',\n text: `Insufficient credits. Balance: ${body.balance_credits} credits. This call requires ${body.required_credits} credits. Top up at ${body.topup_url}`,\n }],\n }\n }\n } catch { }\n return null\n}\n\nfunction formatStructuredError(body: Record<string, unknown>, fallback: string): string {\n if (body.error === 'insufficient_balance') {\n return `Insufficient credits. Balance: ${body.balance_credits} credits. This call requires ${body.required_credits} credits. Top up at ${body.topup_url}`\n }\n if (body.error === 'mcp_request_timeout') {\n return typeof body.message === 'string' ? body.message : 'MCP Scraper request timed out and was cancelled.'\n }\n if (typeof body.error_code === 'string') {\n const message = typeof body.error === 'string'\n ? body.error\n : typeof body.message === 'string'\n ? body.message\n : fallback\n const retryable = body.retryable === true ? ' Retryable: yes.' : ''\n return `${body.error_code}: ${message}${retryable}${errorAttemptsSection(body)}`\n }\n if (typeof body.error === 'string') return body.error\n return fallback || 'Tool error'\n}\n\nfunction parseData(raw: CallToolResult): { data: Record<string, unknown> } | { error: string } {\n const first = raw.content.find(b => b.type === 'text')\n const text = first?.type === 'text' ? first.text : ''\n try {\n const parsed = JSON.parse(text || '{}') as Record<string, unknown>\n if (raw.isError || parsed.error || parsed.error_code) return { error: sanitizeVendorText(formatStructuredError(parsed, text)) }\n const data = (parsed.result as Record<string, unknown>) ?? parsed\n return { data }\n } catch {\n if (raw.isError) return { error: sanitizeVendorText(text || 'Tool error') }\n return { error: 'Failed to parse tool response' }\n }\n}\n\nfunction entityIdsSection(ids?: { kgIds?: string[]; cids?: string[]; gcids?: string[] }): string {\n if (!ids) return ''\n const lines: string[] = []\n if (ids.kgIds?.length) lines.push(`- **Knowledge Graph MID:** ${ids.kgIds.join(', ')}`)\n if (ids.cids?.length) lines.push(`- **CID:** ${ids.cids.join(', ')}`)\n if (ids.gcids?.length) lines.push(`- **GCID:** ${ids.gcids.join(', ')}`)\n return lines.length ? `\\n## Entity IDs\\n${lines.join('\\n')}` : ''\n}\n\nfunction truncate(s: string | null | undefined, max: number): string {\n if (!s) return ''\n return s.length > max ? s.slice(0, max) + '…' : s\n}\n\nexport function cell(s: string | null | undefined): string {\n return String(s ?? '')\n .replace(/\\r?\\n+/g, ' ')\n .replace(/\\|/g, '\\\\|')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\nfunction debugSection(debug: any): string {\n if (!debug || typeof debug !== 'object') return ''\n const request = debug.request ?? {}\n const browser = debug.browser ?? {}\n const kernel = browser.browserRuntime ?? browser.kernel ?? {}\n const network = browser.networkLocation ?? {}\n const nav = browser.serpNavigation ?? {}\n const proxyResolution = kernel.proxyResolution ?? {}\n const locationEvidence = debug.locationEvidence\n const candidates = Array.isArray(locationEvidence?.candidates)\n ? locationEvidence.candidates.slice(0, 4).map((c: any) => `${c.city}, ${c.regionCode} (${c.count})`).join(', ')\n : ''\n const lines = [\n '\\n## Debug',\n `- Proxy mode: ${request.proxyMode ?? kernel.proxyMode ?? 'unknown'} · requested proxy: ${kernel.requestedProxyIdPresent === true ? `yes (${kernel.requestedProxyIdSuffix ?? 'redacted'})` : 'no'}`,\n `- Proxy resolution: ${proxyResolution.source ?? 'unknown'}${proxyResolution.target ? ` · ${proxyResolution.target.level ?? 'city'} ${proxyResolution.target.city}, ${proxyResolution.target.state}` : ''}${proxyResolution.error ? ` · ${truncate(proxyResolution.error, 180)}` : ''}`,\n `- Browser session: ${kernel.sessionId ?? 'unknown'} · retrieved proxy: ${kernel.retrievedProxyIdPresent === true ? `yes (${kernel.retrievedProxyIdSuffix ?? 'redacted'})` : kernel.retrievedProxyIdPresent === false ? 'no' : 'unknown'}`,\n `- Browser IP geo: ${[network.ip, network.city, network.region, network.country].filter(Boolean).join(' · ') || network.error || 'unknown'}`,\n `- Google URL: ${truncate(nav.requestedUrl, 240) || 'unknown'}`,\n `- Final URL: ${truncate(nav.finalUrl, 240) || 'unknown'} · CAPTCHA: ${nav.captchaDetected === true ? 'yes' : nav.captchaDetected === false ? 'no' : 'unknown'} · redirected: ${nav.redirected === true ? 'yes' : nav.redirected === false ? 'no' : 'unknown'}`,\n ]\n if (locationEvidence) {\n lines.push(`- Location evidence: ${locationEvidence.status}${locationEvidence.expected ? ` · expected ${locationEvidence.expected.city}${locationEvidence.expected.regionCode ? `, ${locationEvidence.expected.regionCode}` : ''}` : ''}${candidates ? ` · candidates ${candidates}` : ''}`)\n }\n return sanitizeVendorText(lines.join('\\n'))\n}\n\nfunction errorAttemptsSection(body: Record<string, unknown>): string {\n const attempts = Array.isArray(body.attempts) ? body.attempts as Array<Record<string, any>> : []\n if (attempts.length === 0) return ''\n const lines = attempts.slice(0, 5).map((attempt) => {\n const debug = attempt.debug ?? {}\n const browser = debug.browser ?? {}\n const kernel = browser.browserRuntime ?? browser.kernel ?? {}\n const proxyResolution = kernel.proxyResolution ?? {}\n const network = browser.networkLocation ?? {\n ip: attempt.observedIp ?? attempt.observed_ip,\n city: attempt.observedCity ?? attempt.observed_city,\n region: attempt.observedRegion ?? attempt.observed_region,\n }\n const nav = browser.serpNavigation ?? {}\n const geo = [network.ip, network.city, network.region].filter(Boolean).join(' / ') || 'geo unknown'\n const sessionId = attempt.browser_session_id ?? attempt.browserSessionIdSuffix ?? attempt.kernel_session_id ?? kernel.sessionId ?? 'unknown'\n const cleanupSucceeded = attempt.session_cleanup_succeeded ?? attempt.kernel_delete_succeeded\n const proxySource = proxyResolution.source ?? attempt.proxyResolutionSource\n return `- Attempt ${attempt.attempt_number ?? attempt.attemptNumber ?? '?'}: ${attempt.outcome ?? attempt.status ?? 'unknown'} · session ${sessionId} · proxy ${debug.request?.proxyMode ?? kernel.proxyMode ?? attempt.proxyMode ?? 'unknown'}${proxySource ? `/${proxySource}` : ''} · ${geo} · CAPTCHA ${nav.captchaDetected === true ? 'yes' : nav.captchaDetected === false ? 'no' : 'unknown'} · cleanup ${cleanupSucceeded === true ? 'yes' : cleanupSucceeded === false ? 'no' : 'unknown'}`\n })\n return `\\n\\nAttempts:\\n${lines.join('\\n')}`\n}\n\ninterface FlatRow { question: string; answer?: string; source_site?: string; source_title?: string }\ninterface OrganicResult { position: number; title: string; url: string; domain: string; snippet?: string | null }\ninterface AIOverview { detected: boolean; text?: string | null }\ninterface HarvestDiagnostics { completionStatus?: string; debug?: unknown }\n\nexport function formatHarvestPaa(\n raw: CallToolResult,\n input: { query: string; maxQuestions?: number; location?: string },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data\n\n const flat = (d.flat as FlatRow[]) ?? []\n const organic = (d.organicResults as OrganicResult[]) ?? []\n const entityIds = d.entityIds as { kgIds?: string[]; cids?: string[]; gcids?: string[] } | undefined\n const aiOvw = d.aiOverview as AIOverview | undefined\n const diagnostics = d.diagnostics as HarvestDiagnostics | undefined\n const durationMs = (d.stats as { durationMs?: number } | undefined)?.durationMs\n\n const paaRows = flat.map((r, i) =>\n `| ${i + 1} | ${cell(r.question)} | ${cell(truncate(r.answer, 120))} | ${cell(r.source_title || r.source_site || '')} |`,\n ).join('\\n')\n\n const paaTable = flat.length\n ? `## People Also Ask (${flat.length} questions)\\n| # | Question | Answer | Source |\\n|---|----------|--------|--------|\\n${paaRows}`\n : '## People Also Ask\\n*Google did not return a People Also Ask block for this query/location. SERP data was extracted successfully when available.*'\n\n const serpRows = organic.map(r =>\n `| ${r.position} | ${cell(r.title)} | [${cell(r.domain)}](${r.url}) | ${cell(truncate(r.snippet, 100))} |`,\n ).join('\\n')\n\n const serpTable = organic.length\n ? `\\n## Organic Results (${organic.length})\\n| # | Title | URL | Snippet |\\n|---|-------|-----|----------|\\n${serpRows}`\n : ''\n\n const aiSection = aiOvw?.detected && aiOvw.text\n ? `\\n## AI Overview\\n> ${truncate(aiOvw.text, 600)}`\n : ''\n\n const statsLine = durationMs\n ? `\\n## Stats\\n- Status: ${diagnostics?.completionStatus ?? (flat.length ? 'paa_found' : 'no_paa')} · Questions: ${flat.length} · Duration: ${(durationMs / 1000).toFixed(1)}s`\n : ''\n\n const tips = `\\n---\\n💡 **Tips**\\n- Max questions: \\`maxQuestions: 200\\` (current: ${input.maxQuestions ?? 30})\\n- Organic results only: use \\`search_serp\\`\\n- Dig into a result: use \\`extract_url\\` on any organic URL`\n\n const full = `# PAA Report: \"${input.query}\"${input.location ? ` · ${input.location}` : ''}\\n\\n${paaTable}${serpTable}${entityIdsSection(entityIds)}${aiSection}${statsLine}${debugSection(diagnostics?.debug)}${tips}`\n\n return {\n ...oneBlock(full),\n structuredContent: {\n query: input.query,\n location: input.location ?? null,\n questionCount: flat.length,\n completionStatus: diagnostics?.completionStatus ?? null,\n questions: flat.map(r => ({\n question: String(r.question ?? ''),\n answer: r.answer ?? null,\n sourceTitle: r.source_title ?? null,\n sourceSite: r.source_site ?? null,\n })),\n organicResults: organic.map(r => ({\n position: Number(r.position) || 0,\n title: String(r.title ?? ''),\n url: String(r.url ?? ''),\n domain: String(r.domain ?? ''),\n snippet: r.snippet ?? null,\n })),\n aiOverview: aiOvw ? { detected: aiOvw.detected === true, text: aiOvw.text ?? null } : null,\n entityIds: entityIds\n ? { kgIds: entityIds.kgIds ?? [], cids: entityIds.cids ?? [], gcids: entityIds.gcids ?? [] }\n : null,\n durationMs: durationMs ?? null,\n },\n }\n}\n\ninterface LocalBusiness { position: number; name: string; rating?: string | null; reviewCount?: string | null; websiteUrl?: string | null }\n\nexport function formatSearchSerp(\n raw: CallToolResult,\n input: { query: string; location?: string },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data\n\n const organic = (d.organicResults as OrganicResult[]) ?? []\n const localPack = (d.localPack as LocalBusiness[]) ?? []\n const entityIds = d.entityIds as { kgIds?: string[]; cids?: string[]; gcids?: string[] } | undefined\n const aiOvw = d.aiOverview as AIOverview | undefined\n const diagnostics = d.diagnostics as HarvestDiagnostics | undefined\n\n const serpRows = organic.map(r =>\n `| ${r.position} | ${cell(r.title)} | [${cell(r.domain)}](${r.url}) | ${cell(truncate(r.snippet, 100))} |`,\n ).join('\\n')\n\n const serpTable = organic.length\n ? `## Organic Results (${organic.length})\\n| # | Title | URL | Snippet |\\n|---|-------|-----|----------|\\n${serpRows}`\n : '## Organic Results\\n*None found*'\n\n const localRows = localPack.map(b =>\n `| ${b.position} | ${cell(b.name)} | ${b.rating ?? '—'} (${b.reviewCount ?? '0'}) | ${b.websiteUrl ? `[link](${b.websiteUrl})` : '—'} |`,\n ).join('\\n')\n\n const localSection = localPack.length\n ? `\\n## Local Pack (${localPack.length})\\n| # | Name | Rating | Website |\\n|---|------|--------|---------|\\n${localRows}`\n : ''\n\n const aiSection = aiOvw?.detected && aiOvw.text\n ? `\\n## AI Overview\\n> ${truncate(aiOvw.text, 600)}`\n : ''\n\n const tips = `\\n---\\n💡 **Tips**\\n- Get PAA questions: use \\`harvest_paa\\` for this query\\n- Scrape any result: use \\`extract_url\\`\\n- Business entity IDs (CID/GCID/KG MID) shown above if found`\n\n const full = `# SERP Report: \"${input.query}\"${input.location ? ` · ${input.location}` : ''}\\n\\n${serpTable}${localSection}${entityIdsSection(entityIds)}${aiSection}${debugSection(diagnostics?.debug)}${tips}`\n\n return {\n ...oneBlock(full),\n structuredContent: {\n query: input.query,\n location: input.location ?? null,\n organicResults: organic.map(r => ({\n position: Number(r.position) || 0,\n title: String(r.title ?? ''),\n url: String(r.url ?? ''),\n domain: String(r.domain ?? ''),\n snippet: r.snippet ?? null,\n })),\n localPack: localPack.map(b => ({\n position: Number(b.position) || 0,\n name: String(b.name ?? ''),\n rating: b.rating ?? null,\n reviewCount: b.reviewCount ?? null,\n websiteUrl: b.websiteUrl ?? null,\n })),\n aiOverview: aiOvw ? { detected: aiOvw.detected === true, text: aiOvw.text ?? null } : null,\n entityIds: entityIds\n ? { kgIds: entityIds.kgIds ?? [], cids: entityIds.cids ?? [], gcids: entityIds.gcids ?? [] }\n : null,\n },\n }\n}\n\ninterface Heading { level: number; text: string }\ninterface KpoResult {\n entityName?: string | null; type?: string[]; napScore?: number\n address?: string | null; phone?: string | null; email?: string | null\n sameAs?: string[]; missingFields?: string[]; faqCount?: number\n}\n\nexport function formatExtractUrl(raw: CallToolResult, input: { url: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data\n\n const url = (d.url as string) ?? input.url\n const title = (d.title as string | null) ?? 'Untitled'\n const headings = (d.headings as Heading[]) ?? []\n const kpo = d.kpo as KpoResult | undefined\n const bodyMd = (d.bodyMarkdown as string | null) ?? ''\n const schema = d.schema as unknown[]\n const screenshotMeta = d.screenshot as { base64: string; sizeBytes: number; device: string } | null | undefined\n const screenshotPath = screenshotMeta?.base64 ? persistScreenshotLocally(screenshotMeta.base64, url) : null\n const branding = d.branding as { colorScheme: string | null; colors: Record<string, string | null>; fonts: Record<string, string | null>; assets: Record<string, string | null> } | null | undefined\n const media = d.media as { outputDir: string | null; assets: unknown[]; filteredCount: number; totalFound: number } | null | undefined\n\n const h1Lines = headings.filter(h => h.level === 1).map(h => `- ${h.text}`).join('\\n')\n const h2Lines = headings.filter(h => h.level === 2).map(h => ` - ${h.text}`).join('\\n')\n const headingSection = (h1Lines || h2Lines)\n ? `\\n## Heading Structure\\n${[h1Lines, h2Lines].filter(Boolean).join('\\n')}`\n : ''\n\n const kpoSection = kpo ? [\n `\\n## Entity / Schema`,\n kpo.entityName ? `- **Entity:** ${kpo.entityName}` : '',\n kpo.type?.length ? `- **@type:** ${kpo.type.join(', ')}` : '',\n kpo.napScore !== undefined ? `- **NAP Score:** ${kpo.napScore}/5` : '',\n kpo.address ? `- **Address:** ${kpo.address}` : '',\n kpo.phone ? `- **Phone:** ${kpo.phone}` : '',\n kpo.email ? `- **Email:** ${kpo.email}` : '',\n kpo.faqCount ? `- **FAQ items:** ${kpo.faqCount}` : '',\n kpo.sameAs?.length ? `- **sameAs:** ${kpo.sameAs.slice(0, 5).join(', ')}` : '',\n kpo.missingFields?.length ? `\\n**Missing schema fields:** ${kpo.missingFields.slice(0, 5).join(', ')}` : '',\n ].filter(Boolean).join('\\n') : ''\n\n const bodySection = bodyMd\n ? `\\n## Page Content\\n${bodyMd.slice(0, 3000)}${bodyMd.length > 3000 ? '\\n\\n*(truncated)*' : ''}`\n : ''\n\n const screenshotSection = screenshotMeta\n ? `\\n## Screenshot\\n- **File:** ${screenshotPath ?? '(returned inline only — disk write unavailable in this environment)'}\\n- **Size:** ${(screenshotMeta.sizeBytes / 1024).toFixed(1)} KB\\n- **Device:** ${screenshotMeta.device}`\n : ''\n\n const brandingSection = branding\n ? [\n `\\n## Branding`,\n branding.colorScheme ? `- **Color scheme:** ${branding.colorScheme}` : '',\n `- **Colors:**${Object.entries(branding.colors ?? {}).filter(([,v]) => v).map(([k,v]) => ` ${k}=${v}`).join(',') || ' (none extracted)'}`,\n `- **Fonts:**${Object.entries(branding.fonts ?? {}).filter(([,v]) => v).map(([k,v]) => ` ${k}=${v}`).join(',') || ' (none extracted)'}`,\n branding.assets?.logo ? `- **Logo:** ${branding.assets.logo}` : '',\n branding.assets?.favicon ? `- **Favicon:** ${branding.assets.favicon}` : '',\n ].filter(Boolean).join('\\n')\n : ''\n\n const mediaSection = media\n ? [\n `\\n## Media Assets`,\n `- **Found:** ${media.totalFound} total, ${media.filteredCount} filtered (ads/noise), ${media.assets.length} downloaded`,\n media.outputDir ? `- **Saved to:** ${media.outputDir}` : '',\n ].filter(Boolean).join('\\n')\n : ''\n\n const schemaCount = Array.isArray(schema) ? schema.length : 0\n const tips = `\\n---\\n💡 **Tips**\\n- Crawl entire site: use \\`extract_site\\`\\n- Map all URLs: use \\`map_site_urls\\`\\n- ${schemaCount} JSON-LD schema block(s) detected`\n\n const full = `# URL Extract: ${url}\\n**${title}**\\n${headingSection}${kpoSection}${brandingSection}${bodySection}${screenshotSection}${mediaSection}${tips}`\n\n const textResult = oneBlock(full)\n const structuredContent = {\n url,\n title: (d.title as string | null) ?? null,\n headings: headings.map(h => ({ level: Number(h.level) || 0, text: String(h.text ?? '') })),\n schemaBlockCount: schemaCount,\n entityName: kpo?.entityName ?? null,\n entityTypes: kpo?.type ?? [],\n napScore: kpo?.napScore ?? null,\n missingSchemaFields: kpo?.missingFields ?? [],\n screenshotSaved: screenshotPath ?? null,\n branding: branding ?? null,\n mediaAssets: media?.assets ?? null,\n }\n\n if (screenshotMeta?.base64) {\n return {\n content: [\n ...(textResult.content),\n { type: 'image', data: screenshotMeta.base64, mimeType: 'image/png' },\n ],\n structuredContent,\n }\n }\n\n return { ...textResult, structuredContent }\n}\n\ninterface DiscoveredUrl { url: string; status: number | null }\ninterface SpiderResult { startUrl: string; urls: DiscoveredUrl[]; totalFound: number; durationMs: number; truncated: boolean }\n\nexport function formatMapSiteUrls(raw: CallToolResult, input: { url: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as SpiderResult\n\n const urls = d.urls ?? []\n const ok = urls.filter(u => (u.status ?? 0) >= 200 && (u.status ?? 0) < 300)\n const broken = urls.filter(u => u.status !== null && u.status >= 400)\n const redirects = urls.filter(u => u.status !== null && u.status >= 300 && u.status < 400)\n\n const urlRows = urls.slice(0, 200).map((u, i) => `| ${i + 1} | ${u.url} | ${u.status ?? '—'} |`).join('\\n')\n\n const full = [\n `# URL Map: ${input.url}`,\n `**${d.totalFound} URLs** · ${(d.durationMs / 1000).toFixed(1)}s${d.truncated ? ' · *truncated*' : ''}`,\n `\\n## Summary\\n- ✅ 2xx: ${ok.length}\\n- 🔀 3xx: ${redirects.length}\\n- ❌ 4xx+: ${broken.length}`,\n `\\n## URL Inventory\\n| # | URL | Status |\\n|---|-----|--------|\\n${urlRows}`,\n broken.length ? `\\n## Broken URLs\\n${broken.map(u => `- ${u.url} (${u.status})`).join('\\n')}` : '',\n `\\n---\\n💡 **Tips**\\n- Extract content from all pages: use \\`extract_site\\`\\n- Scrape a single page: use \\`extract_url\\``,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n startUrl: d.startUrl ?? input.url,\n totalFound: d.totalFound ?? urls.length,\n truncated: d.truncated === true,\n okCount: ok.length,\n redirectCount: redirects.length,\n brokenCount: broken.length,\n urls: urls.map(u => ({ url: u.url, status: u.status ?? null })),\n durationMs: d.durationMs ?? 0,\n },\n }\n}\n\ninterface SitePageResult { url: string; title?: string | null; kpo?: KpoResult; schema?: unknown[] }\ninterface ExtractSiteResult { pages: SitePageResult[]; durationMs?: number }\n\nexport function formatExtractSite(raw: CallToolResult, input: { url: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as ExtractSiteResult\n\n const pages = d.pages ?? []\n\n const pageRows = pages.map((p, i) => {\n const schemaInfo = p.kpo?.type?.join(', ') ?? (Array.isArray(p.schema) && p.schema.length ? `${p.schema.length} block(s)` : '—')\n return `| ${i + 1} | ${cell(p.title ?? 'Untitled')} | ${p.url} | ${schemaInfo} |`\n }).join('\\n')\n\n const full = [\n `# Site Extract: ${input.url}`,\n `**${pages.length} pages** · ${(((d.durationMs ?? 0)) / 1000).toFixed(1)}s`,\n `\\n## Pages\\n| # | Title | URL | Schema |\\n|---|-------|-----|--------|\\n${pageRows}`,\n `\\n---\\n💡 **Tips**\\n- Map URLs first: use \\`map_site_urls\\`\\n- Inspect a single page: use \\`extract_url\\``,\n ].join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n url: input.url,\n pageCount: pages.length,\n pages: pages.map(p => ({\n url: String(p.url ?? ''),\n title: p.title ?? null,\n schemaTypes: p.kpo?.type ?? [],\n })),\n durationMs: d.durationMs ?? 0,\n },\n }\n}\n\ninterface YTVideo { videoId: string; title: string; channelName: string; views?: string | null; duration?: string | null; url: string }\ninterface YTHarvestResult { videos: YTVideo[]; channelMeta?: { title?: string; subscriberCount?: string | null } | null; stats: { durationMs: number } }\n\nexport function formatYoutubeHarvest(\n raw: CallToolResult,\n input: { mode: string; query?: string; channelHandle?: string },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as YTHarvestResult\n\n const videos = d.videos ?? []\n const label = input.mode === 'channel' ? (input.channelHandle ?? 'channel') : `\"${input.query ?? ''}\"`\n\n const videoRows = videos.map((v, i) =>\n `| ${i + 1} | ${cell(truncate(v.title, 70))} | ${cell(v.channelName)} | ${v.views ?? '—'} | ${v.duration ?? '—'} | \\`${v.videoId}\\` |`,\n ).join('\\n')\n\n const channelSection = d.channelMeta\n ? `\\n## Channel\\n- **Name:** ${d.channelMeta.title ?? '—'}\\n- **Subscribers:** ${d.channelMeta.subscriberCount ?? '—'}`\n : ''\n\n const full = [\n `# YouTube Harvest: ${label}`,\n `**${videos.length} videos** · ${(d.stats.durationMs / 1000).toFixed(1)}s`,\n channelSection,\n `\\n## Videos\\n| # | Title | Channel | Views | Duration | Video ID |\\n|---|-------|---------|-------|----------|----------|\\n${videoRows}`,\n `\\n---\\n💡 **Tips**\\n- Transcribe a video: use \\`youtube_transcribe\\` with the \\`videoId\\` above\\n- Switch mode: \\`mode: \"channel\"\\` with \\`channelHandle\\` or \\`mode: \"search\"\\` with \\`query\\``,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n mode: input.mode,\n videoCount: videos.length,\n channel: d.channelMeta\n ? { title: d.channelMeta.title ?? null, subscriberCount: d.channelMeta.subscriberCount ?? null }\n : null,\n videos: videos.map(v => ({\n videoId: String(v.videoId ?? ''),\n title: String(v.title ?? ''),\n channelName: v.channelName ?? null,\n views: v.views ?? null,\n duration: v.duration ?? null,\n url: v.url ?? null,\n })),\n },\n }\n}\n\ninterface TranscriptChunk { timestamp: [number, number]; text: string }\ninterface TranscriptResult { videoId?: string | null; text: string; chunks?: TranscriptChunk[]; durationMs?: number }\n\nfunction structuredTranscriptChunks(chunks: TranscriptChunk[]): Array<{ startSec: number; endSec: number; text: string }> {\n return chunks.map(c => ({\n startSec: Number.isFinite(c.timestamp?.[0]) ? c.timestamp[0] : 0,\n endSec: Number.isFinite(c.timestamp?.[1]) ? c.timestamp[1] : 0,\n text: c.text,\n }))\n}\n\nfunction wordCount(text: string): number {\n return text.trim() ? text.trim().split(/\\s+/).length : 0\n}\n\nexport function formatYoutubeTranscribe(raw: CallToolResult, input: { videoId?: string; url?: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as TranscriptResult\n\n const text = d.text ?? ''\n const chunks = d.chunks ?? []\n const videoId = d.videoId ?? input.videoId ?? null\n const durSec = d.durationMs ? (d.durationMs / 1000).toFixed(0) : '—'\n const words = wordCount(text)\n\n const chunkRows = chunks.slice(0, 50).map(c => {\n const sec = Number.isFinite(c.timestamp[0]) ? Math.floor(c.timestamp[0]) : 0\n const mm = String(Math.floor(sec / 60)).padStart(2, '0')\n const ss = String(sec % 60).padStart(2, '0')\n return `| ${mm}:${ss} | ${cell(truncate(c.text, 120))} |`\n }).join('\\n')\n\n const full = [\n `# YouTube Transcript: \\`${videoId ?? input.url ?? 'video'}\\``,\n `**Duration:** ${durSec}s · **${words} words**`,\n `\\n## Full Transcript\\n${text}`,\n chunks.length ? `\\n## Timestamped Chunks\\n| Time | Text |\\n|------|------|\\n${chunkRows}` : '',\n `\\n---\\n💡 Harvest more from this channel: use \\`youtube_harvest\\` with \\`mode: \"channel\"\\``,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n videoId,\n url: videoId ? `https://www.youtube.com/watch?v=${videoId}` : input.url ?? null,\n wordCount: words,\n chunkCount: chunks.length,\n durationMs: typeof d.durationMs === 'number' ? d.durationMs : null,\n transcriptText: text,\n chunks: structuredTranscriptChunks(chunks),\n resolvedInputs: {\n videoId,\n url: input.url ?? null,\n },\n },\n }\n}\n\ninterface FbAd {\n libraryId?: string; status?: string; creativeType?: string\n headline?: string | null; primaryText?: string | null; cta?: string | null\n startDate?: string | null; started?: string | null\n landingUrl?: string | null; domain?: string | null\n videoUrl?: string | null; videoSrc?: string | null\n imageUrl?: string | null; imageSrc?: string | null; videoPoster?: string | null\n variations?: number; clusterCount?: number | null\n}\ninterface FbPageResult {\n advertiserName?: string | null\n summary: { totalAds: number; activeCount: number; videoCount: number; imageCount: number }\n ads: FbAd[]\n}\n\nexport function formatFacebookPageIntel(\n raw: CallToolResult,\n input: { pageId?: string; libraryId?: string; query?: string },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as FbPageResult\n\n const advertiser = d.advertiserName ?? input.query ?? input.pageId ?? input.libraryId ?? 'Advertiser'\n const ads = d.ads ?? []\n const s = d.summary ?? { totalAds: 0, activeCount: 0, videoCount: 0, imageCount: 0 }\n\n const adBlocks = ads.map((ad, i) => [\n `### Ad ${i + 1}${ad.libraryId ? ` · \\`${ad.libraryId}\\`` : ''} — ${ad.status ?? '—'} · ${ad.creativeType ?? '—'} · ${ad.startDate ?? ad.started ?? '—'}`,\n ad.headline ? `**Headline:** ${ad.headline}` : '',\n ad.primaryText ? `**Copy:** ${truncate(ad.primaryText, 200)}` : '',\n ad.cta ? `**CTA:** ${ad.cta}` : '',\n ad.landingUrl ? `**Landing URL:** ${ad.landingUrl}` : '',\n (ad.videoUrl ?? ad.videoSrc) ? `**Video URL:** \\`${ad.videoUrl ?? ad.videoSrc}\\`` : '',\n (ad.variations ?? ad.clusterCount) ? `**Variations:** ${ad.variations ?? ad.clusterCount}` : '',\n ].filter(Boolean).join('\\n')).join('\\n\\n---\\n\\n')\n\n const full = [\n `# Facebook Ad Intel: ${advertiser}`,\n `**${s.totalAds} ads** · ${s.activeCount} active · ${s.videoCount} video · ${s.imageCount} image`,\n `\\n${adBlocks}`,\n `\\n---\\n💡 **Tips**\\n- Transcribe video ads: use \\`facebook_ad_transcribe\\` with the direct \\`videoUrl\\` above\\n- Transcribe organic Facebook reels/posts: use \\`facebook_video_transcribe\\` with the public Facebook URL\\n- Find other advertisers: use \\`facebook_ad_search\\``,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n advertiserName: d.advertiserName ?? null,\n totalAds: s.totalAds ?? 0,\n activeCount: s.activeCount ?? 0,\n videoCount: s.videoCount ?? 0,\n imageCount: s.imageCount ?? 0,\n ads: ads.map(ad => ({\n libraryId: ad.libraryId ?? null,\n status: ad.status ?? null,\n creativeType: ad.creativeType ?? null,\n primaryText: ad.primaryText ?? null,\n headline: ad.headline ?? null,\n cta: ad.cta ?? null,\n startDate: ad.startDate ?? ad.started ?? null,\n landingUrl: ad.landingUrl ?? null,\n domain: ad.domain ?? null,\n videoUrl: ad.videoUrl ?? ad.videoSrc ?? null,\n imageUrl: ad.imageUrl ?? ad.imageSrc ?? null,\n videoPoster: ad.videoPoster ?? null,\n variations: typeof ad.variations === 'number'\n ? ad.variations\n : typeof ad.clusterCount === 'number'\n ? ad.clusterCount\n : null,\n })),\n },\n }\n}\n\ninterface FbAdvertiserResult { name?: string; pageName?: string; pageId?: string; pageUrl?: string; adCount?: number; libraryId?: string; sampleLibraryId?: string }\ninterface FbSearchResult { results?: FbAdvertiserResult[]; advertisers?: FbAdvertiserResult[] }\n\nexport function formatFacebookAdSearch(raw: CallToolResult, input: { query: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as FbSearchResult\n\n const advertisers = d.results ?? d.advertisers ?? []\n\n const rows = advertisers.map((a, i) =>\n `| ${i + 1} | ${cell(a.pageName ?? a.name)} | ${a.adCount ?? '—'} | \\`${a.sampleLibraryId ?? a.libraryId ?? '—'}\\` |`,\n ).join('\\n')\n\n const full = [\n `# Facebook Ad Library Search: \"${input.query}\"`,\n `**${advertisers.length} advertisers found**`,\n `\\n## Advertisers\\n| # | Name | Ad Count | Library ID |\\n|---|------|----------|------------|\\n${rows}`,\n `\\n---\\n💡 **Tips**\\n- Scan all ads: use \\`facebook_page_intel\\` with \\`libraryId\\`\\n- Or pass the advertiser name as \\`query\\` in \\`facebook_page_intel\\``,\n ].join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n query: input.query,\n advertiserCount: advertisers.length,\n advertisers: advertisers.map(a => ({\n name: a.pageName ?? a.name ?? null,\n pageId: a.pageId ?? null,\n pageUrl: a.pageUrl ?? null,\n adCount: typeof a.adCount === 'number' ? a.adCount : null,\n libraryId: a.sampleLibraryId ?? a.libraryId ?? null,\n sampleLibraryId: a.sampleLibraryId ?? null,\n })),\n },\n }\n}\n\ninterface MapsReviewCard { author: string | null; stars: string | null; date: string | null; text: string | null }\ntype ReviewsStatus = 'collected' | 'none_exist' | 'unavailable' | 'not_requested'\ninterface MapsHistogramEntry { stars: number; count: string }\ninterface MapsTopicEntry { label: string; count: string }\ninterface MapsAboutEntry { section: string; attribute: string }\ninterface MapsSearchBusiness {\n position: number\n name: string\n placeUrl: string\n cid: string | null\n cidDecimal: string | null\n rating: string | null\n reviewCount: string | null\n category: string | null\n address: string | null\n phone: string | null\n hoursStatus: string | null\n websiteUrl: string | null\n directionsUrl: string | null\n metadata: string[]\n}\ninterface MapsSearchAttempt {\n attemptNumber?: number\n attempt_number?: number\n maxAttempts?: number\n max_attempts?: number\n status?: 'ok' | 'failed'\n outcome?: string\n willRetry?: boolean\n will_retry?: boolean\n durationMs?: number\n duration_ms?: number\n resultCount?: number\n result_count?: number\n error?: string | null\n proxyMode?: 'location' | 'configured' | 'none'\n proxy_mode?: 'location' | 'configured' | 'none'\n proxyResolutionSource?: string | null\n proxy_resolution_source?: string | null\n proxyIdSuffix?: string | null\n proxy_id_suffix?: string | null\n proxyTargetLevel?: 'zip' | 'city' | 'state' | null\n proxy_target_level?: 'zip' | 'city' | 'state' | null\n proxyTargetLocation?: string | null\n proxy_target_location?: string | null\n proxyTargetZip?: string | null\n proxy_target_zip?: string | null\n browserSessionIdSuffix?: string | null\n browser_session_id?: string | null\n observedIp?: string | null\n observed_ip?: string | null\n observedCity?: string | null\n observed_city?: string | null\n observedRegion?: string | null\n observed_region?: string | null\n}\ninterface DirectoryWorkflowCity {\n city: string\n state: string\n location: string\n cityKey: string\n censusName: string\n population: number\n populationYear: number\n zips: string[]\n counties: string[]\n status: 'ok' | 'empty' | 'failed'\n error: string | null\n resultCount: number\n durationMs: number\n attempts?: MapsSearchAttempt[]\n results: MapsSearchBusiness[]\n}\ninterface CreditCostEntry { key: string; label: string; credits: number; unit: string; notes?: string }\ninterface CreditLedgerEntry { amount_mc: number; operation: string; description: string | null; created_at: string }\n\nfunction normalizeMapsAttempts(value: unknown): Array<{\n attemptNumber: number\n maxAttempts: number\n status: 'ok' | 'failed'\n outcome: string\n willRetry: boolean\n durationMs: number\n resultCount: number\n error: string | null\n proxyMode: 'location' | 'configured' | 'none'\n proxyResolutionSource: string | null\n proxyIdSuffix: string | null\n proxyTargetLevel: 'zip' | 'city' | 'state' | null\n proxyTargetLocation: string | null\n proxyTargetZip: string | null\n browserSessionIdSuffix: string | null\n observedIp: string | null\n observedCity: string | null\n observedRegion: string | null\n}> {\n const attempts = Array.isArray(value) ? value as MapsSearchAttempt[] : []\n return attempts.map((attempt, index) => ({\n attemptNumber: attempt.attemptNumber ?? attempt.attempt_number ?? index + 1,\n maxAttempts: attempt.maxAttempts ?? attempt.max_attempts ?? attempts.length,\n status: attempt.status === 'ok' ? 'ok' : 'failed',\n outcome: attempt.outcome ?? attempt.status ?? 'unknown',\n willRetry: attempt.willRetry ?? attempt.will_retry ?? false,\n durationMs: attempt.durationMs ?? attempt.duration_ms ?? 0,\n resultCount: attempt.resultCount ?? attempt.result_count ?? 0,\n error: attempt.error ? sanitizeVendorText(attempt.error) : null,\n proxyMode: attempt.proxyMode ?? attempt.proxy_mode ?? 'location',\n proxyResolutionSource: attempt.proxyResolutionSource ?? attempt.proxy_resolution_source ?? null,\n proxyIdSuffix: attempt.proxyIdSuffix ?? attempt.proxy_id_suffix ?? null,\n proxyTargetLevel: attempt.proxyTargetLevel ?? attempt.proxy_target_level ?? null,\n proxyTargetLocation: attempt.proxyTargetLocation ?? attempt.proxy_target_location ?? null,\n proxyTargetZip: attempt.proxyTargetZip ?? attempt.proxy_target_zip ?? null,\n browserSessionIdSuffix: attempt.browserSessionIdSuffix ?? attempt.browser_session_id ?? null,\n observedIp: attempt.observedIp ?? attempt.observed_ip ?? null,\n observedCity: attempt.observedCity ?? attempt.observed_city ?? null,\n observedRegion: attempt.observedRegion ?? attempt.observed_region ?? null,\n }))\n}\n\nfunction workflowArtifactsFrom(run: Record<string, unknown> | undefined): Array<Record<string, unknown>> {\n return Array.isArray(run?.artifacts) ? run.artifacts as Array<Record<string, unknown>> : []\n}\n\nfunction workflowArtifactRows(artifacts: Array<Record<string, unknown>>): string {\n if (!artifacts.length) return ''\n return [\n '| Artifact | Type | ID | Rows/Bytes |',\n '|---|---|---|---|',\n ...artifacts.map(artifact => {\n const rows = artifact.rows_count ?? artifact.rows ?? ''\n const bytes = artifact.bytes ?? ''\n const size = [rows ? `${rows} rows` : '', bytes ? `${bytes} bytes` : ''].filter(Boolean).join(' / ')\n return `| ${cell(String(artifact.label ?? artifact.path ?? 'artifact'))} | ${cell(String(artifact.kind ?? artifact.content_type ?? 'file'))} | \\`${String(artifact.id ?? '')}\\` | ${cell(size || '—')} |`\n }),\n ].join('\\n')\n}\n\nexport function formatWorkflowList(raw: CallToolResult, input: { includeRecipes?: boolean }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const workflows = Array.isArray(parsed.data.workflows) ? parsed.data.workflows as Array<Record<string, unknown>> : []\n const workflowRows = [\n '| Workflow ID | Title | Use |',\n '|---|---|---|',\n ...workflows.map(workflow => `| \\`${String(workflow.id ?? '')}\\` | ${cell(String(workflow.title ?? ''))} | ${cell(String(workflow.description ?? ''))} |`),\n ].join('\\n')\n const recipes = input.includeRecipes === false ? [] : WORKFLOW_RECIPES\n const full = [\n '# MCP Scraper Workflows',\n 'Use `workflow_suggest` when the user describes a high-level job. Use `workflow_run` when the workflow id and input are known. Use `workflow_status` and `workflow_artifact_read` to inspect completed runs and pull evidence back into context.',\n workflows.length ? `\\n## Runnable Workflows\\n${workflowRows}` : '',\n recipes.length ? `\\n## High-Level Recipes\\n${workflowRecipeTable(recipes)}` : '',\n recipes.length ? '\\nThese recipes cover market analysis, ICP research, forum and review acquisition, brand design briefings, CRO audits, competitive positioning, content gaps, and AI search visibility audits.' : '',\n ].filter(Boolean).join('\\n')\n return {\n ...oneBlock(full),\n structuredContent: {\n workflows: workflows.map(workflow => ({\n id: String(workflow.id ?? ''),\n title: String(workflow.title ?? ''),\n description: String(workflow.description ?? ''),\n })),\n recipes,\n },\n }\n}\n\nexport function formatWorkflowSuggest(input: { goal: string; maxSuggestions?: number }): CallToolResult {\n const suggestions = suggestWorkflowRecipes(input.goal, input.maxSuggestions ?? 3)\n const full = [\n `# Workflow Suggestions`,\n `**Goal:** ${input.goal}`,\n '',\n workflowRecipeTable(suggestions),\n '',\n '## How To Execute',\n '1. Pick the closest recipe.',\n '2. If it has a `primaryWorkflowId`, call `workflow_run` with that id and the required inputs.',\n '3. After the run completes, use `workflow_artifact_read` on the most relevant CSV/JSON/Markdown artifacts before writing the final answer.',\n ].join('\\n')\n return {\n ...oneBlock(full),\n structuredContent: {\n goal: input.goal,\n suggestions,\n },\n }\n}\n\nfunction workflowStepLines(data: Record<string, unknown>): string[] {\n const step = data.step as Record<string, unknown> | undefined\n const nextStep = data.nextStep as Record<string, unknown> | null | undefined\n const done = data.done === true\n const lines: string[] = []\n if (step) {\n const index = Number(step.index ?? 0)\n const totalSteps = step.totalSteps != null ? Number(step.totalSteps) : undefined\n const stepLabel = totalSteps ? `${index + 1}/${totalSteps}` : `${index + 1}`\n lines.push(`\\n## Step ${stepLabel}: ${step.title ?? step.id ?? ''}`)\n const output = step.output as Record<string, unknown> | undefined\n if (output && Object.keys(output).length) {\n lines.push(Object.entries(output).map(([k, v]) => `- ${k}: ${typeof v === 'object' ? JSON.stringify(v) : String(v)}`).join('\\n'))\n }\n const warnings = Array.isArray(step.warnings) ? step.warnings as string[] : []\n if (warnings.length) lines.push(`\\n**Warnings:**\\n${warnings.map(w => `- ${w}`).join('\\n')}`)\n }\n if (done) {\n lines.push('\\n**Done.** All steps complete.')\n } else if (nextStep && typeof nextStep === 'object') {\n lines.push(`\\n**Next step:** \\`${nextStep.id ?? nextStep.index}\\` — call \\`workflow_step\\` with this run id to continue.`)\n }\n return lines\n}\n\nexport function formatWorkflowRun(raw: CallToolResult, input: { workflowId: string; input?: Record<string, unknown> }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const run = parsed.data.run as Record<string, unknown> | undefined\n const summary = parsed.data.summary as Record<string, unknown> | undefined\n const artifacts = workflowArtifactsFrom(run)\n const runId = String(run?.id ?? '')\n const status = String(run?.status ?? summary?.status ?? 'unknown')\n const full = [\n `# Workflow Run: ${input.workflowId}`,\n `**Run ID:** \\`${runId || 'unknown'}\\``,\n `**Status:** ${status}`,\n summary?.title ? `**Title:** ${summary.title}` : '',\n ...workflowStepLines(parsed.data),\n summary?.summary ? `\\n## Summary\\n${summary.summary}` : '',\n artifacts.length ? `\\n## Artifacts\\n${workflowArtifactRows(artifacts)}` : '',\n artifacts.length ? '\\nUse `workflow_artifact_read` with the run id and artifact id to pull CSV, JSON, Markdown, or report content into context.' : '',\n ].filter(Boolean).join('\\n')\n return {\n ...oneBlock(full),\n structuredContent: {\n workflowId: input.workflowId,\n input: input.input ?? {},\n run,\n summary,\n step: parsed.data.step,\n nextStep: parsed.data.nextStep ?? null,\n done: parsed.data.done === true,\n artifacts,\n },\n }\n}\n\nexport function formatWorkflowStep(raw: CallToolResult, input: { runId: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const run = parsed.data.run as Record<string, unknown> | undefined\n const summary = parsed.data.summary as Record<string, unknown> | undefined\n const artifacts = workflowArtifactsFrom(run)\n const done = parsed.data.done === true\n const full = [\n `# Workflow Step`,\n `**Run ID:** \\`${input.runId}\\``,\n `**Status:** ${run?.status ?? (done ? 'done' : 'running')}`,\n ...workflowStepLines(parsed.data),\n done && summary?.summary ? `\\n## Summary\\n${summary.summary}` : '',\n artifacts.length ? `\\n## Artifacts\\n${workflowArtifactRows(artifacts)}` : '',\n done && artifacts.length ? '\\nUse `workflow_artifact_read` with the run id and artifact id to pull CSV, JSON, Markdown, or report content into context.' : '',\n ].filter(Boolean).join('\\n')\n return {\n ...oneBlock(full),\n structuredContent: {\n runId: input.runId,\n run,\n summary: summary ?? null,\n step: parsed.data.step,\n nextStep: parsed.data.nextStep ?? null,\n done,\n artifacts,\n },\n }\n}\n\nexport function formatWorkflowStatus(raw: CallToolResult, input: { runId: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const run = parsed.data.run as Record<string, unknown> | undefined\n const artifacts = workflowArtifactsFrom(run)\n const full = [\n `# Workflow Status`,\n `**Run ID:** \\`${input.runId}\\``,\n `**Workflow:** ${run?.workflow_id ?? 'unknown'}`,\n `**Status:** ${run?.status ?? 'unknown'}`,\n run?.error_message ? `\\n## Error\\n${run.error_message}` : '',\n artifacts.length ? `\\n## Artifacts\\n${workflowArtifactRows(artifacts)}` : '',\n ].filter(Boolean).join('\\n')\n return {\n ...oneBlock(full),\n structuredContent: {\n run,\n artifacts,\n },\n }\n}\n\nexport function formatWorkflowArtifactRead(raw: CallToolResult, input: { runId: string; artifactId: string; maxBytes?: number }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const text = typeof parsed.data.text === 'string' ? parsed.data.text : ''\n const contentType = String(parsed.data.contentType ?? 'text/plain')\n const bytes = Number(parsed.data.bytes ?? 0)\n const truncated = parsed.data.truncated === true\n const full = [\n `# Workflow Artifact`,\n `**Run ID:** \\`${input.runId}\\``,\n `**Artifact ID:** \\`${input.artifactId}\\``,\n `**Content-Type:** ${contentType}`,\n `**Bytes:** ${bytes}${truncated ? ` (truncated to ${input.maxBytes ?? 200000})` : ''}`,\n '',\n '```',\n text,\n '```',\n ].join('\\n')\n return {\n ...oneBlock(full),\n structuredContent: {\n runId: input.runId,\n artifactId: input.artifactId,\n contentType,\n bytes,\n truncated,\n text,\n },\n }\n}\n\nexport function formatCreditsInfo(raw: CallToolResult, input: { item?: string; includeLedger?: boolean }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as Record<string, unknown>\n\n const balance = d.balance_credits as number | undefined\n const costs = (d.costs as CreditCostEntry[] | undefined) ?? []\n const matched = d.matched_cost as CreditCostEntry | null\n const ledger = (d.ledger as CreditLedgerEntry[] | undefined) ?? []\n const concurrencyRaw = d.concurrency as Record<string, unknown> | undefined\n const upgradeRaw = concurrencyRaw?.upgrade as Record<string, unknown> | undefined\n\n const costRows = costs.map(c => {\n const notes = c.notes ? ` ${c.notes}` : ''\n return `| ${c.label} | ${c.credits} | ${c.unit}${notes} |`\n }).join('\\n')\n\n const ledgerRows = ledger.map(row => {\n const credits = row.amount_mc / 1000\n return `| ${row.created_at} | ${row.operation} | ${credits} | ${row.description ?? ''} |`\n }).join('\\n')\n\n const matchedSection = matched\n ? `\\n## Matched Cost\\n**${matched.label}:** ${matched.credits} credits ${matched.unit}${matched.notes ? `\\n\\n${matched.notes}` : ''}`\n : input.item\n ? `\\n## Matched Cost\\nNo exact cost match found for \"${input.item}\". See the full cost table below.`\n : ''\n\n const concurrencySection = concurrencyRaw\n ? [\n `\\n## Concurrency`,\n `**Current limit:** ${concurrencyRaw.current_limit ?? 'unknown'} concurrent operation${concurrencyRaw.current_limit === 1 ? '' : 's'}`,\n `**Extra slots:** ${concurrencyRaw.current_extra_slots ?? 'unknown'}`,\n `**Extra concurrency slot:** ${upgradeRaw?.price_label ?? '$5/month'}`,\n `**Upgrade in terminal:** \\`${upgradeRaw?.terminal_command ?? 'npx -y -p mcp-scraper@latest mcp-scraper-cli billing concurrency checkout'}\\``,\n `**Billing URL:** ${upgradeRaw?.billing_url ?? 'https://mcpscraper.dev/billing'}`,\n ].join('\\n')\n : ''\n\n const full = [\n `# Credits`,\n `**Balance:** ${balance ?? 'unknown'} credits`,\n matchedSection,\n concurrencySection,\n costs.length ? `\\n## Cost Table\\n| Item | Credits | Unit |\\n|------|---------|------|\\n${costRows}` : '',\n ledger.length ? `\\n## Recent Ledger\\n| Date | Operation | Credits | Description |\\n|------|-----------|---------|-------------|\\n${ledgerRows}` : '',\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n balanceCredits: typeof balance === 'number' ? balance : null,\n matchedCost: matched\n ? { label: matched.label, credits: matched.credits, unit: matched.unit, notes: matched.notes ?? null }\n : null,\n costs: costs.map(c => ({\n key: c.key,\n label: c.label,\n credits: c.credits,\n unit: c.unit,\n notes: c.notes ?? null,\n })),\n ledger: ledger.map(row => ({\n createdAt: String(row.created_at ?? ''),\n operation: String(row.operation ?? ''),\n credits: row.amount_mc / 1000,\n description: row.description ?? null,\n })),\n concurrency: concurrencyRaw && upgradeRaw\n ? {\n currentExtraSlots: Number(concurrencyRaw.current_extra_slots ?? 0),\n currentLimit: Number(concurrencyRaw.current_limit ?? 1),\n hasSubscription: concurrencyRaw.has_subscription === true,\n upgrade: {\n product: String(upgradeRaw.product ?? 'Extra concurrency slot'),\n priceLabel: String(upgradeRaw.price_label ?? '$5/month'),\n unitAmountUsd: Number(upgradeRaw.unit_amount_usd ?? 5),\n currency: String(upgradeRaw.currency ?? 'usd'),\n interval: String(upgradeRaw.interval ?? 'month'),\n billingUrl: String(upgradeRaw.billing_url ?? 'https://mcpscraper.dev/billing'),\n terminalCommand: String(upgradeRaw.terminal_command ?? 'npx -y -p mcp-scraper@latest mcp-scraper-cli billing concurrency checkout'),\n terminalCommandWithApiKeyEnv: String(upgradeRaw.terminal_command_with_api_key_env ?? 'MCP_SCRAPER_API_KEY=sk_live_your_key npx -y -p mcp-scraper@latest mcp-scraper-cli billing concurrency checkout'),\n },\n }\n : null,\n },\n }\n}\n\nexport function formatMapsSearch(\n raw: CallToolResult,\n input: { query: string; location?: string; maxResults?: number },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as Record<string, unknown>\n const results = (d.results as MapsSearchBusiness[]) ?? []\n const normalizedResults = results.map(result => ({\n ...result,\n phone: result.phone ?? null,\n hoursStatus: result.hoursStatus ?? null,\n }))\n const searchQuery = (d.searchQuery as string | undefined) ?? [input.query, input.location].filter(Boolean).join(' ')\n const requestedMax = (d.requestedMaxResults as number | undefined) ?? input.maxResults ?? 10\n const durationMs = d.durationMs as number | undefined\n const attempts = normalizeMapsAttempts(d.attempts)\n const lastAttempt = attempts.at(-1)\n\n const rows = results.map((r) => {\n const rating = [r.rating, r.reviewCount ? `(${r.reviewCount})` : null].filter(Boolean).join(' ')\n return `| ${r.position} | ${cell(r.name)} | ${cell(r.category)} | ${cell(rating)} | ${cell(r.address)} | ${r.cidDecimal ? `\\`${r.cidDecimal}\\`` : '—'} | ${r.websiteUrl ? `[site](${r.websiteUrl})` : '—'} | [maps](${r.placeUrl}) |`\n }).join('\\n')\n\n const metadataSection = results.length\n ? `\\n## Candidate Metadata\\n${results.map(r => {\n const meta = r.metadata?.length ? r.metadata.slice(0, 8).map(m => ` - ${m}`).join('\\n') : ' - none'\n return `### ${r.position}. ${r.name}\\n${meta}`\n }).join('\\n\\n')}`\n : ''\n\n const full = [\n `# Google Maps Search: \"${searchQuery}\"`,\n `**Returned:** ${results.length} profile candidate${results.length === 1 ? '' : 's'} · **Requested max:** ${requestedMax} · **Limit:** 50`,\n attempts.length ? `**Attempts:** ${attempts.length}/${lastAttempt?.maxAttempts ?? attempts.length} · **Proxy:** ${lastAttempt?.proxyMode ?? 'unknown'}${lastAttempt?.proxyResolutionSource ? `/${lastAttempt.proxyResolutionSource}` : ''} · **Observed:** ${[lastAttempt?.observedCity, lastAttempt?.observedRegion].filter(Boolean).join(', ') || 'unknown'}` : null,\n `\\n## Results\\n| # | Name | Category | Rating | Address | CID | Website | Maps |\\n|---|------|----------|--------|---------|-----|---------|------|\\n${rows}`,\n metadataSection,\n `\\n---\\n💡 **Next step:** use \\`maps_place_intel\\` with a selected business name and location to hydrate full hours, phone, review topics, and optional review cards.`,\n durationMs != null ? `\\n*Extracted in ${(durationMs / 1000).toFixed(1)}s*` : null,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n query: d.query,\n location: d.location ?? null,\n searchQuery: d.searchQuery,\n searchUrl: d.searchUrl,\n extractedAt: d.extractedAt,\n requestedMaxResults: requestedMax,\n resultCount: results.length,\n results: normalizedResults,\n attempts,\n durationMs: durationMs ?? 0,\n },\n }\n}\n\nexport function formatDirectoryWorkflow(\n raw: CallToolResult,\n input: { query: string; state?: string; minPopulation?: number; maxResultsPerCity?: number },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as Record<string, unknown>\n const cities = ((d.cities as DirectoryWorkflowCity[]) ?? []).map(city => ({\n ...city,\n attempts: normalizeMapsAttempts(city.attempts),\n results: city.results.map(result => ({\n ...result,\n phone: result.phone ?? null,\n hoursStatus: result.hoursStatus ?? null,\n })),\n }))\n const warnings = (d.warnings as string[] | undefined) ?? []\n const csvPath = (d.csvPath as string | null | undefined) ?? null\n const totalResultCount = (d.totalResultCount as number | undefined) ?? cities.reduce((sum, city) => sum + city.resultCount, 0)\n const durationMs = d.durationMs as number | undefined\n\n const marketRows = cities.map((city) => {\n const zips = city.zips?.length ? city.zips.slice(0, 8).join(' ') + (city.zips.length > 8 ? ` +${city.zips.length - 8}` : '') : '—'\n return `| ${cell(city.city)} | ${city.population.toLocaleString()} | ${city.zips?.length ?? 0} | ${city.resultCount} | ${city.status} | ${cell(zips)} |`\n }).join('\\n')\n\n const businessRows = cities\n .flatMap(city => city.results.slice(0, 3).map(result => ({ city, result })))\n .map(({ city, result }) => {\n const rating = [result.rating, result.reviewCount ? `(${result.reviewCount})` : null].filter(Boolean).join(' ')\n return `| ${cell(city.city)} | ${result.position} | ${cell(result.name)} | ${cell(result.category)} | ${cell(rating)} | ${result.websiteUrl ? `[site](${result.websiteUrl})` : '—'} | [maps](${result.placeUrl}) |`\n }).join('\\n')\n\n const warningText = warnings.length ? `\\n## Warnings\\n${warnings.map(w => `- ${w}`).join('\\n')}` : ''\n const csvText = csvPath ? `\\n**CSV:** \\`${csvPath}\\`` : ''\n const full = [\n `# Directory Workflow: ${input.query}`,\n `**Markets:** ${cities.length} · **Maps results:** ${totalResultCount} · **State:** ${d.state ?? input.state ?? 'US'} · **Population threshold:** ${d.minPopulation ?? input.minPopulation ?? 100000}`,\n csvText,\n `\\n## Markets\\n| City | Population | ZIPs | Maps Results | Status | ZIP Sample |\\n|---|---:|---:|---:|---|---|\\n${marketRows}`,\n businessRows ? `\\n## Top Candidates By City\\n| City | # | Name | Category | Rating | Website | Maps |\\n|---|---:|---|---|---|---|---|\\n${businessRows}` : null,\n warningText,\n `\\n## Sources\\n- Population: ${d.censusSourceUrl ?? 'Census Population Estimates Program'}\\n- ZIP groups: ${d.usZipsSourcePath ?? 'not configured'}`,\n durationMs != null ? `\\n*Completed in ${(durationMs / 1000).toFixed(1)}s*` : null,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n query: d.query,\n state: d.state,\n minPopulation: d.minPopulation,\n populationYear: d.populationYear,\n maxResultsPerCity: d.maxResultsPerCity,\n concurrency: d.concurrency,\n censusSourceUrl: d.censusSourceUrl,\n usZipsSourcePath: d.usZipsSourcePath ?? null,\n warnings,\n extractedAt: d.extractedAt,\n selectedCityCount: d.selectedCityCount,\n totalResultCount,\n csvPath,\n cities,\n durationMs: durationMs ?? 0,\n },\n }\n}\n\nexport function formatMapsPlaceIntel(\n raw: CallToolResult,\n input: { businessName: string; location: string; includeReviews?: boolean },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as Record<string, unknown>\n\n const name = (d.name as string | null) ?? input.businessName\n const rating = d.rating as string | null\n const reviewCount = d.reviewCount as string | null\n const category = d.category as string | null\n const address = d.address as string | null\n const phone = d.phoneDisplay as string | null\n const website = d.website as string | null\n const hoursSummary = d.hoursSummary as string | null\n const plusCode = d.plusCode as string | null\n const bookingUrl = d.bookingUrl as string | null\n const kgmid = d.kgmid as string | null\n const cidDecimal = d.cidDecimal as string | null\n const cidUrl = d.cidUrl as string | null\n const lat = d.lat as number | null\n const lng = d.lng as number | null\n const durationMs = d.durationMs as number | null\n\n const histogram = (d.reviewHistogram as MapsHistogramEntry[]) ?? []\n const topics = (d.reviewTopics as MapsTopicEntry[]) ?? []\n const about = (d.aboutAttributes as MapsAboutEntry[]) ?? []\n const reviews = (d.reviews as MapsReviewCard[]) ?? []\n const reviewsStatus = (d.reviewsStatus as ReviewsStatus | undefined) ?? 'not_requested'\n\n const hoursTable = (d.hoursTable as Array<{ day: string; hours: string }>) ?? []\n\n const ratingLine = [rating, reviewCount ? `(${reviewCount} reviews)` : null].filter(Boolean).join(' ')\n\n const basicLines = [\n address ? `- **Address:** ${address}` : null,\n phone ? `- **Phone:** ${phone}` : null,\n website ? `- **Website:** ${website}` : null,\n hoursSummary ? `- **Hours:** ${hoursSummary}` : null,\n plusCode ? `- **Plus Code:** ${plusCode}` : null,\n bookingUrl ? `- **Book:** ${bookingUrl}` : null,\n ].filter(Boolean).join('\\n')\n\n const hoursSection = hoursTable.length\n ? `\\n## Hours\\n| Day | Hours |\\n|-----|-------|\\n${hoursTable.map(r => `| ${r.day} | ${r.hours} |`).join('\\n')}`\n : ''\n\n const histSection = histogram.length\n ? `\\n## Rating Distribution\\n| Stars | Count |\\n|-------|-------|\\n${histogram.map(r => `| ${'★'.repeat(r.stars)}${'☆'.repeat(5 - r.stars)} | ${r.count} |`).join('\\n')}`\n : ''\n\n const topicsSection = topics.length\n ? `\\n## Review Topics\\n${topics.map(t => `- **${t.label}:** ${t.count} mentions`).join('\\n')}`\n : ''\n\n const aboutBySection: Record<string, string[]> = {}\n for (const a of about) {\n if (!aboutBySection[a.section]) aboutBySection[a.section] = []\n aboutBySection[a.section].push(a.attribute)\n }\n const aboutSection = Object.keys(aboutBySection).length\n ? `\\n## About\\n${Object.entries(aboutBySection).map(([s, attrs]) => `**${s}**\\n${attrs.map(a => `- ${a}`).join('\\n')}`).join('\\n\\n')}`\n : ''\n\n const entitySection = [\n kgmid ? `- **KGMID:** \\`${kgmid}\\`` : null,\n cidDecimal ? `- **CID:** \\`${cidDecimal}\\`` : null,\n cidUrl ? `- **Maps CID URL:** ${cidUrl}` : null,\n lat != null && lng != null ? `- **Coordinates:** ${lat}, ${lng}` : null,\n ].filter(Boolean).join('\\n')\n\n const reviewsSection = (() => {\n if (reviewsStatus === 'not_requested') return ''\n if (reviewsStatus === 'unavailable') return '\\n## Reviews\\n> Reviews could not be retrieved this run — retry with `includeReviews: true`.'\n if (reviewsStatus === 'none_exist') return '\\n## Reviews\\n*This business has no reviews on Google Maps.*'\n if (reviews.length === 0) return '\\n## Reviews\\n*0 reviews collected.*'\n return `\\n## Reviews (${reviews.length})\\n${reviews.map((r, i) => {\n const starsN = parseInt(r.stars ?? '0')\n const stars = '★'.repeat(starsN) + '☆'.repeat(5 - starsN)\n return `### ${i + 1}. ${r.author ?? 'Anonymous'} — ${stars}\\n*${r.date ?? ''}*\\n\\n${r.text ?? ''}`\n }).join('\\n\\n')}`\n })()\n\n const full = [\n `# ${name}`,\n category ? `*${category}*` : null,\n ratingLine ? `\\n**Rating:** ${ratingLine}` : null,\n basicLines ? `\\n${basicLines}` : null,\n hoursSection,\n histSection,\n topicsSection,\n aboutSection,\n entitySection ? `\\n## Entity IDs\\n${entitySection}` : null,\n reviewsSection,\n durationMs != null ? `\\n---\\n*Extracted in ${(durationMs / 1000).toFixed(1)}s*` : null,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n name,\n rating: rating ?? null,\n reviewCount: reviewCount ?? null,\n category: category ?? null,\n address: address ?? null,\n phone: phone ?? null,\n website: website ?? null,\n hoursSummary: hoursSummary ?? null,\n bookingUrl: bookingUrl ?? null,\n kgmid: kgmid ?? null,\n cidDecimal: cidDecimal ?? null,\n cidUrl: cidUrl ?? null,\n lat: lat ?? null,\n lng: lng ?? null,\n reviewsStatus,\n reviewsCollected: reviews.length,\n reviewTopics: topics.map(t => ({ label: String(t.label ?? ''), count: String(t.count ?? '') })),\n },\n }\n}\n\nexport function formatFacebookAdTranscribe(raw: CallToolResult, input: { videoUrl: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as TranscriptResult\n\n const text = d.text ?? ''\n const chunks = d.chunks ?? []\n const durSec = d.durationMs ? (d.durationMs / 1000).toFixed(0) : '—'\n const words = wordCount(text)\n\n const chunkRows = chunks.slice(0, 50).map(c => {\n const sec = Number.isFinite(c.timestamp[0]) ? Math.floor(c.timestamp[0]) : 0\n const mm = String(Math.floor(sec / 60)).padStart(2, '0')\n const ss = String(sec % 60).padStart(2, '0')\n return `| ${mm}:${ss} | ${cell(truncate(c.text, 120))} |`\n }).join('\\n')\n\n const full = [\n `# Facebook Ad Transcript`,\n `**Duration:** ${durSec}s · **${words} words**`,\n `\\n## Full Transcript\\n${text}`,\n chunks.length ? `\\n## Timestamped Chunks\\n| Time | Text |\\n|------|------|\\n${chunkRows}` : '',\n `\\n---\\n💡 Get more ads from this advertiser: use \\`facebook_page_intel\\`. For public Facebook reel/post URLs, use \\`facebook_video_transcribe\\`.`,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n videoUrl: input.videoUrl,\n wordCount: words,\n chunkCount: chunks.length,\n durationMs: typeof d.durationMs === 'number' ? d.durationMs : null,\n transcriptText: text,\n chunks: structuredTranscriptChunks(chunks),\n resolvedInputs: {\n videoUrl: input.videoUrl,\n },\n },\n }\n}\n\ninterface FacebookVideoTranscriptResult extends TranscriptResult {\n sourceUrl?: string\n pageUrl?: string\n videoId?: string | null\n ownerName?: string | null\n selectedQuality?: string\n bitrate?: number | null\n videoDurationSec?: number | null\n videoUrl?: string\n}\n\nexport function formatFacebookVideoTranscribe(raw: CallToolResult, input: { url: string; quality?: string }): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data as unknown as FacebookVideoTranscriptResult\n\n const text = d.text ?? ''\n const chunks = d.chunks ?? []\n const wordCount = text.trim() ? text.trim().split(/\\s+/).length : 0\n const durSec = d.durationMs ? (d.durationMs / 1000).toFixed(0) : '—'\n const videoDuration = typeof d.videoDurationSec === 'number' ? `${Math.round(d.videoDurationSec)}s` : '—'\n const label = d.videoId ? `Facebook Organic Video \\`${d.videoId}\\`` : 'Facebook Organic Video'\n\n const chunkRows = chunks.slice(0, 50).map(c => {\n const sec = Number.isFinite(c.timestamp[0]) ? Math.floor(c.timestamp[0]) : 0\n const mm = String(Math.floor(sec / 60)).padStart(2, '0')\n const ss = String(sec % 60).padStart(2, '0')\n return `| ${mm}:${ss} | ${cell(truncate(c.text, 120))} |`\n }).join('\\n')\n\n const full = [\n `# ${label} Transcript`,\n d.ownerName ? `**Owner:** ${d.ownerName}` : '',\n `**Video duration:** ${videoDuration} · **Transcribed in:** ${durSec}s · **${wordCount} words**`,\n d.pageUrl ? `**Page URL:** ${d.pageUrl}` : `**Page URL:** ${input.url}`,\n d.videoUrl ? `**Extracted MP4:** \\`${d.videoUrl}\\`` : '',\n `\\n## Full Transcript\\n${text}`,\n chunks.length ? `\\n## Timestamped Chunks\\n| Time | Text |\\n|------|------|\\n${chunkRows}` : '',\n `\\n---\\n💡 Use \\`videoUrl\\` as the extracted MP4 for download or follow-up processing. Use \\`facebook_ad_transcribe\\` only for Ad Library videoUrl values.`,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n sourceUrl: d.sourceUrl ?? input.url,\n pageUrl: d.pageUrl ?? input.url,\n videoId: d.videoId ?? null,\n ownerName: d.ownerName ?? null,\n selectedQuality: d.selectedQuality ?? input.quality ?? 'best',\n bitrate: typeof d.bitrate === 'number' ? d.bitrate : null,\n videoDurationSec: typeof d.videoDurationSec === 'number' ? d.videoDurationSec : null,\n videoUrl: d.videoUrl ?? '',\n wordCount,\n chunkCount: chunks.length,\n transcriptText: text,\n chunks: chunks.map(c => ({\n startSec: Number.isFinite(c.timestamp[0]) ? c.timestamp[0] : 0,\n endSec: Number.isFinite(c.timestamp[1]) ? c.timestamp[1] : 0,\n text: c.text,\n })),\n },\n }\n}\n\ninterface InstagramProfileItem {\n url: string\n type: 'post' | 'reel' | 'tv'\n shortcode: string\n anchorText?: string | null\n firstSeenStage?: string\n}\n\ninterface InstagramMediaTrack {\n url: string\n streamType: 'video' | 'audio' | 'unknown'\n bitrate?: number | null\n durationSec?: number | null\n vencodeTag?: string | null\n width?: number | null\n height?: number | null\n}\n\ninterface InstagramDownload {\n kind: 'text' | 'image' | 'video' | 'audio' | 'muxed_video'\n url: string | null\n savedPath: string | null\n sizeBytes: number | null\n mimeType: string | null\n error: string | null\n}\n\ninterface StructuredInstagramBrowser {\n mode: 'hosted'\n requestedMode: 'hosted'\n profileName: string | null\n profileSource: 'hosted'\n profileDirConfigured: boolean\n executablePathConfigured: boolean\n}\n\ninterface StructuredInstagramPagination {\n maxItems: number\n maxScrolls: number\n attemptedScrolls: number\n stableScrolls: number\n stableScrollLimit: number\n scrollDelayMs: number\n reachedMaxItems: boolean\n reachedReportedPostCount: boolean\n finalScrollHeight: number | null\n stoppedReason: 'max_items' | 'reported_post_count' | 'stable_scrolls' | 'max_scrolls' | 'no_scrolls'\n stages: Array<{\n stage: string\n itemCount: number\n addedCount: number\n scrollY: number | null\n scrollHeight: number | null\n }>\n}\n\nfunction structuredInstagramBrowser(raw: unknown): StructuredInstagramBrowser {\n const browser = raw && typeof raw === 'object' ? raw as Record<string, unknown> : {}\n return {\n mode: 'hosted',\n requestedMode: 'hosted',\n profileName: typeof browser.profileName === 'string' ? browser.profileName : null,\n profileSource: 'hosted',\n profileDirConfigured: false,\n executablePathConfigured: false,\n }\n}\n\nfunction structuredInstagramPagination(raw: unknown, input: { maxItems?: number; maxScrolls?: number; scrollDelayMs?: number; stableScrollLimit?: number }): StructuredInstagramPagination {\n const pagination = raw && typeof raw === 'object' ? raw as Record<string, unknown> : {}\n const stages = Array.isArray(pagination.stages) ? pagination.stages : []\n const stoppedReason = (typeof pagination.stoppedReason === 'string'\n && ['max_items', 'reported_post_count', 'stable_scrolls', 'max_scrolls', 'no_scrolls'].includes(pagination.stoppedReason)\n ? pagination.stoppedReason\n : 'no_scrolls') as StructuredInstagramPagination['stoppedReason']\n return {\n maxItems: typeof pagination.maxItems === 'number' ? pagination.maxItems : Number(input.maxItems ?? 50),\n maxScrolls: typeof pagination.maxScrolls === 'number' ? pagination.maxScrolls : Number(input.maxScrolls ?? 10),\n attemptedScrolls: typeof pagination.attemptedScrolls === 'number' ? pagination.attemptedScrolls : 0,\n stableScrolls: typeof pagination.stableScrolls === 'number' ? pagination.stableScrolls : 0,\n stableScrollLimit: typeof pagination.stableScrollLimit === 'number' ? pagination.stableScrollLimit : Number(input.stableScrollLimit ?? 4),\n scrollDelayMs: typeof pagination.scrollDelayMs === 'number' ? pagination.scrollDelayMs : Number(input.scrollDelayMs ?? 1200),\n reachedMaxItems: pagination.reachedMaxItems === true,\n reachedReportedPostCount: pagination.reachedReportedPostCount === true,\n finalScrollHeight: typeof pagination.finalScrollHeight === 'number' ? pagination.finalScrollHeight : null,\n stoppedReason,\n stages: stages.map((stage) => {\n const row = stage && typeof stage === 'object' ? stage as Record<string, unknown> : {}\n return {\n stage: String(row.stage ?? ''),\n itemCount: typeof row.itemCount === 'number' ? row.itemCount : 0,\n addedCount: typeof row.addedCount === 'number' ? row.addedCount : 0,\n scrollY: typeof row.scrollY === 'number' ? row.scrollY : null,\n scrollHeight: typeof row.scrollHeight === 'number' ? row.scrollHeight : null,\n }\n }),\n }\n}\n\nexport function formatInstagramProfileContent(\n raw: CallToolResult,\n input: { handle?: string; url?: string; maxItems?: number; maxScrolls?: number; scrollDelayMs?: number; stableScrollLimit?: number },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data\n const items = (Array.isArray(d.items) ? d.items : []) as InstagramProfileItem[]\n const typeCounts = d.typeCounts as Record<string, number> | undefined\n const limitations = Array.isArray(d.limitations) ? d.limitations.map(String) : []\n const browser = structuredInstagramBrowser(d.browser)\n const pagination = structuredInstagramPagination(d.pagination, input)\n const itemRows = items.slice(0, 100).map((item, i) =>\n `| ${i + 1} | ${item.type} | \\`${item.shortcode}\\` | ${item.url} | ${cell(item.firstSeenStage ?? '')} |`,\n ).join('\\n')\n const browserLabel = browser.profileName ? `hosted browser profile ${browser.profileName}` : 'hosted browser'\n\n const full = [\n `# Instagram Profile Content: ${d.handle ?? input.handle ?? input.url ?? 'profile'}`,\n `**Collected:** ${items.length} items · posts ${typeCounts?.post ?? 0} · reels ${typeCounts?.reel ?? 0} · tv ${typeCounts?.tv ?? 0}`,\n `**Browser:** ${browserLabel}`,\n `**Pagination:** ${pagination.attemptedScrolls} scrolls · stopped: ${pagination.stoppedReason}`,\n d.reportedPostCountText ? `**Profile count:** ${d.reportedPostCountText}` : '',\n d.followerCountText ? `**Followers:** ${d.followerCountText}` : '',\n `\\n## Content Links\\n| # | Type | Shortcode | URL | First Seen |\\n|---|------|-----------|-----|------------|\\n${itemRows || '| — | — | — | — | — |'}`,\n limitations.length ? `\\n## Limits\\n${limitations.map(l => `- ${l}`).join('\\n')}` : '',\n `\\n---\\n💡 Use \\`instagram_media_download\\` with one of these URLs to download text, image, reel tracks, and optional transcript.`,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n handle: String(d.handle ?? input.handle ?? ''),\n profileUrl: String(d.profileUrl ?? input.url ?? ''),\n pageUrl: String(d.pageUrl ?? d.profileUrl ?? input.url ?? ''),\n browser,\n profileName: typeof d.profileName === 'string' ? d.profileName : null,\n reportedPostCount: typeof d.reportedPostCount === 'number' ? d.reportedPostCount : null,\n reportedPostCountText: typeof d.reportedPostCountText === 'string' ? d.reportedPostCountText : null,\n followerCountText: typeof d.followerCountText === 'string' ? d.followerCountText : null,\n followingCountText: typeof d.followingCountText === 'string' ? d.followingCountText : null,\n collectedContentCount: items.length,\n typeCounts: {\n post: Number(typeCounts?.post ?? 0),\n reel: Number(typeCounts?.reel ?? 0),\n tv: Number(typeCounts?.tv ?? 0),\n },\n pagination,\n limited: d.limited === true,\n limitations,\n items: items.map(item => ({\n url: String(item.url ?? ''),\n type: item.type,\n shortcode: String(item.shortcode ?? ''),\n anchorText: item.anchorText ?? null,\n firstSeenStage: String(item.firstSeenStage ?? ''),\n })),\n },\n }\n}\n\nfunction structuredInstagramTrack(track: InstagramMediaTrack | null | undefined): Record<string, unknown> | null {\n if (!track) return null\n return {\n url: String(track.url ?? ''),\n streamType: track.streamType ?? 'unknown',\n bitrate: typeof track.bitrate === 'number' ? track.bitrate : null,\n durationSec: typeof track.durationSec === 'number' ? track.durationSec : null,\n vencodeTag: track.vencodeTag ?? null,\n width: typeof track.width === 'number' ? track.width : null,\n height: typeof track.height === 'number' ? track.height : null,\n }\n}\n\nexport function formatInstagramMediaDownload(\n raw: CallToolResult,\n input: { url: string; includeTranscript?: boolean },\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data\n const tracks = (Array.isArray(d.tracks) ? d.tracks : []) as InstagramMediaTrack[]\n const downloads = (Array.isArray(d.downloads) ? d.downloads : []) as InstagramDownload[]\n const warnings = Array.isArray(d.warnings) ? d.warnings.map(String) : []\n const limitations = Array.isArray(d.limitations) ? d.limitations.map(String) : []\n const transcript = d.transcript as TranscriptResult | null | undefined\n const transcriptText = transcript?.text ?? ''\n const chunks = transcript?.chunks ?? []\n const browser = structuredInstagramBrowser(d.browser)\n const browserLabel = browser.profileName ? `hosted browser profile ${browser.profileName}` : 'hosted browser'\n\n const downloadRows = downloads.map((download, i) => {\n const status = download.error ? `error: ${cell(download.error)}` : `${download.sizeBytes ?? 0} bytes`\n return `| ${i + 1} | ${download.kind} | ${download.savedPath ? `\\`${download.savedPath}\\`` : '—'} | ${status} |`\n }).join('\\n')\n const trackRows = tracks.slice(0, 20).map((track, i) =>\n `| ${i + 1} | ${track.streamType} | ${track.bitrate ?? '—'} | ${track.durationSec ?? '—'} | ${cell(track.vencodeTag ?? '')} |`,\n ).join('\\n')\n\n const full = [\n `# Instagram Media Download`,\n `**URL:** ${d.pageUrl ?? input.url}`,\n `**Browser:** ${browserLabel}`,\n d.ownerName ? `**Owner:** ${d.ownerName}` : '',\n d.shortcode ? `**Shortcode:** \\`${d.shortcode}\\`` : '',\n d.caption ? `\\n## Caption\\n${truncate(String(d.caption), 1200)}` : '',\n d.imageUrl ? `\\n## Image\\n${d.imageUrl}` : '',\n tracks.length ? `\\n## Media Tracks\\n| # | Type | Bitrate | Duration | Tag |\\n|---|------|---------|----------|-----|\\n${trackRows}` : '\\n## Media Tracks\\n*None captured.*',\n downloads.length ? `\\n## Downloads\\n| # | Kind | File | Status |\\n|---|------|------|--------|\\n${downloadRows}` : '',\n d.outputDir ? `\\n**Output directory:** \\`${d.outputDir}\\`` : '',\n transcript ? `\\n## Transcript\\n**${wordCount(transcriptText)} words** · ${chunks.length} chunks\\n\\n${transcriptText}` : '',\n warnings.length ? `\\n## Warnings\\n${warnings.map(w => `- ${w}`).join('\\n')}` : '',\n limitations.length ? `\\n## Limits\\n${limitations.map(l => `- ${l}`).join('\\n')}` : '',\n `\\n---\\n💡 Reels may expose separate video-only and audio-only MP4 tracks. Use the muxed file when present; otherwise use the selected video/audio track URLs or saved files.`,\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n sourceUrl: String(d.sourceUrl ?? input.url),\n pageUrl: String(d.pageUrl ?? input.url),\n browser,\n type: d.type === 'post' || d.type === 'reel' || d.type === 'tv' ? d.type : null,\n shortcode: typeof d.shortcode === 'string' ? d.shortcode : null,\n ownerName: typeof d.ownerName === 'string' ? d.ownerName : null,\n caption: typeof d.caption === 'string' ? d.caption : null,\n imageUrl: typeof d.imageUrl === 'string' ? d.imageUrl : null,\n trackCount: tracks.length,\n selectedVideoTrack: structuredInstagramTrack(d.selectedVideoTrack as InstagramMediaTrack | null | undefined),\n selectedAudioTrack: structuredInstagramTrack(d.selectedAudioTrack as InstagramMediaTrack | null | undefined),\n downloads: downloads.map(download => ({\n kind: download.kind,\n url: download.url ?? null,\n savedPath: download.savedPath ?? null,\n sizeBytes: typeof download.sizeBytes === 'number' ? download.sizeBytes : null,\n mimeType: download.mimeType ?? null,\n error: download.error ?? null,\n })),\n outputDir: typeof d.outputDir === 'string' ? d.outputDir : null,\n warnings,\n limitations,\n transcript: transcript ? {\n wordCount: wordCount(transcriptText),\n chunkCount: chunks.length,\n durationMs: typeof transcript.durationMs === 'number' ? transcript.durationMs : null,\n transcriptText,\n chunks: structuredTranscriptChunks(chunks),\n } : null,\n },\n }\n}\n\nexport function formatCaptureSerpSnapshot(\n raw: CallToolResult,\n input: Record<string, unknown>,\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data\n const providerPayload = d\n const organic = Array.isArray(d.organicResults) ? d.organicResults : Array.isArray(d.organic) ? d.organic : []\n const localPack = Array.isArray(d.localPack) ? d.localPack : []\n const artifacts = Array.isArray(d.artifacts) ? d.artifacts as Array<Record<string, unknown>> : []\n const status = String(d.status ?? d.captureStatus ?? 'captured')\n const query = typeof d.query === 'string' ? d.query : typeof input.query === 'string' ? input.query : null\n const location = typeof d.location === 'string' ? d.location : typeof input.location === 'string' ? input.location : null\n const capturedAt = typeof d.capturedAt === 'string'\n ? d.capturedAt\n : typeof d.extractedAt === 'string'\n ? d.extractedAt\n : null\n const resultCount = organic.length + localPack.length\n\n const full = [\n `# SERP Intelligence Snapshot: ${query ?? 'query'}`,\n `**Status:** ${status}`,\n location ? `**Location:** ${location}` : '',\n `**Result count:** ${resultCount}`,\n artifacts.length ? `**Artifacts:** ${artifacts.length}` : '',\n '',\n 'Use `capture_serp_page_snapshots` when you need page-level evidence for ranking URLs.',\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n schemaVersion: 'serp-intelligence.capture.v1',\n status,\n query,\n location,\n capturedAt,\n resultCount,\n snapshotId: typeof d.snapshotId === 'string'\n ? d.snapshotId\n : typeof d.snapshot_id === 'string'\n ? d.snapshot_id\n : typeof d.id === 'string'\n ? d.id\n : null,\n resolvedInputs: {\n query: input.query ?? null,\n location: input.location ?? null,\n gl: input.gl ?? null,\n hl: input.hl ?? null,\n device: input.device ?? null,\n proxyMode: input.proxyMode ?? null,\n proxyZip: input.proxyZip ?? null,\n pages: input.pages ?? null,\n },\n artifacts,\n diagnostics: d.diagnostics && typeof d.diagnostics === 'object' ? d.diagnostics as Record<string, unknown> : null,\n providerPayload,\n },\n }\n}\n\nexport function formatCaptureSerpPageSnapshots(\n raw: CallToolResult,\n input: Record<string, unknown>,\n): CallToolResult {\n const parsed = parseData(raw)\n if ('error' in parsed) return { content: [{ type: 'text', text: parsed.error }], isError: true }\n const d = parsed.data\n const captures = Array.isArray(d.captures)\n ? d.captures as Array<Record<string, unknown>>\n : Array.isArray(d.results)\n ? d.results as Array<Record<string, unknown>>\n : []\n const failedCount = captures.filter(c => c.status === 'failed' || c.error).length\n const status = String(d.status ?? (failedCount ? 'partial' : 'captured'))\n\n const rows = captures.slice(0, 25).map((capture, i) => {\n const url = typeof capture.url === 'string' ? capture.url : ''\n const sourceKind = typeof capture.sourceKind === 'string' ? capture.sourceKind : typeof capture.source_kind === 'string' ? capture.source_kind : 'configured_target'\n return `| ${i + 1} | ${cell(url)} | ${cell(sourceKind)} | ${cell(String(capture.status ?? (capture.error ? 'failed' : 'ok')))} |`\n }).join('\\n')\n\n const full = [\n '# SERP Intelligence Page Snapshots',\n `**Status:** ${status}`,\n `**Captured:** ${captures.length}`,\n `**Failed:** ${failedCount}`,\n captures.length ? `\\n| # | URL | Source | Status |\\n|---|-----|--------|--------|\\n${rows}` : '',\n ].filter(Boolean).join('\\n')\n\n return {\n ...oneBlock(full),\n structuredContent: {\n schemaVersion: 'serp-intelligence.page-snapshots.v1',\n status,\n count: captures.length,\n failedCount,\n captures,\n resolvedInputs: {\n urls: input.urls ?? null,\n targets: input.targets ?? null,\n maxConcurrency: input.maxConcurrency ?? null,\n timeoutMs: input.timeoutMs ?? null,\n debug: input.debug ?? null,\n },\n diagnostics: d.diagnostics && typeof d.diagnostics === 'object' ? d.diagnostics as Record<string, unknown> : null,\n providerPayload: d,\n },\n }\n}\n","export const RECAPTCHA_INSTRUCTIONS = 'Google returned a CAPTCHA. Run with --headless=false to re-warm the browser profile, then retry.'\n\nexport function sanitizeVendorName(message: string): string {\n return message\n .replace(/kernel\\.sh\\s+sessions?/gi, 'sessions')\n .replace(/kernel\\.sh\\s+session/gi, 'this session')\n .replace(/kernel\\.sh/gi, 'the service')\n .replace(/kernel\\s+sessions?/gi, 'sessions')\n .replace(/kernel\\s+session/gi, 'this session')\n .replace(/\\bkernel\\b/gi, 'the service')\n .replace(/ +/g, ' ')\n .trim()\n}\n\nexport class CaptchaError extends Error {\n readonly name = 'CaptchaError'\n constructor(public readonly instructions: string) {\n super(`CAPTCHA detected. ${instructions}`)\n }\n}\n\nexport class ExtractionError extends Error {\n readonly name = 'ExtractionError'\n constructor(message: string, public readonly cause?: unknown) {\n super(message)\n }\n}\n\nexport class RequestAbortedError extends Error {\n readonly name = 'RequestAbortedError'\n constructor(message = 'Request aborted before harvest completed') {\n super(message)\n }\n}\n\nexport class LocationMismatchError extends Error {\n readonly name = 'LocationMismatchError'\n constructor(message = 'Google returned results for a different location than requested') {\n super(message)\n }\n}\n","export type WorkflowRecipe = {\n id: string\n title: string\n description: string\n primaryWorkflowId: string | null\n recommendedTools: string[]\n requiredInputs: string[]\n optionalInputs: string[]\n produces: string[]\n runHint: string\n}\n\nexport const WORKFLOW_RECIPES: WorkflowRecipe[] = [\n {\n id: 'market_analysis',\n title: 'Market Analysis',\n description: 'Compare a niche across a city, state, or market set using Google Maps competitors, SERP evidence, review counts, categories, and opportunity signals.',\n primaryWorkflowId: 'local-competitive-audit',\n recommendedTools: ['workflow_run', 'directory_workflow', 'maps_search', 'maps_place_intel', 'search_serp', 'harvest_paa'],\n requiredInputs: ['query', 'state or location'],\n optionalInputs: ['domain', 'minPopulation', 'maxCities', 'maxResultsPerCity', 'hydrateTop', 'maxReviews'],\n produces: ['city summary', 'competitor CSV', 'review insight CSV', 'market difficulty/opportunity notes', 'HTML report'],\n runHint: 'Use workflow_run with workflowId local-competitive-audit for state-wide market batches, or map-comparison for one city/location comparison.',\n },\n {\n id: 'icp_research',\n title: 'ICP Research',\n description: 'Build an evidence packet for ideal-customer-profile research from real search demand, PAA language, competing pages, AI Overview citations, and source domains.',\n primaryWorkflowId: 'agent-packet',\n recommendedTools: ['workflow_run', 'harvest_paa', 'search_serp', 'extract_url', 'youtube_harvest', 'facebook_ad_search'],\n requiredInputs: ['keyword or audience problem'],\n optionalInputs: ['domain', 'location', 'maxQuestions'],\n produces: ['evidence JSON', 'sources CSV', 'competitor CSV', 'brief markdown', 'agent task list'],\n runHint: 'Use workflow_run with workflowId agent-packet. Treat keyword as the buyer problem, job-to-be-done, niche, or service category.',\n },\n {\n id: 'forum_review_research',\n title: 'Forum And Review Research',\n description: 'Acquire customer language from Google PAA, forum/Perspectives SERP surfaces, Google Maps reviews, review topics, Facebook ads, and video transcripts.',\n primaryWorkflowId: 'local-competitive-audit',\n recommendedTools: ['workflow_run', 'harvest_paa', 'maps_search', 'maps_place_intel', 'facebook_page_intel', 'facebook_video_transcribe', 'youtube_transcribe'],\n requiredInputs: ['query', 'state or location'],\n optionalInputs: ['maxReviews', 'maxQuestions', 'competitors', 'facebookUrl', 'youtubeVideoId'],\n produces: ['review insight CSV', 'PAA/source language', 'competitor review topics', 'transcripts where supplied', 'pain/theme summary'],\n runHint: 'Use local-competitive-audit for review acquisition, then harvest_paa for forum/Perspectives language and transcript tools for supplied videos.',\n },\n {\n id: 'brand_design_brief',\n title: 'Brand Design Brief',\n description: 'Create a design briefing grounded in a brand site, competitor pages, SERP language, audience pains, visual assets, colors, fonts, screenshots, and positioning evidence.',\n primaryWorkflowId: 'serp-comparison',\n recommendedTools: ['workflow_run', 'extract_url', 'extract_site', 'capture_serp_page_snapshots', 'search_serp', 'harvest_paa', 'browser_open'],\n requiredInputs: ['url or domain', 'keyword or market category'],\n optionalInputs: ['competitorUrls', 'location', 'extractTop'],\n produces: ['page comparison CSV', 'content gaps', 'branding/asset evidence', 'SERP positioning evidence', 'designer-ready brief'],\n runHint: 'Use workflow_run with workflowId serp-comparison for market/page evidence, then extract_url with extractBranding:true for brand assets and colors.',\n },\n {\n id: 'cro_audit',\n title: 'CRO Audit',\n description: 'Audit conversion clarity using page extraction, screenshots, browser DOM inspection, competitor SERP/page comparisons, forms/buttons, proof, offer, trust, and friction evidence.',\n primaryWorkflowId: 'serp-comparison',\n recommendedTools: ['workflow_run', 'extract_url', 'extract_site', 'capture_serp_page_snapshots', 'browser_open', 'browser_screenshot', 'browser_locate'],\n requiredInputs: ['url'],\n optionalInputs: ['keyword', 'domain', 'location', 'competitorUrls'],\n produces: ['page extraction', 'SERP/page comparison', 'screenshot evidence', 'friction checklist', 'CRO recommendations'],\n runHint: 'Use workflow_run with workflowId serp-comparison when a keyword/domain is known; use extract_url and browser tools for page-level CRO evidence.',\n },\n {\n id: 'competitive_positioning_brief',\n title: 'Competitive Positioning Brief',\n description: 'Compare competitors across SERP, PAA, AI Overview citations, page headings, Facebook ads, YouTube angles, Maps proof, and website claims.',\n primaryWorkflowId: 'serp-comparison',\n recommendedTools: ['workflow_run', 'facebook_ad_search', 'facebook_page_intel', 'youtube_harvest', 'youtube_transcribe', 'maps_search', 'extract_url'],\n requiredInputs: ['keyword or query', 'domain or url'],\n optionalInputs: ['location', 'extractTop', 'competitorUrls', 'brandNames'],\n produces: ['SERP comparison', 'content gap CSV', 'AI Overview citation table', 'competitor message map', 'positioning brief'],\n runHint: 'Use workflow_run with workflowId serp-comparison, then enrich with Facebook, YouTube, and Maps tools when the user asks for campaign or offer positioning.',\n },\n {\n id: 'content_gap_brief',\n title: 'Content Gap Brief',\n description: 'Turn live SERP, page extraction, PAA questions, AI Overview citations, and source-domain evidence into a writer-ready content brief.',\n primaryWorkflowId: 'serp-comparison',\n recommendedTools: ['workflow_run', 'paa-expansion-brief', 'harvest_paa', 'extract_url'],\n requiredInputs: ['keyword'],\n optionalInputs: ['domain', 'url', 'location', 'maxQuestions', 'extractTop'],\n produces: ['content gaps', 'page comparison CSV', 'PAA questions CSV', 'section map', 'writer brief'],\n runHint: 'Use workflow_run with workflowId serp-comparison for competitor gaps or paa-expansion-brief when the user mainly wants a section map from PAA data.',\n },\n {\n id: 'ai_search_visibility_audit',\n title: 'AI Search Visibility Audit',\n description: 'Audit whether a brand/domain appears in AI Overview citations, PAA sources, organic results, local pack, and source pages, then produce language guidance.',\n primaryWorkflowId: 'ai-overview-language',\n recommendedTools: ['workflow_run', 'search_serp', 'harvest_paa', 'extract_url', 'capture_serp_snapshot'],\n requiredInputs: ['keyword', 'domain or url'],\n optionalInputs: ['location', 'maxQuestions', 'extractTop'],\n produces: ['AI Overview citations CSV', 'claim patterns', 'language guidance', 'citation hooks', 'visibility gaps'],\n runHint: 'Use workflow_run with workflowId ai-overview-language. Use serp-comparison when the user also wants ranking-page gaps.',\n },\n]\n\nfunction normalize(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()\n}\n\nexport function suggestWorkflowRecipes(goal: string, limit = 3): WorkflowRecipe[] {\n const normalized = normalize(goal)\n const scored = WORKFLOW_RECIPES.map(recipe => {\n const haystack = normalize([\n recipe.id,\n recipe.title,\n recipe.description,\n recipe.requiredInputs.join(' '),\n recipe.optionalInputs.join(' '),\n recipe.produces.join(' '),\n ].join(' '))\n let score = 0\n for (const token of normalized.split(/\\s+/).filter(Boolean)) {\n if (haystack.includes(token)) score += 1\n }\n if (haystack.includes(normalized)) score += 5\n return { recipe, score }\n })\n return scored\n .sort((a, b) => b.score - a.score || a.recipe.title.localeCompare(b.recipe.title))\n .slice(0, Math.max(1, limit))\n .map(item => item.recipe)\n}\n","import { z } from 'zod'\nimport { DEFAULT_MAPS_PROXY_MODE, DEFAULT_PROXY_MODE } from '../schemas.js'\n\nexport const HarvestPaaInputSchema = {\n query: z.string().min(1).describe('Core search topic only. If the user says \"best hvac company in Denver CO\", use query=\"best hvac company\" and location=\"Denver, CO\". Do not include the location in query when it can be separated.'),\n location: z.string().optional().describe('City, region, or country for geo-targeted results, inferred from the user request when present, e.g. \"Denver, CO\", \"Tokyo, Japan\", \"London, UK\".'),\n maxQuestions: z.number().int().min(1).max(200).default(30).describe('Number of PAA questions to extract. Default 30. Maximum 200. Use 10 for quick probes, 30 for normal research, 100-200 when the user asks for everything/full/deep research. Larger harvests get a longer server time budget (151-200 questions → up to 280s). Credits are charged by extracted question; unused request hold is refunded.'),\n 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.'),\n 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.'),\n 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.'),\n proxyMode: z.enum(['location', 'configured', 'none']).default(DEFAULT_PROXY_MODE).describe('Proxy targeting mode. Default configured uses the service proxy without city/ZIP targeting for the highest general success rate. Use location only when the user explicitly needs city/ZIP-targeted residential proxy evidence. Use none only for direct-network debugging.'),\n proxyZip: z.string().regex(/^\\d{5}$/).optional().describe('Optional US ZIP override for residential location proxy targeting. Use only with proxyMode location when the user gives a specific ZIP or city-center targeting needs to be forced.'),\n debug: z.boolean().default(false).describe('Include sanitized browser/session/location diagnostics in the response. Use true when debugging localization, CAPTCHA, or proxy behavior.'),\n}\nexport type HarvestPaaInput = z.infer<ReturnType<typeof z.object<typeof HarvestPaaInputSchema>>>\n\nexport const ExtractUrlInputSchema = {\n url: z.string().url().describe('Public http/https URL to extract. Use this when the user provides one specific page URL.'),\n screenshot: z.boolean().default(false).describe('Also capture a full-page screenshot of the URL. Saved to ~/Downloads/mcp-scraper/screenshots/ and returned inline. Use when the user asks to see or capture the page visually.'),\n screenshotDevice: z.enum(['desktop', 'mobile']).default('desktop').describe('Viewport for screenshot. desktop = 1440×900. mobile = 390×844. Default desktop.'),\n extractBranding: z.boolean().default(false).describe('Extract brand colors, fonts, logo, and favicon using a rendered browser session. Returns colorScheme (light/dark), colors (primary/accent/background/text/heading as hex), fonts (heading/body family names), and assets (logo URL, favicon URL). Use when the user asks about brand colors, site theme, or brand assets.'),\n downloadMedia: z.boolean().default(false).describe('Extract and download all page media (images, video, audio) to ~/Downloads/mcp-scraper/media/. Ad networks, tracking pixels, and noise URLs are filtered automatically. Use when the user asks to download or harvest assets from a page.'),\n mediaTypes: z.array(z.enum(['image', 'video', 'audio'])).default(['image', 'video', 'audio']).describe('Which media types to download. Default all three.'),\n allowLocal: z.boolean().default(false).describe('Allow localhost and private-network URLs. For local development only.'),\n}\nexport type ExtractUrlInput = z.infer<ReturnType<typeof z.object<typeof ExtractUrlInputSchema>>>\n\nexport const MapSiteUrlsInputSchema = {\n url: z.string().url().describe('Public website URL or domain to crawl for internal URLs. Use before extract_site when the user asks to audit/map/crawl a site.'),\n maxUrls: z.number().int().min(1).max(500).optional().describe('Maximum URLs to discover. Use 100 for normal maps, higher when the user asks for a full inventory.'),\n}\nexport type MapSiteUrlsInput = z.infer<ReturnType<typeof z.object<typeof MapSiteUrlsInputSchema>>>\n\nexport const ExtractSiteInputSchema = {\n url: z.string().url().describe('Public website URL or domain to extract across multiple pages. Use when the user asks for a site audit, website crawl, or full-site content/schema extraction.'),\n maxPages: z.number().int().min(1).max(50).optional().describe('Maximum pages to extract. Use 50 when the user asks for full results or a complete crawl within MCP limits.'),\n}\nexport type ExtractSiteInput = z.infer<ReturnType<typeof z.object<typeof ExtractSiteInputSchema>>>\n\nexport const YoutubeHarvestInputSchema = {\n mode: z.enum(['search', 'channel']).describe('Use search for topic/keyword requests. Use channel when the user provides @handle, channel ID, or channel URL.'),\n query: z.string().optional().describe('Required when mode is search. The YouTube search topic in the user’s words.'),\n channelHandle: z.string().optional().describe('YouTube channel handle, channel ID, or URL. Examples: @mkbhd, UC..., https://youtube.com/@mkbhd.'),\n maxVideos: z.number().int().min(1).max(500).default(50).describe('Number of videos to return. Default 50, maximum 500. Use 10-25 for quick topic discovery, 50 for normal channel/search harvests, and larger values only when the user asks for full channel/history because large responses consume more context.'),\n}\nexport type YoutubeHarvestInput = z.infer<ReturnType<typeof z.object<typeof YoutubeHarvestInputSchema>>>\n\nexport const YoutubeTranscribeInputSchema = {\n videoId: z.string().min(1).optional().describe('YouTube video ID, e.g. dQw4w9WgXcQ. Use only an ID returned by youtube_harvest or visible in a YouTube URL; do not invent one.'),\n url: z.string().url().optional().describe('Full YouTube URL, e.g. https://www.youtube.com/watch?v=dQw4w9WgXcQ or https://youtu.be/dQw4w9WgXcQ. Use this when the user pasted a URL instead of an ID. Provide videoId or url.'),\n}\nexport type YoutubeTranscribeInput = z.infer<ReturnType<typeof z.object<typeof YoutubeTranscribeInputSchema>>>\n\nexport const FacebookPageIntelInputSchema = {\n pageId: z.string().optional().describe('Facebook advertiser/page ID. Use only a pageId returned by facebook_ad_search/facebook_page_intel or copied from Facebook Ad Library; do not construct one yourself.'),\n libraryId: z.string().optional().describe('Facebook Ad Library archive ID for a known ad or advertiser sample. Use a libraryId returned by facebook_ad_search, or a libraryId/adArchiveId visible in Ad Library.'),\n query: z.string().optional().describe('Advertiser or brand name when pageId/libraryId is not known. One of pageId, libraryId, or query is required.'),\n maxAds: z.number().int().min(1).max(200).default(50).describe('Maximum ads to inspect. Default 50, maximum 200. Prefer 25-50 for focused advertiser scans; use 100-200 only when the user asks for a broad ad archive sweep.'),\n country: z.string().length(2).default('US').describe('Two-letter Ad Library country code. Default US. Examples: US, CA, GB, AU. Infer from the user request when they name a country.'),\n}\nexport type FacebookPageIntelInput = z.infer<ReturnType<typeof z.object<typeof FacebookPageIntelInputSchema>>>\n\nexport const FacebookAdSearchInputSchema = {\n query: z.string().min(1).describe('Advertiser, brand, competitor, niche, or keyword to search in Facebook Ad Library.'),\n country: z.string().length(2).default('US').describe('Two-letter Ad Library country code. Default US. Examples: US, CA, GB, AU.'),\n maxResults: z.number().int().min(1).max(20).default(10).describe('Maximum advertisers to return. Default 10, maximum 20. Prefer tighter search terms over maxing this out.'),\n}\nexport type FacebookAdSearchInput = z.infer<ReturnType<typeof z.object<typeof FacebookAdSearchInputSchema>>>\n\nexport const FacebookAdTranscribeInputSchema = {\n videoUrl: z.string().url().describe('Direct Facebook CDN video URL from a facebook_page_intel ad result. Do not pass a public Facebook reel/post/share URL here; use facebook_video_transcribe for organic Facebook URLs.'),\n}\nexport type FacebookAdTranscribeInput = z.infer<ReturnType<typeof z.object<typeof FacebookAdTranscribeInputSchema>>>\n\nexport const FacebookVideoTranscribeInputSchema = {\n url: z.string().url().describe('Organic Facebook reel, video, watch, post, or share URL from facebook.com, m.facebook.com, or fb.watch. The tool renders the page, extracts the best matching public Facebook CDN MP4 URL, then transcribes it. Use this when the user pastes a normal Facebook video page URL and asks for the transcript or downloadable MP4.'),\n quality: z.enum(['best', 'hd', 'sd']).default('best').describe('Preferred progressive MP4 quality. Use best by default; hd prefers the highest HD progressive URL; sd forces the SD URL.'),\n}\nexport type FacebookVideoTranscribeInput = z.infer<ReturnType<typeof z.object<typeof FacebookVideoTranscribeInputSchema>>>\n\nexport const InstagramProfileContentInputSchema = {\n handle: z.string().min(1).optional().describe('Instagram handle, with or without @. Provide handle or url.'),\n url: z.string().url().optional().describe('Instagram profile URL, e.g. https://www.instagram.com/nasaartemis/. Provide handle or url.'),\n profile: z.string().min(1).optional().describe('Optional saved hosted browser profile name to load authenticated Instagram access. If omitted, the server uses its configured default profile when present.'),\n saveProfileChanges: z.boolean().optional().describe('Whether to save browser changes back to the hosted profile. Leave unset unless intentionally updating the saved login session.'),\n maxItems: z.number().int().min(1).max(2000).default(50).describe('Maximum profile grid post/reel/tv URLs to collect. Default 50, maximum 2000. Use higher values only when the user asks for a fuller archive.'),\n maxScrolls: z.number().int().min(0).max(250).default(10).describe('Maximum pagination scroll attempts. Default 10, maximum 250. Increase for long profiles when Instagram continues loading more grid links.'),\n scrollDelayMs: z.number().int().min(250).max(5000).default(1200).describe('Delay after each pagination scroll before collecting newly loaded links. Default 1200ms. Increase to 2000-3000ms when Instagram loads slowly.'),\n stableScrollLimit: z.number().int().min(1).max(10).default(4).describe('Stop after this many consecutive scrolls with no new links or scroll progress. Default 4.'),\n}\nexport type InstagramProfileContentInput = z.infer<ReturnType<typeof z.object<typeof InstagramProfileContentInputSchema>>>\n\nexport const InstagramMediaDownloadInputSchema = {\n url: z.string().url().describe('Instagram post, reel, or tv URL, e.g. https://www.instagram.com/reel/SHORTCODE/. The tool renders the page, extracts text, image metadata, and Instagram CDN media tracks.'),\n profile: z.string().min(1).optional().describe('Optional saved hosted browser profile name to load authenticated Instagram access. If omitted, the server uses its configured default profile when present.'),\n saveProfileChanges: z.boolean().optional().describe('Whether to save browser changes back to the hosted profile. Leave unset unless intentionally updating the saved login session.'),\n mediaTypes: z.array(z.enum(['image', 'video', 'audio'])).default(['image', 'video', 'audio']).describe('Which media types to download when downloadMedia is true. Reels commonly expose separate video-only and audio-only MP4 tracks.'),\n downloadMedia: z.boolean().default(true).describe('Download extracted text/media files to the MCP Scraper output directory when the API server can write files. Always returns extracted media URLs even when false.'),\n downloadAllTracks: z.boolean().default(false).describe('Download every captured Instagram MP4 track instead of only the selected best video and audio tracks. Use false by default to avoid duplicate bitrates.'),\n includeTranscript: z.boolean().default(false).describe('Transcribe the selected audio track when available. This adds transcription cost and may take longer.'),\n mux: z.boolean().default(true).describe('When video and audio tracks are downloaded separately, try to mux them into a single MP4 if ffmpeg is available. Returns separate tracks when muxing is unavailable.'),\n}\nexport type InstagramMediaDownloadInput = z.infer<ReturnType<typeof z.object<typeof InstagramMediaDownloadInputSchema>>>\n\nexport const MapsPlaceIntelInputSchema = {\n businessName: z.string().min(1).describe('Business name only. If user says \"Elite Roofing Denver CO\", use businessName=\"Elite Roofing\" and location=\"Denver, CO\".'),\n location: z.string().min(1).describe('City/region/country where the business should be searched, e.g. \"Denver, CO\". Infer from the user request when possible.'),\n gl: z.string().length(2).default('us').describe('Google country code inferred from location.'),\n hl: z.string().length(2).default('en').describe('Language inferred from user request.'),\n includeReviews: z.boolean().default(false).describe('Whether to fetch individual review cards. Use true when the user asks for reviews, customer pain, complaints, praise, themes, or review evidence.'),\n maxReviews: z.number().int().min(1).max(500).default(50).describe('Max review cards to return when includeReviews is true. Default 50, maximum 500. Use 50 for normal review analysis and larger values only for deep review mining.'),\n}\nexport type MapsPlaceIntelInput = z.infer<ReturnType<typeof z.object<typeof MapsPlaceIntelInputSchema>>>\n\nexport const MapsSearchInputSchema = {\n query: z.string().min(1).describe('Business category, niche, keyword, or search term. If the user says \"roofers in Denver CO\", use query=\"roofers\" and location=\"Denver, CO\". Do not put the location here when it can be separated.'),\n location: z.string().optional().describe('City, region, country, or service area for the Maps search, e.g. \"Denver, CO\". Infer from the user request when present.'),\n gl: z.string().length(2).default('us').describe('Google country code inferred from location.'),\n hl: z.string().length(2).default('en').describe('Language inferred from user request.'),\n 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.'),\n proxyMode: z.enum(['location', 'configured', 'none']).default(DEFAULT_MAPS_PROXY_MODE).describe('Proxy targeting mode. Maps defaults to location so local market searches get city/state residential proxy targeting and rotation. Use configured to force the service proxy without city/ZIP targeting, and none only for local direct-network debugging.'),\n 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.'),\n debug: z.boolean().default(false).describe('Include sanitized browser/proxy diagnostics when debugging Maps localization, CAPTCHA, or proxy behavior.'),\n}\nexport type MapsSearchInput = z.infer<ReturnType<typeof z.object<typeof MapsSearchInputSchema>>>\n\nexport const DirectoryWorkflowInputSchema = {\n query: z.string().min(1).describe('Business category, niche, or keyword to search on Google Maps for every selected market, e.g. roofers, dentists, med spas. Do not include the city here.'),\n state: z.string().min(2).default('TN').describe('US state abbreviation or state name used to select Census places, e.g. TN or Tennessee.'),\n minPopulation: z.number().int().min(0).default(100000).describe('Minimum Census place population for market selection. Use 100000 for \"cities above 100k population\".'),\n populationYear: z.number().int().min(2020).max(2025).default(2025).describe('Census population estimate year from the 2020-2025 Population Estimates Program city/place dataset.'),\n maxCities: z.number().int().min(1).max(100).default(25).describe('Maximum number of markets to process after sorting by population descending.'),\n maxResultsPerCity: z.number().int().min(1).max(50).default(50).describe('Google Maps business/profile candidates to collect for each city. Maximum 50.'),\n 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.'),\n 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.'),\n 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.'),\n 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.'),\n proxyMode: z.enum(['location', 'configured', 'none']).default(DEFAULT_MAPS_PROXY_MODE).describe('Proxy targeting mode for every city Maps search. Maps workflows default to location so each city can use city/state or ZIP-group residential proxy targeting. Use configured to force the service proxy without city/ZIP targeting, and none only for local direct-network debugging.'),\n proxyZip: z.string().regex(/^\\d{5}$/).optional().describe('Optional ZIP override for proxy targeting. Normally omit it so each city can use its ZIP group or city/state location.'),\n debug: z.boolean().default(false).describe('Include sanitized browser/proxy diagnostics in each Maps browser session when supported.'),\n}\nexport type DirectoryWorkflowInput = z.infer<ReturnType<typeof z.object<typeof DirectoryWorkflowInputSchema>>>\n\nexport const RankTrackerModeSchema = z.enum(['maps', 'organic', 'ai_overview', 'paa'])\nexport type RankTrackerMode = z.infer<typeof RankTrackerModeSchema>\n\nexport const RankTrackerBlueprintInputSchema = {\n projectName: z.string().min(1).optional().describe('Optional name for the rank tracker project, client, or campaign.'),\n targetDomain: z.string().min(1).optional().describe('Primary domain to track in organic results, AI Overview citations, and PAA sources, e.g. example.com.'),\n targetBusinessName: z.string().min(1).optional().describe('Primary Google Business Profile or brand/business name to match in Maps results. Required for reliable Maps rank tracking.'),\n trackingModes: z.array(RankTrackerModeSchema).min(1).max(4).default(['maps', 'organic', 'ai_overview', 'paa']).describe('Rank tracker surfaces to build. maps uses directory_workflow/maps_search. organic uses search_serp. ai_overview uses search_serp/harvest_paa. paa uses harvest_paa source presence.'),\n keywords: z.array(z.string().min(1)).max(200).default([]).describe('Seed keywords or service queries to track. Leave empty when the downstream AI should create the keyword table from user input.'),\n locations: z.array(z.string().min(1)).max(100).default([]).describe('Markets, cities, ZIPs, or service areas to track. Use city/state strings like Denver, CO for localized SERP and Maps checks.'),\n competitors: z.array(z.string().min(1)).max(100).default([]).describe('Optional competitor domains or business names to persist as comparison targets.'),\n database: z.enum(['postgres', 'neon', 'supabase', 'sqlite', 'mysql']).default('postgres').describe('Database family the downstream AI should target when generating migrations.'),\n scheduleCadence: z.enum(['daily', 'weekly', 'monthly', 'custom']).default('weekly').describe('Default recurring rank check cadence for the generated cron/heartbeat plan.'),\n customCron: z.string().min(1).optional().describe('Cron expression to use when scheduleCadence is custom.'),\n timezone: z.string().min(1).default('UTC').describe('IANA timezone for scheduled rank checks, e.g. America/Denver.'),\n includeCron: z.boolean().default(true).describe('Include a cron or heartbeat worker plan. Keep true for production rank trackers.'),\n includeDashboard: z.boolean().default(true).describe('Include dashboard/reporting requirements in the generated prompt.'),\n includeAlerts: z.boolean().default(true).describe('Include alert rules for rank movement and SERP feature gains/losses.'),\n notes: z.string().max(4000).optional().describe('Extra product, client, stack, or hosting requirements to include in the implementation prompt.'),\n}\nexport type RankTrackerBlueprintInput = z.infer<ReturnType<typeof z.object<typeof RankTrackerBlueprintInputSchema>>>\n\nconst NullableString = z.string().nullable()\n\nconst MapsSearchAttemptOutput = z.object({\n attemptNumber: z.number().int().min(1),\n maxAttempts: z.number().int().min(1),\n status: z.enum(['ok', 'failed']),\n outcome: z.string(),\n willRetry: z.boolean(),\n durationMs: z.number().int().min(0),\n resultCount: z.number().int().min(0),\n error: NullableString,\n proxyMode: z.enum(['location', 'configured', 'none']),\n proxyResolutionSource: z.enum(['disabled', 'location_reused', 'location_created', 'configured_fallback', 'unavailable']).nullable(),\n proxyIdSuffix: NullableString,\n proxyTargetLevel: z.enum(['zip', 'city', 'state']).nullable(),\n proxyTargetLocation: NullableString,\n proxyTargetZip: NullableString,\n browserSessionIdSuffix: NullableString,\n observedIp: NullableString,\n observedCity: NullableString,\n observedRegion: NullableString,\n})\n\nexport const MapsSearchOutputSchema = {\n query: z.string(),\n location: z.string().nullable(),\n searchQuery: z.string(),\n searchUrl: z.string().url(),\n extractedAt: z.string(),\n requestedMaxResults: z.number().int().min(1).max(50),\n resultCount: z.number().int().min(0).max(50),\n results: z.array(z.object({\n position: z.number().int().min(1),\n name: z.string(),\n placeUrl: z.string().url(),\n cid: NullableString,\n cidDecimal: NullableString,\n rating: NullableString,\n reviewCount: NullableString,\n category: NullableString,\n address: NullableString,\n phone: NullableString,\n hoursStatus: NullableString,\n websiteUrl: NullableString,\n directionsUrl: NullableString,\n metadata: z.array(z.string()),\n })),\n attempts: z.array(MapsSearchAttemptOutput),\n durationMs: z.number().int().min(0),\n}\n\nconst DirectoryMapsBusinessOutput = z.object({\n position: z.number().int().min(1),\n name: z.string(),\n placeUrl: z.string().url(),\n cid: NullableString,\n cidDecimal: NullableString,\n rating: NullableString,\n reviewCount: NullableString,\n category: NullableString,\n address: NullableString,\n phone: NullableString,\n hoursStatus: NullableString,\n websiteUrl: NullableString,\n directionsUrl: NullableString,\n metadata: z.array(z.string()),\n})\n\nexport const DirectoryWorkflowOutputSchema = {\n query: z.string(),\n state: z.string(),\n minPopulation: z.number().int().min(0),\n populationYear: z.number().int().min(2020).max(2025),\n maxResultsPerCity: z.number().int().min(1).max(50),\n concurrency: z.number().int().min(1).max(5),\n censusSourceUrl: z.string().url(),\n usZipsSourcePath: NullableString,\n warnings: z.array(z.string()),\n extractedAt: z.string(),\n selectedCityCount: z.number().int().min(0),\n totalResultCount: z.number().int().min(0),\n csvPath: NullableString,\n cities: z.array(z.object({\n city: z.string(),\n state: z.string(),\n location: z.string(),\n cityKey: z.string(),\n censusName: z.string(),\n population: z.number().int().min(0),\n populationYear: z.number().int().min(2020).max(2025),\n zips: z.array(z.string()),\n counties: z.array(z.string()),\n status: z.enum(['ok', 'empty', 'failed']),\n error: NullableString,\n resultCount: z.number().int().min(0),\n durationMs: z.number().int().min(0),\n attempts: z.array(MapsSearchAttemptOutput),\n results: z.array(DirectoryMapsBusinessOutput),\n })),\n durationMs: z.number().int().min(0),\n}\n\nconst RankTrackerToolPlanOutput = z.object({\n tool: z.string(),\n purpose: z.string(),\n})\n\nconst RankTrackerTableOutput = z.object({\n name: z.string(),\n purpose: z.string(),\n keyColumns: z.array(z.string()),\n})\n\nconst RankTrackerCronJobOutput = z.object({\n name: z.string(),\n purpose: z.string(),\n modes: z.array(RankTrackerModeSchema),\n recommendedTools: z.array(z.string()),\n})\n\nexport const RankTrackerBlueprintOutputSchema = {\n projectName: z.string(),\n targetDomain: NullableString,\n targetBusinessName: NullableString,\n trackingModes: z.array(RankTrackerModeSchema),\n database: z.string(),\n recommendedTools: z.array(RankTrackerToolPlanOutput),\n tables: z.array(RankTrackerTableOutput),\n cron: z.object({\n enabled: z.boolean(),\n cadence: z.string(),\n expression: z.string(),\n timezone: z.string(),\n jobs: z.array(RankTrackerCronJobOutput),\n }),\n metrics: z.array(z.string()),\n implementationPrompt: z.string(),\n}\n\nconst OrganicResultOutput = z.object({\n position: z.number().int(),\n title: z.string(),\n url: z.string(),\n domain: z.string(),\n snippet: NullableString,\n})\n\nconst AiOverviewOutput = z.object({\n detected: z.boolean(),\n text: NullableString,\n}).nullable()\n\nconst EntityIdsOutput = z.object({\n kgIds: z.array(z.string()),\n cids: z.array(z.string()),\n gcids: z.array(z.string()),\n}).nullable()\n\nexport const HarvestPaaOutputSchema = {\n query: z.string(),\n location: NullableString,\n questionCount: z.number().int().min(0),\n completionStatus: NullableString,\n questions: z.array(z.object({\n question: z.string(),\n answer: NullableString,\n sourceTitle: NullableString,\n sourceSite: NullableString,\n })),\n organicResults: z.array(OrganicResultOutput),\n aiOverview: AiOverviewOutput,\n entityIds: EntityIdsOutput,\n durationMs: z.number().min(0).nullable(),\n}\n\nexport const SearchSerpOutputSchema = {\n query: z.string(),\n location: NullableString,\n organicResults: z.array(OrganicResultOutput),\n localPack: z.array(z.object({\n position: z.number().int(),\n name: z.string(),\n rating: NullableString,\n reviewCount: NullableString,\n websiteUrl: NullableString,\n })),\n aiOverview: AiOverviewOutput,\n entityIds: EntityIdsOutput,\n}\n\nexport const ExtractUrlOutputSchema = {\n url: z.string(),\n title: NullableString,\n headings: z.array(z.object({\n level: z.number().int(),\n text: z.string(),\n })),\n schemaBlockCount: z.number().int().min(0),\n entityName: NullableString,\n entityTypes: z.array(z.string()),\n napScore: z.number().nullable(),\n missingSchemaFields: z.array(z.string()),\n screenshotSaved: NullableString,\n}\n\nexport const ExtractSiteOutputSchema = {\n url: z.string(),\n pageCount: z.number().int().min(0),\n pages: z.array(z.object({\n url: z.string(),\n title: NullableString,\n schemaTypes: z.array(z.string()),\n })),\n durationMs: z.number().min(0),\n}\n\nexport const MapsPlaceIntelOutputSchema = {\n name: z.string(),\n rating: NullableString,\n reviewCount: NullableString,\n category: NullableString,\n address: NullableString,\n phone: NullableString,\n website: NullableString,\n hoursSummary: NullableString,\n bookingUrl: NullableString,\n kgmid: NullableString,\n cidDecimal: NullableString,\n cidUrl: NullableString,\n lat: z.number().nullable(),\n lng: z.number().nullable(),\n reviewsStatus: z.string(),\n reviewsCollected: z.number().int().min(0),\n reviewTopics: z.array(z.object({\n label: z.string(),\n count: z.string(),\n })),\n}\n\nexport const CreditsInfoOutputSchema = {\n balanceCredits: z.number().nullable(),\n matchedCost: z.object({\n label: z.string(),\n credits: z.number(),\n unit: z.string(),\n notes: NullableString,\n }).nullable(),\n costs: z.array(z.object({\n key: z.string(),\n label: z.string(),\n credits: z.number(),\n unit: z.string(),\n notes: NullableString,\n })),\n ledger: z.array(z.object({\n createdAt: z.string(),\n operation: z.string(),\n credits: z.number(),\n description: NullableString,\n })),\n concurrency: z.object({\n currentExtraSlots: z.number().int().min(0),\n currentLimit: z.number().int().min(1),\n hasSubscription: z.boolean(),\n upgrade: z.object({\n product: z.string(),\n priceLabel: z.string(),\n unitAmountUsd: z.number(),\n currency: z.string(),\n interval: z.string(),\n billingUrl: z.string().url(),\n terminalCommand: z.string(),\n terminalCommandWithApiKeyEnv: z.string(),\n }),\n }).nullable(),\n}\n\nexport const MapSiteUrlsOutputSchema = {\n startUrl: z.string(),\n totalFound: z.number().int().min(0),\n truncated: z.boolean(),\n okCount: z.number().int().min(0),\n redirectCount: z.number().int().min(0),\n brokenCount: z.number().int().min(0),\n urls: z.array(z.object({\n url: z.string(),\n status: z.number().int().nullable(),\n })),\n durationMs: z.number().min(0),\n}\n\nexport const YoutubeHarvestOutputSchema = {\n mode: z.string(),\n videoCount: z.number().int().min(0),\n channel: z.object({\n title: NullableString,\n subscriberCount: NullableString,\n }).nullable(),\n videos: z.array(z.object({\n videoId: z.string(),\n title: z.string(),\n channelName: NullableString,\n views: NullableString,\n duration: NullableString,\n url: NullableString,\n })),\n}\n\nexport const FacebookAdSearchOutputSchema = {\n query: z.string(),\n advertiserCount: z.number().int().min(0),\n advertisers: z.array(z.object({\n name: NullableString,\n pageId: NullableString,\n pageUrl: NullableString,\n adCount: z.number().int().nullable(),\n libraryId: NullableString,\n sampleLibraryId: NullableString,\n })),\n}\n\nexport const FacebookPageIntelOutputSchema = {\n advertiserName: NullableString,\n totalAds: z.number().int().min(0),\n activeCount: z.number().int().min(0),\n videoCount: z.number().int().min(0),\n imageCount: z.number().int().min(0),\n ads: z.array(z.object({\n libraryId: NullableString,\n status: NullableString,\n creativeType: NullableString,\n primaryText: NullableString,\n headline: NullableString,\n cta: NullableString,\n startDate: NullableString,\n landingUrl: NullableString,\n domain: NullableString,\n videoUrl: NullableString,\n imageUrl: NullableString,\n videoPoster: NullableString,\n variations: z.number().int().nullable(),\n })),\n}\n\nexport const FacebookVideoTranscribeOutputSchema = {\n sourceUrl: z.string().url(),\n pageUrl: z.string().url(),\n videoId: NullableString,\n ownerName: NullableString,\n selectedQuality: z.string(),\n bitrate: z.number().int().nullable(),\n videoDurationSec: z.number().nullable(),\n videoUrl: z.string().url(),\n wordCount: z.number().int().min(0),\n chunkCount: z.number().int().min(0),\n transcriptText: z.string(),\n chunks: z.array(z.object({\n startSec: z.number(),\n endSec: z.number(),\n text: z.string(),\n })),\n}\n\nconst TranscriptChunkOutput = z.object({\n startSec: z.number(),\n endSec: z.number(),\n text: z.string(),\n})\n\nconst InstagramBrowserOutput = z.object({\n mode: z.literal('hosted'),\n requestedMode: z.literal('hosted'),\n profileName: NullableString,\n profileSource: z.literal('hosted'),\n profileDirConfigured: z.boolean(),\n executablePathConfigured: z.boolean(),\n})\n\nconst InstagramPaginationOutput = z.object({\n maxItems: z.number().int().min(1).max(2000),\n maxScrolls: z.number().int().min(0).max(250),\n attemptedScrolls: z.number().int().min(0),\n stableScrolls: z.number().int().min(0),\n stableScrollLimit: z.number().int().min(1).max(10),\n scrollDelayMs: z.number().int().min(250).max(5000),\n reachedMaxItems: z.boolean(),\n reachedReportedPostCount: z.boolean(),\n finalScrollHeight: z.number().int().nullable(),\n stoppedReason: z.enum(['max_items', 'reported_post_count', 'stable_scrolls', 'max_scrolls', 'no_scrolls']),\n stages: z.array(z.object({\n stage: z.string(),\n itemCount: z.number().int().min(0),\n addedCount: z.number().int().min(0),\n scrollY: z.number().nullable(),\n scrollHeight: z.number().nullable(),\n })),\n})\n\nexport const InstagramProfileContentOutputSchema = {\n handle: z.string(),\n profileUrl: z.string().url(),\n pageUrl: z.string().url(),\n browser: InstagramBrowserOutput,\n profileName: NullableString,\n reportedPostCount: z.number().int().nullable(),\n reportedPostCountText: NullableString,\n followerCountText: NullableString,\n followingCountText: NullableString,\n collectedContentCount: z.number().int().min(0),\n typeCounts: z.object({\n post: z.number().int().min(0),\n reel: z.number().int().min(0),\n tv: z.number().int().min(0),\n }),\n pagination: InstagramPaginationOutput,\n limited: z.boolean(),\n limitations: z.array(z.string()),\n items: z.array(z.object({\n url: z.string().url(),\n type: z.enum(['post', 'reel', 'tv']),\n shortcode: z.string(),\n anchorText: NullableString,\n firstSeenStage: z.string(),\n })),\n}\n\nconst InstagramMediaTrackOutput = z.object({\n url: z.string().url(),\n streamType: z.enum(['video', 'audio', 'unknown']),\n bitrate: z.number().int().nullable(),\n durationSec: z.number().nullable(),\n vencodeTag: NullableString,\n width: z.number().int().nullable(),\n height: z.number().int().nullable(),\n})\n\nconst InstagramDownloadOutput = z.object({\n kind: z.enum(['text', 'image', 'video', 'audio', 'muxed_video']),\n url: z.string().url().nullable(),\n savedPath: NullableString,\n sizeBytes: z.number().int().nullable(),\n mimeType: NullableString,\n error: NullableString,\n})\n\nexport const InstagramMediaDownloadOutputSchema = {\n sourceUrl: z.string().url(),\n pageUrl: z.string().url(),\n browser: InstagramBrowserOutput,\n type: z.enum(['post', 'reel', 'tv']).nullable(),\n shortcode: NullableString,\n ownerName: NullableString,\n caption: NullableString,\n imageUrl: z.string().url().nullable(),\n trackCount: z.number().int().min(0),\n selectedVideoTrack: InstagramMediaTrackOutput.nullable(),\n selectedAudioTrack: InstagramMediaTrackOutput.nullable(),\n downloads: z.array(InstagramDownloadOutput),\n outputDir: NullableString,\n warnings: z.array(z.string()),\n limitations: z.array(z.string()),\n transcript: z.object({\n wordCount: z.number().int().min(0),\n chunkCount: z.number().int().min(0),\n durationMs: z.number().nullable(),\n transcriptText: z.string(),\n chunks: z.array(TranscriptChunkOutput),\n }).nullable(),\n}\n\nexport const YoutubeTranscribeOutputSchema = {\n videoId: NullableString,\n url: NullableString,\n wordCount: z.number().int().min(0),\n chunkCount: z.number().int().min(0),\n durationMs: z.number().nullable(),\n transcriptText: z.string(),\n chunks: z.array(TranscriptChunkOutput),\n resolvedInputs: z.object({\n videoId: NullableString,\n url: NullableString,\n }),\n}\n\nexport const FacebookAdTranscribeOutputSchema = {\n videoUrl: z.string().url(),\n wordCount: z.number().int().min(0),\n chunkCount: z.number().int().min(0),\n durationMs: z.number().nullable(),\n transcriptText: z.string(),\n chunks: z.array(TranscriptChunkOutput),\n resolvedInputs: z.object({\n videoUrl: z.string().url(),\n }),\n}\n\nexport const CaptureSerpSnapshotOutputSchema = {\n schemaVersion: z.literal('serp-intelligence.capture.v1'),\n status: z.string(),\n query: NullableString,\n location: NullableString,\n capturedAt: NullableString,\n resultCount: z.number().int().min(0).nullable(),\n snapshotId: NullableString,\n resolvedInputs: z.record(z.unknown()),\n artifacts: z.array(z.record(z.unknown())),\n diagnostics: z.record(z.unknown()).nullable(),\n providerPayload: z.record(z.unknown()),\n}\n\nexport const CaptureSerpPageSnapshotsOutputSchema = {\n schemaVersion: z.literal('serp-intelligence.page-snapshots.v1'),\n status: z.string(),\n count: z.number().int().min(0),\n failedCount: z.number().int().min(0),\n captures: z.array(z.record(z.unknown())),\n resolvedInputs: z.record(z.unknown()),\n diagnostics: z.record(z.unknown()).nullable(),\n providerPayload: z.record(z.unknown()),\n}\n\nexport const CreditsInfoInputSchema = {\n item: z.string().optional().describe('Optional tool, action, or feature to look up, e.g. \"maps reviews\", \"extract_url\", \"YouTube transcription\", or \"concurrency\"'),\n includeLedger: z.boolean().default(false).describe('Whether to include recent credit ledger entries'),\n}\nexport type CreditsInfoInput = z.infer<ReturnType<typeof z.object<typeof CreditsInfoInputSchema>>>\n\nexport const WorkflowIdSchema = z.enum([\n 'directory',\n 'agent-packet',\n 'local-competitive-audit',\n 'map-comparison',\n 'serp-comparison',\n 'paa-expansion-brief',\n 'ai-overview-language',\n])\nexport type WorkflowId = z.infer<typeof WorkflowIdSchema>\n\nexport const WorkflowListInputSchema = {\n includeRecipes: z.boolean().default(true).describe('Include high-level AI-facing recipes such as market analysis, ICP research, forum/review research, brand design briefings, CRO audits, positioning briefs, content gaps, and AI search visibility audits.'),\n}\nexport type WorkflowListInput = z.infer<ReturnType<typeof z.object<typeof WorkflowListInputSchema>>>\n\nexport const WorkflowSuggestInputSchema = {\n goal: z.string().min(1).describe('The user goal or job to route, e.g. \"market analysis for roofers in Tennessee\", \"ICP research for med spas\", \"CRO audit for this URL\", or \"brand design briefing\".'),\n query: z.string().optional().describe('Business category, niche, or Maps query when known.'),\n keyword: z.string().optional().describe('Search keyword, audience problem, or content topic when known.'),\n domain: z.string().optional().describe('Target domain or brand domain when known.'),\n url: z.string().url().optional().describe('Target URL when the workflow should inspect a specific page.'),\n location: z.string().optional().describe('City/region/country for localized research, e.g. Denver, CO.'),\n state: z.string().optional().describe('US state abbreviation or name for state-wide market research.'),\n maxSuggestions: z.number().int().min(1).max(8).default(3).describe('Number of matching workflow recipes to return.'),\n}\nexport type WorkflowSuggestInput = z.infer<ReturnType<typeof z.object<typeof WorkflowSuggestInputSchema>>>\n\nexport const WorkflowRunInputSchema = {\n workflowId: WorkflowIdSchema.describe('Workflow to run: directory, agent-packet, local-competitive-audit, map-comparison, serp-comparison, paa-expansion-brief, ai-overview-language. Use only these values; call workflow_list or workflow_suggest first when unsure.'),\n input: z.record(z.unknown()).default({}).describe('Workflow-specific input object. Examples: agent-packet uses {keyword, domain?, location?, maxQuestions?}; local-competitive-audit uses {query, state, minPopulation?, maxCities?, maxResultsPerCity?, hydrateTop?, maxReviews?}; serp-comparison uses {keyword, domain?, url?, location?, extractTop?}.'),\n webhookUrl: z.string().url().optional().describe('Optional HTTPS webhook to receive the completed hosted workflow run event.'),\n}\nexport type WorkflowRunInput = z.infer<ReturnType<typeof z.object<typeof WorkflowRunInputSchema>>>\n\nexport const WorkflowStepInputSchema = {\n runId: z.string().min(1).describe('Workflow run id returned by workflow_run, workflow_step, or workflow_status. Use only a returned runId; do not construct one yourself. Advances the run by exactly one step (one logical leg, e.g. one live harvest).'),\n}\nexport type WorkflowStepInput = z.infer<ReturnType<typeof z.object<typeof WorkflowStepInputSchema>>>\n\nexport const WorkflowStatusInputSchema = {\n runId: z.string().min(1).describe('Workflow run id returned by workflow_run, workflow_step, or workflow_status. Use only a returned runId; do not construct one yourself.'),\n}\nexport type WorkflowStatusInput = z.infer<ReturnType<typeof z.object<typeof WorkflowStatusInputSchema>>>\n\nexport const WorkflowArtifactReadInputSchema = {\n runId: z.string().min(1).describe('Workflow run id returned by workflow_run, workflow_step, or workflow_status. Use only a returned runId; do not construct one yourself.'),\n artifactId: z.string().min(1).describe('Artifact id from the run artifact list returned by workflow_run, workflow_step, or workflow_status. Use only a returned artifactId; do not construct one yourself.'),\n maxBytes: z.number().int().min(1_000).max(1_000_000).default(200_000).describe('Maximum bytes of artifact text to return inline. Use lower values for large CSV/JSON artifacts; call again with the downloadUrl if needed outside MCP.'),\n}\nexport type WorkflowArtifactReadInput = z.infer<ReturnType<typeof z.object<typeof WorkflowArtifactReadInputSchema>>>\n\nconst WorkflowRecipeOutput = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string(),\n primaryWorkflowId: z.string().nullable(),\n recommendedTools: z.array(z.string()),\n requiredInputs: z.array(z.string()),\n optionalInputs: z.array(z.string()),\n produces: z.array(z.string()),\n runHint: z.string(),\n})\n\nconst WorkflowDefinitionOutput = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string(),\n})\n\nconst WorkflowArtifactOutput = z.record(z.unknown())\n\nexport const WorkflowListOutputSchema = {\n workflows: z.array(WorkflowDefinitionOutput),\n recipes: z.array(WorkflowRecipeOutput),\n}\n\nexport const WorkflowSuggestOutputSchema = {\n goal: z.string(),\n suggestions: z.array(WorkflowRecipeOutput),\n}\n\nexport const WorkflowRunOutputSchema = {\n workflowId: z.string(),\n input: z.record(z.unknown()),\n run: z.record(z.unknown()).optional(),\n summary: z.record(z.unknown()).optional(),\n step: z.record(z.unknown()).optional(),\n nextStep: z.record(z.unknown()).nullable().optional(),\n done: z.boolean().optional(),\n artifacts: z.array(WorkflowArtifactOutput),\n}\n\nexport const WorkflowStepOutputSchema = {\n runId: z.string(),\n run: z.record(z.unknown()).optional(),\n summary: z.record(z.unknown()).nullable().optional(),\n step: z.record(z.unknown()).optional(),\n nextStep: z.record(z.unknown()).nullable().optional(),\n done: z.boolean(),\n artifacts: z.array(WorkflowArtifactOutput),\n}\n\nexport const WorkflowStatusOutputSchema = {\n run: z.record(z.unknown()).optional(),\n artifacts: z.array(WorkflowArtifactOutput),\n}\n\nexport const WorkflowArtifactReadOutputSchema = {\n runId: z.string(),\n artifactId: z.string(),\n contentType: z.string(),\n bytes: z.number().int().min(0),\n truncated: z.boolean(),\n text: z.string(),\n}\n\nexport const SearchSerpInputSchema = {\n query: z.string().min(1).describe('Core search topic only. Separate location when possible. If user says \"best dentist in Brooklyn NY serp\", use query=\"best dentist\" and location=\"Brooklyn, NY\".'),\n location: z.string().optional().describe('City, region, or country for geo-targeted results, inferred from user request when present.'),\n gl: z.string().length(2).default('us').describe('Google country code inferred from location or user language.'),\n hl: z.string().default('en').describe('Google interface/content language inferred from user request.'),\n 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.'),\n proxyMode: z.enum(['location', 'configured', 'none']).default(DEFAULT_PROXY_MODE).describe('Proxy targeting mode. Default configured uses the service proxy without city/ZIP targeting for the highest general SERP success rate. Use location only when the user explicitly needs city/ZIP-targeted residential proxy evidence. Use none only for direct-network debugging.'),\n proxyZip: z.string().regex(/^\\d{5}$/).optional().describe('Optional US ZIP override for residential location proxy targeting. Use only with proxyMode location when the user gives a specific ZIP or city-center targeting needs to be forced.'),\n debug: z.boolean().default(false).describe('Include sanitized browser/session/location diagnostics in the response. Use true when debugging localization, CAPTCHA, or proxy behavior.'),\n pages: z.number().int().min(1).max(2).default(1).describe('Number of result pages to fetch (1–2)'),\n}\nexport type SearchSerpInput = z.infer<ReturnType<typeof z.object<typeof SearchSerpInputSchema>>>\n\nexport const CaptureSerpSnapshotInputSchema = {\n query: z.string().min(1).describe('Core search query to capture as a structured SERP Intelligence snapshot. Separate the place into location when the user gives a city, region, country, or ZIP.'),\n location: z.string().optional().describe('City, region, country, or service area used for localized Google results. MCP Scraper records location evidence; UULE alone is not proof of localization.'),\n gl: z.string().length(2).default('us').describe('Google country code inferred from the requested market, e.g. us, gb, ca, au.'),\n hl: z.string().default('en').describe('Google interface/content language inferred from the user request.'),\n 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.'),\n proxyMode: z.enum(['location', 'configured', 'none']).default(DEFAULT_PROXY_MODE).describe('Proxy behavior for capture. Default configured uses the service proxy without city/ZIP targeting for the highest general capture success rate. Use location only when the user explicitly needs city/ZIP-targeted residential proxy evidence. Use none only for direct-network debugging.'),\n proxyZip: z.string().regex(/^\\d{5}$/).optional().describe('Optional US ZIP override for residential location proxy targeting. Use only with proxyMode location when a precise city-center or ZIP proxy is needed.'),\n 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.'),\n debug: z.boolean().default(false).describe('Include sanitized browser, proxy, and location diagnostics. Use true when debugging localization, CAPTCHA, proxy selection, or capture reliability.'),\n includePageSnapshots: z.boolean().default(false).describe('Also capture ranking-page snapshots for selected SERP URLs through the same product capture path.'),\n pageSnapshotLimit: z.number().int().min(0).max(10).default(0).describe('Maximum ranking-page snapshots to capture when includePageSnapshots is true. Use 0 when only SERP evidence is needed.'),\n}\nexport type CaptureSerpSnapshotInput = z.infer<ReturnType<typeof z.object<typeof CaptureSerpSnapshotInputSchema>>>\n\nexport const ScreenshotInputSchema = {\n url: z.string().url().describe('URL to capture as a full-page screenshot. Use http or https. Pass allowLocal: true to capture localhost or private-network URLs during development.'),\n device: z.enum(['desktop', 'mobile']).default('desktop').describe('Viewport profile. desktop = 1440×900. mobile = 390×844. Use desktop by default; use mobile when the user asks for a mobile view.'),\n allowLocal: z.boolean().default(false).describe('Allow localhost and private-network URLs (127.x, 192.168.x, 10.x, etc.). For local development only — not for production use.'),\n}\nexport type ScreenshotInput = z.infer<ReturnType<typeof z.object<typeof ScreenshotInputSchema>>>\n\nexport const CaptureSerpPageSnapshotsInputSchema = {\n urls: z.array(z.string().url()).min(1).max(25).describe('Public HTTP/HTTPS URLs to capture as SERP Intelligence page snapshots. Do not pass localhost, private IPs, file URLs, or internal admin URLs.'),\n targets: z.array(z.object({\n url: z.string().url().describe('Public HTTP/HTTPS URL to capture.'),\n sourceKind: z.enum(['organic', 'ai_citation', 'local_pack_website', 'configured_target', 'site_subject']).default('configured_target').describe('Why this page is being captured for SERP Intelligence evidence.'),\n sourcePosition: z.number().int().min(1).optional().describe('Ranking or citation position when the page came from SERP evidence.'),\n }).strict()).min(1).max(25).optional().describe('Structured page snapshot targets. Use this instead of urls when source kind or position should be preserved.'),\n maxConcurrency: z.number().int().min(1).max(5).default(2).describe('Parallel page captures. Use 2 normally; higher values can increase proxy/browser pressure.'),\n timeoutMs: z.number().int().min(1_000).max(60_000).default(15_000).describe('Per-page capture timeout in milliseconds. Increase for slow pages; timeout artifacts are returned as structured capture failures.'),\n debug: z.boolean().default(false).describe('Include sanitized browser/proxy diagnostics for page snapshot debugging. Use true for capture, network, or proxy troubleshooting.'),\n}\nexport type CaptureSerpPageSnapshotsInput = z.infer<ReturnType<typeof z.object<typeof CaptureSerpPageSnapshotsInputSchema>>>\n","import { z } from 'zod'\n\nexport const DEFAULT_PROXY_MODE = 'configured' as const\nexport const DEFAULT_MAPS_PROXY_MODE = 'location' as const\n\nexport const HarvestOptionsSchema = z.object({\n query: z.string().min(1),\n location: z.string().optional(),\n gl: z.string().length(2).default('us'),\n hl: z.string().length(2).default('en'),\n device: z.enum(['desktop', 'mobile']).default('desktop'),\n proxyMode: z.enum(['location', 'configured', 'none']).default(DEFAULT_PROXY_MODE),\n proxyZip: z.string().regex(/^\\d{5}$/).optional(),\n debug: z.boolean().default(false),\n depth: z.number().int().min(1).max(30).default(3),\n maxQuestions: z.number().int().min(1).max(1000).default(100),\n headless: z.boolean().default(false),\n profileDir: z.string().optional(),\n proxy: z.string().url().optional(),\n kernelApiKey: z.string().optional(),\n kernelProxyId: z.string().optional(),\n kernelProxyResolution: z.unknown().optional(),\n outputDir: z.string().default('./paa-output'),\n format: z.enum(['json', 'csv', 'both']).default('both'),\n serpOnly: z.boolean().default(false),\n pages: z.number().int().min(1).max(2).default(1),\n})\n\nexport const MapsPlaceOptionsSchema = z.object({\n businessName: z.string().min(1),\n location: z.string().min(1),\n gl: z.string().length(2).default('us'),\n hl: z.string().length(2).default('en'),\n includeReviews: z.boolean().default(false),\n maxReviews: z.number().int().min(1).max(500).default(50),\n kernelApiKey: z.string().optional(),\n kernelProxyId: z.string().optional(),\n headless: z.boolean().default(true),\n})\n\nexport const MapsSearchOptionsSchema = z.object({\n query: z.string().min(1),\n location: z.string().optional(),\n gl: z.string().length(2).default('us'),\n hl: z.string().length(2).default('en'),\n maxResults: z.number().int().min(1).max(50).default(10),\n proxyMode: z.enum(['location', 'configured', 'none']).default(DEFAULT_MAPS_PROXY_MODE),\n proxyZip: z.string().regex(/^\\d{5}$/).optional(),\n debug: z.boolean().default(false),\n kernelApiKey: z.string().optional(),\n kernelProxyId: z.string().optional(),\n kernelProxyResolution: z.unknown().optional(),\n headless: z.boolean().default(true),\n})\n\nexport const RawPAAItemSchema = z.object({\n question: z.string().min(1),\n answer: z.string().optional(),\n sourceTitle: z.string().optional(),\n sourceSite: z.string().optional(),\n sourceCite: z.string().optional(),\n})\n\nexport const RawMapsOverviewSchema = z.object({\n name: z.string().nullable(),\n rating: z.string().nullable(),\n reviewCount: z.string().nullable(),\n category: z.string().nullable(),\n address: z.string().nullable(),\n hoursSummary: z.string().nullable(),\n phone: z.string().nullable(),\n phoneDisplay: z.string().nullable(),\n website: z.string().nullable(),\n plusCode: z.string().nullable(),\n bookingUrl: z.string().nullable(),\n})\n\nexport const RawMapsHoursRowSchema = z.object({\n day: z.string(),\n hours: z.string(),\n})\n\nexport const RawMapsReviewStatsSchema = z.object({\n reviewHistogram: z.array(z.object({\n stars: z.number(),\n count: z.string(),\n })),\n reviewTopics: z.array(z.object({\n label: z.string(),\n count: z.string(),\n })),\n})\n\nexport const RawMapsReviewCardSchema = z.object({\n reviewId: z.string(),\n author: z.string().nullable(),\n stars: z.string().nullable(),\n date: z.string().nullable(),\n text: z.string().nullable(),\n ownerResponse: z.string().nullable(),\n})\n\nexport const RawMapsAboutAttributeSchema = z.object({\n section: z.string(),\n attribute: z.string(),\n})\n","import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'\nimport type { RankTrackerBlueprintInput, RankTrackerMode } from './mcp-tool-schemas.js'\n\ntype ToolPlan = {\n tool: string\n purpose: string\n}\n\ntype TablePlan = {\n name: string\n purpose: string\n keyColumns: string[]\n}\n\ntype CronJobPlan = {\n name: string\n purpose: string\n modes: RankTrackerMode[]\n recommendedTools: string[]\n}\n\ntype RankTrackerBlueprint = {\n projectName: string\n targetDomain: string | null\n targetBusinessName: string | null\n trackingModes: RankTrackerMode[]\n database: string\n recommendedTools: ToolPlan[]\n tables: TablePlan[]\n cron: {\n enabled: boolean\n cadence: string\n expression: string\n timezone: string\n jobs: CronJobPlan[]\n }\n metrics: string[]\n implementationPrompt: string\n}\n\nconst DEFAULT_MODES: RankTrackerMode[] = ['maps', 'organic', 'ai_overview', 'paa']\n\nfunction normalizeDomain(value?: string): string | null {\n const trimmed = value?.trim()\n if (!trimmed) return null\n try {\n const url = new URL(trimmed.includes('://') ? trimmed : `https://${trimmed}`)\n return url.hostname.replace(/^www\\./, '').toLowerCase()\n } catch {\n return trimmed.replace(/^https?:\\/\\//, '').replace(/^www\\./, '').split('/')[0]?.toLowerCase() || trimmed\n }\n}\n\nfunction uniqueModes(input?: RankTrackerMode[]): RankTrackerMode[] {\n const modes = input?.length ? input : DEFAULT_MODES\n return [...new Set(modes)]\n}\n\nfunction cronExpression(cadence: RankTrackerBlueprintInput['scheduleCadence'], customCron?: string): string {\n if (cadence === 'daily') return '15 6 * * *'\n if (cadence === 'monthly') return '15 6 1 * *'\n if (cadence === 'custom') return customCron?.trim() || 'CUSTOM_CRON_EXPRESSION_REQUIRED'\n return '15 6 * * 1'\n}\n\nfunction includes(modes: RankTrackerMode[], mode: RankTrackerMode): boolean {\n return modes.includes(mode)\n}\n\nfunction buildToolPlan(modes: RankTrackerMode[]): ToolPlan[] {\n const plans: ToolPlan[] = []\n const push = (tool: string, purpose: string) => {\n if (!plans.some((plan) => plan.tool === tool)) plans.push({ tool, purpose })\n }\n\n push('credits_info', 'Check account balance and rates before scheduling recurring rank checks.')\n\n if (includes(modes, 'maps')) {\n push('directory_workflow', 'Seed or refresh city-by-city Maps datasets when building local market coverage.')\n push('maps_search', 'Run recurring Google Maps category checks for each keyword and location.')\n push('maps_place_intel', 'Hydrate selected target or competitor GBP details when profile-level evidence is needed.')\n }\n if (includes(modes, 'organic')) {\n push('search_serp', 'Capture localized organic rankings, local pack data, and AI Overview status without PAA expansion.')\n }\n if (includes(modes, 'ai_overview')) {\n push('search_serp', 'Capture quick AI Overview detection and organic context for each tracked query.')\n push('harvest_paa', 'Use when AI Overview text, PAA context, or source-level evidence needs deeper capture.')\n }\n if (includes(modes, 'paa')) {\n push('harvest_paa', 'Capture People Also Ask questions, answers, and source sites for PAA presence tracking.')\n }\n\n return plans\n}\n\nfunction buildTables(modes: RankTrackerMode[], includeDashboard: boolean, includeAlerts: boolean, hasCompetitors: boolean): TablePlan[] {\n const tables: TablePlan[] = [\n {\n name: 'rank_tracker_projects',\n purpose: 'One row per client, campaign, or tracked property.',\n keyColumns: ['id', 'name', 'target_domain', 'target_business_name', 'database_mode', 'timezone', 'created_at'],\n },\n {\n name: 'rank_tracker_targets',\n purpose: 'Normalized target identities and match rules for domains, URLs, business names, CIDs, and competitors.',\n keyColumns: ['id', 'project_id', 'kind', 'value', 'display_name', 'match_rules_json', 'active'],\n },\n {\n name: 'rank_tracker_keywords',\n purpose: 'Tracked keywords or service queries, separated from location so calls can localize correctly.',\n keyColumns: ['id', 'project_id', 'keyword', 'intent', 'tags_json', 'active'],\n },\n {\n name: 'rank_tracker_locations',\n purpose: 'Markets, cities, ZIPs, country/language settings, and proxy targeting hints.',\n keyColumns: ['id', 'project_id', 'label', 'gl', 'hl', 'proxy_zip', 'device', 'active'],\n },\n {\n name: 'rank_tracker_runs',\n purpose: 'Heartbeat table for every scheduled or manual rank check batch.',\n keyColumns: ['id', 'project_id', 'scheduled_for', 'started_at', 'completed_at', 'status', 'idempotency_key', 'error_message'],\n },\n ]\n\n if (includes(modes, 'organic')) {\n tables.push({\n name: 'rank_tracker_organic_results',\n purpose: 'SERP organic result rows from search_serp, including target-domain matches and competitor rows.',\n keyColumns: ['id', 'run_id', 'keyword_id', 'location_id', 'device', 'position', 'title', 'url', 'domain', 'is_target'],\n })\n }\n\n if (includes(modes, 'maps')) {\n tables.push({\n name: 'rank_tracker_maps_results',\n purpose: 'Google Maps result rows from maps_search and directory_workflow, including GBP identity fields.',\n keyColumns: ['id', 'run_id', 'keyword_id', 'location_id', 'position', 'business_name', 'place_url', 'cid', 'website_url', 'rating', 'review_count', 'is_target'],\n })\n tables.push({\n name: 'rank_tracker_market_seeds',\n purpose: 'Directory workflow city, population, ZIP-group, and market seed records used to build local tracking coverage.',\n keyColumns: ['id', 'project_id', 'query', 'city', 'state', 'population', 'zip_group_json', 'last_seeded_run_id'],\n })\n }\n\n if (includes(modes, 'ai_overview')) {\n tables.push({\n name: 'rank_tracker_ai_overviews',\n purpose: 'AI Overview detection, text snapshot, citation domains, and target citation status per query/location.',\n keyColumns: ['id', 'run_id', 'keyword_id', 'location_id', 'detected', 'target_cited', 'cited_domains_json', 'overview_text'],\n })\n }\n\n if (includes(modes, 'paa')) {\n tables.push({\n name: 'rank_tracker_paa_sources',\n purpose: 'People Also Ask questions, answers, and source sites, with target source presence flags.',\n keyColumns: ['id', 'run_id', 'keyword_id', 'location_id', 'question', 'answer', 'source_title', 'source_site', 'target_present'],\n })\n }\n\n if (hasCompetitors) {\n tables.push({\n name: 'rank_tracker_competitor_snapshots',\n purpose: 'Per-run competitor visibility summaries across organic, Maps, AI Overview, and PAA surfaces.',\n keyColumns: ['id', 'run_id', 'target_id', 'surface', 'best_position', 'presence_count', 'share_of_surface'],\n })\n }\n\n if (includeDashboard) {\n tables.push({\n name: 'rank_tracker_daily_metrics',\n purpose: 'Rollup table for dashboard charts, trend lines, and share-of-visibility summaries.',\n keyColumns: ['id', 'project_id', 'metric_date', 'keyword_id', 'location_id', 'surface', 'metric_name', 'metric_value'],\n })\n }\n\n if (includeAlerts) {\n tables.push({\n name: 'rank_tracker_alert_events',\n purpose: 'Deduplicated gain/loss events for rank movement, Maps top 3, AI Overview citations, and PAA source presence.',\n keyColumns: ['id', 'project_id', 'run_id', 'surface', 'severity', 'event_key', 'message', 'created_at', 'acknowledged_at'],\n })\n }\n\n return tables\n}\n\nfunction buildCronJobs(modes: RankTrackerMode[], includeDashboard: boolean, includeAlerts: boolean): CronJobPlan[] {\n const jobs: CronJobPlan[] = [\n {\n name: 'rank-tracker-dispatch',\n purpose: 'Find due keyword/location/mode combinations, create a rank_tracker_runs row, and enqueue idempotent work items.',\n modes,\n recommendedTools: ['credits_info'],\n },\n ]\n\n if (includes(modes, 'maps')) {\n jobs.push({\n name: 'maps-rank-check',\n purpose: 'Run maps_search per keyword/location and optionally directory_workflow for market seed refreshes.',\n modes: ['maps'],\n recommendedTools: ['maps_search', 'directory_workflow', 'maps_place_intel'],\n })\n }\n\n if (includes(modes, 'organic') || includes(modes, 'ai_overview')) {\n jobs.push({\n name: 'serp-rank-check',\n purpose: 'Run search_serp per keyword/location/device and persist organic ranks, local pack, and AI Overview status.',\n modes: modes.filter((mode) => mode === 'organic' || mode === 'ai_overview'),\n recommendedTools: ['search_serp'],\n })\n }\n\n if (includes(modes, 'paa') || includes(modes, 'ai_overview')) {\n jobs.push({\n name: 'paa-ai-evidence-check',\n purpose: 'Run harvest_paa for PAA source presence and deeper AI Overview/PAA evidence where needed.',\n modes: modes.filter((mode) => mode === 'paa' || mode === 'ai_overview'),\n recommendedTools: ['harvest_paa'],\n })\n }\n\n if (includeDashboard) {\n jobs.push({\n name: 'rank-tracker-rollups',\n purpose: 'Aggregate raw rows into daily metrics for charts, comparison tables, and trend lines.',\n modes,\n recommendedTools: [],\n })\n }\n\n if (includeAlerts) {\n jobs.push({\n name: 'rank-tracker-alerts',\n purpose: 'Compare latest run against prior snapshots and emit deduplicated visibility gain/loss events.',\n modes,\n recommendedTools: [],\n })\n }\n\n return jobs\n}\n\nfunction buildMetrics(modes: RankTrackerMode[], includeDashboard: boolean, includeAlerts: boolean): string[] {\n const metrics: string[] = ['run_success_rate', 'last_successful_run_at', 'stale_keyword_location_count']\n\n if (includes(modes, 'maps')) {\n metrics.push('maps_best_position', 'maps_top_3_presence', 'maps_target_found', 'maps_competitor_count_above_target')\n }\n if (includes(modes, 'organic')) {\n metrics.push('organic_best_position', 'organic_top_3_presence', 'organic_top_10_presence', 'organic_best_url')\n }\n if (includes(modes, 'ai_overview')) {\n metrics.push('ai_overview_detected', 'target_ai_overview_cited', 'ai_overview_citation_domain_count')\n }\n if (includes(modes, 'paa')) {\n metrics.push('paa_question_count', 'target_paa_source_count', 'paa_presence_rate', 'paa_source_domains')\n }\n if (includeDashboard) metrics.push('share_of_visibility', 'position_delta_7d', 'position_delta_30d')\n if (includeAlerts) metrics.push('visibility_gain_events', 'visibility_loss_events')\n\n return metrics\n}\n\nfunction listOrPlaceholder(values: string[] | undefined, fallback: string): string {\n const clean = values?.map((value) => value.trim()).filter(Boolean) ?? []\n if (!clean.length) return fallback\n return clean.map((value) => `- ${value}`).join('\\n')\n}\n\nfunction buildPrompt(\n input: RankTrackerBlueprintInput,\n modes: RankTrackerMode[],\n tools: ToolPlan[],\n tables: TablePlan[],\n jobs: CronJobPlan[],\n metrics: string[],\n expression: string,\n targetDomain: string | null,\n targetBusinessName: string | null,\n): string {\n const keywords = listOrPlaceholder(input.keywords, '- TODO: add tracked keywords')\n const locations = listOrPlaceholder(input.locations, '- TODO: add tracked markets/locations')\n const competitors = listOrPlaceholder(input.competitors, '- Optional: add competitor domains or GBP names')\n const notes = input.notes?.trim() || 'No extra implementation notes.'\n\n return [\n 'You are building a production rank tracker powered by MCP Scraper. Create the database migrations, scheduled worker, ingestion functions, and dashboard/query layer described below.',\n '',\n `Project: ${input.projectName || 'MCP Scraper Rank Tracker'}`,\n `Target domain: ${targetDomain || 'TODO_TARGET_DOMAIN'}`,\n `Target business/GBP name: ${targetBusinessName || 'TODO_TARGET_BUSINESS_NAME'}`,\n `Database target: ${input.database || 'postgres'}`,\n `Tracking modes: ${modes.join(', ')}`,\n '',\n 'Seed keywords:',\n keywords,\n '',\n 'Seed locations:',\n locations,\n '',\n 'Competitors:',\n competitors,\n '',\n 'MCP Scraper calls to use:',\n tools.map((tool) => `- ${tool.tool}: ${tool.purpose}`).join('\\n'),\n '',\n 'Database tables to create:',\n tables.map((table) => `- ${table.name}: ${table.keyColumns.join(', ')}`).join('\\n'),\n '',\n 'Scheduler and heartbeat requirements:',\n `- Use cron expression \"${expression}\" in timezone \"${input.timezone || 'UTC'}\" unless the user changes cadence.`,\n '- Every scheduled batch must insert or update rank_tracker_runs before calling MCP tools.',\n '- Use idempotency_key = project_id + keyword_id + location_id + mode + device + scheduled_date.',\n '- Mark runs as running, succeeded, failed, or skipped; persist error_message on failures.',\n '- Run MCP calls sequentially by default because accounts have one concurrency slot unless the user bought more.',\n '- Retry retryable upstream failures with backoff, but do not duplicate rows for the same idempotency key.',\n '',\n 'Mode-specific ingestion rules:',\n '- maps: Use directory_workflow to seed/refresh market coverage and maps_search for recurring keyword/location rank checks. Match the target by targetBusinessName, website domain, CID, and place URL when available.',\n '- organic: Use search_serp and persist every organic result row. Compute the best targetDomain position and best ranking URL per keyword/location/device.',\n '- ai_overview: Use search_serp for quick detection and harvest_paa when deeper text/source evidence is needed. Track detected, overview_text, cited domains, and whether targetDomain is cited.',\n '- paa: Use harvest_paa and persist each question/source pair. Track whether sourceSite or answer/source evidence matches targetDomain, then compute PAA presence rate.',\n '',\n 'Metrics to expose:',\n metrics.map((metric) => `- ${metric}`).join('\\n'),\n '',\n 'Alert requirements:',\n input.includeAlerts\n ? '- Emit deduplicated alert_events when target gains/loses Maps top 3, organic top 10, AI Overview citation, or PAA source presence.'\n : '- Alerts are out of scope for this build unless the user asks for them.',\n '',\n 'Dashboard requirements:',\n input.includeDashboard\n ? '- Build views for latest position by keyword/location, trend deltas, competitors above target, AI Overview citations, and PAA source wins/losses.'\n : '- Dashboard is out of scope for this build unless the user asks for it.',\n '',\n 'Extra notes:',\n notes,\n ].join('\\n')\n}\n\nexport function buildRankTrackerBlueprint(input: RankTrackerBlueprintInput): CallToolResult {\n const trackingModes = uniqueModes(input.trackingModes)\n const targetDomain = normalizeDomain(input.targetDomain)\n const targetBusinessName = input.targetBusinessName?.trim() || null\n const projectName = input.projectName?.trim() || 'MCP Scraper Rank Tracker'\n const database = input.database || 'postgres'\n const expression = cronExpression(input.scheduleCadence || 'weekly', input.customCron)\n const tools = buildToolPlan(trackingModes)\n const tables = buildTables(trackingModes, input.includeDashboard !== false, input.includeAlerts !== false, Boolean(input.competitors?.length))\n const jobs = input.includeCron === false ? [] : buildCronJobs(trackingModes, input.includeDashboard !== false, input.includeAlerts !== false)\n const metrics = buildMetrics(trackingModes, input.includeDashboard !== false, input.includeAlerts !== false)\n const implementationPrompt = buildPrompt(input, trackingModes, tools, tables, jobs, metrics, expression, targetDomain, targetBusinessName)\n\n const blueprint: RankTrackerBlueprint = {\n projectName,\n targetDomain,\n targetBusinessName,\n trackingModes,\n database,\n recommendedTools: tools,\n tables,\n cron: {\n enabled: input.includeCron !== false,\n cadence: input.scheduleCadence || 'weekly',\n expression: input.includeCron === false ? 'disabled' : expression,\n timezone: input.timezone || 'UTC',\n jobs,\n },\n metrics,\n implementationPrompt,\n }\n\n const text = [\n `# ${projectName}`,\n '',\n 'Rank tracker build blueprint generated from MCP Scraper tool capabilities.',\n '',\n '## Modes',\n trackingModes.map((mode) => `- ${mode}`).join('\\n'),\n '',\n '## Recommended MCP Tools',\n tools.map((tool) => `- \\`${tool.tool}\\` - ${tool.purpose}`).join('\\n'),\n '',\n '## Database Tables',\n tables.map((table) => `- \\`${table.name}\\` - ${table.purpose}`).join('\\n'),\n '',\n '## Cron / Heartbeat',\n blueprint.cron.enabled\n ? `- Cadence: ${blueprint.cron.cadence}\\n- Cron: \\`${blueprint.cron.expression}\\`\\n- Timezone: ${blueprint.cron.timezone}\\n- Jobs: ${jobs.map((job) => job.name).join(', ')}`\n : '- Disabled by input. Still create rank_tracker_runs for manual runs.',\n '',\n '## Implementation Prompt',\n '```text',\n implementationPrompt,\n '```',\n ].join('\\n')\n\n return {\n content: [{ type: 'text', text }],\n structuredContent: blueprint,\n }\n}\n"],"mappings":";;;;AACA,IAAAA,kBAA6B;AAC7B,IAAAC,kBAAwB;AACxB,IAAAC,oBAAqB;AACrB,mBAAqC;;;ACJ9B,IAAM,yBAAyB;AAE/B,IAAM,+BAA+B;AAOrC,SAAS,qBAAqB,cAAsB,WAAW,OAA6B;AACjG,QAAM,YAAY,OAAO,SAAS,YAAY,KAAK,eAAe,IAAI,KAAK,MAAM,YAAY,IAAI;AACjG,MAAI;AACJ,MAAI,YAAY,aAAa,GAAI,YAAW;AAAA,WACnC,aAAa,IAAK,YAAW;AAAA,WAC7B,aAAa,IAAK,YAAW;AAAA,MACjC,YAAW;AAChB,QAAM,WAAW,KAAK,IAAI,WAAW,8BAA8B,yBAAyB,GAAK;AACjG,SAAO,EAAE,UAAU,SAAS;AAC9B;;;ACYA,SAAS,sBAAsB,KAAwC;AACrE,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,SAAS,IAAI,IAAI,GAAG;AAC1B,UAAM,OAAO,O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AG,CAAC;AAAA,CAAI;AAC5E,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["import_node_fs","import_node_os","import_node_path","baseUrl","apiKey","import_node_fs","import_node_path","wordCount","import_zod","server","executor"]}
|