searchfetch 3.3.4__tar.gz → 4.0.0__tar.gz
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.
- searchfetch-4.0.0/.gitignore +51 -0
- searchfetch-4.0.0/PKG-INFO +172 -0
- searchfetch-4.0.0/README.md +147 -0
- searchfetch-4.0.0/pyproject.toml +63 -0
- searchfetch-4.0.0/searchfetch/__init__.py +5 -0
- searchfetch-4.0.0/searchfetch/__main__.py +3 -0
- searchfetch-4.0.0/searchfetch/browser.py +220 -0
- searchfetch-4.0.0/searchfetch/compose.py +123 -0
- searchfetch-4.0.0/searchfetch/extract.py +227 -0
- searchfetch-4.0.0/searchfetch/markdown.py +55 -0
- searchfetch-4.0.0/searchfetch/server.py +211 -0
- searchfetch-4.0.0/searchfetch/templates.py +242 -0
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/crates-package.json +1 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/devto.json +1 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/docker-hub.json +1 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/docs-page.json +1 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/docs-rs.json +1 -1
- searchfetch-4.0.0/templates/duckduckgo-lite-search.json +49 -0
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/duckduckgo-search.json +3 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/github-issue.json +1 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/github-repo.json +1 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/gitlab.json +1 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/go-pkg.json +1 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/google-search.json +3 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/javadoc.json +1 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/mdn-web-docs.json +1 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/npm-package.json +1 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/pypi-package.json +1 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/raw.json +1 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/reddit.json +1 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/wikipedia.json +1 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/templates/youtube.json +1 -1
- searchfetch-4.0.0/tests/e2e/node.mjs +186 -0
- searchfetch-4.0.0/tests/e2e/python.py +188 -0
- searchfetch-4.0.0/tests/fixtures/composition.json +168 -0
- searchfetch-4.0.0/tests/fixtures/extraction.json +28 -0
- searchfetch-4.0.0/tests/fixtures/page.html +12 -0
- searchfetch-4.0.0/tests/fixtures/templates.json +168 -0
- searchfetch-4.0.0/tests/node/browser.test.js +288 -0
- searchfetch-4.0.0/tests/node/builtin-templates.test.js +45 -0
- searchfetch-4.0.0/tests/node/compose.test.js +137 -0
- searchfetch-4.0.0/tests/node/extract.test.js +466 -0
- searchfetch-4.0.0/tests/node/fake-browser.js +45 -0
- searchfetch-4.0.0/tests/node/server.test.js +307 -0
- searchfetch-4.0.0/tests/node/templates.test.js +429 -0
- searchfetch-4.0.0/tests/python/conftest.py +103 -0
- searchfetch-4.0.0/tests/python/test_browser.py +474 -0
- searchfetch-4.0.0/tests/python/test_compose.py +155 -0
- searchfetch-4.0.0/tests/python/test_extract.py +384 -0
- searchfetch-4.0.0/tests/python/test_markdown.py +119 -0
- searchfetch-4.0.0/tests/python/test_server.py +378 -0
- searchfetch-4.0.0/tests/python/test_templates.py +731 -0
- searchfetch-3.3.4/MANIFEST.in +0 -1
- searchfetch-3.3.4/PKG-INFO +0 -166
- searchfetch-3.3.4/README.md +0 -142
- searchfetch-3.3.4/pyproject.toml +0 -57
- searchfetch-3.3.4/searchfetch.egg-info/PKG-INFO +0 -166
- searchfetch-3.3.4/searchfetch.egg-info/SOURCES.txt +0 -32
- searchfetch-3.3.4/searchfetch.egg-info/dependency_links.txt +0 -1
- searchfetch-3.3.4/searchfetch.egg-info/entry_points.txt +0 -2
- searchfetch-3.3.4/searchfetch.egg-info/requires.txt +0 -11
- searchfetch-3.3.4/searchfetch.egg-info/top_level.txt +0 -3
- searchfetch-3.3.4/selectors_utils.py +0 -31
- searchfetch-3.3.4/server.py +0 -1270
- searchfetch-3.3.4/setup.cfg +0 -4
- searchfetch-3.3.4/templates/__init__.py +0 -1
- {searchfetch-3.3.4 → searchfetch-4.0.0}/LICENSE +0 -0
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# =========================
|
|
2
|
+
# Node.js
|
|
3
|
+
# =========================
|
|
4
|
+
node_modules/
|
|
5
|
+
npm-debug.log*
|
|
6
|
+
yarn-debug.log*
|
|
7
|
+
yarn-error.log*
|
|
8
|
+
.pnpm-debug.log*
|
|
9
|
+
|
|
10
|
+
# =========================
|
|
11
|
+
# Python
|
|
12
|
+
# =========================
|
|
13
|
+
__pycache__/
|
|
14
|
+
*.py[cod]
|
|
15
|
+
*$py.class
|
|
16
|
+
*.so
|
|
17
|
+
build/
|
|
18
|
+
develop-eggs/
|
|
19
|
+
dist/
|
|
20
|
+
downloads/
|
|
21
|
+
eggs/
|
|
22
|
+
.eggs/
|
|
23
|
+
lib64/
|
|
24
|
+
parts/
|
|
25
|
+
sdist/
|
|
26
|
+
var/
|
|
27
|
+
wheels/
|
|
28
|
+
*.egg-info/
|
|
29
|
+
.installed.cfg
|
|
30
|
+
*.egg
|
|
31
|
+
|
|
32
|
+
# =========================
|
|
33
|
+
# Virtual Environments
|
|
34
|
+
# =========================
|
|
35
|
+
venv/
|
|
36
|
+
.venv/
|
|
37
|
+
env/
|
|
38
|
+
.env
|
|
39
|
+
|
|
40
|
+
# =========================
|
|
41
|
+
# OS / IDE / Caching
|
|
42
|
+
# =========================
|
|
43
|
+
.DS_Store
|
|
44
|
+
.vscode/
|
|
45
|
+
.idea/
|
|
46
|
+
*.swp
|
|
47
|
+
*.swo
|
|
48
|
+
.cache/
|
|
49
|
+
.pytest_cache/
|
|
50
|
+
.ruff_cache/
|
|
51
|
+
.cloakbrowser/
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: searchfetch
|
|
3
|
+
Version: 4.0.0
|
|
4
|
+
Summary: Fault-tolerant MCP server for stealth web search and page fetching
|
|
5
|
+
Project-URL: Homepage, https://github.com/maxylev/searchfetch
|
|
6
|
+
Project-URL: Repository, https://github.com/maxylev/searchfetch
|
|
7
|
+
Author: Max
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: agent,ai,fetch,llm,mcp,search,stealth
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
|
|
13
|
+
Requires-Python: >=3.11.5
|
|
14
|
+
Requires-Dist: beautifulsoup4>=4.15.0
|
|
15
|
+
Requires-Dist: cloakbrowser>=0.6.3
|
|
16
|
+
Requires-Dist: markdownify>=1.2.3
|
|
17
|
+
Requires-Dist: mcp>=2.3.0
|
|
18
|
+
Requires-Dist: playwright>=1.64.0
|
|
19
|
+
Requires-Dist: pydantic>=2.14.1
|
|
20
|
+
Requires-Dist: soupsieve>=3.0.3
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Requires-Dist: pytest>=9.1.1; extra == 'dev'
|
|
23
|
+
Requires-Dist: ruff>=0.17.1; extra == 'dev'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# SearchFetch
|
|
27
|
+
|
|
28
|
+
An [MCP](https://modelcontextprotocol.io) server that gives AI agents web search and page
|
|
29
|
+
fetching through a stealth browser. Pages are rendered with JavaScript, stripped of noise, and
|
|
30
|
+
returned as compact Markdown.
|
|
31
|
+
|
|
32
|
+
- **Browser rendering:** [CloakBrowser](https://github.com/CloakHQ/CloakBrowser) runs Chromium
|
|
33
|
+
with humanized input. Each fetch uses an isolated browser context. Sites may still demand
|
|
34
|
+
logins or challenges.
|
|
35
|
+
- **Fault tolerance:** relaunches a disconnected browser and retries timeouts, network failures
|
|
36
|
+
and HTTP 429 (honoring `Retry-After`, capped at 30 s) once. Built-in search engines fall back
|
|
37
|
+
to DuckDuckGo HTML and then DuckDuckGo Lite.
|
|
38
|
+
- **Token-efficient output:** scripts, styles, SVGs, inline styles and embedded `data:` images
|
|
39
|
+
are removed before conversion; images, media and fonts are blocked at the network layer.
|
|
40
|
+
- **Template-driven extraction:** JSON templates for GitHub, GitLab, npm, PyPI, crates.io,
|
|
41
|
+
docs.rs, Docker Hub, Wikipedia, MDN, Reddit, YouTube, DEV, pkg.go.dev, Javadoc and generic
|
|
42
|
+
documentation sites. Custom templates can be passed inline.
|
|
43
|
+
- **Two runtimes:** Python (`uvx`, Python 3.11.5+) or Node.js (`npx`, Node 24+), with the same
|
|
44
|
+
tools, templates and output. The first run downloads the browser binary.
|
|
45
|
+
|
|
46
|
+
## Setup
|
|
47
|
+
|
|
48
|
+
No manual install is needed. Point your MCP client at `uvx` or `npx`:
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
{
|
|
52
|
+
"mcpServers": {
|
|
53
|
+
"searchfetch": {
|
|
54
|
+
"command": "uvx",
|
|
55
|
+
"args": ["searchfetch"]
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
For Node.js, use `"command": "npx", "args": ["-y", "searchfetch"]`. In Cursor, add a `command`
|
|
62
|
+
server with `uvx searchfetch` or `npx -y searchfetch`.
|
|
63
|
+
|
|
64
|
+
## Tools
|
|
65
|
+
|
|
66
|
+
Both tools are read-only. Failures are returned as MCP tool errors.
|
|
67
|
+
|
|
68
|
+
### `websearch`
|
|
69
|
+
|
|
70
|
+
| Parameter | Type | Default | Description |
|
|
71
|
+
| ------------- | ------------ | -------------- | --------------------------------------------------------------------------------- |
|
|
72
|
+
| `query` | string | _required_ | Search query (must not be blank). |
|
|
73
|
+
| `engine` | string | `"duckduckgo"` | `"duckduckgo"`, `"google"`, a search template name, or an inline JSON template. |
|
|
74
|
+
| `region` | string/null | `null` | Region-language code such as `"us-en"`. DuckDuckGo: `kl`; Google: `gl` and `hl`. |
|
|
75
|
+
| `safe_search` | boolean/null | `null` | `true` or `false` sets the engine's safe search; `null` keeps the engine default. |
|
|
76
|
+
| `max_results` | integer | `10` | Maximum results (positive). |
|
|
77
|
+
| `block_media` | boolean | `true` | Block images, media and fonts at the network layer. |
|
|
78
|
+
|
|
79
|
+
Results are a numbered list of titles, URLs and snippets. When an engine fails or returns no
|
|
80
|
+
results, the next template in its `fallback` chain is tried (`google` → `duckduckgo-search` →
|
|
81
|
+
`duckduckgo-lite-search`), and a `[websearch: …]` note at the top of the output explains why.
|
|
82
|
+
|
|
83
|
+
### `webfetch`
|
|
84
|
+
|
|
85
|
+
| Parameter | Type | Default | Description |
|
|
86
|
+
| ------------- | ------- | ---------- | ------------------------------------------------------------------- |
|
|
87
|
+
| `url` | string | _required_ | Absolute `http`/`https` URL. |
|
|
88
|
+
| `template` | string | `"auto"` | `"auto"` (detect by URL), a template name, or inline JSON template. |
|
|
89
|
+
| `start_index` | integer | `0` | Start offset in Unicode code points (non-negative). |
|
|
90
|
+
| `max_length` | integer | `10000` | Maximum code points to return (positive). |
|
|
91
|
+
| `block_media` | boolean | `true` | Block images, media and fonts at the network layer. |
|
|
92
|
+
|
|
93
|
+
Output ends with a footer naming the template and the character window, plus the next
|
|
94
|
+
`start_index` when more content remains. Pages that match no template are converted whole after
|
|
95
|
+
removing navigation, headers, footers, sidebars, dialogs and media (`template="auto (fallback)"`).
|
|
96
|
+
The `raw` template converts the full `<body>` with no removal.
|
|
97
|
+
|
|
98
|
+
## Templates
|
|
99
|
+
|
|
100
|
+
Built-in templates live in [`templates/`](templates/) and are shared by both runtimes. Page
|
|
101
|
+
templates: `github-repo`, `github-issue`, `npm-package`, `pypi-package`, `crates-package`,
|
|
102
|
+
`docs-rs`, `javadoc`, `docs-page`, `docker-hub`, `wikipedia`, `gitlab`, `reddit`,
|
|
103
|
+
`mdn-web-docs`, `devto`, `go-pkg`, `youtube`, `raw`. Search templates: `google-search`,
|
|
104
|
+
`duckduckgo-search`, `duckduckgo-lite-search`.
|
|
105
|
+
|
|
106
|
+
Templates are validated when they are loaded or passed inline:
|
|
107
|
+
|
|
108
|
+
| Field | Description |
|
|
109
|
+
| ----------------- | ------------------------------------------------------------------------------------------------ |
|
|
110
|
+
| `name` | Required unique name (inline templates default to `"custom"`). |
|
|
111
|
+
| `sections` | Required list of sections (see below). |
|
|
112
|
+
| `order` | Precedence for `auto` detection; lower wins. |
|
|
113
|
+
| `url_patterns` | Regular expressions (compatible with JavaScript and Python) that select the template for `auto`. |
|
|
114
|
+
| `remove` | CSS selectors removed before extraction. Defaults to scripts, styles, SVG, nav, footer, iframes. |
|
|
115
|
+
| `source_url` | Raw Markdown source tried first, e.g. `"{url}.md"`; HTML responses are ignored. |
|
|
116
|
+
| `cookies` | Playwright cookies added to the browser context. |
|
|
117
|
+
| `block_resources` | Resource types blocked when `block_media` is on. Default: `image`, `media`, `font`. |
|
|
118
|
+
| `url_template` | Search URL with `{placeholders}`; makes the template usable by `websearch`. |
|
|
119
|
+
| `url_params` | Per placeholder: `required`, `default`, and `encode: "url"`. |
|
|
120
|
+
| `engine` | `"duckduckgo"` or `"google"`: how `region` and `safe_search` map to URL parameters. |
|
|
121
|
+
| `fallback` | Name of the search template to try when this one fails. |
|
|
122
|
+
|
|
123
|
+
Each section has a `name`, a `selector` (empty selects `<body>`), and optionally `format` (`text`, `markdown`,
|
|
124
|
+
`attribute` with `attribute`, or `html`), `transform` (one or a list of `strip`,
|
|
125
|
+
`decode_google_url`, `decode_ddg_url`, `json_parse`, `resolve_href`), `required`, `multiple`,
|
|
126
|
+
`max_items`, and `children` (fields extracted from inside each matched element).
|
|
127
|
+
|
|
128
|
+
Selectors separated by top-level commas are ordered fallbacks: the first selector that matches
|
|
129
|
+
wins, and an empty fallback selects the current element. Children search inside their parent
|
|
130
|
+
element and its ancestors, never neighbouring results, so a missing field stays missing. Missing
|
|
131
|
+
`required` sections or fields are reported as errors.
|
|
132
|
+
|
|
133
|
+
A records section whose first item has `Author`/`User` and `Comment`/`Body` fields is rendered as
|
|
134
|
+
a comment thread; other records render as indented `Key: value` blocks.
|
|
135
|
+
|
|
136
|
+
## Development
|
|
137
|
+
|
|
138
|
+
```bash
|
|
139
|
+
npm ci && uv sync --locked --extra dev
|
|
140
|
+
git config core.hooksPath .githooks # optional: format, lint and unit tests before commits
|
|
141
|
+
|
|
142
|
+
npm test # Node (node:test) and Python (pytest) unit tests
|
|
143
|
+
npm run lint # ESLint and Ruff
|
|
144
|
+
npm run format # Prettier and Ruff format (format:check to verify)
|
|
145
|
+
npm run e2e # real browser against local fixtures, plus the packed npm and wheel builds
|
|
146
|
+
npm run check # everything CI runs
|
|
147
|
+
npm run inspect:node # MCP Inspector (inspect:py for Python)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### Layout
|
|
151
|
+
|
|
152
|
+
| Path | Contents |
|
|
153
|
+
| ---------------------------- | ------------------------------------------------------------------------- |
|
|
154
|
+
| `src/` | Node.js runtime (`index.js` is the `searchfetch` executable). |
|
|
155
|
+
| `searchfetch/` | Python package (`python -m searchfetch` or the `searchfetch` script). |
|
|
156
|
+
| `templates/` | Shared templates; bundled into the npm package and the Python wheel. |
|
|
157
|
+
| `tests/fixtures/` | Shared fixtures that keep both runtimes' extraction and output identical. |
|
|
158
|
+
| `tests/node`, `tests/python` | Unit tests. |
|
|
159
|
+
| `tests/e2e/` | MCP end-to-end tests over stdio against a local HTTP server. |
|
|
160
|
+
|
|
161
|
+
The runtimes mirror each other module for module (`templates`, `extract`, `markdown`, `compose`,
|
|
162
|
+
`browser`, `server`). Any change to one should be made to the other, with a shared fixture if
|
|
163
|
+
the behavior is observable.
|
|
164
|
+
|
|
165
|
+
### Limits
|
|
166
|
+
|
|
167
|
+
- HTML-to-Markdown conversion uses turndown (Node) and markdownify (Python). They agree on
|
|
168
|
+
common content, but edge cases such as tables differ.
|
|
169
|
+
- After the DOM is ready, each fetch waits up to five seconds for network activity to settle.
|
|
170
|
+
Pages that keep rendering after that may return partial content.
|
|
171
|
+
- E2E tests use local fixtures. Live search-engine availability and third-party page layouts
|
|
172
|
+
change over time and need separate live checks.
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# SearchFetch
|
|
2
|
+
|
|
3
|
+
An [MCP](https://modelcontextprotocol.io) server that gives AI agents web search and page
|
|
4
|
+
fetching through a stealth browser. Pages are rendered with JavaScript, stripped of noise, and
|
|
5
|
+
returned as compact Markdown.
|
|
6
|
+
|
|
7
|
+
- **Browser rendering:** [CloakBrowser](https://github.com/CloakHQ/CloakBrowser) runs Chromium
|
|
8
|
+
with humanized input. Each fetch uses an isolated browser context. Sites may still demand
|
|
9
|
+
logins or challenges.
|
|
10
|
+
- **Fault tolerance:** relaunches a disconnected browser and retries timeouts, network failures
|
|
11
|
+
and HTTP 429 (honoring `Retry-After`, capped at 30 s) once. Built-in search engines fall back
|
|
12
|
+
to DuckDuckGo HTML and then DuckDuckGo Lite.
|
|
13
|
+
- **Token-efficient output:** scripts, styles, SVGs, inline styles and embedded `data:` images
|
|
14
|
+
are removed before conversion; images, media and fonts are blocked at the network layer.
|
|
15
|
+
- **Template-driven extraction:** JSON templates for GitHub, GitLab, npm, PyPI, crates.io,
|
|
16
|
+
docs.rs, Docker Hub, Wikipedia, MDN, Reddit, YouTube, DEV, pkg.go.dev, Javadoc and generic
|
|
17
|
+
documentation sites. Custom templates can be passed inline.
|
|
18
|
+
- **Two runtimes:** Python (`uvx`, Python 3.11.5+) or Node.js (`npx`, Node 24+), with the same
|
|
19
|
+
tools, templates and output. The first run downloads the browser binary.
|
|
20
|
+
|
|
21
|
+
## Setup
|
|
22
|
+
|
|
23
|
+
No manual install is needed. Point your MCP client at `uvx` or `npx`:
|
|
24
|
+
|
|
25
|
+
```json
|
|
26
|
+
{
|
|
27
|
+
"mcpServers": {
|
|
28
|
+
"searchfetch": {
|
|
29
|
+
"command": "uvx",
|
|
30
|
+
"args": ["searchfetch"]
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
For Node.js, use `"command": "npx", "args": ["-y", "searchfetch"]`. In Cursor, add a `command`
|
|
37
|
+
server with `uvx searchfetch` or `npx -y searchfetch`.
|
|
38
|
+
|
|
39
|
+
## Tools
|
|
40
|
+
|
|
41
|
+
Both tools are read-only. Failures are returned as MCP tool errors.
|
|
42
|
+
|
|
43
|
+
### `websearch`
|
|
44
|
+
|
|
45
|
+
| Parameter | Type | Default | Description |
|
|
46
|
+
| ------------- | ------------ | -------------- | --------------------------------------------------------------------------------- |
|
|
47
|
+
| `query` | string | _required_ | Search query (must not be blank). |
|
|
48
|
+
| `engine` | string | `"duckduckgo"` | `"duckduckgo"`, `"google"`, a search template name, or an inline JSON template. |
|
|
49
|
+
| `region` | string/null | `null` | Region-language code such as `"us-en"`. DuckDuckGo: `kl`; Google: `gl` and `hl`. |
|
|
50
|
+
| `safe_search` | boolean/null | `null` | `true` or `false` sets the engine's safe search; `null` keeps the engine default. |
|
|
51
|
+
| `max_results` | integer | `10` | Maximum results (positive). |
|
|
52
|
+
| `block_media` | boolean | `true` | Block images, media and fonts at the network layer. |
|
|
53
|
+
|
|
54
|
+
Results are a numbered list of titles, URLs and snippets. When an engine fails or returns no
|
|
55
|
+
results, the next template in its `fallback` chain is tried (`google` → `duckduckgo-search` →
|
|
56
|
+
`duckduckgo-lite-search`), and a `[websearch: …]` note at the top of the output explains why.
|
|
57
|
+
|
|
58
|
+
### `webfetch`
|
|
59
|
+
|
|
60
|
+
| Parameter | Type | Default | Description |
|
|
61
|
+
| ------------- | ------- | ---------- | ------------------------------------------------------------------- |
|
|
62
|
+
| `url` | string | _required_ | Absolute `http`/`https` URL. |
|
|
63
|
+
| `template` | string | `"auto"` | `"auto"` (detect by URL), a template name, or inline JSON template. |
|
|
64
|
+
| `start_index` | integer | `0` | Start offset in Unicode code points (non-negative). |
|
|
65
|
+
| `max_length` | integer | `10000` | Maximum code points to return (positive). |
|
|
66
|
+
| `block_media` | boolean | `true` | Block images, media and fonts at the network layer. |
|
|
67
|
+
|
|
68
|
+
Output ends with a footer naming the template and the character window, plus the next
|
|
69
|
+
`start_index` when more content remains. Pages that match no template are converted whole after
|
|
70
|
+
removing navigation, headers, footers, sidebars, dialogs and media (`template="auto (fallback)"`).
|
|
71
|
+
The `raw` template converts the full `<body>` with no removal.
|
|
72
|
+
|
|
73
|
+
## Templates
|
|
74
|
+
|
|
75
|
+
Built-in templates live in [`templates/`](templates/) and are shared by both runtimes. Page
|
|
76
|
+
templates: `github-repo`, `github-issue`, `npm-package`, `pypi-package`, `crates-package`,
|
|
77
|
+
`docs-rs`, `javadoc`, `docs-page`, `docker-hub`, `wikipedia`, `gitlab`, `reddit`,
|
|
78
|
+
`mdn-web-docs`, `devto`, `go-pkg`, `youtube`, `raw`. Search templates: `google-search`,
|
|
79
|
+
`duckduckgo-search`, `duckduckgo-lite-search`.
|
|
80
|
+
|
|
81
|
+
Templates are validated when they are loaded or passed inline:
|
|
82
|
+
|
|
83
|
+
| Field | Description |
|
|
84
|
+
| ----------------- | ------------------------------------------------------------------------------------------------ |
|
|
85
|
+
| `name` | Required unique name (inline templates default to `"custom"`). |
|
|
86
|
+
| `sections` | Required list of sections (see below). |
|
|
87
|
+
| `order` | Precedence for `auto` detection; lower wins. |
|
|
88
|
+
| `url_patterns` | Regular expressions (compatible with JavaScript and Python) that select the template for `auto`. |
|
|
89
|
+
| `remove` | CSS selectors removed before extraction. Defaults to scripts, styles, SVG, nav, footer, iframes. |
|
|
90
|
+
| `source_url` | Raw Markdown source tried first, e.g. `"{url}.md"`; HTML responses are ignored. |
|
|
91
|
+
| `cookies` | Playwright cookies added to the browser context. |
|
|
92
|
+
| `block_resources` | Resource types blocked when `block_media` is on. Default: `image`, `media`, `font`. |
|
|
93
|
+
| `url_template` | Search URL with `{placeholders}`; makes the template usable by `websearch`. |
|
|
94
|
+
| `url_params` | Per placeholder: `required`, `default`, and `encode: "url"`. |
|
|
95
|
+
| `engine` | `"duckduckgo"` or `"google"`: how `region` and `safe_search` map to URL parameters. |
|
|
96
|
+
| `fallback` | Name of the search template to try when this one fails. |
|
|
97
|
+
|
|
98
|
+
Each section has a `name`, a `selector` (empty selects `<body>`), and optionally `format` (`text`, `markdown`,
|
|
99
|
+
`attribute` with `attribute`, or `html`), `transform` (one or a list of `strip`,
|
|
100
|
+
`decode_google_url`, `decode_ddg_url`, `json_parse`, `resolve_href`), `required`, `multiple`,
|
|
101
|
+
`max_items`, and `children` (fields extracted from inside each matched element).
|
|
102
|
+
|
|
103
|
+
Selectors separated by top-level commas are ordered fallbacks: the first selector that matches
|
|
104
|
+
wins, and an empty fallback selects the current element. Children search inside their parent
|
|
105
|
+
element and its ancestors, never neighbouring results, so a missing field stays missing. Missing
|
|
106
|
+
`required` sections or fields are reported as errors.
|
|
107
|
+
|
|
108
|
+
A records section whose first item has `Author`/`User` and `Comment`/`Body` fields is rendered as
|
|
109
|
+
a comment thread; other records render as indented `Key: value` blocks.
|
|
110
|
+
|
|
111
|
+
## Development
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
npm ci && uv sync --locked --extra dev
|
|
115
|
+
git config core.hooksPath .githooks # optional: format, lint and unit tests before commits
|
|
116
|
+
|
|
117
|
+
npm test # Node (node:test) and Python (pytest) unit tests
|
|
118
|
+
npm run lint # ESLint and Ruff
|
|
119
|
+
npm run format # Prettier and Ruff format (format:check to verify)
|
|
120
|
+
npm run e2e # real browser against local fixtures, plus the packed npm and wheel builds
|
|
121
|
+
npm run check # everything CI runs
|
|
122
|
+
npm run inspect:node # MCP Inspector (inspect:py for Python)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### Layout
|
|
126
|
+
|
|
127
|
+
| Path | Contents |
|
|
128
|
+
| ---------------------------- | ------------------------------------------------------------------------- |
|
|
129
|
+
| `src/` | Node.js runtime (`index.js` is the `searchfetch` executable). |
|
|
130
|
+
| `searchfetch/` | Python package (`python -m searchfetch` or the `searchfetch` script). |
|
|
131
|
+
| `templates/` | Shared templates; bundled into the npm package and the Python wheel. |
|
|
132
|
+
| `tests/fixtures/` | Shared fixtures that keep both runtimes' extraction and output identical. |
|
|
133
|
+
| `tests/node`, `tests/python` | Unit tests. |
|
|
134
|
+
| `tests/e2e/` | MCP end-to-end tests over stdio against a local HTTP server. |
|
|
135
|
+
|
|
136
|
+
The runtimes mirror each other module for module (`templates`, `extract`, `markdown`, `compose`,
|
|
137
|
+
`browser`, `server`). Any change to one should be made to the other, with a shared fixture if
|
|
138
|
+
the behavior is observable.
|
|
139
|
+
|
|
140
|
+
### Limits
|
|
141
|
+
|
|
142
|
+
- HTML-to-Markdown conversion uses turndown (Node) and markdownify (Python). They agree on
|
|
143
|
+
common content, but edge cases such as tables differ.
|
|
144
|
+
- After the DOM is ready, each fetch waits up to five seconds for network activity to settle.
|
|
145
|
+
Pages that keep rendering after that may return partial content.
|
|
146
|
+
- E2E tests use local fixtures. Live search-engine availability and third-party page layouts
|
|
147
|
+
change over time and need separate live checks.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.32"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "searchfetch"
|
|
7
|
+
version = "4.0.0"
|
|
8
|
+
description = "Fault-tolerant MCP server for stealth web search and page fetching"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.11.5"
|
|
13
|
+
authors = [{ name = "Max" }]
|
|
14
|
+
keywords = ["mcp", "search", "fetch", "llm", "ai", "agent", "stealth"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Topic :: Internet :: WWW/HTTP :: Indexing/Search",
|
|
18
|
+
]
|
|
19
|
+
dependencies = [
|
|
20
|
+
"beautifulsoup4>=4.15.0",
|
|
21
|
+
"cloakbrowser>=0.6.3",
|
|
22
|
+
"markdownify>=1.2.3",
|
|
23
|
+
"mcp>=2.3.0",
|
|
24
|
+
"playwright>=1.64.0",
|
|
25
|
+
"pydantic>=2.14.1",
|
|
26
|
+
"soupsieve>=3.0.3",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.optional-dependencies]
|
|
30
|
+
dev = ["pytest>=9.1.1", "ruff>=0.17.1"]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://github.com/maxylev/searchfetch"
|
|
34
|
+
Repository = "https://github.com/maxylev/searchfetch"
|
|
35
|
+
|
|
36
|
+
[project.scripts]
|
|
37
|
+
searchfetch = "searchfetch.server:main"
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.wheel]
|
|
40
|
+
packages = ["searchfetch"]
|
|
41
|
+
|
|
42
|
+
# Templates live at the repository root so both runtimes share them; bundle them in the wheel.
|
|
43
|
+
[tool.hatch.build.targets.wheel.force-include]
|
|
44
|
+
"templates" = "searchfetch/templates"
|
|
45
|
+
|
|
46
|
+
[tool.hatch.build.targets.sdist]
|
|
47
|
+
include = ["searchfetch/", "templates/", "tests/", "README.md", "LICENSE"]
|
|
48
|
+
|
|
49
|
+
[tool.pytest.ini_options]
|
|
50
|
+
testpaths = ["tests/python"]
|
|
51
|
+
addopts = "-q"
|
|
52
|
+
|
|
53
|
+
[tool.ruff]
|
|
54
|
+
line-length = 100
|
|
55
|
+
target-version = "py311"
|
|
56
|
+
extend-exclude = ["node_modules"]
|
|
57
|
+
|
|
58
|
+
[tool.ruff.lint]
|
|
59
|
+
select = ["E", "F", "I", "W", "UP", "B", "SIM", "RUF"]
|
|
60
|
+
|
|
61
|
+
[tool.ruff.format]
|
|
62
|
+
quote-style = "double"
|
|
63
|
+
indent-style = "space"
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Shared stealth browser and page fetching.
|
|
2
|
+
|
|
3
|
+
One CloakBrowser instance is reused; every fetch attempt gets an isolated context so cookies and
|
|
4
|
+
storage never leak between requests. Mirrors ``src/browser.js``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import contextlib
|
|
9
|
+
import math
|
|
10
|
+
import re
|
|
11
|
+
from datetime import UTC, datetime
|
|
12
|
+
from email.utils import parsedate_to_datetime
|
|
13
|
+
|
|
14
|
+
from bs4 import BeautifulSoup
|
|
15
|
+
from cloakbrowser import launch_async
|
|
16
|
+
from playwright.async_api import Browser, BrowserContext, Page, Route
|
|
17
|
+
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
|
|
18
|
+
|
|
19
|
+
from searchfetch.markdown import clean_source_markdown, is_markdown
|
|
20
|
+
from searchfetch.templates import Template, validate_url
|
|
21
|
+
|
|
22
|
+
NAVIGATION_TIMEOUT_MS = 15_000
|
|
23
|
+
SOURCE_TIMEOUT_MS = 10_000
|
|
24
|
+
NETWORK_IDLE_TIMEOUT_MS = 5_000
|
|
25
|
+
MAX_ATTEMPTS = 2
|
|
26
|
+
RATE_LIMIT_DELAY = 2.0
|
|
27
|
+
MAX_RATE_LIMIT_DELAY = 30.0
|
|
28
|
+
NETWORK_RETRY_DELAY = 0.5
|
|
29
|
+
DEFAULT_BLOCKED_RESOURCES = ["image", "media", "font"]
|
|
30
|
+
|
|
31
|
+
_LAUNCH_ARGS = ["--disable-blink-features=AutomationControlled", "--disable-dev-shm-usage"]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class BrowserManager:
|
|
35
|
+
"""Lazily launch one browser and relaunch it after a disconnect."""
|
|
36
|
+
|
|
37
|
+
def __init__(self) -> None:
|
|
38
|
+
self._browser: Browser | None = None
|
|
39
|
+
self._lock = asyncio.Lock()
|
|
40
|
+
|
|
41
|
+
async def get(self) -> Browser:
|
|
42
|
+
async with self._lock:
|
|
43
|
+
if self._browser is None or not self._browser.is_connected():
|
|
44
|
+
self._browser = await launch_async(headless=True, humanize=True, args=_LAUNCH_ARGS)
|
|
45
|
+
return self._browser
|
|
46
|
+
|
|
47
|
+
async def close(self) -> None:
|
|
48
|
+
"""Close the browser, waiting for an in-flight launch so it cannot outlive shutdown."""
|
|
49
|
+
async with self._lock:
|
|
50
|
+
browser, self._browser = self._browser, None
|
|
51
|
+
if browser is not None:
|
|
52
|
+
await browser.close()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class HttpStatusError(RuntimeError):
|
|
56
|
+
def __init__(self, status: int, url: str, retry_after: float | None = None) -> None:
|
|
57
|
+
super().__init__(f"HTTP {status} when fetching {url}")
|
|
58
|
+
self.status = status
|
|
59
|
+
self.retry_after = retry_after
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def parse_retry_after(value: str | None, now: datetime | None = None) -> float:
|
|
63
|
+
"""Parse a Retry-After header (seconds or HTTP date) into a capped delay in seconds."""
|
|
64
|
+
if not value:
|
|
65
|
+
return RATE_LIMIT_DELAY
|
|
66
|
+
try:
|
|
67
|
+
delay = float(value)
|
|
68
|
+
except ValueError:
|
|
69
|
+
try:
|
|
70
|
+
delay = (parsedate_to_datetime(value) - (now or datetime.now(UTC))).total_seconds()
|
|
71
|
+
except (TypeError, ValueError):
|
|
72
|
+
return RATE_LIMIT_DELAY
|
|
73
|
+
if not math.isfinite(delay):
|
|
74
|
+
return RATE_LIMIT_DELAY
|
|
75
|
+
return min(max(delay, 0.0), MAX_RATE_LIMIT_DELAY)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
_DENIED_TITLES = (
|
|
79
|
+
"access denied",
|
|
80
|
+
"are you a human",
|
|
81
|
+
"are you a robot",
|
|
82
|
+
"ddos protection",
|
|
83
|
+
"forbidden",
|
|
84
|
+
"one more step",
|
|
85
|
+
"security check",
|
|
86
|
+
"sorry, you have been blocked",
|
|
87
|
+
"unusual traffic",
|
|
88
|
+
"verify you are human",
|
|
89
|
+
)
|
|
90
|
+
_DENIED_BODY = (
|
|
91
|
+
"bots use duckduckgo too",
|
|
92
|
+
"our systems have detected unusual traffic",
|
|
93
|
+
"sorry, you have been blocked",
|
|
94
|
+
"to continue, please type the characters",
|
|
95
|
+
)
|
|
96
|
+
#: Only conclusive on short pages; long articles may legitimately mention these phrases.
|
|
97
|
+
_DENIED_SHORT_BODY = ("access denied", "are you a robot", "verify you are human")
|
|
98
|
+
_SHORT_BODY_LENGTH = 1200
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def is_access_denied(soup: BeautifulSoup) -> bool:
|
|
102
|
+
"""Heuristically detect CAPTCHA, bot-check and block pages."""
|
|
103
|
+
title = soup.title.get_text().lower() if soup.title else ""
|
|
104
|
+
body = re.sub(r"\s+", " ", soup.body.get_text()).strip().lower() if soup.body else ""
|
|
105
|
+
return (
|
|
106
|
+
any(phrase in title for phrase in _DENIED_TITLES)
|
|
107
|
+
or any(phrase in body for phrase in _DENIED_BODY)
|
|
108
|
+
or (len(body) < _SHORT_BODY_LENGTH and any(phrase in body for phrase in _DENIED_SHORT_BODY))
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
_TRANSIENT_ERROR = re.compile(
|
|
113
|
+
r"net::|ERR_|navigation|navigating|connection|target closed|browser has been closed",
|
|
114
|
+
re.IGNORECASE,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def retry_delay(exc: BaseException) -> float | None:
|
|
119
|
+
"""Rate limits, timeouts and network/browser failures are worth one more attempt."""
|
|
120
|
+
if isinstance(exc, HttpStatusError):
|
|
121
|
+
if exc.status != 429:
|
|
122
|
+
return None
|
|
123
|
+
return RATE_LIMIT_DELAY if exc.retry_after is None else exc.retry_after
|
|
124
|
+
if isinstance(exc, PlaywrightTimeoutError) or _TRANSIENT_ERROR.search(str(exc)):
|
|
125
|
+
return NETWORK_RETRY_DELAY
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
async def _open_page(
|
|
130
|
+
browser: Browser, template: Template | None, block_media: bool
|
|
131
|
+
) -> tuple[BrowserContext, Page]:
|
|
132
|
+
"""Open a page in a fresh context with template cookies and resource blocking applied."""
|
|
133
|
+
context = await browser.new_context()
|
|
134
|
+
try:
|
|
135
|
+
if template and template.get("cookies"):
|
|
136
|
+
await context.add_cookies(template["cookies"])
|
|
137
|
+
page = await context.new_page()
|
|
138
|
+
blocked = set((template or {}).get("block_resources", DEFAULT_BLOCKED_RESOURCES))
|
|
139
|
+
if block_media and blocked:
|
|
140
|
+
|
|
141
|
+
async def route(route: Route) -> None:
|
|
142
|
+
if route.request.resource_type in blocked:
|
|
143
|
+
await route.abort()
|
|
144
|
+
else:
|
|
145
|
+
await route.continue_()
|
|
146
|
+
|
|
147
|
+
await page.route("**/*", route)
|
|
148
|
+
return context, page
|
|
149
|
+
except BaseException:
|
|
150
|
+
await context.close()
|
|
151
|
+
raise
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
async def _fetch_html_once(
|
|
155
|
+
manager: BrowserManager, url: str, template: Template | None, block_media: bool
|
|
156
|
+
) -> str:
|
|
157
|
+
context, page = await _open_page(await manager.get(), template, block_media)
|
|
158
|
+
try:
|
|
159
|
+
# Check the status before waiting for rendering so a slow page cannot hide an HTTP error.
|
|
160
|
+
response = await page.goto(
|
|
161
|
+
url, wait_until="domcontentloaded", timeout=NAVIGATION_TIMEOUT_MS
|
|
162
|
+
)
|
|
163
|
+
status = response.status if response else 0
|
|
164
|
+
if status >= 400:
|
|
165
|
+
retry_after = (
|
|
166
|
+
parse_retry_after(response.headers.get("retry-after")) if status == 429 else None
|
|
167
|
+
)
|
|
168
|
+
raise HttpStatusError(status, url, retry_after)
|
|
169
|
+
# Long polling must not prevent extraction of an already loaded document.
|
|
170
|
+
with contextlib.suppress(PlaywrightTimeoutError):
|
|
171
|
+
await page.wait_for_load_state("networkidle", timeout=NETWORK_IDLE_TIMEOUT_MS)
|
|
172
|
+
html = await page.content()
|
|
173
|
+
if is_access_denied(BeautifulSoup(html, "html.parser")):
|
|
174
|
+
raise RuntimeError(f"Access denied: CAPTCHA or block page detected at {url}.")
|
|
175
|
+
return html
|
|
176
|
+
finally:
|
|
177
|
+
await context.close()
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
async def fetch_html(
|
|
181
|
+
manager: BrowserManager, url: str, template: Template | None, block_media: bool
|
|
182
|
+
) -> str:
|
|
183
|
+
"""Render *url* and return its HTML, retrying rate limits and transient failures once."""
|
|
184
|
+
validate_url(url)
|
|
185
|
+
for attempt in range(1, MAX_ATTEMPTS + 1):
|
|
186
|
+
try:
|
|
187
|
+
return await _fetch_html_once(manager, url, template, block_media)
|
|
188
|
+
except Exception as exc:
|
|
189
|
+
delay = retry_delay(exc)
|
|
190
|
+
if attempt >= MAX_ATTEMPTS or delay is None:
|
|
191
|
+
raise
|
|
192
|
+
await asyncio.sleep(delay)
|
|
193
|
+
raise AssertionError("unreachable")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
async def fetch_source_markdown(
|
|
197
|
+
manager: BrowserManager, url: str, template: Template | None, block_media: bool
|
|
198
|
+
) -> str | None:
|
|
199
|
+
"""Best-effort fetch of a raw Markdown source (e.g. ``page.md``).
|
|
200
|
+
|
|
201
|
+
Returns the cleaned Markdown, or ``None`` when the source is missing, is HTML, or does not
|
|
202
|
+
look like Markdown.
|
|
203
|
+
"""
|
|
204
|
+
validate_url(url)
|
|
205
|
+
context = None
|
|
206
|
+
try:
|
|
207
|
+
context, page = await _open_page(await manager.get(), template, block_media)
|
|
208
|
+
response = await page.goto(url, wait_until="domcontentloaded", timeout=SOURCE_TIMEOUT_MS)
|
|
209
|
+
if response is None or response.status >= 400:
|
|
210
|
+
return None
|
|
211
|
+
content_type = response.headers.get("content-type", "").lower()
|
|
212
|
+
if "text/html" in content_type or "application/xhtml+xml" in content_type:
|
|
213
|
+
return None
|
|
214
|
+
text = clean_source_markdown(await response.text())
|
|
215
|
+
return text if is_markdown(text) else None
|
|
216
|
+
except Exception:
|
|
217
|
+
return None
|
|
218
|
+
finally:
|
|
219
|
+
if context is not None:
|
|
220
|
+
await context.close()
|