scorchcrawl-mcp 2.1.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,319 @@
1
+ /**
2
+ * Local Scraper — fetches pages through the LOCAL machine's IP and converts to markdown.
3
+ * Used when SCORCHCRAWL_LOCAL_PROXY=true is set, so scraping traffic exits through
4
+ * the user's residential IP instead of the server's datacenter IP.
5
+ *
6
+ * Falls back to the remote ScorchCrawl API for features that need server-side
7
+ * processing (search, crawl, extract, agent, JSON schema extraction).
8
+ *
9
+ * SPA Detection:
10
+ * When the fetched HTML looks like a Single Page Application shell
11
+ * (minimal text, loading indicators, heavy JS bundles), the scraper returns
12
+ * a `SPA_SKELETON_DETECTED` error so the caller can retry via the engine's
13
+ * Playwright-backed scraper which executes JavaScript.
14
+ */
15
+ import TurndownService from 'turndown';
16
+ import * as cheerio from 'cheerio';
17
+ // Lazy-init singleton
18
+ let _turndown = null;
19
+ function getTurndown() {
20
+ if (!_turndown) {
21
+ _turndown = new TurndownService({
22
+ headingStyle: 'atx',
23
+ codeBlockStyle: 'fenced',
24
+ bulletListMarker: '-',
25
+ });
26
+ // Strip script/style/nav/footer tags
27
+ _turndown.remove(['script', 'style', 'noscript', 'iframe']);
28
+ }
29
+ return _turndown;
30
+ }
31
+ // ---------------------------------------------------------------------------
32
+ // SPA / JS-rendered page detection
33
+ // ---------------------------------------------------------------------------
34
+ /**
35
+ * Common phrases found in SPA shell HTML before JS hydrates the page.
36
+ * Matched case-insensitively against the visible body text.
37
+ */
38
+ const SPA_LOADING_PATTERNS = [
39
+ 'loading...',
40
+ 'loading…',
41
+ 'please wait',
42
+ 'just a moment',
43
+ 'checking your browser',
44
+ 'one moment please',
45
+ 'redirecting',
46
+ 'enable javascript',
47
+ 'javascript is required',
48
+ 'javascript must be enabled',
49
+ 'this app requires javascript',
50
+ 'you need to enable javascript',
51
+ 'noscript',
52
+ ];
53
+ /**
54
+ * CSS selectors whose sole presence (with no other meaningful content)
55
+ * strongly indicates a JS-only SPA shell.
56
+ */
57
+ const SPA_ROOT_SELECTORS = [
58
+ '#root', // React (CRA, Vite)
59
+ '#app', // Vue
60
+ '#__next', // Next.js
61
+ '#__nuxt', // Nuxt
62
+ '#svelte', // SvelteKit
63
+ 'app-root', // Angular
64
+ '#___gatsby', // Gatsby
65
+ '#main-app', // misc
66
+ ];
67
+ /** Minimum characters of visible text for a page to be considered "real" content. */
68
+ const MIN_MEANINGFUL_TEXT_LENGTH = 200;
69
+ /** Ratio: if (script bytes / total HTML bytes) exceeds this, it's likely a SPA shell. */
70
+ const SCRIPT_HEAVY_RATIO = 0.65;
71
+ /**
72
+ * Inspect raw HTML + extracted text to decide if the page is a SPA shell
73
+ * that hasn't been hydrated (no JS execution happened).
74
+ *
75
+ * Returns a short reason string if SPA-like, or `null` if the page looks real.
76
+ */
77
+ export function detectSPASkeleton(rawHtml, _bodyText, $) {
78
+ // Get visible text only (strip script, style, noscript content)
79
+ const $clone = cheerio.load($.html());
80
+ $clone('script, style, noscript').remove();
81
+ const visibleText = $clone('body').text() || '';
82
+ const trimmedText = visibleText.replace(/\s+/g, ' ').trim();
83
+ const lowerText = trimmedText.toLowerCase();
84
+ // 1. Very little visible text — likely a shell that JS would populate
85
+ if (trimmedText.length < MIN_MEANINGFUL_TEXT_LENGTH) {
86
+ // Check for SPA root containers
87
+ for (const sel of SPA_ROOT_SELECTORS) {
88
+ const el = $(sel);
89
+ if (el.length > 0) {
90
+ const innerText = el.text().replace(/\s+/g, ' ').trim();
91
+ if (innerText.length < MIN_MEANINGFUL_TEXT_LENGTH) {
92
+ return `SPA root container "${sel}" with minimal content (${innerText.length} chars)`;
93
+ }
94
+ }
95
+ }
96
+ // Check for loading phrases in the sparse text
97
+ for (const pattern of SPA_LOADING_PATTERNS) {
98
+ if (lowerText.includes(pattern)) {
99
+ return `Loading indicator detected: "${pattern}"`;
100
+ }
101
+ }
102
+ // Even without a known root, < 50 chars of body text is almost certainly a shell
103
+ if (trimmedText.length < 50) {
104
+ return `Near-empty body text (${trimmedText.length} chars)`;
105
+ }
106
+ }
107
+ // 2. Loading phrases in an otherwise short page (< 500 chars)
108
+ if (trimmedText.length < 500) {
109
+ for (const pattern of SPA_LOADING_PATTERNS) {
110
+ if (lowerText.includes(pattern)) {
111
+ return `Short page with loading indicator: "${pattern}"`;
112
+ }
113
+ }
114
+ }
115
+ // 3. Script-heavy pages: mostly <script> tags, very little content
116
+ const scriptContent = $('script')
117
+ .toArray()
118
+ .reduce((sum, el) => sum + ($(el).html()?.length || 0), 0);
119
+ const htmlLength = rawHtml.length;
120
+ if (htmlLength > 1000 &&
121
+ scriptContent / htmlLength > SCRIPT_HEAVY_RATIO &&
122
+ trimmedText.length < MIN_MEANINGFUL_TEXT_LENGTH) {
123
+ return `Script-heavy page (${Math.round((scriptContent / htmlLength) * 100)}% scripts, ${trimmedText.length} chars text)`;
124
+ }
125
+ return null;
126
+ }
127
+ /**
128
+ * Fetches a URL locally (through the user's IP) and converts to markdown.
129
+ */
130
+ export async function localScrape(url, options = {}) {
131
+ const timeout = options.timeout || 30000;
132
+ // Determine requested formats
133
+ const formats = (options.formats || ['markdown']).map((f) => typeof f === 'string' ? f : f.type);
134
+ const wantMarkdown = formats.includes('markdown');
135
+ const wantHtml = formats.includes('html');
136
+ const wantRawHtml = formats.includes('rawHtml');
137
+ const wantLinks = formats.includes('links');
138
+ // Needs JSON/screenshot/branding? Can't do locally — return null to fall back
139
+ const needsServerSide = formats.some((f) => f === 'json' || f === 'screenshot' || f === 'branding' || f === 'summary');
140
+ if (needsServerSide) {
141
+ return { success: false, error: 'FORMAT_NEEDS_SERVER' };
142
+ }
143
+ try {
144
+ const controller = new AbortController();
145
+ const timer = setTimeout(() => controller.abort(), timeout);
146
+ const fetchOptions = {
147
+ signal: controller.signal,
148
+ headers: {
149
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
150
+ Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
151
+ 'Accept-Language': 'en-US,en;q=0.9',
152
+ 'Accept-Encoding': 'gzip, deflate, br',
153
+ 'Cache-Control': 'no-cache',
154
+ ...(options.headers || {}),
155
+ },
156
+ redirect: 'follow',
157
+ };
158
+ // Node 18+ native TLS rejection control
159
+ if (options.skipTlsVerification) {
160
+ fetchOptions.dispatcher = undefined; // handled below
161
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
162
+ }
163
+ const response = await fetch(url, fetchOptions);
164
+ clearTimeout(timer);
165
+ if (options.skipTlsVerification) {
166
+ delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;
167
+ }
168
+ const rawHtml = await response.text();
169
+ const statusCode = response.status;
170
+ const contentType = response.headers.get('content-type') || 'text/html';
171
+ // Parse with Cheerio
172
+ const $ = cheerio.load(rawHtml);
173
+ // Extract metadata
174
+ const title = $('title').first().text().trim() ||
175
+ $('meta[property="og:title"]').attr('content') ||
176
+ '';
177
+ const description = $('meta[name="description"]').attr('content') ||
178
+ $('meta[property="og:description"]').attr('content') ||
179
+ '';
180
+ const language = $('html').attr('lang') || '';
181
+ // Remove unwanted elements if onlyMainContent
182
+ if (options.onlyMainContent) {
183
+ $('nav, header, footer, aside, .sidebar, .menu, .navigation, .breadcrumb, .cookie-banner, .ad, .advertisement, [role="navigation"], [role="banner"], [role="complementary"]').remove();
184
+ }
185
+ // Apply excludeTags
186
+ if (options.excludeTags?.length) {
187
+ $(options.excludeTags.join(', ')).remove();
188
+ }
189
+ // Get the target HTML content
190
+ let targetHtml;
191
+ if (options.includeTags?.length) {
192
+ targetHtml = options.includeTags
193
+ .map((sel) => $(sel).html() || '')
194
+ .filter(Boolean)
195
+ .join('\n');
196
+ }
197
+ else if (options.onlyMainContent) {
198
+ // Try to find main content area
199
+ const mainSelectors = [
200
+ 'main',
201
+ 'article',
202
+ '[role="main"]',
203
+ '.main-content',
204
+ '.content',
205
+ '#content',
206
+ '#main',
207
+ ];
208
+ let mainHtml = '';
209
+ for (const sel of mainSelectors) {
210
+ const el = $(sel).first();
211
+ if (el.length && (el.html()?.length || 0) > 100) {
212
+ mainHtml = el.html() || '';
213
+ break;
214
+ }
215
+ }
216
+ targetHtml = mainHtml || $('body').html() || rawHtml;
217
+ }
218
+ else {
219
+ targetHtml = $('body').html() || rawHtml;
220
+ }
221
+ // Build response
222
+ const data = {
223
+ metadata: {
224
+ title,
225
+ description: description || undefined,
226
+ language: language || undefined,
227
+ sourceURL: url,
228
+ url: response.url || url,
229
+ statusCode,
230
+ contentType,
231
+ proxyUsed: 'local',
232
+ },
233
+ };
234
+ if (wantMarkdown) {
235
+ data.markdown = getTurndown().turndown(targetHtml);
236
+ }
237
+ if (wantHtml) {
238
+ data.html = targetHtml;
239
+ }
240
+ if (wantRawHtml) {
241
+ data.rawHtml = rawHtml;
242
+ }
243
+ if (wantLinks) {
244
+ const links = [];
245
+ $('a[href]').each((_, el) => {
246
+ const href = $(el).attr('href');
247
+ if (href && !href.startsWith('#') && !href.startsWith('javascript:')) {
248
+ try {
249
+ links.push(new URL(href, url).href);
250
+ }
251
+ catch {
252
+ links.push(href);
253
+ }
254
+ }
255
+ });
256
+ data.links = [...new Set(links)];
257
+ }
258
+ // --- SPA detection: check if the fetched content is a JS-only shell ---
259
+ const bodyText = $('body').text() || '';
260
+ const spaReason = detectSPASkeleton(rawHtml, bodyText, $);
261
+ if (spaReason) {
262
+ return { success: false, error: 'SPA_SKELETON_DETECTED', data };
263
+ }
264
+ return { success: true, data };
265
+ }
266
+ catch (err) {
267
+ if (err.name === 'AbortError') {
268
+ return { success: false, error: `Timeout after ${timeout}ms` };
269
+ }
270
+ return { success: false, error: err.message || String(err) };
271
+ }
272
+ }
273
+ /**
274
+ * Check if local proxy mode is enabled.
275
+ * Controlled by:
276
+ * - SCORCHCRAWL_LOCAL_PROXY=true env var
277
+ * - ?localProxy=true query param in SCORCHCRAWL_API_URL
278
+ */
279
+ export function isLocalProxyEnabled() {
280
+ // Check env var
281
+ if (process.env.SCORCHCRAWL_LOCAL_PROXY?.toLowerCase() === 'true' ||
282
+ process.env.SCORCHCRAWL_LOCAL_PROXY === '1') {
283
+ return true;
284
+ }
285
+ // Check URL query param
286
+ const apiUrl = process.env.SCORCHCRAWL_API_URL;
287
+ if (apiUrl) {
288
+ try {
289
+ const parsed = new URL(apiUrl);
290
+ if (parsed.searchParams.get('localProxy') === 'true' ||
291
+ parsed.searchParams.get('localProxy') === '1') {
292
+ return true;
293
+ }
294
+ }
295
+ catch {
296
+ // ignore invalid URL
297
+ }
298
+ }
299
+ return false;
300
+ }
301
+ /**
302
+ * Returns SCORCHCRAWL_API_URL without the localProxy query param
303
+ * (so the scraping SDK doesn't pass it to the API).
304
+ */
305
+ export function getCleanApiUrl() {
306
+ const apiUrl = process.env.SCORCHCRAWL_API_URL;
307
+ if (!apiUrl)
308
+ return undefined;
309
+ try {
310
+ const parsed = new URL(apiUrl);
311
+ parsed.searchParams.delete('localProxy');
312
+ const cleaned = parsed.toString();
313
+ // Remove trailing ? if no other params
314
+ return cleaned.replace(/\?$/, '');
315
+ }
316
+ catch {
317
+ return apiUrl;
318
+ }
319
+ }
@@ -0,0 +1,375 @@
1
+ /**
2
+ * Response Processing Utilities
3
+ *
4
+ * Two layers of intelligent response handling for MCP tool results:
5
+ * 1. Error Mapping — classifies errors and returns actionable guidance
6
+ * 2. Content Truncation — smart paragraph-boundary truncation with notices
7
+ *
8
+ * No competitor MCP scraper implements any of these. This is a ScorchCrawl
9
+ * differentiator.
10
+ */
11
+ // ---------------------------------------------------------------------------
12
+ // Configuration (from environment)
13
+ // ---------------------------------------------------------------------------
14
+ const MAX_CONTENT_CHARS = parseInt(process.env.SCORCHCRAWL_MAX_CONTENT_CHARS || '25000', 10);
15
+ /**
16
+ * Classify a raw error (from fetch, SDK, or engine) into a structured
17
+ * MappedError with actionable guidance for the LLM.
18
+ */
19
+ export function mapError(err) {
20
+ const raw = normalizeErrorString(err);
21
+ const lower = raw.toLowerCase();
22
+ // --- HTTP status-based patterns ---
23
+ if (matches(lower, ['403', 'forbidden', 'cloudflare', 'cf-ray', 'challenge', 'access denied'])) {
24
+ return {
25
+ code: 'ACCESS_DENIED',
26
+ message: 'This site blocks automated access.',
27
+ suggestions: [
28
+ 'Try scorch_search to find cached/indexed content instead',
29
+ 'Add waitFor: 5000 to let challenge pages resolve',
30
+ 'Try with proxy: "stealth" for enhanced bot evasion',
31
+ ],
32
+ originalError: raw,
33
+ };
34
+ }
35
+ if (matches(lower, ['404', 'not found', 'page not found', 'does not exist'])) {
36
+ return {
37
+ code: 'NOT_FOUND',
38
+ message: 'Page does not exist at this URL.',
39
+ suggestions: [
40
+ 'Use scorch_map to discover correct URLs on the site',
41
+ 'Check if the URL has a typo or outdated path',
42
+ 'Try scorch_search to find the current location of this content',
43
+ ],
44
+ originalError: raw,
45
+ };
46
+ }
47
+ if (matches(lower, ['429', 'rate limit', 'too many requests', 'throttl'])) {
48
+ return {
49
+ code: 'RATE_LIMITED',
50
+ message: 'Rate limited by the target site.',
51
+ suggestions: [
52
+ 'Wait 30 seconds and retry',
53
+ 'Try a different URL on the same site',
54
+ 'Use scorch_search to find the content from a different source',
55
+ ],
56
+ originalError: raw,
57
+ };
58
+ }
59
+ if (matchesStatusRange(lower, 500, 599)) {
60
+ return {
61
+ code: 'SERVER_ERROR',
62
+ message: 'The target site returned a server error.',
63
+ suggestions: [
64
+ 'Retry once — the site may be experiencing temporary issues',
65
+ 'Try again in a few minutes if it persists',
66
+ ],
67
+ originalError: raw,
68
+ };
69
+ }
70
+ // --- Network/connection errors ---
71
+ if (matches(lower, ['timeout', 'aborterror', 'aborted', 'timed out', 'etimedout'])) {
72
+ return {
73
+ code: 'TIMEOUT',
74
+ message: 'Page took too long to load.',
75
+ suggestions: [
76
+ 'Add onlyMainContent: true to reduce processing time',
77
+ 'Increase waitFor to give JS more time to render',
78
+ 'Try with a simpler format like markdown instead of screenshot',
79
+ ],
80
+ originalError: raw,
81
+ };
82
+ }
83
+ if (matches(lower, ['econnrefused', 'enotfound', 'dns', 'getaddrinfo', 'connect failed'])) {
84
+ // Distinguish between engine-down and remote-site-down
85
+ if (matches(lower, ['localhost', '127.0.0.1', '0.0.0.0', '3002', 'engine', 'api'])) {
86
+ return {
87
+ code: 'ENGINE_UNAVAILABLE',
88
+ message: 'Scraping engine is not running.',
89
+ suggestions: [
90
+ 'Check that Docker services are up: docker compose up -d',
91
+ 'Verify SCORCHCRAWL_API_URL is correct in your config',
92
+ ],
93
+ originalError: raw,
94
+ };
95
+ }
96
+ return {
97
+ code: 'CONNECTION_FAILED',
98
+ message: 'Cannot reach this URL.',
99
+ suggestions: [
100
+ 'Check if the URL is correct and accessible',
101
+ 'The site may be down — try again later',
102
+ 'Try scorch_search to find alternative sources',
103
+ ],
104
+ originalError: raw,
105
+ };
106
+ }
107
+ if (matches(lower, ['ssl', 'tls', 'certificate', 'cert', 'self-signed', 'unable to verify'])) {
108
+ return {
109
+ code: 'TLS_ERROR',
110
+ message: 'SSL certificate issue with this site.',
111
+ suggestions: [
112
+ 'Try with skipTlsVerification: true',
113
+ ],
114
+ originalError: raw,
115
+ };
116
+ }
117
+ if (matches(lower, ['empty', 'no content', 'no markdown', 'no extractable'])) {
118
+ return {
119
+ code: 'EMPTY_CONTENT',
120
+ message: 'Page returned no extractable content.',
121
+ suggestions: [
122
+ 'Use scorch_map with a search param to find the right page',
123
+ 'Add waitFor: 5000 for JavaScript-rendered pages',
124
+ 'Try with formats: ["html"] to see the raw page structure',
125
+ ],
126
+ originalError: raw,
127
+ };
128
+ }
129
+ if (matches(lower, ['spa_skeleton_detected', 'spa detected', 'javascript is required'])) {
130
+ return {
131
+ code: 'SPA_DETECTED',
132
+ message: 'Page requires JavaScript rendering (SPA detected).',
133
+ suggestions: [
134
+ 'Add waitFor: 5000 to allow JavaScript to render',
135
+ 'The engine will automatically retry with Playwright',
136
+ ],
137
+ originalError: raw,
138
+ };
139
+ }
140
+ // --- Catch-all ---
141
+ return {
142
+ code: 'UNKNOWN_ERROR',
143
+ message: `Scraping failed: ${truncateString(raw, 200)}`,
144
+ suggestions: [
145
+ 'Try a different URL or format',
146
+ 'Use scorch_search as an alternative data source',
147
+ ],
148
+ originalError: raw,
149
+ };
150
+ }
151
+ /** Normalize any error-like value to a string */
152
+ function normalizeErrorString(err) {
153
+ if (err == null)
154
+ return 'Unknown error';
155
+ if (err instanceof Error) {
156
+ // Include status code from Axios/fetch errors
157
+ const axiosStatus = err?.response?.status;
158
+ const status = err?.status || err?.statusCode || axiosStatus;
159
+ const prefix = status ? `HTTP ${status}: ` : '';
160
+ return `${prefix}${err.message}`;
161
+ }
162
+ if (typeof err === 'string')
163
+ return err;
164
+ try {
165
+ const s = JSON.stringify(err);
166
+ return s || 'Unknown error';
167
+ }
168
+ catch {
169
+ return String(err);
170
+ }
171
+ }
172
+ /** Check if a lowered string contains any of the patterns */
173
+ function matches(lower, patterns) {
174
+ return patterns.some((p) => lower.includes(p));
175
+ }
176
+ /** Check if an error string refers to an HTTP status in a range */
177
+ function matchesStatusRange(lower, from, to) {
178
+ const statusMatch = lower.match(/(?:status\s*(?:code\s*)?|http\s*)(\d{3})/);
179
+ if (statusMatch) {
180
+ const code = parseInt(statusMatch[1], 10);
181
+ return code >= from && code <= to;
182
+ }
183
+ // Also check for bare 5xx patterns
184
+ for (let s = from; s <= to; s++) {
185
+ if (lower.includes(String(s)))
186
+ return true;
187
+ }
188
+ return false;
189
+ }
190
+ /** Safely truncate a string for display */
191
+ function truncateString(s, maxLen) {
192
+ if (s.length <= maxLen)
193
+ return s;
194
+ return s.slice(0, maxLen - 3) + '...';
195
+ }
196
+ // ---------------------------------------------------------------------------
197
+ // Feature 2: Content Truncation
198
+ // ---------------------------------------------------------------------------
199
+ /**
200
+ * Content fields that may need truncation.
201
+ * Metadata, links, and structured data are NEVER truncated.
202
+ */
203
+ const CONTENT_FIELDS = ['markdown', 'html', 'rawHtml'];
204
+ /**
205
+ * For crawl results: max fraction of total limit a single page can use.
206
+ */
207
+ const SINGLE_PAGE_MAX_FRACTION = 0.3;
208
+ /**
209
+ * Truncate a markdown/html string at the nearest paragraph or heading
210
+ * boundary before the character limit.
211
+ */
212
+ export function truncateAtBoundary(content, maxChars) {
213
+ if (content.length <= maxChars) {
214
+ return { text: content, wasTruncated: false };
215
+ }
216
+ // Search backward from maxChars for a good break point
217
+ const searchWindow = content.slice(0, maxChars);
218
+ // Priority 1: Last heading boundary (# at start of line)
219
+ const headingMatch = searchWindow.lastIndexOf('\n#');
220
+ // Priority 2: Last double newline (paragraph boundary)
221
+ const paraMatch = searchWindow.lastIndexOf('\n\n');
222
+ // Priority 3: Last single newline
223
+ const lineMatch = searchWindow.lastIndexOf('\n');
224
+ // Priority 4: Last sentence end
225
+ const sentenceMatch = Math.max(searchWindow.lastIndexOf('. '), searchWindow.lastIndexOf('.\n'));
226
+ // Pick the best break point (prefer heading > paragraph > line > sentence)
227
+ let breakPoint = -1;
228
+ // Only use if it's in the last 30% of the window (don't cut too aggressively)
229
+ const minBreak = Math.floor(maxChars * 0.7);
230
+ if (headingMatch > minBreak)
231
+ breakPoint = headingMatch;
232
+ else if (paraMatch > minBreak)
233
+ breakPoint = paraMatch;
234
+ else if (lineMatch > minBreak)
235
+ breakPoint = lineMatch;
236
+ else if (sentenceMatch > minBreak)
237
+ breakPoint = sentenceMatch + 1; // include the period
238
+ else
239
+ breakPoint = maxChars; // hard cut as last resort
240
+ const truncated = content.slice(0, breakPoint).trimEnd();
241
+ return { text: truncated, wasTruncated: true };
242
+ }
243
+ /**
244
+ * Process a single scrape/crawl data object, truncating content fields
245
+ * while preserving metadata and structured data.
246
+ *
247
+ * Returns the processed data and truncation metadata.
248
+ */
249
+ export function truncateContent(data) {
250
+ if (MAX_CONTENT_CHARS <= 0) {
251
+ const serialized = JSON.stringify(data, null, 2);
252
+ return { result: data, wasTruncated: false, originalLength: serialized.length };
253
+ }
254
+ const serialized = JSON.stringify(data, null, 2);
255
+ if (serialized.length <= MAX_CONTENT_CHARS) {
256
+ return { result: data, wasTruncated: false, originalLength: serialized.length };
257
+ }
258
+ // Deep clone to avoid mutating the original
259
+ const cloned = JSON.parse(serialized);
260
+ let wasTruncated = false;
261
+ // Handle single scrape result (has data.markdown, data.html, etc.)
262
+ if (cloned && typeof cloned === 'object') {
263
+ const target = cloned.data || cloned;
264
+ for (const field of CONTENT_FIELDS) {
265
+ if (typeof target[field] === 'string' && target[field].length > 0) {
266
+ // Budget for this field: total limit minus overhead from other fields
267
+ const otherFieldsSize = serialized.length - target[field].length;
268
+ const fieldBudget = Math.max(MAX_CONTENT_CHARS - otherFieldsSize, Math.floor(MAX_CONTENT_CHARS * 0.5));
269
+ if (target[field].length > fieldBudget) {
270
+ const { text } = truncateAtBoundary(target[field], fieldBudget);
271
+ const originalLen = target[field].length;
272
+ target[field] = text + buildTruncationNotice(text.length, originalLen);
273
+ wasTruncated = true;
274
+ }
275
+ }
276
+ }
277
+ // Handle crawl results (array of pages)
278
+ if (Array.isArray(target)) {
279
+ const result = truncateCrawlArray(target);
280
+ return { result: cloned, wasTruncated: result.wasTruncated, originalLength: serialized.length };
281
+ }
282
+ // Add truncation metadata
283
+ if (wasTruncated) {
284
+ const meta = target.metadata || target;
285
+ meta._truncated = true;
286
+ meta._originalLength = serialized.length;
287
+ }
288
+ }
289
+ return { result: cloned, wasTruncated, originalLength: serialized.length };
290
+ }
291
+ /**
292
+ * Truncate a crawl result array: limit per-page content and total page count.
293
+ */
294
+ function truncateCrawlArray(pages) {
295
+ if (pages.length === 0)
296
+ return { wasTruncated: false };
297
+ const perPageLimit = Math.floor(MAX_CONTENT_CHARS * SINGLE_PAGE_MAX_FRACTION);
298
+ let wasTruncated = false;
299
+ let totalSize = 0;
300
+ for (let i = 0; i < pages.length; i++) {
301
+ const page = pages[i];
302
+ if (!page || typeof page !== 'object')
303
+ continue;
304
+ const target = page.data || page;
305
+ for (const field of CONTENT_FIELDS) {
306
+ if (typeof target[field] === 'string' && target[field].length > perPageLimit) {
307
+ const { text } = truncateAtBoundary(target[field], perPageLimit);
308
+ target[field] = text + buildTruncationNotice(text.length, target[field].length);
309
+ wasTruncated = true;
310
+ }
311
+ }
312
+ totalSize += JSON.stringify(page).length;
313
+ // If total exceeds limit, truncate the array
314
+ if (totalSize > MAX_CONTENT_CHARS && i < pages.length - 1) {
315
+ const originalCount = pages.length;
316
+ pages.length = i + 1;
317
+ pages.push({
318
+ _notice: `Showing ${i + 1} of ${originalCount} crawled pages. Use scorch_check_crawl_status with pagination to see more.`,
319
+ });
320
+ wasTruncated = true;
321
+ break;
322
+ }
323
+ }
324
+ return { wasTruncated };
325
+ }
326
+ /** Build a truncation notice for appending to content */
327
+ function buildTruncationNotice(shownChars, originalChars) {
328
+ return `\n\n---\n[Content truncated. Showing ~${Math.round(shownChars / 1000)}k of ~${Math.round(originalChars / 1000)}k characters.\nTo get specific information, try:\n- Use JSON format with a schema to extract only the data you need\n- Add onlyMainContent: true to exclude navigation/footers\n- Use scorch_map to find a more specific page URL]`;
329
+ }
330
+ // ---------------------------------------------------------------------------
331
+ // Combined Processing Pipeline
332
+ // ---------------------------------------------------------------------------
333
+ /**
334
+ * Safe wrapper for tool execution. Catches errors and returns
335
+ * mapped, LLM-friendly error responses.
336
+ */
337
+ export async function safeExecute(fn, context) {
338
+ try {
339
+ return await fn();
340
+ }
341
+ catch (err) {
342
+ const mapped = mapError(err);
343
+ console.error(`[${context.tool}] ${mapped.code}`, {
344
+ url: context.url,
345
+ original: mapped.originalError,
346
+ });
347
+ return JSON.stringify({
348
+ success: false,
349
+ error: mapped.message,
350
+ code: mapped.code,
351
+ suggestions: mapped.suggestions,
352
+ }, null, 2);
353
+ }
354
+ }
355
+ /**
356
+ * Process a successful response: truncate content if needed.
357
+ *
358
+ * Replaces the old `asText()` function.
359
+ */
360
+ export async function processResponse(data, options) {
361
+ const { result, wasTruncated } = truncateContent(data);
362
+ return JSON.stringify(result, null, 2);
363
+ }
364
+ /**
365
+ * Simple `asText` replacement for backward compatibility.
366
+ * Applies truncation only.
367
+ */
368
+ export function processResponseSync(data) {
369
+ const { result } = truncateContent(data);
370
+ return JSON.stringify(result, null, 2);
371
+ }
372
+ // ---------------------------------------------------------------------------
373
+ // Exports for testing
374
+ // ---------------------------------------------------------------------------
375
+ export { MAX_CONTENT_CHARS };