searchfetch 3.1.0 → 3.2.2
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 +67 -44
- package/index.js +123 -99
- package/package.json +18 -5
package/README.md
CHANGED
|
@@ -1,23 +1,25 @@
|
|
|
1
1
|
# SearchFetch (MCP Server)
|
|
2
2
|
|
|
3
|
-
A
|
|
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
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
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
|
|
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:
|
|
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:
|
|
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
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
##
|
|
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
|
-
#
|
|
90
|
-
npm
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
#
|
|
94
|
-
|
|
95
|
-
npm run
|
|
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,15 +1,7 @@
|
|
|
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
|
-
import { readdirSync, readFileSync } from "node:fs";
|
|
4
|
+
import { readdirSync, readFileSync, realpathSync } from "node:fs";
|
|
13
5
|
import { dirname, join } from "node:path";
|
|
14
6
|
import { fileURLToPath } from "node:url";
|
|
15
7
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
@@ -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
|
-
//
|
|
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
|
|
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)))
|
|
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
|
}
|
|
@@ -505,7 +485,13 @@ async function fetchSourceMarkdown(sourceUrl, template, blockMedia) {
|
|
|
505
485
|
// === HTML CLEANUP ========================================================
|
|
506
486
|
|
|
507
487
|
const DEFAULT_REMOVE_SELECTORS = [
|
|
508
|
-
"script",
|
|
488
|
+
"script",
|
|
489
|
+
"style",
|
|
490
|
+
"svg",
|
|
491
|
+
"nav",
|
|
492
|
+
"footer",
|
|
493
|
+
"noscript",
|
|
494
|
+
"iframe",
|
|
509
495
|
".advertisement",
|
|
510
496
|
];
|
|
511
497
|
|
|
@@ -518,8 +504,9 @@ function applyRemove($, template) {
|
|
|
518
504
|
for (const selector of removeSelectors) {
|
|
519
505
|
try {
|
|
520
506
|
$(selector).remove();
|
|
521
|
-
} catch (
|
|
522
|
-
//
|
|
507
|
+
} catch (_invalidSelector) {
|
|
508
|
+
// Invalid remove selectors are tolerated — templates can express
|
|
509
|
+
// broad cleanup rules that don't apply to every page.
|
|
523
510
|
}
|
|
524
511
|
}
|
|
525
512
|
|
|
@@ -716,9 +703,7 @@ function extractChildSection($, $parentEl, section, origin) {
|
|
|
716
703
|
|
|
717
704
|
if (!elements || elements.length === 0) {
|
|
718
705
|
if (section.required) {
|
|
719
|
-
throw new Error(
|
|
720
|
-
`Required section '${section.name}' not found on page.`,
|
|
721
|
-
);
|
|
706
|
+
throw new Error(`Required section '${section.name}' not found on page.`);
|
|
722
707
|
}
|
|
723
708
|
return null;
|
|
724
709
|
}
|
|
@@ -737,9 +722,7 @@ function extractSection($, section, context) {
|
|
|
737
722
|
|
|
738
723
|
if (!elements || elements.length === 0) {
|
|
739
724
|
if (section.required) {
|
|
740
|
-
throw new Error(
|
|
741
|
-
`Required section '${section.name}' not found on page.`,
|
|
742
|
-
);
|
|
725
|
+
throw new Error(`Required section '${section.name}' not found on page.`);
|
|
743
726
|
}
|
|
744
727
|
return null;
|
|
745
728
|
}
|
|
@@ -825,13 +808,13 @@ function extractTemplate($, template, context) {
|
|
|
825
808
|
results.push(result);
|
|
826
809
|
}
|
|
827
810
|
} catch (err) {
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
err.message.includes("Required section")
|
|
831
|
-
) {
|
|
811
|
+
// Required-section errors must surface to the user.
|
|
812
|
+
if (err.message && err.message.includes("Required section")) {
|
|
832
813
|
throw err;
|
|
833
814
|
}
|
|
834
|
-
// Non-required failures
|
|
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.
|
|
835
818
|
}
|
|
836
819
|
}
|
|
837
820
|
|
|
@@ -877,8 +860,7 @@ function composeSections(extracted, template, startIndex, maxLength) {
|
|
|
877
860
|
if (isCommentStyle(result)) {
|
|
878
861
|
const commentParts = [];
|
|
879
862
|
for (const item of result.items) {
|
|
880
|
-
const author =
|
|
881
|
-
item["Author"] || item["author"] || item["User"] || item["user"] || "";
|
|
863
|
+
const author = item["Author"] || item["author"] || item["User"] || item["user"] || "";
|
|
882
864
|
const comment =
|
|
883
865
|
item["Comment"] || item["Body"] || item["comment"] || item["body"] || "";
|
|
884
866
|
if (author) {
|
|
@@ -888,9 +870,7 @@ function composeSections(extracted, template, startIndex, maxLength) {
|
|
|
888
870
|
}
|
|
889
871
|
}
|
|
890
872
|
if (commentParts.length > 0) {
|
|
891
|
-
parts.push(
|
|
892
|
-
`## ${result.section.name}\n\n${commentParts.join("\n\n---\n\n")}`,
|
|
893
|
-
);
|
|
873
|
+
parts.push(`## ${result.section.name}\n\n${commentParts.join("\n\n---\n\n")}`);
|
|
894
874
|
}
|
|
895
875
|
} else {
|
|
896
876
|
const itemParts = [];
|
|
@@ -904,9 +884,7 @@ function composeSections(extracted, template, startIndex, maxLength) {
|
|
|
904
884
|
if (lines.length > 0) itemParts.push(lines.join("\n"));
|
|
905
885
|
}
|
|
906
886
|
if (itemParts.length > 0) {
|
|
907
|
-
parts.push(
|
|
908
|
-
`## ${result.section.name}\n\n${itemParts.join("\n\n")}`,
|
|
909
|
-
);
|
|
887
|
+
parts.push(`## ${result.section.name}\n\n${itemParts.join("\n\n")}`);
|
|
910
888
|
}
|
|
911
889
|
}
|
|
912
890
|
}
|
|
@@ -949,12 +927,9 @@ function composeSearchResults(extracted) {
|
|
|
949
927
|
const item = items[i];
|
|
950
928
|
const num = i + 1;
|
|
951
929
|
|
|
952
|
-
const title =
|
|
953
|
-
|
|
954
|
-
const
|
|
955
|
-
item["URL"] || item["url"] || item["Url"] || "";
|
|
956
|
-
const snippet =
|
|
957
|
-
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"] || "";
|
|
958
933
|
|
|
959
934
|
// Filter out non-http URLs and google internal links
|
|
960
935
|
let cleanUrl = url;
|
|
@@ -963,8 +938,7 @@ function composeSearchResults(extracted) {
|
|
|
963
938
|
}
|
|
964
939
|
if (
|
|
965
940
|
cleanUrl &&
|
|
966
|
-
(cleanUrl.includes("google.com/search") ||
|
|
967
|
-
cleanUrl.includes("support.google.com"))
|
|
941
|
+
(cleanUrl.includes("google.com/search") || cleanUrl.includes("support.google.com"))
|
|
968
942
|
) {
|
|
969
943
|
cleanUrl = ""; // Skip google internal links
|
|
970
944
|
}
|
|
@@ -1029,19 +1003,14 @@ function resolveSearchTemplate(engine, query, region, safeSearch) {
|
|
|
1029
1003
|
}
|
|
1030
1004
|
|
|
1031
1005
|
if (!template.url_template) {
|
|
1032
|
-
throw new Error(
|
|
1033
|
-
`Template '${template.name}' is not a search template (no url_template).`,
|
|
1034
|
-
);
|
|
1006
|
+
throw new Error(`Template '${template.name}' is not a search template (no url_template).`);
|
|
1035
1007
|
}
|
|
1036
1008
|
|
|
1037
1009
|
const params = mapSearchParams(engine, query, region, safeSearch);
|
|
1038
1010
|
let url = resolveUrlTemplate(template, params);
|
|
1039
1011
|
|
|
1040
1012
|
// Google safe_search: append safe=active to URL
|
|
1041
|
-
if (
|
|
1042
|
-
(engine === "google" || templateName === "google-search") &&
|
|
1043
|
-
safeSearch === true
|
|
1044
|
-
) {
|
|
1013
|
+
if ((engine === "google" || templateName === "google-search") && safeSearch === true) {
|
|
1045
1014
|
url += "&safe=active";
|
|
1046
1015
|
}
|
|
1047
1016
|
|
|
@@ -1050,7 +1019,7 @@ function resolveSearchTemplate(engine, query, region, safeSearch) {
|
|
|
1050
1019
|
|
|
1051
1020
|
// === MCP SERVER & TOOLS ==================================================
|
|
1052
1021
|
|
|
1053
|
-
const server = new McpServer({ name: "searchfetch", version: "3.
|
|
1022
|
+
const server = new McpServer({ name: "searchfetch", version: "3.2.2" });
|
|
1054
1023
|
|
|
1055
1024
|
// --- websearch tool ---
|
|
1056
1025
|
|
|
@@ -1097,12 +1066,7 @@ server.registerTool(
|
|
|
1097
1066
|
async ({ query, engine, region, safe_search, max_results, block_media }) => {
|
|
1098
1067
|
try {
|
|
1099
1068
|
// 1. Resolve search template (+ url_params mapping + url building)
|
|
1100
|
-
const { template, url } = resolveSearchTemplate(
|
|
1101
|
-
engine,
|
|
1102
|
-
query,
|
|
1103
|
-
region,
|
|
1104
|
-
safe_search,
|
|
1105
|
-
);
|
|
1069
|
+
const { template, url } = resolveSearchTemplate(engine, query, region, safe_search);
|
|
1106
1070
|
|
|
1107
1071
|
// 2. Fetch
|
|
1108
1072
|
const html = await fetchHtmlWithRetry(url, template, block_media);
|
|
@@ -1143,27 +1107,20 @@ server.registerTool(
|
|
|
1143
1107
|
description:
|
|
1144
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.",
|
|
1145
1109
|
inputSchema: z.object({
|
|
1146
|
-
url: z
|
|
1147
|
-
|
|
1148
|
-
|
|
1110
|
+
url: z
|
|
1111
|
+
.string()
|
|
1112
|
+
.describe("The full URL of the webpage to fetch (must start with http/https)."),
|
|
1149
1113
|
template: z
|
|
1150
1114
|
.string()
|
|
1151
1115
|
.default("auto")
|
|
1152
1116
|
.describe(
|
|
1153
1117
|
"Template to use: 'auto' (auto-detect from URL), a built-in name, or inline JSON.",
|
|
1154
1118
|
),
|
|
1155
|
-
start_index: z
|
|
1156
|
-
.number()
|
|
1157
|
-
.default(0)
|
|
1158
|
-
.describe(
|
|
1159
|
-
"Character offset for pagination. Default: 0.",
|
|
1160
|
-
),
|
|
1119
|
+
start_index: z.number().default(0).describe("Character offset for pagination. Default: 0."),
|
|
1161
1120
|
max_length: z
|
|
1162
1121
|
.number()
|
|
1163
1122
|
.default(10000)
|
|
1164
|
-
.describe(
|
|
1165
|
-
"Maximum characters to return per request. Default is 10000.",
|
|
1166
|
-
),
|
|
1123
|
+
.describe("Maximum characters to return per request. Default is 10000."),
|
|
1167
1124
|
block_media: z
|
|
1168
1125
|
.boolean()
|
|
1169
1126
|
.default(true)
|
|
@@ -1203,8 +1160,7 @@ server.registerTool(
|
|
|
1203
1160
|
`\n\n---\n[webfetch: template="${template ? template.name : "auto"}" (source markdown), ` +
|
|
1204
1161
|
`showing characters ${start_index} to ${start_index + paginated.length} of ${totalLength} total.`;
|
|
1205
1162
|
if (start_index + max_length < totalLength) {
|
|
1206
|
-
metadata +=
|
|
1207
|
-
` Use start_index=${start_index + max_length} to read more.`;
|
|
1163
|
+
metadata += ` Use start_index=${start_index + max_length} to read more.`;
|
|
1208
1164
|
}
|
|
1209
1165
|
metadata += "]";
|
|
1210
1166
|
return { content: [{ type: "text", text: paginated + metadata }] };
|
|
@@ -1242,15 +1198,83 @@ server.registerTool(
|
|
|
1242
1198
|
},
|
|
1243
1199
|
);
|
|
1244
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
|
+
isMainModule,
|
|
1228
|
+
BUILTIN_TEMPLATES,
|
|
1229
|
+
TEMPLATE_MAP,
|
|
1230
|
+
};
|
|
1231
|
+
|
|
1245
1232
|
// === MAIN =================================================================
|
|
1246
1233
|
|
|
1234
|
+
function redirectStartupOutputToStderr() {
|
|
1235
|
+
const originalStdoutWrite = process.stdout.write.bind(process.stdout);
|
|
1236
|
+
const originalConsoleLog = console.log;
|
|
1237
|
+
const originalConsoleInfo = console.info;
|
|
1238
|
+
|
|
1239
|
+
process.stdout.write = (chunk, encoding, callback) => {
|
|
1240
|
+
return process.stderr.write(chunk, encoding, callback);
|
|
1241
|
+
};
|
|
1242
|
+
console.log = (...args) => console.error(...args);
|
|
1243
|
+
console.info = (...args) => console.error(...args);
|
|
1244
|
+
|
|
1245
|
+
return () => {
|
|
1246
|
+
process.stdout.write = originalStdoutWrite;
|
|
1247
|
+
console.log = originalConsoleLog;
|
|
1248
|
+
console.info = originalConsoleInfo;
|
|
1249
|
+
};
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
function isMainModule(argvPath = process.argv[1], modulePath = __filename) {
|
|
1253
|
+
if (!argvPath) return false;
|
|
1254
|
+
try {
|
|
1255
|
+
return realpathSync(argvPath) === realpathSync(modulePath);
|
|
1256
|
+
} catch {
|
|
1257
|
+
return false;
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1247
1261
|
async function main() {
|
|
1262
|
+
process.on("SIGINT", cleanup);
|
|
1263
|
+
process.on("SIGTERM", cleanup);
|
|
1264
|
+
|
|
1265
|
+
const restoreStdout = redirectStartupOutputToStderr();
|
|
1248
1266
|
await ensureBinary();
|
|
1249
|
-
|
|
1267
|
+
restoreStdout();
|
|
1250
1268
|
const transport = new StdioServerTransport();
|
|
1251
1269
|
await server.connect(transport);
|
|
1252
1270
|
}
|
|
1253
1271
|
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1272
|
+
// Guard: only start server when run directly (including via npm bin symlink),
|
|
1273
|
+
// not when imported. Uses realpath so that `npx` / `node_modules/.bin`
|
|
1274
|
+
// symlinks resolve to the module file correctly.
|
|
1275
|
+
const isMain = isMainModule();
|
|
1276
|
+
if (isMain) {
|
|
1277
|
+
main().catch((_err) => {
|
|
1278
|
+
process.exit(1);
|
|
1279
|
+
});
|
|
1280
|
+
}
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "searchfetch",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.2.2",
|
|
4
4
|
"description": "Fault-tolerant MCP Server for Stealth Web Search and Fetching",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
|
-
"searchfetch": "
|
|
7
|
+
"searchfetch": "index.js"
|
|
8
8
|
},
|
|
9
9
|
"files": [
|
|
10
10
|
"index.js",
|
|
@@ -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.
|
|
29
|
-
"playwright-core": "^1.
|
|
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
|
}
|