searchfetch 3.0.1 → 3.2.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/README.md CHANGED
@@ -1,23 +1,25 @@
1
1
  # SearchFetch (MCP Server)
2
2
 
3
- A maximum fault-tolerant, stealth-enabled Model Context Protocol (MCP) server for web searching and content fetching. Built specifically for AI Agents (Cursor, Claude Code, OpenCode), it completely bypasses bot detection (Cloudflare Turnstile, Datadome), dynamically handles SPAs/React, and converts bloat into token-optimized Markdown.
3
+ A fault-tolerant, stealth-enabled Model Context Protocol (MCP) server for web searching and content fetching. Built for AI Agents (Cursor, Claude Code, OpenCode), it uses a stealth browser engine to fetch pages, dynamically handles SPAs/React, and converts bloat into token-optimized Markdown.
4
4
 
5
5
  ## Features
6
- * **Maximum Fault Tolerance:** Implements auto-healing browser sessions, grace-period timeouts for clunky SPAs, and network-level aborting of tracking scripts and media.
7
- * **Stealth Engine:** Powered by CloakBrowser C++ patches + `humanize` logic. Antibot systems score it as a normal browser because it mathematically moves and renders exactly like one.
8
- * **Nuclear Token Scrubber:** Strips Base64 images, SVGs, scripts, and inline styles out of the DOM *before* Markdown conversion, guaranteeing your LLM context window won't blow out.
9
- * **Dual Execution Paths:** Natively supports zero-install execution via both Python (`uvx`) and Node.js (`npx`).
6
+
7
+ - **Stealth Engine:** Powered by CloakBrowser C++ patches + `humanize` logic. The browser renders and moves like a real user, reducing bot-detection scores.
8
+ - **Fault Tolerance:** Auto-healing browser sessions, grace-period timeouts for SPAs, and network-level blocking of tracking scripts and media.
9
+ - **Token-Optimized Output:** Strips base64 images, SVGs, scripts, and inline styles from the DOM _before_ Markdown conversion.
10
+ - **Dual Runtime:** Natively supports zero-install execution via both Python (`uvx`) and Node.js (`npx`).
11
+ - **Template-Driven Extraction:** Structured extraction via shared JSON templates (GitHub, npm, PyPI, crates.io, docs pages, Docker Hub, and more). Supports custom inline templates.
10
12
 
11
13
  ---
12
14
 
13
15
  ## Usage & Installation
14
16
 
15
- You do not need to install this repository manually. Configure your agent to use the zero-install commands `npx` or `uvx` depending on your environment.
17
+ You do not need to install this repository manually. Configure your agent to use the zero-install commands `npx` or `uvx`.
16
18
 
17
19
  ### Claude Desktop Configuration
18
- Add the following to your config:
19
20
 
20
- **Option A: Using Python (`uvx` - Recommended)**
21
+ **Option A: Python (`uvx` - Recommended)**
22
+
21
23
  ```json
22
24
  {
23
25
  "mcpServers": {
@@ -29,7 +31,8 @@ Add the following to your config:
29
31
  }
30
32
  ```
31
33
 
32
- **Option B: Using Node.js (`npx`)**
34
+ **Option B: Node.js (`npx`)**
35
+
33
36
  ```json
34
37
  {
35
38
  "mcpServers": {
@@ -42,55 +45,75 @@ Add the following to your config:
42
45
  ```
43
46
 
44
47
  ### Cursor / IDE Configuration
45
- Add it via the **MCP panel** in Cursor settings:
46
- * **Type:** `command`
47
- * **Command:** `uvx searchfetch` (or `npx -y searchfetch`)
48
+
49
+ Add via the **MCP panel** in Cursor settings:
50
+
51
+ - **Type:** `command`
52
+ - **Command:** `uvx searchfetch` (or `npx -y searchfetch`)
48
53
 
49
54
  ---
50
55
 
51
56
  ## Available Tools
52
57
 
53
58
  ### 1. `websearch`
54
- Searches the web through the v3 template pipeline. DuckDuckGo and Google are built-in templates, and custom search templates can be selected by name.
55
-
56
- **Parameters:**
57
- * **`query`** *(string, required)*: The search query string.
58
- * **`engine`** *(string, optional)*: Search engine/template to use. Can be `"duckduckgo"`, `"google"`, or a custom search template name. Default is `"duckduckgo"`.
59
- * **`max_results`** *(number, optional)*: Maximum number of results to return. Default is `10`.
60
- * **`region`** *(string/null, optional)*: Region and language code to localize search results.
61
- * Examples: `"us-en"`, `"uk-en"`, `"de-de"`.
62
- * For DuckDuckGo, it maps directly.
63
- * For Google, it maps to the `gl` (country) and `hl` (language) query parameters automatically.
64
- * `null` uses the template default.
65
- * **`safe_search`** *(boolean/null, optional)*: Enable safe search. Maps to DuckDuckGo/Google parameters automatically; `null` uses the template default.
66
- * **`block_media`** *(boolean, optional)*: Block images, media, and fonts at the network layer. Default is `true`.
59
+
60
+ Search the web through the template pipeline. DuckDuckGo and Google are built-in; custom search templates can be selected by name.
61
+
62
+ | Parameter | Type | Default | Description |
63
+ | ------------- | ------------ | -------------- | ---------------------------------------------------------------------------------------------- |
64
+ | `query` | string | _required_ | The search query string. |
65
+ | `engine` | string | `"duckduckgo"` | `"duckduckgo"`, `"google"`, or a custom search template name. |
66
+ | `max_results` | number | `10` | Maximum number of results to return. |
67
+ | `region` | string/null | `null` | Region/language code (e.g. `"us-en"`, `"de-de"`). DDG maps directly; Google maps to `gl`/`hl`. |
68
+ | `safe_search` | boolean/null | `null` | Enable safe search. `null` uses the template default. |
69
+ | `block_media` | boolean | `true` | Block images, media, and fonts at the network layer. |
67
70
 
68
71
  ### 2. `webfetch`
69
- Fetches a page with CloakBrowser and extracts structured Markdown using a named, inline, or auto-detected template. Built-ins include GitHub repositories/issues, npm, PyPI, crates.io, and ReadTheDocs-style docs pages. Unknown pages fall back to generic Markdown extraction.
70
72
 
71
- **Parameters:**
72
- * **`url`** *(string, required)*: The full URL of the webpage to fetch (must start with http/https).
73
- * **`template`** *(string, optional)*: `"auto"`, a built-in template name, or inline JSON template. Default is `"auto"`.
74
- * **`start_index`** *(number, optional)*: Character offset to start reading from for pagination. Use this if a document is too large to fit in the context window. Default is `0`.
75
- * **`max_length`** *(number, optional)*: Maximum characters to return per request. Default is `10000`.
76
- * **`block_media`** *(boolean, optional)*: Block images, videos, and fonts entirely at the network layer to drastically speed up page loads and dodge tracking pixels. Default is `true`.
73
+ Fetch a page with the stealth browser and extract structured Markdown using a template. Falls back to generic Markdown extraction for unknown pages.
77
74
 
78
- Template extraction supports `text`, `markdown`, `attribute`, and `html` sections; nested children; repeated sections; URL decoding transforms; per-template cookies; and per-template resource blocking.
75
+ | Parameter | Type | Default | Description |
76
+ | ------------- | ------- | ---------- | ----------------------------------------------------- |
77
+ | `url` | string | _required_ | Full URL (must start with `http`/`https`). |
78
+ | `template` | string | `"auto"` | `"auto"`, a built-in name, or inline JSON template. |
79
+ | `start_index` | number | `0` | Character offset for pagination. |
80
+ | `max_length` | number | `10000` | Maximum characters per request. |
81
+ | `block_media` | boolean | `true` | Block images, videos, and fonts at the network layer. |
79
82
 
80
- Built-in templates live in `templates/*.json` and are shared by the Node.js and Python implementations. Each JSON file defines exactly one template — no duplication between languages.
83
+ Template extraction supports `text`, `markdown`, `attribute`, and `html` formats; nested children; repeated sections; URL-decoding transforms; per-template cookies; and per-template resource blocking.
84
+
85
+ Built-in templates live in `templates/*.json` and are shared by the Node.js and Python implementations.
81
86
 
82
87
  ---
83
88
 
84
- ## Architecture & Contributions
85
- This repository utilizes a flat dual-manifest file structure (`package.json` and `pyproject.toml` in the root). When committing changes, ensure parity between `index.js` and `server.py` logic.
89
+ ## Local Development
86
90
 
87
- ### Local Development
88
91
  ```bash
89
- # Node.js Testing
90
- npm i
91
- npm run inspector-js
92
-
93
- # Python Testing
94
- pip install -e .
95
- npm run inspector-py
92
+ # Install dependencies
93
+ npm install
94
+ pip install -e ".[dev]"
95
+
96
+ # Run tests
97
+ npm test # runs all tests (JS + Python)
98
+ npm run test:js # Node.js unit tests (built-in test runner)
99
+ npm run test:py # Python unit tests (pytest)
100
+
101
+ # Lint
102
+ npm run lint # runs all linters
103
+ npm run lint:js # ESLint
104
+ npm run lint:py # Ruff
105
+
106
+ # Format
107
+ npm run format # auto-format all source files
108
+ npm run format:check # check formatting without changes
109
+
110
+ # MCP inspector (for manual testing)
111
+ npm run inspector-js # test with MCP Inspector (Node.js)
112
+ npm run inspector-py # test with MCP Inspector (Python)
96
113
  ```
114
+
115
+ ---
116
+
117
+ ## Architecture
118
+
119
+ This repository uses a flat dual-manifest structure (`package.json` and `pyproject.toml` in the root). Both runtimes (`index.js` for Node, `server.py` for Python) share the same `templates/*.json` files and maintain feature parity.
package/index.js CHANGED
@@ -1,13 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // === STDOUT/STDERR REDIRECTION ===========================================
4
- const originalStdoutWrite = process.stdout.write.bind(process.stdout);
5
- process.stdout.write = (chunk, encoding, callback) => {
6
- return process.stderr.write(chunk, encoding, callback);
7
- };
8
- console.log = (...args) => console.error(...args);
9
- console.info = (...args) => console.error(...args);
10
-
11
3
  // === IMPORTS =============================================================
12
4
  import { readdirSync, readFileSync } from "node:fs";
13
5
  import { dirname, join } from "node:path";
@@ -70,8 +62,6 @@ const cleanup = async () => {
70
62
  await browserManager.close();
71
63
  process.exit(0);
72
64
  };
73
- process.on("SIGINT", cleanup);
74
- process.on("SIGTERM", cleanup);
75
65
 
76
66
  // === TURNDOWN ============================================================
77
67
  const turndown = new TurndownService({
@@ -91,19 +81,13 @@ function loadBuiltinTemplates() {
91
81
  try {
92
82
  files = readdirSync(TEMPLATES_DIR);
93
83
  } catch (err) {
94
- throw new Error(
95
- `Cannot read templates directory '${TEMPLATES_DIR}': ${err.message}`,
96
- );
84
+ throw new Error(`Cannot read templates directory '${TEMPLATES_DIR}': ${err.message}`);
97
85
  }
98
86
 
99
- const jsonFiles = files
100
- .filter((f) => f.endsWith(".json"))
101
- .sort();
87
+ const jsonFiles = files.filter((f) => f.endsWith(".json")).sort();
102
88
 
103
89
  if (jsonFiles.length === 0) {
104
- throw new Error(
105
- `No template JSON files found in '${TEMPLATES_DIR}'`,
106
- );
90
+ throw new Error(`No template JSON files found in '${TEMPLATES_DIR}'`);
107
91
  }
108
92
 
109
93
  const templates = [];
@@ -114,14 +98,10 @@ function loadBuiltinTemplates() {
114
98
  try {
115
99
  template = JSON.parse(content);
116
100
  } catch (err) {
117
- throw new Error(
118
- `Invalid JSON in template file '${filePath}': ${err.message}`,
119
- );
101
+ throw new Error(`Invalid JSON in template file '${filePath}': ${err.message}`);
120
102
  }
121
103
  if (!template.name || typeof template.name !== "string") {
122
- throw new Error(
123
- `Template file '${filePath}' is missing a valid "name" field`,
124
- );
104
+ throw new Error(`Template file '${filePath}' is missing a valid "name" field`);
125
105
  }
126
106
  templates.push(template);
127
107
  }
@@ -144,9 +124,7 @@ function getTemplateByName(name) {
144
124
  const t = TEMPLATE_MAP.get(name);
145
125
  if (!t) {
146
126
  const names = [...TEMPLATE_MAP.keys()].join(", ");
147
- throw new Error(
148
- `Unknown template '${name}'. Available: ${names}`,
149
- );
127
+ throw new Error(`Unknown template '${name}'. Available: ${names}`);
150
128
  }
151
129
  return t;
152
130
  }
@@ -159,8 +137,9 @@ function detectTemplateByUrl(url) {
159
137
  if (new RegExp(pattern).test(url)) {
160
138
  return template;
161
139
  }
162
- } catch (_) {
163
- // Skip invalid regex
140
+ } catch (_invalidRegex) {
141
+ // Invalid URL patterns are tolerated — templates may contain
142
+ // broad patterns that don't compile correctly in every context.
164
143
  }
165
144
  }
166
145
  }
@@ -205,7 +184,10 @@ function resolveUrlTemplate(template, providedParams) {
205
184
  }
206
185
 
207
186
  // Remove any remaining unreplaced placeholders
208
- url = url.replace(/\{\w+\}/g, "").replace(/&{2,}/g, "&").replace(/\?&/, "?");
187
+ url = url
188
+ .replace(/\{\w+\}/g, "")
189
+ .replace(/&{2,}/g, "&")
190
+ .replace(/\?&/, "?");
209
191
 
210
192
  return url;
211
193
  }
@@ -301,7 +283,8 @@ function isAccessDenied($) {
301
283
  "access denied",
302
284
  ];
303
285
 
304
- if (bodyText.length < 1200 && bodyDenyPatterns.some((pattern) => bodyText.includes(pattern))) return true;
286
+ if (bodyText.length < 1200 && bodyDenyPatterns.some((pattern) => bodyText.includes(pattern)))
287
+ return true;
305
288
 
306
289
  return false;
307
290
  }
@@ -386,10 +369,7 @@ async function fetchHtmlWithRetry(url, template, blockMedia) {
386
369
  return await fetchHtml(url, template, blockMedia);
387
370
  } catch (err) {
388
371
  lastError = err;
389
- if (
390
- attempt < FETCH_MAX_ATTEMPTS - 1 &&
391
- err.httpStatus === 429
392
- ) {
372
+ if (attempt < FETCH_MAX_ATTEMPTS - 1 && err.httpStatus === 429) {
393
373
  await sleep(err.retryAfterMs ?? HTTP_429_RETRY_DELAY_MS);
394
374
  continue;
395
375
  }
@@ -408,10 +388,110 @@ async function fetchHtmlWithRetry(url, template, blockMedia) {
408
388
  throw lastError;
409
389
  }
410
390
 
391
+ // === SOURCE MARKDOWN DETECTION ===========================================
392
+
393
+ function isMarkdownContent(text) {
394
+ if (!text) return false;
395
+ const htmlTagCount = (text.match(/<\w+[^>]*>/g) || []).length;
396
+ if (htmlTagCount > 3) return false;
397
+ const patterns = [
398
+ /^#{1,6}\s+\S/m,
399
+ /\[.+?\]\(.+?\)/,
400
+ /```\w*\n/,
401
+ /^\s*[-*+]\s+\S/m,
402
+ /\*\*[^*]+\*\*/,
403
+ /^>\s+\S/m,
404
+ ];
405
+ for (const pat of patterns) {
406
+ if (pat.test(text)) return true;
407
+ }
408
+ return false;
409
+ }
410
+
411
+ function stripSourceMarkdown(content) {
412
+ return content
413
+ .replace(/^@twoslash-cache:.*$/gm, "")
414
+ .replace(/\n{3,}/g, "\n\n")
415
+ .trim();
416
+ }
417
+
418
+ function resolveSourceUrl(sourceTemplate, url) {
419
+ if (sourceTemplate === "{url}.md") {
420
+ return `${url.replace(/\/+$/, "")}.md`;
421
+ }
422
+ return sourceTemplate.replace("{url}", url);
423
+ }
424
+
425
+ async function fetchSourceMarkdown(sourceUrl, template, blockMedia) {
426
+ const browser = await browserManager.getBrowser();
427
+ const context = await browser.newContext();
428
+
429
+ try {
430
+ if (template && template.cookies && template.cookies.length > 0) {
431
+ await context.addCookies(template.cookies);
432
+ }
433
+
434
+ const page = await context.newPage();
435
+ try {
436
+ if (blockMedia) {
437
+ const blockedTypes =
438
+ template && template.block_resources
439
+ ? template.block_resources
440
+ : ["image", "media", "font"];
441
+ if (blockedTypes.length > 0) {
442
+ await page.route("**/*", (route) => {
443
+ const type = route.request().resourceType();
444
+ if (blockedTypes.includes(type)) route.abort();
445
+ else route.continue();
446
+ });
447
+ }
448
+ }
449
+
450
+ let response;
451
+ try {
452
+ response = await page.goto(sourceUrl, {
453
+ waitUntil: "domcontentloaded",
454
+ timeout: 10000,
455
+ });
456
+ } catch (_) {
457
+ return null;
458
+ }
459
+
460
+ if (response && response.status() >= 400) return null;
461
+
462
+ let text;
463
+ try {
464
+ text = await page.evaluate(
465
+ "() => document.body?.innerText || document.body?.textContent || ''",
466
+ );
467
+ } catch (_) {
468
+ text = await page.content();
469
+ }
470
+
471
+ if (!text || typeof text !== "string") return null;
472
+
473
+ text = stripSourceMarkdown(text.trim());
474
+ return isMarkdownContent(text) ? text : null;
475
+ } finally {
476
+ await page.close();
477
+ }
478
+ } catch (_) {
479
+ return null;
480
+ } finally {
481
+ await context.close();
482
+ }
483
+ }
484
+
411
485
  // === HTML CLEANUP ========================================================
412
486
 
413
487
  const DEFAULT_REMOVE_SELECTORS = [
414
- "script", "style", "svg", "nav", "footer", "noscript", "iframe",
488
+ "script",
489
+ "style",
490
+ "svg",
491
+ "nav",
492
+ "footer",
493
+ "noscript",
494
+ "iframe",
415
495
  ".advertisement",
416
496
  ];
417
497
 
@@ -424,8 +504,9 @@ function applyRemove($, template) {
424
504
  for (const selector of removeSelectors) {
425
505
  try {
426
506
  $(selector).remove();
427
- } catch (_) {
428
- // Skip invalid selectors
507
+ } catch (_invalidSelector) {
508
+ // Invalid remove selectors are tolerated — templates can express
509
+ // broad cleanup rules that don't apply to every page.
429
510
  }
430
511
  }
431
512
 
@@ -622,9 +703,7 @@ function extractChildSection($, $parentEl, section, origin) {
622
703
 
623
704
  if (!elements || elements.length === 0) {
624
705
  if (section.required) {
625
- throw new Error(
626
- `Required section '${section.name}' not found on page.`,
627
- );
706
+ throw new Error(`Required section '${section.name}' not found on page.`);
628
707
  }
629
708
  return null;
630
709
  }
@@ -643,9 +722,7 @@ function extractSection($, section, context) {
643
722
 
644
723
  if (!elements || elements.length === 0) {
645
724
  if (section.required) {
646
- throw new Error(
647
- `Required section '${section.name}' not found on page.`,
648
- );
725
+ throw new Error(`Required section '${section.name}' not found on page.`);
649
726
  }
650
727
  return null;
651
728
  }
@@ -731,13 +808,13 @@ function extractTemplate($, template, context) {
731
808
  results.push(result);
732
809
  }
733
810
  } catch (err) {
734
- if (
735
- err.message &&
736
- err.message.includes("Required section")
737
- ) {
811
+ // Required-section errors must surface to the user.
812
+ if (err.message && err.message.includes("Required section")) {
738
813
  throw err;
739
814
  }
740
- // Non-required failures are silently skipped
815
+ // Non-required extraction failures: selector mismatches or format
816
+ // processing issues. Broad templates legitimately don't match every
817
+ // section on every page — skip and continue.
741
818
  }
742
819
  }
743
820
 
@@ -783,8 +860,7 @@ function composeSections(extracted, template, startIndex, maxLength) {
783
860
  if (isCommentStyle(result)) {
784
861
  const commentParts = [];
785
862
  for (const item of result.items) {
786
- const author =
787
- item["Author"] || item["author"] || item["User"] || item["user"] || "";
863
+ const author = item["Author"] || item["author"] || item["User"] || item["user"] || "";
788
864
  const comment =
789
865
  item["Comment"] || item["Body"] || item["comment"] || item["body"] || "";
790
866
  if (author) {
@@ -794,9 +870,7 @@ function composeSections(extracted, template, startIndex, maxLength) {
794
870
  }
795
871
  }
796
872
  if (commentParts.length > 0) {
797
- parts.push(
798
- `## ${result.section.name}\n\n${commentParts.join("\n\n---\n\n")}`,
799
- );
873
+ parts.push(`## ${result.section.name}\n\n${commentParts.join("\n\n---\n\n")}`);
800
874
  }
801
875
  } else {
802
876
  const itemParts = [];
@@ -810,9 +884,7 @@ function composeSections(extracted, template, startIndex, maxLength) {
810
884
  if (lines.length > 0) itemParts.push(lines.join("\n"));
811
885
  }
812
886
  if (itemParts.length > 0) {
813
- parts.push(
814
- `## ${result.section.name}\n\n${itemParts.join("\n\n")}`,
815
- );
887
+ parts.push(`## ${result.section.name}\n\n${itemParts.join("\n\n")}`);
816
888
  }
817
889
  }
818
890
  }
@@ -855,12 +927,9 @@ function composeSearchResults(extracted) {
855
927
  const item = items[i];
856
928
  const num = i + 1;
857
929
 
858
- const title =
859
- item["Title"] || item["title"] || Object.values(item)[0] || "";
860
- const url =
861
- item["URL"] || item["url"] || item["Url"] || "";
862
- const snippet =
863
- item["Snippet"] || item["snippet"] || "";
930
+ const title = item["Title"] || item["title"] || Object.values(item)[0] || "";
931
+ const url = item["URL"] || item["url"] || item["Url"] || "";
932
+ const snippet = item["Snippet"] || item["snippet"] || "";
864
933
 
865
934
  // Filter out non-http URLs and google internal links
866
935
  let cleanUrl = url;
@@ -869,8 +938,7 @@ function composeSearchResults(extracted) {
869
938
  }
870
939
  if (
871
940
  cleanUrl &&
872
- (cleanUrl.includes("google.com/search") ||
873
- cleanUrl.includes("support.google.com"))
941
+ (cleanUrl.includes("google.com/search") || cleanUrl.includes("support.google.com"))
874
942
  ) {
875
943
  cleanUrl = ""; // Skip google internal links
876
944
  }
@@ -935,19 +1003,14 @@ function resolveSearchTemplate(engine, query, region, safeSearch) {
935
1003
  }
936
1004
 
937
1005
  if (!template.url_template) {
938
- throw new Error(
939
- `Template '${template.name}' is not a search template (no url_template).`,
940
- );
1006
+ throw new Error(`Template '${template.name}' is not a search template (no url_template).`);
941
1007
  }
942
1008
 
943
1009
  const params = mapSearchParams(engine, query, region, safeSearch);
944
1010
  let url = resolveUrlTemplate(template, params);
945
1011
 
946
1012
  // Google safe_search: append safe=active to URL
947
- if (
948
- (engine === "google" || templateName === "google-search") &&
949
- safeSearch === true
950
- ) {
1013
+ if ((engine === "google" || templateName === "google-search") && safeSearch === true) {
951
1014
  url += "&safe=active";
952
1015
  }
953
1016
 
@@ -956,7 +1019,7 @@ function resolveSearchTemplate(engine, query, region, safeSearch) {
956
1019
 
957
1020
  // === MCP SERVER & TOOLS ==================================================
958
1021
 
959
- const server = new McpServer({ name: "searchfetch", version: "3.0.1" });
1022
+ const server = new McpServer({ name: "searchfetch", version: "3.2.0" });
960
1023
 
961
1024
  // --- websearch tool ---
962
1025
 
@@ -1003,12 +1066,7 @@ server.registerTool(
1003
1066
  async ({ query, engine, region, safe_search, max_results, block_media }) => {
1004
1067
  try {
1005
1068
  // 1. Resolve search template (+ url_params mapping + url building)
1006
- const { template, url } = resolveSearchTemplate(
1007
- engine,
1008
- query,
1009
- region,
1010
- safe_search,
1011
- );
1069
+ const { template, url } = resolveSearchTemplate(engine, query, region, safe_search);
1012
1070
 
1013
1071
  // 2. Fetch
1014
1072
  const html = await fetchHtmlWithRetry(url, template, block_media);
@@ -1049,27 +1107,20 @@ server.registerTool(
1049
1107
  description:
1050
1108
  "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.",
1051
1109
  inputSchema: z.object({
1052
- url: z.string().describe(
1053
- "The full URL of the webpage to fetch (must start with http/https).",
1054
- ),
1110
+ url: z
1111
+ .string()
1112
+ .describe("The full URL of the webpage to fetch (must start with http/https)."),
1055
1113
  template: z
1056
1114
  .string()
1057
1115
  .default("auto")
1058
1116
  .describe(
1059
1117
  "Template to use: 'auto' (auto-detect from URL), a built-in name, or inline JSON.",
1060
1118
  ),
1061
- start_index: z
1062
- .number()
1063
- .default(0)
1064
- .describe(
1065
- "Character offset for pagination. Default: 0.",
1066
- ),
1119
+ start_index: z.number().default(0).describe("Character offset for pagination. Default: 0."),
1067
1120
  max_length: z
1068
1121
  .number()
1069
1122
  .default(10000)
1070
- .describe(
1071
- "Maximum characters to return per request. Default is 10000.",
1072
- ),
1123
+ .describe("Maximum characters to return per request. Default is 10000."),
1073
1124
  block_media: z
1074
1125
  .boolean()
1075
1126
  .default(true)
@@ -1095,10 +1146,30 @@ server.registerTool(
1095
1146
  template = getTemplateByName(templateParam);
1096
1147
  }
1097
1148
 
1098
- // 2. Fetch
1149
+ // 2. Try source markdown if template specifies source_url
1150
+ let sourceMd = null;
1151
+ if (template && template.source_url) {
1152
+ const sourceUrl = resolveSourceUrl(template.source_url, url);
1153
+ sourceMd = await fetchSourceMarkdown(sourceUrl, template, block_media);
1154
+ }
1155
+
1156
+ if (sourceMd !== null) {
1157
+ const totalLength = sourceMd.length;
1158
+ const paginated = sourceMd.substring(start_index, start_index + max_length);
1159
+ let metadata =
1160
+ `\n\n---\n[webfetch: template="${template ? template.name : "auto"}" (source markdown), ` +
1161
+ `showing characters ${start_index} to ${start_index + paginated.length} of ${totalLength} total.`;
1162
+ if (start_index + max_length < totalLength) {
1163
+ metadata += ` Use start_index=${start_index + max_length} to read more.`;
1164
+ }
1165
+ metadata += "]";
1166
+ return { content: [{ type: "text", text: paginated + metadata }] };
1167
+ }
1168
+
1169
+ // 3. Fetch
1099
1170
  const html = await fetchHtmlWithRetry(url, template, block_media);
1100
1171
 
1101
- // 3. Extract and compose
1172
+ // 4. Extract and compose
1102
1173
  const $ = cheerio.load(html);
1103
1174
 
1104
1175
  if (template) {
@@ -1127,15 +1198,71 @@ server.registerTool(
1127
1198
  },
1128
1199
  );
1129
1200
 
1201
+ // === EXPORTS (for testing without starting server) =========================
1202
+
1203
+ export {
1204
+ loadBuiltinTemplates,
1205
+ getTemplateByName,
1206
+ detectTemplateByUrl,
1207
+ resolveUrlTemplate,
1208
+ resolveEngineToTemplateName,
1209
+ mapSearchParams,
1210
+ resolveSearchTemplate,
1211
+ isMarkdownContent,
1212
+ stripSourceMarkdown,
1213
+ resolveSourceUrl,
1214
+ parseRetryAfterMs,
1215
+ isAccessDenied,
1216
+ findScoped,
1217
+ findFirstMatch,
1218
+ resolveTopElements,
1219
+ applyTransform,
1220
+ extractValue,
1221
+ extractChildSection,
1222
+ extractSection,
1223
+ extractTemplate,
1224
+ composeSections,
1225
+ composeSearchResults,
1226
+ genericFallback,
1227
+ BUILTIN_TEMPLATES,
1228
+ TEMPLATE_MAP,
1229
+ };
1230
+
1130
1231
  // === MAIN =================================================================
1131
1232
 
1233
+ function redirectStartupOutputToStderr() {
1234
+ const originalStdoutWrite = process.stdout.write.bind(process.stdout);
1235
+ const originalConsoleLog = console.log;
1236
+ const originalConsoleInfo = console.info;
1237
+
1238
+ process.stdout.write = (chunk, encoding, callback) => {
1239
+ return process.stderr.write(chunk, encoding, callback);
1240
+ };
1241
+ console.log = (...args) => console.error(...args);
1242
+ console.info = (...args) => console.error(...args);
1243
+
1244
+ return () => {
1245
+ process.stdout.write = originalStdoutWrite;
1246
+ console.log = originalConsoleLog;
1247
+ console.info = originalConsoleInfo;
1248
+ };
1249
+ }
1250
+
1132
1251
  async function main() {
1252
+ process.on("SIGINT", cleanup);
1253
+ process.on("SIGTERM", cleanup);
1254
+
1255
+ const restoreStdout = redirectStartupOutputToStderr();
1133
1256
  await ensureBinary();
1134
- process.stdout.write = originalStdoutWrite;
1257
+ restoreStdout();
1135
1258
  const transport = new StdioServerTransport();
1136
1259
  await server.connect(transport);
1137
1260
  }
1138
1261
 
1139
- main().catch((err) => {
1140
- process.exit(1);
1141
- });
1262
+ // Guard: only start server when run directly, not when imported
1263
+ const isMain = process.argv[1] === __filename;
1264
+ if (isMain) {
1265
+ main().catch((_err) => {
1266
+ process.exit(1);
1267
+ });
1268
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "searchfetch",
3
- "version": "3.0.1",
3
+ "version": "3.2.0",
4
4
  "description": "Fault-tolerant MCP Server for Stealth Web Search and Fetching",
5
5
  "type": "module",
6
6
  "bin": {
@@ -20,14 +20,27 @@
20
20
  "scripts": {
21
21
  "start": "node ./index.js",
22
22
  "inspector-js": "npx @modelcontextprotocol/inspector node ./index.js",
23
- "inspector-py": "npx @modelcontextprotocol/inspector uv run python ./server.py"
23
+ "inspector-py": "npx @modelcontextprotocol/inspector uv run python ./server.py",
24
+ "test": "npm run test:js && npm run test:py",
25
+ "test:js": "node --test \"*.test.js\"",
26
+ "test:py": "uv run pytest test_*.py -v",
27
+ "lint": "npm run lint:js && npm run lint:py",
28
+ "lint:js": "npx eslint \"*.js\"",
29
+ "lint:py": "uv run ruff check server.py test_*.py",
30
+ "format": "npx prettier --write \"*.js\" \"*.json\" \"*.md\" && uv run ruff format server.py test_*.py",
31
+ "format:check": "npx prettier --check \"*.js\" \"*.json\" \"*.md\" && uv run ruff format --check server.py test_*.py",
32
+ "e2e": "npm run test"
24
33
  },
25
34
  "dependencies": {
26
35
  "@modelcontextprotocol/sdk": "^1.29.0",
27
36
  "cheerio": "^1.2.0",
28
- "cloakbrowser": "^0.3.31",
29
- "playwright-core": "^1.60.0",
37
+ "cloakbrowser": "^0.4.5",
38
+ "playwright-core": "^1.61.1",
30
39
  "turndown": "^7.2.4",
31
40
  "zod": "^4.4.3"
41
+ },
42
+ "devDependencies": {
43
+ "eslint": "^10.6.0",
44
+ "prettier": "^3.9.4"
32
45
  }
33
46
  }
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "docker-hub",
3
+ "description": "Docker Hub image page — official and community images with description and README",
4
+ "order": 10,
5
+ "url_patterns": [
6
+ "^https?://hub\\.docker\\.com/_/[^/]+/?$",
7
+ "^https?://hub\\.docker\\.com/r/[^/]+/[^/]+/?$"
8
+ ],
9
+ "remove": [
10
+ "script",
11
+ "style",
12
+ "svg",
13
+ "nav",
14
+ "footer",
15
+ "header",
16
+ ".styles_sidebar__",
17
+ ".styles_chatbot__",
18
+ "[data-testid='chatbot']"
19
+ ],
20
+ "sections": [
21
+ {
22
+ "name": "Image",
23
+ "selector": "h1",
24
+ "format": "text",
25
+ "required": false
26
+ },
27
+ {
28
+ "name": "Description",
29
+ "selector": "meta[name='description']",
30
+ "format": "attribute",
31
+ "attribute": "content",
32
+ "required": false
33
+ },
34
+ {
35
+ "name": "Content",
36
+ "selector": "#readme-more-content-wrapper, article, [data-testid='description'], main, .MuiContainer-root",
37
+ "format": "markdown",
38
+ "required": false
39
+ }
40
+ ]
41
+ }
@@ -1,29 +1,40 @@
1
1
  {
2
2
  "name": "docs-page",
3
- "description": "Documentation page (ReadTheDocs, Sphinx, etc.)",
4
- "order": 8,
3
+ "description": "Documentation page (ReadTheDocs, Sphinx, Mintlify, VitePress, Docusaurus, Nextra, etc.)",
4
+ "order": 9,
5
5
  "url_patterns": [
6
6
  "^https?://[^/]+\\.readthedocs\\.io/.*",
7
- "^https?://[^/]+\\.rtfd\\.io/.*"
7
+ "^https?://[^/]+\\.rtfd\\.io/.*",
8
+ "^https?://docs\\.mintlify\\.com/.*",
9
+ "^https?://[^/]+\\.mintlify\\.(?:com|app|dev)/.*",
10
+ "^https?://[^/]+/docs(?:/.*)?$",
11
+ "^https?://[^/]+/doc(?:/.*)?$",
12
+ "^https?://docs\\.[^/]+\\.[^/]+/.*"
8
13
  ],
14
+ "source_url": "{url}.md",
9
15
  "remove": [
10
16
  "script",
11
17
  "style",
12
18
  "svg",
13
19
  "nav",
14
20
  "footer",
15
- ".sphinxsidebar"
21
+ ".sphinxsidebar",
22
+ ".sidebar",
23
+ "aside",
24
+ ".nextra-toc",
25
+ ".table-of-contents",
26
+ ".pagination-nav"
16
27
  ],
17
28
  "sections": [
18
29
  {
19
30
  "name": "Title",
20
- "selector": "h1",
31
+ "selector": "h1, h2",
21
32
  "format": "text",
22
33
  "required": false
23
34
  },
24
35
  {
25
36
  "name": "Content",
26
- "selector": "[role='main'], .document, .rst-content, article",
37
+ "selector": "[role='main'], .document, .rst-content, article, .content, .markdown-body, .prose, main, .nextra-content, .doc-content",
27
38
  "format": "markdown",
28
39
  "required": false
29
40
  }
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "docs-rs",
3
+ "description": "docs.rs rustdoc documentation page — crate docs, struct/enum/fn items",
4
+ "order": 6,
5
+ "url_patterns": [
6
+ "^https?://docs\\.rs/[^/]+/[^/]+/[^/]+/?$",
7
+ "^https?://docs\\.rs/[^/]+/[^/]+/[^/]+/index\\.html$",
8
+ "^https?://docs\\.rs/[^/]+/[^/]+/[^/]+/.+\\.html$"
9
+ ],
10
+ "remove": [
11
+ "script",
12
+ "style",
13
+ "svg",
14
+ "nav.sidebar",
15
+ "nav.sub",
16
+ "footer",
17
+ ".search-form",
18
+ ".rustdoc-version-dialog",
19
+ ".mobile-topbar",
20
+ ".out-of-band",
21
+ "#source-sidebar",
22
+ "#theme-picker",
23
+ "#settings-menu",
24
+ ".since",
25
+ ".srclink"
26
+ ],
27
+ "sections": [
28
+ {
29
+ "name": "Crate",
30
+ "selector": "h1.crate-title, .crate-title h1, .in-band .crate-name",
31
+ "format": "text",
32
+ "required": false
33
+ },
34
+ {
35
+ "name": "Title",
36
+ "selector": "h1.fqn, .in-band h1, h1",
37
+ "format": "text",
38
+ "required": false
39
+ },
40
+ {
41
+ "name": "Content",
42
+ "selector": "#main-content, main, .main, .docblock",
43
+ "format": "markdown",
44
+ "required": false
45
+ }
46
+ ]
47
+ }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "duckduckgo-search",
3
3
  "description": "DuckDuckGo HTML search results",
4
- "order": 7,
4
+ "order": 8,
5
5
  "url_patterns": [
6
6
  "^https?://html\\.duckduckgo\\.com/html/\\?"
7
7
  ],
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "google-search",
3
3
  "description": "Google web search results",
4
- "order": 6,
4
+ "order": 7,
5
5
  "url_patterns": [
6
6
  "^https?://(www\\.)?google\\.[^/]+/search\\?"
7
7
  ],