searchfetch 3.3.3 → 4.0.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.
package/index.js DELETED
@@ -1,1350 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // === IMPORTS =============================================================
4
- import { readdirSync, readFileSync, realpathSync } from "node:fs";
5
- import { dirname, join } from "node:path";
6
- import { fileURLToPath } from "node:url";
7
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
8
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
9
- import { z } from "zod";
10
- import { launch, ensureBinary } from "cloakbrowser";
11
- import * as cheerio from "cheerio";
12
- import TurndownService from "turndown";
13
-
14
- // === BROWSER MANAGER =====================================================
15
- class BrowserManager {
16
- constructor() {
17
- this.browser = null;
18
- this.launchPromise = null;
19
- }
20
-
21
- async getBrowser() {
22
- if (this.browser && this.browser.isConnected()) return this.browser;
23
- if (this.launchPromise) return this.launchPromise;
24
-
25
- this.launchPromise = launch({
26
- headless: true,
27
- humanize: true,
28
- args: [
29
- "--disable-blink-features=AutomationControlled",
30
- "--no-sandbox",
31
- "--disable-dev-shm-usage",
32
- ],
33
- })
34
- .then((browser) => {
35
- this.browser = browser;
36
- this.browser.on("disconnected", () => {
37
- this.browser = null;
38
- });
39
- return browser;
40
- })
41
- .catch((err) => {
42
- throw err;
43
- })
44
- .finally(() => {
45
- this.launchPromise = null;
46
- });
47
-
48
- return this.launchPromise;
49
- }
50
-
51
- async close() {
52
- if (this.browser) {
53
- await this.browser.close();
54
- this.browser = null;
55
- }
56
- }
57
- }
58
-
59
- const browserManager = new BrowserManager();
60
-
61
- const cleanup = async () => {
62
- await browserManager.close();
63
- process.exit(0);
64
- };
65
-
66
- // === TURNDOWN ============================================================
67
- const turndown = new TurndownService({
68
- headingStyle: "atx",
69
- codeBlockStyle: "fenced",
70
- emDelimiter: "*",
71
- });
72
-
73
- // === BUILT-IN TEMPLATES (loaded from templates/*.json) ====================
74
-
75
- const __filename = fileURLToPath(import.meta.url);
76
- const __dirname = dirname(__filename);
77
- const TEMPLATES_DIR = join(__dirname, "templates");
78
-
79
- function loadBuiltinTemplates() {
80
- let files;
81
- try {
82
- files = readdirSync(TEMPLATES_DIR);
83
- } catch (err) {
84
- throw new Error(`Cannot read templates directory '${TEMPLATES_DIR}': ${err.message}`);
85
- }
86
-
87
- const jsonFiles = files.filter((f) => f.endsWith(".json")).sort();
88
-
89
- if (jsonFiles.length === 0) {
90
- throw new Error(`No template JSON files found in '${TEMPLATES_DIR}'`);
91
- }
92
-
93
- const templates = [];
94
- for (const file of jsonFiles) {
95
- const filePath = join(TEMPLATES_DIR, file);
96
- const content = readFileSync(filePath, "utf-8");
97
- let template;
98
- try {
99
- template = JSON.parse(content);
100
- } catch (err) {
101
- throw new Error(`Invalid JSON in template file '${filePath}': ${err.message}`);
102
- }
103
- if (!template.name || typeof template.name !== "string") {
104
- throw new Error(`Template file '${filePath}' is missing a valid "name" field`);
105
- }
106
- templates.push(template);
107
- }
108
-
109
- // Sort by "order" field for deterministic URL-pattern matching
110
- templates.sort((a, b) => (a.order ?? 999) - (b.order ?? 999));
111
-
112
- return templates;
113
- }
114
-
115
- const BUILTIN_TEMPLATES = loadBuiltinTemplates();
116
-
117
- // === TEMPLATE LOOKUP =====================================================
118
- const TEMPLATE_MAP = new Map();
119
- for (const t of BUILTIN_TEMPLATES) {
120
- TEMPLATE_MAP.set(t.name, t);
121
- }
122
-
123
- function getTemplateByName(name) {
124
- const t = TEMPLATE_MAP.get(name);
125
- if (!t) {
126
- const names = [...TEMPLATE_MAP.keys()].join(", ");
127
- throw new Error(`Unknown template '${name}'. Available: ${names}`);
128
- }
129
- return t;
130
- }
131
-
132
- function detectTemplateByUrl(url) {
133
- for (const template of BUILTIN_TEMPLATES) {
134
- if (!template.url_patterns) continue;
135
- for (const pattern of template.url_patterns) {
136
- try {
137
- if (new RegExp(pattern).test(url)) {
138
- return template;
139
- }
140
- } catch (_invalidRegex) {
141
- // Invalid URL patterns are tolerated — templates may contain
142
- // broad patterns that don't compile correctly in every context.
143
- }
144
- }
145
- }
146
- return null;
147
- }
148
-
149
- // === URL TEMPLATE RESOLUTION =============================================
150
-
151
- function resolveUrlTemplate(template, providedParams) {
152
- const urlParams = template.url_params || {};
153
- let url = template.url_template;
154
- if (!url) return null;
155
-
156
- let match;
157
- const re = /\{(\w+)\}/g;
158
- while ((match = re.exec(url)) !== null) {
159
- const name = match[1];
160
- const def = urlParams[name] || {};
161
-
162
- let value;
163
- if (
164
- name in providedParams &&
165
- providedParams[name] !== null &&
166
- providedParams[name] !== undefined
167
- ) {
168
- value = String(providedParams[name]);
169
- } else if (def.default !== undefined) {
170
- value = String(def.default);
171
- } else if (def.required) {
172
- throw new Error(
173
- `Required URL parameter '${name}' not provided for template '${template.name}'.`,
174
- );
175
- } else {
176
- value = "";
177
- }
178
-
179
- if (def.encode === "url") {
180
- value = encodeURIComponent(value);
181
- }
182
-
183
- url = url.replace(match[0], value);
184
- }
185
-
186
- // Remove any remaining unreplaced placeholders
187
- url = url
188
- .replace(/\{\w+\}/g, "")
189
- .replace(/&{2,}/g, "&")
190
- .replace(/\?&/, "?");
191
-
192
- return url;
193
- }
194
-
195
- // === SEARCH PARAM MAPPING ================================================
196
-
197
- function resolveEngineToTemplateName(engine) {
198
- if (engine === "duckduckgo") return "duckduckgo-search";
199
- if (engine === "google") return "google-search";
200
- return engine;
201
- }
202
-
203
- function mapSearchParams(engine, query, region, safeSearch) {
204
- const params = { query };
205
- const resolved = resolveEngineToTemplateName(engine);
206
-
207
- if (resolved === "duckduckgo-search") {
208
- if (region !== null && region !== undefined) {
209
- params.kl = region;
210
- }
211
- if (safeSearch === true) {
212
- params.kp = "1";
213
- } else if (safeSearch === false) {
214
- params.kp = "-2";
215
- }
216
- } else if (resolved === "google-search") {
217
- if (region !== null && region !== undefined) {
218
- const parts = region.split("-");
219
- params.hl = parts[0];
220
- params.gl = parts.length > 1 ? parts[1] : parts[0];
221
- }
222
- }
223
-
224
- return params;
225
- }
226
-
227
- // === FETCH ===============================================================
228
-
229
- const FETCH_MAX_ATTEMPTS = 2;
230
- const HTTP_429_RETRY_DELAY_MS = 2000;
231
-
232
- function sleep(ms) {
233
- return new Promise((resolve) => setTimeout(resolve, ms));
234
- }
235
-
236
- function parseRetryAfterMs(value) {
237
- if (!value) return HTTP_429_RETRY_DELAY_MS;
238
- const seconds = Number(value);
239
- if (Number.isFinite(seconds) && seconds >= 0) {
240
- return Math.min(seconds * 1000, 30000);
241
- }
242
- const dateMs = Date.parse(value);
243
- if (Number.isFinite(dateMs)) {
244
- return Math.min(Math.max(dateMs - Date.now(), 0), 30000);
245
- }
246
- return HTTP_429_RETRY_DELAY_MS;
247
- }
248
-
249
- function makeHttpStatusError(status, url, retryAfterMs = null) {
250
- const err = new Error(`Access denied: HTTP ${status} when fetching ${url}`);
251
- err.httpStatus = status;
252
- err.retryAfterMs = retryAfterMs;
253
- return err;
254
- }
255
-
256
- function isAccessDenied($) {
257
- const title = ($("title").text() || "").toLowerCase();
258
- const bodyText = ($("body").text() || "").replace(/\s+/g, " ").trim().toLowerCase();
259
-
260
- const titleDenyPatterns = [
261
- "captcha",
262
- "are you a robot",
263
- "access denied",
264
- "blocked",
265
- "forbidden",
266
- "unusual traffic",
267
- "sorry, you have been blocked",
268
- "verify you are human",
269
- "one more step",
270
- "security check",
271
- "ddos protection",
272
- "cloudflare",
273
- ];
274
-
275
- if (titleDenyPatterns.some((pattern) => title.includes(pattern))) return true;
276
-
277
- const strongBodyDenyPatterns = [
278
- "to continue, please type the characters",
279
- "our systems have detected unusual traffic",
280
- "sorry, you have been blocked",
281
- "bots use duckduckgo too",
282
- ];
283
-
284
- if (strongBodyDenyPatterns.some((pattern) => bodyText.includes(pattern))) return true;
285
-
286
- const shortBodyDenyPatterns = ["verify you are human", "are you a robot", "access denied"];
287
-
288
- if (bodyText.length < 1200 && shortBodyDenyPatterns.some((pattern) => bodyText.includes(pattern)))
289
- return true;
290
-
291
- return false;
292
- }
293
-
294
- async function fetchHtml(url, template, blockMedia) {
295
- const browser = await browserManager.getBrowser();
296
- const context = await browser.newContext();
297
-
298
- try {
299
- // Pre-load cookies from template
300
- if (template && template.cookies && template.cookies.length > 0) {
301
- await context.addCookies(template.cookies);
302
- }
303
-
304
- const page = await context.newPage();
305
-
306
- try {
307
- // Route blocked resource types
308
- if (blockMedia) {
309
- const blockedTypes =
310
- template && template.block_resources
311
- ? template.block_resources
312
- : ["image", "media", "font"];
313
-
314
- if (blockedTypes.length > 0) {
315
- await page.route("**/*", (route) => {
316
- const type = route.request().resourceType();
317
- if (blockedTypes.includes(type)) {
318
- route.abort();
319
- } else {
320
- route.continue();
321
- }
322
- });
323
- }
324
- }
325
-
326
- let response;
327
- try {
328
- response = await page.goto(url, {
329
- waitUntil: "networkidle",
330
- timeout: 15000,
331
- });
332
- } catch (_navError) {
333
- // Allow partial rendering on timeout only
334
- if (!_navError.message?.includes("timeout") && !_navError.message?.includes("Timeout")) {
335
- throw _navError;
336
- }
337
- }
338
-
339
- // Check HTTP status for access failures
340
- if (response) {
341
- const status = response.status();
342
- if ([401, 403, 429].includes(status)) {
343
- throw makeHttpStatusError(
344
- status,
345
- url,
346
- status === 429 ? parseRetryAfterMs(response.headers()["retry-after"]) : null,
347
- );
348
- }
349
- }
350
-
351
- const pageContent = await page.content();
352
-
353
- // Check for CAPTCHA / access-denied pages
354
- const $ = cheerio.load(pageContent);
355
- if (isAccessDenied($)) {
356
- throw new Error(
357
- `Access denied: CAPTCHA or block page detected at ${url}. The site is blocking automated access.`,
358
- );
359
- }
360
-
361
- return pageContent;
362
- } finally {
363
- await page.close();
364
- }
365
- } finally {
366
- await context.close();
367
- }
368
- }
369
-
370
- async function fetchHtmlWithRetry(url, template, blockMedia) {
371
- let lastError;
372
- for (let attempt = 0; attempt < FETCH_MAX_ATTEMPTS; attempt++) {
373
- try {
374
- return await fetchHtml(url, template, blockMedia);
375
- } catch (err) {
376
- lastError = err;
377
- if (attempt < FETCH_MAX_ATTEMPTS - 1 && err.httpStatus === 429) {
378
- await sleep(err.retryAfterMs ?? HTTP_429_RETRY_DELAY_MS);
379
- continue;
380
- }
381
- if (
382
- attempt < FETCH_MAX_ATTEMPTS - 1 &&
383
- (err.message.includes("net::") ||
384
- err.message.includes("ERR_") ||
385
- err.message.includes("Navigation failed") ||
386
- err.message.includes("navigating"))
387
- ) {
388
- await sleep(500);
389
- continue;
390
- }
391
- throw err;
392
- }
393
- }
394
- throw lastError;
395
- }
396
-
397
- // === SOURCE MARKDOWN DETECTION ===========================================
398
-
399
- function isMarkdownContent(text) {
400
- if (!text) return false;
401
- const htmlTagCount = (text.match(/<\w+[^>]*>/g) || []).length;
402
- if (htmlTagCount > 3) return false;
403
- const patterns = [
404
- /^#{1,6}\s+\S/m,
405
- /\[.+?\]\(.+?\)/,
406
- /```\w*\n/,
407
- /^\s*[-*+]\s+\S/m,
408
- /\*\*[^*]+\*\*/,
409
- /^>\s+\S/m,
410
- ];
411
- for (const pat of patterns) {
412
- if (pat.test(text)) return true;
413
- }
414
- return false;
415
- }
416
-
417
- function stripSourceMarkdown(content) {
418
- return content
419
- .replace(/^@twoslash-cache:.*$/gm, "")
420
- .replace(/\n{3,}/g, "\n\n")
421
- .trim();
422
- }
423
-
424
- function resolveSourceUrl(sourceTemplate, url) {
425
- if (sourceTemplate === "{url}.md") {
426
- return `${url.replace(/\/+$/, "")}.md`;
427
- }
428
- return sourceTemplate.replace("{url}", url);
429
- }
430
-
431
- async function fetchSourceMarkdown(sourceUrl, template, blockMedia) {
432
- const browser = await browserManager.getBrowser();
433
- const context = await browser.newContext();
434
-
435
- try {
436
- if (template && template.cookies && template.cookies.length > 0) {
437
- await context.addCookies(template.cookies);
438
- }
439
-
440
- const page = await context.newPage();
441
- try {
442
- if (blockMedia) {
443
- const blockedTypes =
444
- template && template.block_resources
445
- ? template.block_resources
446
- : ["image", "media", "font"];
447
- if (blockedTypes.length > 0) {
448
- await page.route("**/*", (route) => {
449
- const type = route.request().resourceType();
450
- if (blockedTypes.includes(type)) route.abort();
451
- else route.continue();
452
- });
453
- }
454
- }
455
-
456
- let response;
457
- try {
458
- response = await page.goto(sourceUrl, {
459
- waitUntil: "domcontentloaded",
460
- timeout: 10000,
461
- });
462
- } catch (_) {
463
- return null;
464
- }
465
-
466
- if (response && response.status() >= 400) return null;
467
-
468
- let text;
469
- try {
470
- text = await page.evaluate(
471
- "() => document.body?.innerText || document.body?.textContent || ''",
472
- );
473
- } catch (_) {
474
- text = await page.content();
475
- }
476
-
477
- if (!text || typeof text !== "string") return null;
478
-
479
- text = stripSourceMarkdown(text.trim());
480
- return isMarkdownContent(text) ? text : null;
481
- } finally {
482
- await page.close();
483
- }
484
- } catch (_) {
485
- return null;
486
- } finally {
487
- await context.close();
488
- }
489
- }
490
-
491
- // === HTML CLEANUP ========================================================
492
-
493
- const DEFAULT_REMOVE_SELECTORS = [
494
- "script",
495
- "style",
496
- "svg",
497
- "nav",
498
- "footer",
499
- "noscript",
500
- "iframe",
501
- ".advertisement",
502
- ];
503
-
504
- function applyRemove($, template) {
505
- const removeSelectors =
506
- template && template.remove && template.remove.length > 0
507
- ? template.remove
508
- : DEFAULT_REMOVE_SELECTORS;
509
-
510
- for (const selector of removeSelectors) {
511
- try {
512
- $(selector).remove();
513
- } catch (_invalidSelector) {
514
- // Invalid remove selectors are tolerated — templates can express
515
- // broad cleanup rules that don't apply to every page.
516
- }
517
- }
518
-
519
- // Strip style attributes and data:image src
520
- $("[style]").removeAttr("style");
521
- $("*").each((_i, el) => {
522
- const src = $(el).attr("src");
523
- if (src && src.startsWith("data:image")) {
524
- $(el).removeAttr("src");
525
- }
526
- });
527
- }
528
-
529
- // === EXTRACTION ENGINE ===================================================
530
-
531
- /**
532
- * Find elements matching selector, scoped to $parent.
533
- * Search order: descendants → closest ancestor → ancestor subtrees (up to 4 levels).
534
- */
535
- function findScoped($parent, selector) {
536
- if (!selector || selector.trim() === "") {
537
- return $parent;
538
- }
539
-
540
- // 1. Descendants
541
- let result = $parent.find(selector);
542
- if (result.length > 0) return result;
543
-
544
- // 2. Closest ancestor matching selector
545
- result = $parent.closest(selector);
546
- if (result.length > 0) return result;
547
-
548
- // 3. Ancestor subtrees (up to 4 levels up)
549
- let ancestor = $parent.parent();
550
- for (let i = 0; i < 4 && ancestor.length > 0; i++) {
551
- result = ancestor.find(selector);
552
- if (result.length > 0) return result;
553
- ancestor = ancestor.parent();
554
- }
555
-
556
- return $parent.find("__nonexistent__");
557
- }
558
-
559
- /**
560
- * Try comma-separated selectors in order; first match wins.
561
- */
562
- function findFirstMatch($parent, selectorStr) {
563
- if (!selectorStr || selectorStr.trim() === "") {
564
- return $parent;
565
- }
566
-
567
- const selectors = selectorStr
568
- .split(",")
569
- .map((s) => s.trim())
570
- .filter(Boolean);
571
-
572
- for (const sel of selectors) {
573
- const matches = findScoped($parent, sel);
574
- if (matches.length > 0) return matches;
575
- }
576
-
577
- return $parent.find("__nonexistent__");
578
- }
579
-
580
- /**
581
- * Resolve top-level elements for a section (document-wide with fallback).
582
- */
583
- function resolveTopElements($, selectorStr) {
584
- if (!selectorStr || selectorStr.trim() === "") {
585
- return $("body");
586
- }
587
-
588
- const selectors = selectorStr
589
- .split(",")
590
- .map((s) => s.trim())
591
- .filter(Boolean);
592
-
593
- for (const sel of selectors) {
594
- try {
595
- const matches = $(sel);
596
- if (matches.length > 0) return matches;
597
- } catch (_) {
598
- // Skip invalid selectors
599
- }
600
- }
601
-
602
- return $();
603
- }
604
-
605
- // === TRANSFORMS ==========================================================
606
-
607
- function applyTransform(value, transform, origin) {
608
- const transforms = Array.isArray(transform) ? transform : [transform];
609
- let result = value;
610
-
611
- for (const t of transforms) {
612
- if (!result) continue;
613
- switch (t) {
614
- case "strip":
615
- result = result.trim();
616
- break;
617
-
618
- case "decode_google_url":
619
- if (result.startsWith("/url?q=")) {
620
- try {
621
- const urlPart = result.split("/url?q=")[1].split("&")[0];
622
- result = decodeURIComponent(urlPart);
623
- } catch (_) {
624
- // Leave as-is
625
- }
626
- }
627
- break;
628
-
629
- case "decode_ddg_url":
630
- if (result.includes("/l/?uddg=")) {
631
- try {
632
- const queryString = result.split("?")[1] || "";
633
- const params = new URLSearchParams(queryString);
634
- const uddg = params.get("uddg");
635
- if (uddg) result = decodeURIComponent(uddg);
636
- } catch (_) {
637
- // Leave as-is
638
- }
639
- }
640
- break;
641
-
642
- case "json_parse":
643
- try {
644
- result = JSON.stringify(JSON.parse(result), null, 2);
645
- } catch (_) {
646
- // Leave as-is
647
- }
648
- break;
649
-
650
- case "resolve_href":
651
- if (origin && result.startsWith("/") && !result.startsWith("//")) {
652
- try {
653
- result = new URL(result, origin).href;
654
- } catch (_) {
655
- // Leave as-is
656
- }
657
- }
658
- break;
659
- }
660
- }
661
-
662
- return result;
663
- }
664
-
665
- // === EXTRACTION ==========================================================
666
-
667
- function extractValue($el, section, origin) {
668
- let value;
669
-
670
- switch (section.format) {
671
- case "text":
672
- value = $el.text().replace(/\s+/g, " ").trim();
673
- break;
674
-
675
- case "markdown": {
676
- const html = $el.html() || "";
677
- value = turndown
678
- .turndown(html)
679
- .replace(/\n{3,}/g, "\n\n")
680
- .trim();
681
- break;
682
- }
683
-
684
- case "attribute":
685
- value = $el.attr(section.attribute) || "";
686
- break;
687
-
688
- case "html":
689
- value = $el.html() || "";
690
- break;
691
-
692
- default:
693
- value = $el.text().replace(/\s+/g, " ").trim();
694
- }
695
-
696
- if (section.transform && value) {
697
- value = applyTransform(value, section.transform, origin);
698
- }
699
-
700
- return value;
701
- }
702
-
703
- /**
704
- * Extract one child section, scoped to $parentEl.
705
- * Returns { type: "value", text } or null.
706
- */
707
- function extractChildSection($, $parentEl, section, origin) {
708
- const elements = findFirstMatch($parentEl, section.selector);
709
-
710
- if (!elements || elements.length === 0) {
711
- if (section.required) {
712
- throw new Error(`Required section '${section.name}' not found on page.`);
713
- }
714
- return null;
715
- }
716
-
717
- const el = elements.eq(0);
718
- const value = extractValue(el, section, origin);
719
- return { type: "value", text: value };
720
- }
721
-
722
- /**
723
- * Extract a top-level section from the document.
724
- * Returns a SectionResult or null.
725
- */
726
- function extractSection($, section, context) {
727
- const elements = resolveTopElements($, section.selector);
728
-
729
- if (!elements || elements.length === 0) {
730
- if (section.required) {
731
- throw new Error(`Required section '${section.name}' not found on page.`);
732
- }
733
- return null;
734
- }
735
-
736
- // Determine limit
737
- let limit = elements.length;
738
- if (section.multiple && section.max_items) {
739
- limit = Math.min(limit, section.max_items);
740
- }
741
- // Override max_items with max_results for first multiple+children section
742
- if (
743
- context.isWebsearch &&
744
- context.maxResultsOverride &&
745
- !context._maxResultsConsumed &&
746
- section.multiple &&
747
- section.children &&
748
- section.children.length > 0
749
- ) {
750
- limit = Math.min(limit, context.maxResultsOverride);
751
- context._maxResultsConsumed = true;
752
- }
753
-
754
- if (section.multiple) {
755
- const items = [];
756
-
757
- for (let i = 0; i < limit; i++) {
758
- const el = elements.eq(i);
759
-
760
- if (section.children && section.children.length > 0) {
761
- // Multiple parents, each with children
762
- const childValues = {};
763
- for (const child of section.children) {
764
- const cr = extractChildSection($, el, child, context.origin);
765
- if (cr && cr.type === "value" && cr.text !== null && cr.text !== undefined) {
766
- childValues[child.name] = cr.text;
767
- }
768
- }
769
- if (Object.keys(childValues).length > 0) {
770
- items.push(childValues);
771
- }
772
- } else {
773
- // Multiple parents, no children
774
- const value = extractValue(el, section, context.origin);
775
- if (value && value.trim()) {
776
- items.push(value.trim());
777
- }
778
- }
779
- }
780
-
781
- if (section.children && section.children.length > 0) {
782
- return { section, type: "children-multiple", items };
783
- } else {
784
- return { section, type: "list", items };
785
- }
786
- } else {
787
- // Single parent
788
- const el = elements.eq(0);
789
-
790
- if (section.children && section.children.length > 0) {
791
- // Single parent with children — parent format ignored
792
- const childValues = {};
793
- for (const child of section.children) {
794
- const cr = extractChildSection($, el, child, context.origin);
795
- if (cr && cr.type === "value" && cr.text !== null && cr.text !== undefined) {
796
- childValues[child.name] = cr.text;
797
- }
798
- }
799
- return { section, type: "children", items: childValues };
800
- } else {
801
- const value = extractValue(el, section, context.origin);
802
- return { section, type: "value", text: value };
803
- }
804
- }
805
- }
806
-
807
- function extractTemplate($, template, context) {
808
- const results = [];
809
-
810
- for (const section of template.sections) {
811
- try {
812
- const result = extractSection($, section, context);
813
- if (result !== null) {
814
- results.push(result);
815
- }
816
- } catch (err) {
817
- // Required-section errors must surface to the user.
818
- if (err.message && err.message.includes("Required section")) {
819
- throw err;
820
- }
821
- // Non-required extraction failures: selector mismatches or format
822
- // processing issues. Broad templates legitimately don't match every
823
- // section on every page — skip and continue.
824
- }
825
- }
826
-
827
- return results;
828
- }
829
-
830
- // === COMPOSITION: WEBFETCH ===============================================
831
-
832
- function isCommentStyle(result) {
833
- if (!result.items || result.items.length === 0) return false;
834
- const first = result.items[0];
835
- const keys = Object.keys(first).map((k) => k.toLowerCase());
836
- return (
837
- (keys.includes("author") && (keys.includes("comment") || keys.includes("body"))) ||
838
- (keys.includes("user") && (keys.includes("comment") || keys.includes("body")))
839
- );
840
- }
841
-
842
- function composeSections(extracted, template, startIndex, maxLength) {
843
- const parts = [];
844
-
845
- for (const result of extracted) {
846
- if (result.type === "value") {
847
- const text = result.text;
848
- if (text && String(text).trim()) {
849
- parts.push(`## ${result.section.name}\n\n${String(text).trim()}`);
850
- }
851
- } else if (result.type === "list") {
852
- if (result.items && result.items.length > 0) {
853
- const listText = result.items.map((item) => `- ${item}`).join("\n");
854
- parts.push(`## ${result.section.name}\n\n${listText}`);
855
- }
856
- } else if (result.type === "children") {
857
- if (result.items && Object.keys(result.items).length > 0) {
858
- for (const [childName, value] of Object.entries(result.items)) {
859
- if (value && String(value).trim()) {
860
- parts.push(`## ${childName}\n\n${String(value).trim()}`);
861
- }
862
- }
863
- }
864
- } else if (result.type === "children-multiple") {
865
- if (result.items && result.items.length > 0) {
866
- if (isCommentStyle(result)) {
867
- const commentParts = [];
868
- for (const item of result.items) {
869
- const author = item["Author"] || item["author"] || item["User"] || item["user"] || "";
870
- const comment =
871
- item["Comment"] || item["Body"] || item["comment"] || item["body"] || "";
872
- if (author) {
873
- commentParts.push(`**${author}:**\n\n${comment}`);
874
- } else if (comment) {
875
- commentParts.push(comment);
876
- }
877
- }
878
- if (commentParts.length > 0) {
879
- parts.push(`## ${result.section.name}\n\n${commentParts.join("\n\n---\n\n")}`);
880
- }
881
- } else {
882
- const itemParts = [];
883
- for (const item of result.items) {
884
- const lines = [];
885
- for (const [key, value] of Object.entries(item)) {
886
- if (value && String(value).trim()) {
887
- lines.push(` ${key}: ${String(value).trim()}`);
888
- }
889
- }
890
- if (lines.length > 0) itemParts.push(lines.join("\n"));
891
- }
892
- if (itemParts.length > 0) {
893
- parts.push(`## ${result.section.name}\n\n${itemParts.join("\n\n")}`);
894
- }
895
- }
896
- }
897
- }
898
- }
899
-
900
- if (parts.length === 0) {
901
- return "(No content extracted from this page.)";
902
- }
903
-
904
- const full = parts.join("\n\n---\n\n");
905
- const totalLength = full.length;
906
- const paginated = full.substring(startIndex, startIndex + maxLength);
907
-
908
- const templateName = template ? template.name : "auto";
909
- let metadata = `\n\n---\n[webfetch: template="${templateName}", showing characters ${startIndex} to ${startIndex + paginated.length} of ${totalLength} total.`;
910
- if (startIndex + maxLength < totalLength) {
911
- metadata += ` Use start_index=${startIndex + maxLength} to read more.`;
912
- }
913
- metadata += `]`;
914
-
915
- return paginated + metadata;
916
- }
917
-
918
- // === COMPOSITION: WEBSEARCH ==============================================
919
-
920
- function composeSearchResults(extracted) {
921
- // Find the search results section (first children-multiple)
922
- const searchSection = extracted.find((r) => r.type === "children-multiple");
923
-
924
- if (!searchSection || !searchSection.items || searchSection.items.length === 0) {
925
- // Fall back to section-based output
926
- return composeSections(extracted, null, 0, Infinity);
927
- }
928
-
929
- const items = searchSection.items;
930
- const parts = [];
931
-
932
- for (let i = 0; i < items.length; i++) {
933
- const item = items[i];
934
- const num = i + 1;
935
-
936
- const title = item["Title"] || item["title"] || Object.values(item)[0] || "";
937
- const url = item["URL"] || item["url"] || item["Url"] || "";
938
- const snippet = item["Snippet"] || item["snippet"] || "";
939
-
940
- // Filter out non-http URLs and google internal links
941
- let cleanUrl = url;
942
- if (cleanUrl && !cleanUrl.startsWith("http")) {
943
- cleanUrl = ""; // Skip internal/non-web URLs
944
- }
945
- if (
946
- cleanUrl &&
947
- (cleanUrl.includes("google.com/search") || cleanUrl.includes("support.google.com"))
948
- ) {
949
- cleanUrl = ""; // Skip google internal links
950
- }
951
-
952
- if (!title) continue;
953
-
954
- const lines = [`[${num}] ${title}`];
955
- if (cleanUrl) lines.push(` URL: ${cleanUrl}`);
956
- if (snippet) lines.push(` Snippet: ${snippet}`);
957
-
958
- parts.push(lines.join("\n"));
959
- }
960
-
961
- if (parts.length === 0) {
962
- return "(No content extracted from this page.)";
963
- }
964
-
965
- return `## ${searchSection.section.name}\n\n${parts.join("\n\n")}`;
966
- }
967
-
968
- // === GENERIC FALLBACK ====================================================
969
-
970
- function genericFallback($, startIndex, maxLength) {
971
- applyRemove($, null);
972
-
973
- const bodyHtml = $("body").html() || "";
974
- let markdown = turndown
975
- .turndown(bodyHtml)
976
- .replace(/\n{3,}/g, "\n\n")
977
- .trim();
978
-
979
- if (!markdown || markdown.trim().length === 0) {
980
- return "(No content extracted from this page.)";
981
- }
982
-
983
- const totalLength = markdown.length;
984
- const paginated = markdown.substring(startIndex, startIndex + maxLength);
985
-
986
- let metadata = `\n\n---\n[webfetch: template="auto (fallback)", showing characters ${startIndex} to ${startIndex + paginated.length} of ${totalLength} total.`;
987
- if (startIndex + maxLength < totalLength) {
988
- metadata += ` Use start_index=${startIndex + maxLength} to read more.`;
989
- }
990
- metadata += `]`;
991
-
992
- return paginated + metadata;
993
- }
994
-
995
- // === SEARCH TEMPLATE RESOLUTION ==========================================
996
-
997
- function resolveSearchTemplate(engine, query, region, safeSearch) {
998
- const templateName = resolveEngineToTemplateName(engine);
999
-
1000
- let template;
1001
- if (templateName.startsWith("{")) {
1002
- try {
1003
- template = JSON.parse(templateName);
1004
- } catch (e) {
1005
- throw new Error(`Invalid inline JSON template: ${e.message}`);
1006
- }
1007
- } else {
1008
- template = getTemplateByName(templateName);
1009
- }
1010
-
1011
- if (!template.url_template) {
1012
- throw new Error(`Template '${template.name}' is not a search template (no url_template).`);
1013
- }
1014
-
1015
- const params = mapSearchParams(engine, query, region, safeSearch);
1016
- let url = resolveUrlTemplate(template, params);
1017
-
1018
- // Google safe_search: append safe=active to URL
1019
- if ((engine === "google" || templateName === "google-search") && safeSearch === true) {
1020
- url += "&safe=active";
1021
- }
1022
-
1023
- return { template, url };
1024
- }
1025
-
1026
- function resolveDuckDuckGoLiteTemplate(query, region, safeSearch) {
1027
- const template = {
1028
- ...getTemplateByName("duckduckgo-search"),
1029
- name: "duckduckgo-lite-search",
1030
- url_template: "https://lite.duckduckgo.com/lite/?q={query}&kl={kl}&kp={kp}",
1031
- sections: [
1032
- {
1033
- name: "Results",
1034
- selector: "a.result-link",
1035
- multiple: true,
1036
- max_items: 10,
1037
- children: [
1038
- { name: "Title", selector: "", format: "text" },
1039
- {
1040
- name: "URL",
1041
- selector: "",
1042
- format: "attribute",
1043
- attribute: "href",
1044
- transform: "decode_ddg_url",
1045
- },
1046
- ],
1047
- },
1048
- ],
1049
- };
1050
- const params = mapSearchParams("duckduckgo", query, region, safeSearch);
1051
- return { template, url: resolveUrlTemplate(template, params), engine: "duckduckgo-lite" };
1052
- }
1053
-
1054
- function resolveSearchCandidates(engine, query, region, safeSearch) {
1055
- const primary = { ...resolveSearchTemplate(engine, query, region, safeSearch), engine };
1056
- if (engine === "google") {
1057
- return [
1058
- primary,
1059
- {
1060
- ...resolveSearchTemplate("duckduckgo", query, region, safeSearch),
1061
- engine: "duckduckgo",
1062
- },
1063
- resolveDuckDuckGoLiteTemplate(query, region, safeSearch),
1064
- ];
1065
- }
1066
- if (engine === "duckduckgo") {
1067
- return [primary, resolveDuckDuckGoLiteTemplate(query, region, safeSearch)];
1068
- }
1069
- return [primary];
1070
- }
1071
-
1072
- // === MCP SERVER & TOOLS ==================================================
1073
-
1074
- const server = new McpServer({ name: "searchfetch", version: "3.3.3" });
1075
-
1076
- // --- websearch tool ---
1077
-
1078
- server.registerTool(
1079
- "websearch",
1080
- {
1081
- title: "Web Search",
1082
- description:
1083
- "Search the web using DuckDuckGo or Google. Returns a clean list of titles, URLs, and snippets. Excellent for researching general knowledge, news, and finding URLs.",
1084
- inputSchema: z.object({
1085
- query: z.string().describe("The search query string."),
1086
- engine: z
1087
- .string()
1088
- .default("duckduckgo")
1089
- .describe(
1090
- "Search engine to use. Can be 'duckduckgo' or 'google'. Default is 'duckduckgo'.",
1091
- ),
1092
- region: z
1093
- .string()
1094
- .nullable()
1095
- .default(null)
1096
- .describe(
1097
- "Region and language code to localize search results (e.g., 'us-en', 'uk-en', 'de-de'). For DuckDuckGo it maps directly. For Google, 'us' is country code and 'en' is language. Default is null (uses template default).",
1098
- ),
1099
- safe_search: z
1100
- .boolean()
1101
- .nullable()
1102
- .default(null)
1103
- .describe(
1104
- "Enable safe search filtering. null = use template default. Applies to both DuckDuckGo and Google.",
1105
- ),
1106
- max_results: z
1107
- .number()
1108
- .default(10)
1109
- .describe("Maximum number of search results to return. Default is 10."),
1110
- block_media: z
1111
- .boolean()
1112
- .default(true)
1113
- .describe(
1114
- "Block images, videos, and fonts entirely at the network layer. Default is true.",
1115
- ),
1116
- }),
1117
- },
1118
- async ({ query, engine, region, safe_search, max_results, block_media }) => {
1119
- try {
1120
- const candidates = resolveSearchCandidates(engine, query, region, safe_search);
1121
- let extracted;
1122
- let selectedEngine;
1123
- let lastError;
1124
-
1125
- for (const candidate of candidates) {
1126
- try {
1127
- const html = await fetchHtmlWithRetry(candidate.url, candidate.template, block_media);
1128
- const $ = cheerio.load(html);
1129
- applyRemove($, candidate.template);
1130
- extracted = extractTemplate($, candidate.template, {
1131
- origin: new URL(candidate.url).origin,
1132
- isWebsearch: true,
1133
- maxResultsOverride: max_results,
1134
- _maxResultsConsumed: false,
1135
- });
1136
- const resultSection = extracted.find((result) => result.type === "children-multiple");
1137
- if (resultSection?.items?.length > 0) {
1138
- selectedEngine = candidate.engine;
1139
- break;
1140
- }
1141
- lastError = new Error(`No results extracted from ${candidate.engine}.`);
1142
- } catch (err) {
1143
- lastError = err;
1144
- }
1145
- }
1146
-
1147
- if (!extracted || !selectedEngine) throw lastError || new Error("No search results found.");
1148
-
1149
- let result = composeSearchResults(extracted);
1150
- if (selectedEngine !== engine) {
1151
- result =
1152
- `[websearch: ${engine} was unavailable; results are from ${selectedEngine}.]\n\n` +
1153
- result;
1154
- }
1155
-
1156
- return { content: [{ type: "text", text: result }] };
1157
- } catch (err) {
1158
- return {
1159
- content: [{ type: "text", text: `Search Error: ${err.message}` }],
1160
- isError: true,
1161
- };
1162
- }
1163
- },
1164
- );
1165
-
1166
- // --- webfetch tool ---
1167
-
1168
- server.registerTool(
1169
- "webfetch",
1170
- {
1171
- title: "Web Fetch",
1172
- description:
1173
- "Fetch and extract the main text content from any webpage. Fully executes JavaScript to load React/SPAs and aggressively strips images/media (including base64) to save context tokens.",
1174
- inputSchema: z.object({
1175
- url: z
1176
- .string()
1177
- .describe("The full URL of the webpage to fetch (must start with http/https)."),
1178
- template: z
1179
- .string()
1180
- .default("auto")
1181
- .describe(
1182
- "Template to use: 'auto' (auto-detect from URL), a built-in page template name " +
1183
- "(wikipedia, reddit, mdn-web-docs, gitlab, youtube, devto, go-pkg, javadoc, " +
1184
- "github-repo, github-issue, npm-package, pypi-package, crates-package, " +
1185
- "docker-hub, docs-rs, docs-page), 'raw' for minimal-filtering full-page output, " +
1186
- "or inline JSON.",
1187
- ),
1188
- start_index: z.number().default(0).describe("Character offset for pagination. Default: 0."),
1189
- max_length: z
1190
- .number()
1191
- .default(10000)
1192
- .describe("Maximum characters to return per request. Default is 10000."),
1193
- block_media: z
1194
- .boolean()
1195
- .default(true)
1196
- .describe(
1197
- "Block images, videos, and fonts entirely at the network layer. Default is true.",
1198
- ),
1199
- }),
1200
- },
1201
- async ({ url, template: templateParam, start_index, max_length, block_media }) => {
1202
- try {
1203
- // 1. Resolve template
1204
- let template;
1205
-
1206
- if (templateParam.startsWith("{")) {
1207
- try {
1208
- template = JSON.parse(templateParam);
1209
- } catch (e) {
1210
- throw new Error(`Invalid inline JSON template: ${e.message}`);
1211
- }
1212
- } else if (templateParam === "auto") {
1213
- template = detectTemplateByUrl(url);
1214
- } else {
1215
- template = getTemplateByName(templateParam);
1216
- }
1217
-
1218
- // 2. Try source markdown if template specifies source_url
1219
- let sourceMd = null;
1220
- if (template && template.source_url) {
1221
- const sourceUrl = resolveSourceUrl(template.source_url, url);
1222
- sourceMd = await fetchSourceMarkdown(sourceUrl, template, block_media);
1223
- }
1224
-
1225
- if (sourceMd !== null) {
1226
- const totalLength = sourceMd.length;
1227
- const paginated = sourceMd.substring(start_index, start_index + max_length);
1228
- let metadata =
1229
- `\n\n---\n[webfetch: template="${template ? template.name : "auto"}" (source markdown), ` +
1230
- `showing characters ${start_index} to ${start_index + paginated.length} of ${totalLength} total.`;
1231
- if (start_index + max_length < totalLength) {
1232
- metadata += ` Use start_index=${start_index + max_length} to read more.`;
1233
- }
1234
- metadata += "]";
1235
- return { content: [{ type: "text", text: paginated + metadata }] };
1236
- }
1237
-
1238
- // 3. Fetch
1239
- const html = await fetchHtmlWithRetry(url, template, block_media);
1240
-
1241
- // 4. Extract and compose
1242
- const $ = cheerio.load(html);
1243
-
1244
- if (template) {
1245
- applyRemove($, template);
1246
-
1247
- const pageOrigin = new URL(url).origin;
1248
- const context = {
1249
- origin: pageOrigin,
1250
- isWebsearch: false,
1251
- };
1252
-
1253
- const extracted = extractTemplate($, template, context);
1254
- const result = composeSections(extracted, template, start_index, max_length);
1255
- return { content: [{ type: "text", text: result }] };
1256
- } else {
1257
- // Generic fallback
1258
- const result = genericFallback($, start_index, max_length);
1259
- return { content: [{ type: "text", text: result }] };
1260
- }
1261
- } catch (err) {
1262
- return {
1263
- content: [{ type: "text", text: `Fetch Error: ${err.message}` }],
1264
- isError: true,
1265
- };
1266
- }
1267
- },
1268
- );
1269
-
1270
- // === EXPORTS (for testing without starting server) =========================
1271
-
1272
- export {
1273
- loadBuiltinTemplates,
1274
- getTemplateByName,
1275
- detectTemplateByUrl,
1276
- resolveUrlTemplate,
1277
- resolveEngineToTemplateName,
1278
- mapSearchParams,
1279
- resolveSearchTemplate,
1280
- resolveSearchCandidates,
1281
- isMarkdownContent,
1282
- stripSourceMarkdown,
1283
- resolveSourceUrl,
1284
- parseRetryAfterMs,
1285
- isAccessDenied,
1286
- findScoped,
1287
- findFirstMatch,
1288
- resolveTopElements,
1289
- applyTransform,
1290
- extractValue,
1291
- extractChildSection,
1292
- extractSection,
1293
- extractTemplate,
1294
- composeSections,
1295
- composeSearchResults,
1296
- genericFallback,
1297
- isMainModule,
1298
- BUILTIN_TEMPLATES,
1299
- TEMPLATE_MAP,
1300
- };
1301
-
1302
- // === MAIN =================================================================
1303
-
1304
- function redirectStartupOutputToStderr() {
1305
- const originalStdoutWrite = process.stdout.write.bind(process.stdout);
1306
- const originalConsoleLog = console.log;
1307
- const originalConsoleInfo = console.info;
1308
-
1309
- process.stdout.write = (chunk, encoding, callback) => {
1310
- return process.stderr.write(chunk, encoding, callback);
1311
- };
1312
- console.log = (...args) => console.error(...args);
1313
- console.info = (...args) => console.error(...args);
1314
-
1315
- return () => {
1316
- process.stdout.write = originalStdoutWrite;
1317
- console.log = originalConsoleLog;
1318
- console.info = originalConsoleInfo;
1319
- };
1320
- }
1321
-
1322
- function isMainModule(argvPath = process.argv[1], modulePath = __filename) {
1323
- if (!argvPath) return false;
1324
- try {
1325
- return realpathSync(argvPath) === realpathSync(modulePath);
1326
- } catch {
1327
- return false;
1328
- }
1329
- }
1330
-
1331
- async function main() {
1332
- process.on("SIGINT", cleanup);
1333
- process.on("SIGTERM", cleanup);
1334
-
1335
- const restoreStdout = redirectStartupOutputToStderr();
1336
- await ensureBinary();
1337
- restoreStdout();
1338
- const transport = new StdioServerTransport();
1339
- await server.connect(transport);
1340
- }
1341
-
1342
- // Guard: only start server when run directly (including via npm bin symlink),
1343
- // not when imported. Uses realpath so that `npx` / `node_modules/.bin`
1344
- // symlinks resolve to the module file correctly.
1345
- const isMain = isMainModule();
1346
- if (isMain) {
1347
- main().catch((_err) => {
1348
- process.exit(1);
1349
- });
1350
- }