scorchcrawl-mcp 2.1.0 → 2.1.1
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/dist/cli.js +207 -0
- package/package.json +15 -36
- package/dist/copilot-client.js +0 -39
- package/dist/index.js +0 -717
- package/dist/lib/fastmcp/index.js +0 -6
- package/dist/lib/scorch-client/index.js +0 -9
- package/dist/local-scraper.js +0 -319
- package/dist/response-utils.js +0 -375
package/dist/index.js
DELETED
|
@@ -1,717 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import dotenv from 'dotenv';
|
|
3
|
-
import { FastMCP } from './lib/fastmcp/index.js';
|
|
4
|
-
import { z } from 'zod';
|
|
5
|
-
import ScorchClient from './lib/scorch-client/index.js';
|
|
6
|
-
import { localScrape, isLocalProxyEnabled, getCleanApiUrl } from './local-scraper.js';
|
|
7
|
-
import { mapError, safeExecute, processResponse, processResponseSync, } from './response-utils.js';
|
|
8
|
-
dotenv.config({ debug: false, quiet: true });
|
|
9
|
-
function extractApiKey(headers) {
|
|
10
|
-
const headerAuth = headers['authorization'];
|
|
11
|
-
const headerApiKey = (headers['x-scorchcrawl-api-key'] ||
|
|
12
|
-
headers['x-api-key']);
|
|
13
|
-
if (headerApiKey) {
|
|
14
|
-
return Array.isArray(headerApiKey) ? headerApiKey[0] : headerApiKey;
|
|
15
|
-
}
|
|
16
|
-
if (typeof headerAuth === 'string' &&
|
|
17
|
-
headerAuth.toLowerCase().startsWith('bearer ')) {
|
|
18
|
-
return headerAuth.slice(7).trim();
|
|
19
|
-
}
|
|
20
|
-
return undefined;
|
|
21
|
-
}
|
|
22
|
-
function removeEmptyTopLevel(obj) {
|
|
23
|
-
const out = {};
|
|
24
|
-
for (const [k, v] of Object.entries(obj)) {
|
|
25
|
-
if (v == null)
|
|
26
|
-
continue;
|
|
27
|
-
if (typeof v === 'string' && v.trim() === '')
|
|
28
|
-
continue;
|
|
29
|
-
if (Array.isArray(v) && v.length === 0)
|
|
30
|
-
continue;
|
|
31
|
-
if (typeof v === 'object' &&
|
|
32
|
-
!Array.isArray(v) &&
|
|
33
|
-
Object.keys(v).length === 0)
|
|
34
|
-
continue;
|
|
35
|
-
// @ts-expect-error dynamic assignment
|
|
36
|
-
out[k] = v;
|
|
37
|
-
}
|
|
38
|
-
return out;
|
|
39
|
-
}
|
|
40
|
-
class ConsoleLogger {
|
|
41
|
-
shouldLog = process.env.CLOUD_SERVICE === 'true' ||
|
|
42
|
-
process.env.SSE_LOCAL === 'true' ||
|
|
43
|
-
process.env.HTTP_STREAMABLE_SERVER === 'true';
|
|
44
|
-
debug(...args) {
|
|
45
|
-
if (this.shouldLog) {
|
|
46
|
-
console.debug('[DEBUG]', new Date().toISOString(), ...args);
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
error(...args) {
|
|
50
|
-
if (this.shouldLog) {
|
|
51
|
-
console.error('[ERROR]', new Date().toISOString(), ...args);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
info(...args) {
|
|
55
|
-
if (this.shouldLog) {
|
|
56
|
-
console.log('[INFO]', new Date().toISOString(), ...args);
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
log(...args) {
|
|
60
|
-
if (this.shouldLog) {
|
|
61
|
-
console.log('[LOG]', new Date().toISOString(), ...args);
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
warn(...args) {
|
|
65
|
-
if (this.shouldLog) {
|
|
66
|
-
console.warn('[WARN]', new Date().toISOString(), ...args);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
const server = new FastMCP({
|
|
71
|
-
name: 'scorchcrawl',
|
|
72
|
-
version: '1.0.0',
|
|
73
|
-
logger: new ConsoleLogger(),
|
|
74
|
-
roots: { enabled: false },
|
|
75
|
-
authenticate: async (request) => {
|
|
76
|
-
if (process.env.CLOUD_SERVICE === 'true') {
|
|
77
|
-
const apiKey = extractApiKey(request.headers);
|
|
78
|
-
if (!apiKey) {
|
|
79
|
-
throw new Error('API key is required');
|
|
80
|
-
}
|
|
81
|
-
return { scraperApiKey: apiKey };
|
|
82
|
-
}
|
|
83
|
-
else {
|
|
84
|
-
// For self-hosted instances, API key is optional if SCORCHCRAWL_API_URL is provided
|
|
85
|
-
if (!process.env.SCORCHCRAWL_API_KEY && !process.env.SCORCHCRAWL_API_URL) {
|
|
86
|
-
console.error('Either SCORCHCRAWL_API_KEY or SCORCHCRAWL_API_URL must be provided');
|
|
87
|
-
process.exit(1);
|
|
88
|
-
}
|
|
89
|
-
return { scraperApiKey: process.env.SCORCHCRAWL_API_KEY };
|
|
90
|
-
}
|
|
91
|
-
},
|
|
92
|
-
// Lightweight health endpoint for LB checks
|
|
93
|
-
health: {
|
|
94
|
-
enabled: true,
|
|
95
|
-
message: 'ok',
|
|
96
|
-
path: '/health',
|
|
97
|
-
status: 200,
|
|
98
|
-
},
|
|
99
|
-
});
|
|
100
|
-
function createClient(apiKey) {
|
|
101
|
-
// Use cleaned URL (strips ?localProxy= param so the server doesn't see it)
|
|
102
|
-
const cleanUrl = getCleanApiUrl();
|
|
103
|
-
const config = {
|
|
104
|
-
...(cleanUrl && {
|
|
105
|
-
apiUrl: cleanUrl,
|
|
106
|
-
}),
|
|
107
|
-
};
|
|
108
|
-
// Only add apiKey if it's provided (required for cloud, optional for self-hosted)
|
|
109
|
-
if (apiKey) {
|
|
110
|
-
config.apiKey = apiKey;
|
|
111
|
-
}
|
|
112
|
-
return new ScorchClient(config);
|
|
113
|
-
}
|
|
114
|
-
const ORIGIN = 'scorchcrawl-mcp';
|
|
115
|
-
// Safe mode is enabled by default for cloud service to comply with ChatGPT safety requirements
|
|
116
|
-
const SAFE_MODE = process.env.CLOUD_SERVICE === 'true';
|
|
117
|
-
function getClient(session) {
|
|
118
|
-
// For cloud service, API key is required
|
|
119
|
-
if (process.env.CLOUD_SERVICE === 'true') {
|
|
120
|
-
if (!session || !session.scraperApiKey) {
|
|
121
|
-
throw new Error('Unauthorized');
|
|
122
|
-
}
|
|
123
|
-
return createClient(session.scraperApiKey);
|
|
124
|
-
}
|
|
125
|
-
// For self-hosted instances, API key is optional if SCORCHCRAWL_API_URL is provided
|
|
126
|
-
if (!process.env.SCORCHCRAWL_API_URL &&
|
|
127
|
-
(!session || !session.scraperApiKey)) {
|
|
128
|
-
throw new Error('Unauthorized: API key is required when not using a self-hosted instance');
|
|
129
|
-
}
|
|
130
|
-
return createClient(session?.scraperApiKey);
|
|
131
|
-
}
|
|
132
|
-
function asText(data) {
|
|
133
|
-
return processResponseSync(data);
|
|
134
|
-
}
|
|
135
|
-
// scrape tool (v2 semantics, minimal args)
|
|
136
|
-
// Centralized scrape params (used by scrape, and referenced in search/crawl scrapeOptions)
|
|
137
|
-
// Define safe action types
|
|
138
|
-
const safeActionTypes = ['wait', 'screenshot', 'scroll', 'scrape'];
|
|
139
|
-
const otherActions = [
|
|
140
|
-
'click',
|
|
141
|
-
'write',
|
|
142
|
-
'press',
|
|
143
|
-
'executeJavascript',
|
|
144
|
-
'generatePDF',
|
|
145
|
-
];
|
|
146
|
-
const allActionTypes = [...safeActionTypes, ...otherActions];
|
|
147
|
-
// Use appropriate action types based on safe mode
|
|
148
|
-
const allowedActionTypes = SAFE_MODE ? safeActionTypes : allActionTypes;
|
|
149
|
-
const scrapeParamsSchema = z.object({
|
|
150
|
-
url: z.string().url(),
|
|
151
|
-
formats: z
|
|
152
|
-
.array(z.union([
|
|
153
|
-
z.enum([
|
|
154
|
-
'markdown',
|
|
155
|
-
'html',
|
|
156
|
-
'rawHtml',
|
|
157
|
-
'screenshot',
|
|
158
|
-
'links',
|
|
159
|
-
'summary',
|
|
160
|
-
'changeTracking',
|
|
161
|
-
'branding',
|
|
162
|
-
]),
|
|
163
|
-
z.object({
|
|
164
|
-
type: z.literal('json'),
|
|
165
|
-
prompt: z.string().optional(),
|
|
166
|
-
schema: z.record(z.string(), z.any()).optional(),
|
|
167
|
-
}),
|
|
168
|
-
z.object({
|
|
169
|
-
type: z.literal('screenshot'),
|
|
170
|
-
fullPage: z.boolean().optional(),
|
|
171
|
-
quality: z.number().optional(),
|
|
172
|
-
viewport: z
|
|
173
|
-
.object({ width: z.number(), height: z.number() })
|
|
174
|
-
.optional(),
|
|
175
|
-
}),
|
|
176
|
-
]))
|
|
177
|
-
.optional(),
|
|
178
|
-
parsers: z
|
|
179
|
-
.array(z.union([
|
|
180
|
-
z.enum(['pdf']),
|
|
181
|
-
z.object({
|
|
182
|
-
type: z.enum(['pdf']),
|
|
183
|
-
maxPages: z.number().int().min(1).max(10000).optional(),
|
|
184
|
-
}),
|
|
185
|
-
]))
|
|
186
|
-
.optional(),
|
|
187
|
-
onlyMainContent: z.boolean().optional(),
|
|
188
|
-
includeTags: z.array(z.string()).optional(),
|
|
189
|
-
excludeTags: z.array(z.string()).optional(),
|
|
190
|
-
waitFor: z.number().optional(),
|
|
191
|
-
...(SAFE_MODE
|
|
192
|
-
? {}
|
|
193
|
-
: {
|
|
194
|
-
actions: z
|
|
195
|
-
.array(z.object({
|
|
196
|
-
type: z.enum(allowedActionTypes),
|
|
197
|
-
selector: z.string().optional(),
|
|
198
|
-
milliseconds: z.number().optional(),
|
|
199
|
-
text: z.string().optional(),
|
|
200
|
-
key: z.string().optional(),
|
|
201
|
-
direction: z.enum(['up', 'down']).optional(),
|
|
202
|
-
script: z.string().optional(),
|
|
203
|
-
fullPage: z.boolean().optional(),
|
|
204
|
-
}))
|
|
205
|
-
.optional(),
|
|
206
|
-
}),
|
|
207
|
-
mobile: z.boolean().optional(),
|
|
208
|
-
skipTlsVerification: z.boolean().optional(),
|
|
209
|
-
removeBase64Images: z.boolean().optional(),
|
|
210
|
-
location: z
|
|
211
|
-
.object({
|
|
212
|
-
country: z.string().optional(),
|
|
213
|
-
languages: z.array(z.string()).optional(),
|
|
214
|
-
})
|
|
215
|
-
.optional(),
|
|
216
|
-
storeInCache: z.boolean().optional(),
|
|
217
|
-
zeroDataRetention: z.boolean().optional(),
|
|
218
|
-
maxAge: z.number().optional(),
|
|
219
|
-
proxy: z.enum(['basic', 'stealth', 'enhanced', 'auto']).optional(),
|
|
220
|
-
});
|
|
221
|
-
server.addTool({
|
|
222
|
-
name: 'scorch_scrape',
|
|
223
|
-
description: `
|
|
224
|
-
Scrape content from a single URL with advanced options.
|
|
225
|
-
This is the most powerful, fastest and most reliable scraper tool, if available you should always default to using this tool for any web scraping needs.
|
|
226
|
-
|
|
227
|
-
**Best for:** Single page content extraction, when you know exactly which page contains the information.
|
|
228
|
-
**Not recommended for:** Multiple pages (call scrape multiple times or use crawl), unknown page location (use search).
|
|
229
|
-
**Common mistakes:** Using markdown format when extracting specific data points (use JSON instead).
|
|
230
|
-
**Other Features:** Use 'branding' format to extract brand identity (colors, fonts, typography, spacing, UI components) for design analysis or style replication.
|
|
231
|
-
|
|
232
|
-
**CRITICAL - Format Selection (you MUST follow this):**
|
|
233
|
-
When the user asks for SPECIFIC data points, you MUST use JSON format with a schema. Only use markdown when the user needs the ENTIRE page content.
|
|
234
|
-
|
|
235
|
-
**Use JSON format when user asks for:**
|
|
236
|
-
- Parameters, fields, or specifications (e.g., "get the header parameters", "what are the required fields")
|
|
237
|
-
- Prices, numbers, or structured data (e.g., "extract the pricing", "get the product details")
|
|
238
|
-
- API details, endpoints, or technical specs (e.g., "find the authentication endpoint")
|
|
239
|
-
- Lists of items or properties (e.g., "list the features", "get all the options")
|
|
240
|
-
- Any specific piece of information from a page
|
|
241
|
-
|
|
242
|
-
**Use markdown format ONLY when:**
|
|
243
|
-
- User wants to read/summarize an entire article or blog post
|
|
244
|
-
- User needs to see all content on a page without specific extraction
|
|
245
|
-
- User explicitly asks for the full page content
|
|
246
|
-
|
|
247
|
-
**Handling JavaScript-rendered pages (SPAs):**
|
|
248
|
-
If JSON extraction returns empty, minimal, or just navigation content, the page is likely JavaScript-rendered or the content is on a different URL. Try these steps IN ORDER:
|
|
249
|
-
1. **Add waitFor parameter:** Set \`waitFor: 5000\` to \`waitFor: 10000\` to allow JavaScript to render before extraction
|
|
250
|
-
2. **Try a different URL:** If the URL has a hash fragment (#section), try the base URL or look for a direct page URL
|
|
251
|
-
3. **Use scorch_map to find the correct page:** Large documentation sites or SPAs often spread content across multiple URLs. Use \`scorch_map\` with a \`search\` parameter to discover the specific page containing your target content, then scrape that URL directly.
|
|
252
|
-
Example: If scraping "https://docs.example.com/reference" fails to find webhook parameters, use \`scorch_map\` with \`{"url": "https://docs.example.com/reference", "search": "webhook"}\` to find URLs like "/reference/webhook-events", then scrape that specific page.
|
|
253
|
-
4. **Escalate manually:** If map+scrape still fails, inspect the rendered page yourself and decide whether a custom context-cutter or page-specific flow is warranted
|
|
254
|
-
|
|
255
|
-
**Usage Example (JSON format - REQUIRED for specific data extraction):**
|
|
256
|
-
\`\`\`json
|
|
257
|
-
{
|
|
258
|
-
"name": "scorch_scrape",
|
|
259
|
-
"arguments": {
|
|
260
|
-
"url": "https://example.com/api-docs",
|
|
261
|
-
"formats": [{
|
|
262
|
-
"type": "json",
|
|
263
|
-
"prompt": "Extract the header parameters for the authentication endpoint",
|
|
264
|
-
"schema": {
|
|
265
|
-
"type": "object",
|
|
266
|
-
"properties": {
|
|
267
|
-
"parameters": {
|
|
268
|
-
"type": "array",
|
|
269
|
-
"items": {
|
|
270
|
-
"type": "object",
|
|
271
|
-
"properties": {
|
|
272
|
-
"name": { "type": "string" },
|
|
273
|
-
"type": { "type": "string" },
|
|
274
|
-
"required": { "type": "boolean" },
|
|
275
|
-
"description": { "type": "string" }
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
}]
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
\`\`\`
|
|
285
|
-
**Usage Example (markdown format - ONLY when full content genuinely needed):**
|
|
286
|
-
\`\`\`json
|
|
287
|
-
{
|
|
288
|
-
"name": "scorch_scrape",
|
|
289
|
-
"arguments": {
|
|
290
|
-
"url": "https://example.com/article",
|
|
291
|
-
"formats": ["markdown"],
|
|
292
|
-
"onlyMainContent": true
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
\`\`\`
|
|
296
|
-
**Usage Example (branding format - extract brand identity):**
|
|
297
|
-
\`\`\`json
|
|
298
|
-
{
|
|
299
|
-
"name": "scorch_scrape",
|
|
300
|
-
"arguments": {
|
|
301
|
-
"url": "https://example.com",
|
|
302
|
-
"formats": ["branding"]
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
\`\`\`
|
|
306
|
-
**Branding format:** Extracts comprehensive brand identity (colors, fonts, typography, spacing, logo, UI components) for design analysis or style replication.
|
|
307
|
-
**Performance:** Add maxAge parameter for 500% faster scrapes using cached data.
|
|
308
|
-
**Returns:** JSON structured data, markdown, branding profile, or other formats as specified.
|
|
309
|
-
${SAFE_MODE
|
|
310
|
-
? '**Safe Mode:** Read-only content extraction. Interactive actions (click, write, executeJavascript) are disabled for security.'
|
|
311
|
-
: ''}
|
|
312
|
-
`,
|
|
313
|
-
parameters: scrapeParamsSchema,
|
|
314
|
-
execute: async (args, { session, log }) => {
|
|
315
|
-
const { url, ...options } = args;
|
|
316
|
-
const cleaned = removeEmptyTopLevel(options);
|
|
317
|
-
return safeExecute(async () => {
|
|
318
|
-
// --- Local proxy mode: fetch through user's IP ---
|
|
319
|
-
if (isLocalProxyEnabled()) {
|
|
320
|
-
log.info('Scraping URL via LOCAL PROXY (user IP)', { url: String(url) });
|
|
321
|
-
const localResult = await localScrape(String(url), cleaned);
|
|
322
|
-
// If the requested format needs server-side processing, fall back
|
|
323
|
-
if (!localResult.success && localResult.error === 'FORMAT_NEEDS_SERVER') {
|
|
324
|
-
log.info('Format requires server-side processing, falling back to API', { url: String(url) });
|
|
325
|
-
const client = getClient(session);
|
|
326
|
-
const res = await client.scrape(String(url), {
|
|
327
|
-
...cleaned,
|
|
328
|
-
origin: ORIGIN,
|
|
329
|
-
});
|
|
330
|
-
return await processResponse(res, {
|
|
331
|
-
url: String(url),
|
|
332
|
-
});
|
|
333
|
-
}
|
|
334
|
-
// SPA detected: the local fetch returned a JS-only shell.
|
|
335
|
-
// Retry via the engine's Playwright scraper with waitFor for JS rendering.
|
|
336
|
-
if (!localResult.success && localResult.error === 'SPA_SKELETON_DETECTED') {
|
|
337
|
-
const waitMs = cleaned.waitFor || 5000;
|
|
338
|
-
log.info(`SPA skeleton detected, retrying via engine with waitFor=${waitMs}ms`, { url: String(url) });
|
|
339
|
-
const client = getClient(session);
|
|
340
|
-
const res = await client.scrape(String(url), {
|
|
341
|
-
...cleaned,
|
|
342
|
-
waitFor: waitMs,
|
|
343
|
-
origin: ORIGIN,
|
|
344
|
-
});
|
|
345
|
-
return await processResponse(res, {
|
|
346
|
-
url: String(url),
|
|
347
|
-
});
|
|
348
|
-
}
|
|
349
|
-
// Errors from local scraper
|
|
350
|
-
if (!localResult.success && localResult.error) {
|
|
351
|
-
const mapped = mapError(localResult.error);
|
|
352
|
-
return JSON.stringify({
|
|
353
|
-
success: false,
|
|
354
|
-
error: mapped.message,
|
|
355
|
-
code: mapped.code,
|
|
356
|
-
suggestions: mapped.suggestions,
|
|
357
|
-
}, null, 2);
|
|
358
|
-
}
|
|
359
|
-
return await processResponse(localResult, {
|
|
360
|
-
url: String(url),
|
|
361
|
-
});
|
|
362
|
-
}
|
|
363
|
-
// --- Normal mode: use remote scraping API ---
|
|
364
|
-
const client = getClient(session);
|
|
365
|
-
log.info('Scraping URL', { url: String(url) });
|
|
366
|
-
const res = await client.scrape(String(url), {
|
|
367
|
-
...cleaned,
|
|
368
|
-
origin: ORIGIN,
|
|
369
|
-
});
|
|
370
|
-
return await processResponse(res, {
|
|
371
|
-
url: String(url),
|
|
372
|
-
});
|
|
373
|
-
}, { tool: 'scorch_scrape', url: String(url) });
|
|
374
|
-
},
|
|
375
|
-
});
|
|
376
|
-
server.addTool({
|
|
377
|
-
name: 'scorch_map',
|
|
378
|
-
description: `
|
|
379
|
-
Map a website to discover all indexed URLs on the site.
|
|
380
|
-
|
|
381
|
-
**Best for:** Discovering URLs on a website before deciding what to scrape; finding specific sections or pages within a large site; locating the correct page when scrape returns empty or incomplete results.
|
|
382
|
-
**Not recommended for:** When you already know which specific URL you need (use scrape); when you need the content of the pages (use scrape after mapping).
|
|
383
|
-
**Common mistakes:** Using crawl to discover URLs instead of map; giving up on map too early when scrape fails to find the right page.
|
|
384
|
-
|
|
385
|
-
**IMPORTANT - Use map before custom handling:** If \`scorch_scrape\` returns empty, minimal, or irrelevant content, use \`scorch_map\` with the \`search\` parameter to find the specific page URL containing your target content before building any page-specific handling.
|
|
386
|
-
|
|
387
|
-
**Prompt Example:** "Find the webhook documentation page on this API docs site."
|
|
388
|
-
**Usage Example (discover all URLs):**
|
|
389
|
-
\`\`\`json
|
|
390
|
-
{
|
|
391
|
-
"name": "scorch_map",
|
|
392
|
-
"arguments": {
|
|
393
|
-
"url": "https://example.com"
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
\`\`\`
|
|
397
|
-
**Usage Example (search for specific content - RECOMMENDED when scrape fails):**
|
|
398
|
-
\`\`\`json
|
|
399
|
-
{
|
|
400
|
-
"name": "scorch_map",
|
|
401
|
-
"arguments": {
|
|
402
|
-
"url": "https://docs.example.com/api",
|
|
403
|
-
"search": "webhook events"
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
\`\`\`
|
|
407
|
-
**Returns:** Array of URLs found on the site, filtered by search query if provided.
|
|
408
|
-
`,
|
|
409
|
-
parameters: z.object({
|
|
410
|
-
url: z.string().url(),
|
|
411
|
-
search: z.string().optional(),
|
|
412
|
-
sitemap: z.enum(['include', 'skip', 'only']).optional(),
|
|
413
|
-
includeSubdomains: z.boolean().optional(),
|
|
414
|
-
limit: z.number().optional(),
|
|
415
|
-
ignoreQueryParameters: z.boolean().optional(),
|
|
416
|
-
}),
|
|
417
|
-
execute: async (args, { session, log }) => {
|
|
418
|
-
const { url, ...options } = args;
|
|
419
|
-
return safeExecute(async () => {
|
|
420
|
-
const client = getClient(session);
|
|
421
|
-
const cleaned = removeEmptyTopLevel(options);
|
|
422
|
-
log.info('Mapping URL', { url: String(url) });
|
|
423
|
-
const res = await client.map(String(url), {
|
|
424
|
-
...cleaned,
|
|
425
|
-
origin: ORIGIN,
|
|
426
|
-
});
|
|
427
|
-
return asText(res);
|
|
428
|
-
}, { tool: 'scorch_map', url: String(url) });
|
|
429
|
-
},
|
|
430
|
-
});
|
|
431
|
-
server.addTool({
|
|
432
|
-
name: 'scorch_search',
|
|
433
|
-
description: `
|
|
434
|
-
Search the web and optionally extract content from search results. This is the most powerful web search tool available, and if available you should always default to using this tool for any web search needs.
|
|
435
|
-
|
|
436
|
-
The query also supports search operators, that you can use if needed to refine the search:
|
|
437
|
-
| Operator | Functionality | Examples |
|
|
438
|
-
---|-|-|
|
|
439
|
-
| \`"\"\` | Non-fuzzy matches a string of text | \`"ScorchCrawl"\`
|
|
440
|
-
| \`-\` | Excludes certain keywords or negates other operators | \`-bad\`, \`-site:example.com\`
|
|
441
|
-
| \`site:\` | Only returns results from a specified website | \`site:example.com\`
|
|
442
|
-
| \`inurl:\` | Only returns results that include a word in the URL | \`inurl:example\`
|
|
443
|
-
| \`allinurl:\` | Only returns results that include multiple words in the URL | \`allinurl:git example\`
|
|
444
|
-
| \`intitle:\` | Only returns results that include a word in the title of the page | \`intitle:ScorchCrawl\`
|
|
445
|
-
| \`allintitle:\` | Only returns results that include multiple words in the title of the page | \`allintitle:example playground\`
|
|
446
|
-
| \`related:\` | Only returns results that are related to a specific domain | \`related:example.com\`
|
|
447
|
-
| \`imagesize:\` | Only returns images with exact dimensions | \`imagesize:1920x1080\`
|
|
448
|
-
| \`larger:\` | Only returns images larger than specified dimensions | \`larger:1920x1080\`
|
|
449
|
-
|
|
450
|
-
**Best for:** Finding specific information across multiple websites, when you don't know which website has the information; when you need the most relevant content for a query.
|
|
451
|
-
**Not recommended for:** When you need to search the filesystem. When you already know which website to scrape (use scrape); when you need comprehensive coverage of a single website (use map or crawl.
|
|
452
|
-
**Common mistakes:** Using crawl or map for open-ended questions (use search instead).
|
|
453
|
-
**Prompt Example:** "Find the latest research papers on AI published in 2023."
|
|
454
|
-
**Sources:** web, images, news, default to web unless needed images or news.
|
|
455
|
-
**Scrape Options:** Only use scrapeOptions when you think it is absolutely necessary. When you do so default to a lower limit to avoid timeouts, 5 or lower.
|
|
456
|
-
**Optimal Workflow:** Search first using scorch_search without formats, then after fetching the results, use the scrape tool to get the content of the relevantpage(s) that you want to scrape
|
|
457
|
-
|
|
458
|
-
**Usage Example without formats (Preferred):**
|
|
459
|
-
\`\`\`json
|
|
460
|
-
{
|
|
461
|
-
"name": "scorch_search",
|
|
462
|
-
"arguments": {
|
|
463
|
-
"query": "top AI companies",
|
|
464
|
-
"limit": 5,
|
|
465
|
-
"sources": [
|
|
466
|
-
{ "type": "web" }
|
|
467
|
-
]
|
|
468
|
-
}
|
|
469
|
-
}
|
|
470
|
-
\`\`\`
|
|
471
|
-
**Usage Example with formats:**
|
|
472
|
-
\`\`\`json
|
|
473
|
-
{
|
|
474
|
-
"name": "scorch_search",
|
|
475
|
-
"arguments": {
|
|
476
|
-
"query": "latest AI research papers 2023",
|
|
477
|
-
"limit": 5,
|
|
478
|
-
"lang": "en",
|
|
479
|
-
"country": "us",
|
|
480
|
-
"sources": [
|
|
481
|
-
{ "type": "web" },
|
|
482
|
-
{ "type": "images" },
|
|
483
|
-
{ "type": "news" }
|
|
484
|
-
],
|
|
485
|
-
"scrapeOptions": {
|
|
486
|
-
"formats": ["markdown"],
|
|
487
|
-
"onlyMainContent": true
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
}
|
|
491
|
-
\`\`\`
|
|
492
|
-
**Returns:** Array of search results (with optional scraped content).
|
|
493
|
-
`,
|
|
494
|
-
parameters: z.object({
|
|
495
|
-
query: z.string().min(1),
|
|
496
|
-
limit: z.number().optional(),
|
|
497
|
-
tbs: z.string().optional(),
|
|
498
|
-
filter: z.string().optional(),
|
|
499
|
-
location: z.string().optional(),
|
|
500
|
-
sources: z
|
|
501
|
-
.array(z.object({ type: z.enum(['web', 'images', 'news']) }))
|
|
502
|
-
.optional(),
|
|
503
|
-
scrapeOptions: scrapeParamsSchema.omit({ url: true }).partial().optional(),
|
|
504
|
-
enterprise: z.array(z.enum(['default', 'anon', 'zdr'])).optional(),
|
|
505
|
-
}),
|
|
506
|
-
execute: async (args, { session, log }) => {
|
|
507
|
-
const { query, ...opts } = args;
|
|
508
|
-
return safeExecute(async () => {
|
|
509
|
-
const client = getClient(session);
|
|
510
|
-
const cleaned = removeEmptyTopLevel(opts);
|
|
511
|
-
log.info('Searching', { query: String(query) });
|
|
512
|
-
const res = await client.search(query, {
|
|
513
|
-
...cleaned,
|
|
514
|
-
origin: ORIGIN,
|
|
515
|
-
});
|
|
516
|
-
// Search results are already concise snippets — skip summarization
|
|
517
|
-
return await processResponse(res, {
|
|
518
|
-
skipSummarization: true,
|
|
519
|
-
});
|
|
520
|
-
}, { tool: 'scorch_search' });
|
|
521
|
-
},
|
|
522
|
-
});
|
|
523
|
-
server.addTool({
|
|
524
|
-
name: 'scorch_crawl',
|
|
525
|
-
description: `
|
|
526
|
-
Starts a crawl job on a website and extracts content from all pages.
|
|
527
|
-
|
|
528
|
-
**Best for:** Extracting content from multiple related pages, when you need comprehensive coverage.
|
|
529
|
-
**Not recommended for:** Extracting content from a single page (use scrape); when token limits are a concern (use map + batch_scrape); when you need fast results (crawling can be slow).
|
|
530
|
-
**Warning:** Crawl responses can be very large and may exceed token limits. Limit the crawl depth and number of pages, or use map + batch_scrape for better control.
|
|
531
|
-
**Common mistakes:** Setting limit or maxDiscoveryDepth too high (causes token overflow) or too low (causes missing pages); using crawl for a single page (use scrape instead). Using a /* wildcard is not recommended.
|
|
532
|
-
**Prompt Example:** "Get all blog posts from the first two levels of example.com/blog."
|
|
533
|
-
**Usage Example:**
|
|
534
|
-
\`\`\`json
|
|
535
|
-
{
|
|
536
|
-
"name": "scorch_crawl",
|
|
537
|
-
"arguments": {
|
|
538
|
-
"url": "https://example.com/blog/*",
|
|
539
|
-
"maxDiscoveryDepth": 5,
|
|
540
|
-
"limit": 20,
|
|
541
|
-
"allowExternalLinks": false,
|
|
542
|
-
"deduplicateSimilarURLs": true,
|
|
543
|
-
"sitemap": "include"
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
\`\`\`
|
|
547
|
-
**Returns:** Operation ID for status checking; use scorch_check_crawl_status to check progress.
|
|
548
|
-
${SAFE_MODE
|
|
549
|
-
? '**Safe Mode:** Read-only crawling. Webhooks and interactive actions are disabled for security.'
|
|
550
|
-
: ''}
|
|
551
|
-
`,
|
|
552
|
-
parameters: z.object({
|
|
553
|
-
url: z.string(),
|
|
554
|
-
prompt: z.string().optional(),
|
|
555
|
-
excludePaths: z.array(z.string()).optional(),
|
|
556
|
-
includePaths: z.array(z.string()).optional(),
|
|
557
|
-
maxDiscoveryDepth: z.number().optional(),
|
|
558
|
-
sitemap: z.enum(['skip', 'include', 'only']).optional(),
|
|
559
|
-
limit: z.number().optional(),
|
|
560
|
-
allowExternalLinks: z.boolean().optional(),
|
|
561
|
-
allowSubdomains: z.boolean().optional(),
|
|
562
|
-
crawlEntireDomain: z.boolean().optional(),
|
|
563
|
-
delay: z.number().optional(),
|
|
564
|
-
maxConcurrency: z.number().optional(),
|
|
565
|
-
...(SAFE_MODE
|
|
566
|
-
? {}
|
|
567
|
-
: {
|
|
568
|
-
webhook: z
|
|
569
|
-
.union([
|
|
570
|
-
z.string(),
|
|
571
|
-
z.object({
|
|
572
|
-
url: z.string(),
|
|
573
|
-
headers: z.record(z.string(), z.string()).optional(),
|
|
574
|
-
}),
|
|
575
|
-
])
|
|
576
|
-
.optional(),
|
|
577
|
-
}),
|
|
578
|
-
deduplicateSimilarURLs: z.boolean().optional(),
|
|
579
|
-
ignoreQueryParameters: z.boolean().optional(),
|
|
580
|
-
scrapeOptions: scrapeParamsSchema.omit({ url: true }).partial().optional(),
|
|
581
|
-
}),
|
|
582
|
-
execute: async (args, { session, log }) => {
|
|
583
|
-
const { url, ...options } = args;
|
|
584
|
-
return safeExecute(async () => {
|
|
585
|
-
const client = getClient(session);
|
|
586
|
-
const cleaned = removeEmptyTopLevel(options);
|
|
587
|
-
log.info('Starting crawl', { url: String(url) });
|
|
588
|
-
const res = await client.crawl(String(url), {
|
|
589
|
-
...cleaned,
|
|
590
|
-
origin: ORIGIN,
|
|
591
|
-
});
|
|
592
|
-
// Crawl results use truncation only (no summarization — multi-page)
|
|
593
|
-
return await processResponse(res, {
|
|
594
|
-
url: String(url),
|
|
595
|
-
skipSummarization: true,
|
|
596
|
-
});
|
|
597
|
-
}, { tool: 'scorch_crawl', url: String(url) });
|
|
598
|
-
},
|
|
599
|
-
});
|
|
600
|
-
server.addTool({
|
|
601
|
-
name: 'scorch_check_crawl_status',
|
|
602
|
-
description: `
|
|
603
|
-
Check the status of a crawl job.
|
|
604
|
-
|
|
605
|
-
**Usage Example:**
|
|
606
|
-
\`\`\`json
|
|
607
|
-
{
|
|
608
|
-
"name": "scorch_check_crawl_status",
|
|
609
|
-
"arguments": {
|
|
610
|
-
"id": "550e8400-e29b-41d4-a716-446655440000"
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
\`\`\`
|
|
614
|
-
**Returns:** Status and progress of the crawl job, including results if available.
|
|
615
|
-
`,
|
|
616
|
-
parameters: z.object({ id: z.string() }),
|
|
617
|
-
execute: async (args, { session }) => {
|
|
618
|
-
return safeExecute(async () => {
|
|
619
|
-
const client = getClient(session);
|
|
620
|
-
const res = await client.getCrawlStatus(args.id);
|
|
621
|
-
return asText(res);
|
|
622
|
-
}, { tool: 'scorch_check_crawl_status' });
|
|
623
|
-
},
|
|
624
|
-
});
|
|
625
|
-
server.addTool({
|
|
626
|
-
name: 'scorch_extract',
|
|
627
|
-
description: `
|
|
628
|
-
Extract structured information from web pages using LLM capabilities. Supports both cloud AI and self-hosted LLM extraction.
|
|
629
|
-
|
|
630
|
-
**Best for:** Extracting specific structured data like prices, names, details from web pages.
|
|
631
|
-
**Not recommended for:** When you need the full content of a page (use scrape); when you're not looking for specific structured data.
|
|
632
|
-
**Arguments:**
|
|
633
|
-
- urls: Array of URLs to extract information from
|
|
634
|
-
- prompt: Custom prompt for the LLM extraction
|
|
635
|
-
- schema: JSON schema for structured data extraction
|
|
636
|
-
- allowExternalLinks: Allow extraction from external links
|
|
637
|
-
- enableWebSearch: Enable web search for additional context
|
|
638
|
-
- includeSubdomains: Include subdomains in extraction
|
|
639
|
-
**Prompt Example:** "Extract the product name, price, and description from these product pages."
|
|
640
|
-
**Usage Example:**
|
|
641
|
-
\`\`\`json
|
|
642
|
-
{
|
|
643
|
-
"name": "scorch_extract",
|
|
644
|
-
"arguments": {
|
|
645
|
-
"urls": ["https://example.com/page1", "https://example.com/page2"],
|
|
646
|
-
"prompt": "Extract product information including name, price, and description",
|
|
647
|
-
"schema": {
|
|
648
|
-
"type": "object",
|
|
649
|
-
"properties": {
|
|
650
|
-
"name": { "type": "string" },
|
|
651
|
-
"price": { "type": "number" },
|
|
652
|
-
"description": { "type": "string" }
|
|
653
|
-
},
|
|
654
|
-
"required": ["name", "price"]
|
|
655
|
-
},
|
|
656
|
-
"allowExternalLinks": false,
|
|
657
|
-
"enableWebSearch": false,
|
|
658
|
-
"includeSubdomains": false
|
|
659
|
-
}
|
|
660
|
-
}
|
|
661
|
-
\`\`\`
|
|
662
|
-
**Returns:** Extracted structured data as defined by your schema.
|
|
663
|
-
`,
|
|
664
|
-
parameters: z.object({
|
|
665
|
-
urls: z.array(z.string()),
|
|
666
|
-
prompt: z.string().optional(),
|
|
667
|
-
schema: z.record(z.string(), z.any()).optional(),
|
|
668
|
-
allowExternalLinks: z.boolean().optional(),
|
|
669
|
-
enableWebSearch: z.boolean().optional(),
|
|
670
|
-
includeSubdomains: z.boolean().optional(),
|
|
671
|
-
}),
|
|
672
|
-
execute: async (args, { session, log }) => {
|
|
673
|
-
const a = args;
|
|
674
|
-
return safeExecute(async () => {
|
|
675
|
-
const client = getClient(session);
|
|
676
|
-
log.info('Extracting from URLs', {
|
|
677
|
-
count: Array.isArray(a.urls) ? a.urls.length : 0,
|
|
678
|
-
});
|
|
679
|
-
const extractBody = removeEmptyTopLevel({
|
|
680
|
-
urls: a.urls,
|
|
681
|
-
prompt: a.prompt,
|
|
682
|
-
schema: a.schema || undefined,
|
|
683
|
-
allowExternalLinks: a.allowExternalLinks,
|
|
684
|
-
enableWebSearch: a.enableWebSearch,
|
|
685
|
-
includeSubdomains: a.includeSubdomains,
|
|
686
|
-
origin: ORIGIN,
|
|
687
|
-
});
|
|
688
|
-
const res = await client.extract(extractBody);
|
|
689
|
-
// Extract returns structured data — skip summarization
|
|
690
|
-
return await processResponse(res, { skipSummarization: true });
|
|
691
|
-
}, { tool: 'scorch_extract' });
|
|
692
|
-
},
|
|
693
|
-
});
|
|
694
|
-
const PORT = Number(process.env.PORT || 3000);
|
|
695
|
-
const HOST = process.env.CLOUD_SERVICE === 'true'
|
|
696
|
-
? '0.0.0.0'
|
|
697
|
-
: process.env.HOST || 'localhost';
|
|
698
|
-
let args;
|
|
699
|
-
if (process.env.CLOUD_SERVICE === 'true' ||
|
|
700
|
-
process.env.SSE_LOCAL === 'true' ||
|
|
701
|
-
process.env.HTTP_STREAMABLE_SERVER === 'true') {
|
|
702
|
-
args = {
|
|
703
|
-
transportType: 'httpStream',
|
|
704
|
-
httpStream: {
|
|
705
|
-
port: PORT,
|
|
706
|
-
host: HOST,
|
|
707
|
-
stateless: true,
|
|
708
|
-
},
|
|
709
|
-
};
|
|
710
|
-
}
|
|
711
|
-
else {
|
|
712
|
-
// default: stdio
|
|
713
|
-
args = {
|
|
714
|
-
transportType: 'stdio',
|
|
715
|
-
};
|
|
716
|
-
}
|
|
717
|
-
await server.start(args);
|