web-fetch-mcp 0.1.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.
Files changed (35) hide show
  1. web_fetch_mcp-0.1.0/.gitignore +16 -0
  2. web_fetch_mcp-0.1.0/LICENSE +202 -0
  3. web_fetch_mcp-0.1.0/NOTICE +5 -0
  4. web_fetch_mcp-0.1.0/PKG-INFO +152 -0
  5. web_fetch_mcp-0.1.0/README.md +120 -0
  6. web_fetch_mcp-0.1.0/TODO.md +140 -0
  7. web_fetch_mcp-0.1.0/assets/benchmarks.md +79 -0
  8. web_fetch_mcp-0.1.0/pyproject.toml +90 -0
  9. web_fetch_mcp-0.1.0/src/web_fetch_mcp/__init__.py +22 -0
  10. web_fetch_mcp-0.1.0/src/web_fetch_mcp/accessor/__init__.py +7 -0
  11. web_fetch_mcp-0.1.0/src/web_fetch_mcp/accessor/browser.py +195 -0
  12. web_fetch_mcp-0.1.0/src/web_fetch_mcp/accessor/dynamic_client.py +66 -0
  13. web_fetch_mcp-0.1.0/src/web_fetch_mcp/accessor/static_client.py +47 -0
  14. web_fetch_mcp-0.1.0/src/web_fetch_mcp/accessor/stealth_client.py +90 -0
  15. web_fetch_mcp-0.1.0/src/web_fetch_mcp/controller/__init__.py +6 -0
  16. web_fetch_mcp-0.1.0/src/web_fetch_mcp/controller/app.py +189 -0
  17. web_fetch_mcp-0.1.0/src/web_fetch_mcp/core/__init__.py +6 -0
  18. web_fetch_mcp-0.1.0/src/web_fetch_mcp/core/backoff.py +67 -0
  19. web_fetch_mcp-0.1.0/src/web_fetch_mcp/core/config.py +57 -0
  20. web_fetch_mcp-0.1.0/src/web_fetch_mcp/core/detection.py +105 -0
  21. web_fetch_mcp-0.1.0/src/web_fetch_mcp/core/models.py +44 -0
  22. web_fetch_mcp-0.1.0/src/web_fetch_mcp/core/proxy.py +60 -0
  23. web_fetch_mcp-0.1.0/src/web_fetch_mcp/core/rendering.py +141 -0
  24. web_fetch_mcp-0.1.0/src/web_fetch_mcp/py.typed +0 -0
  25. web_fetch_mcp-0.1.0/src/web_fetch_mcp/service/__init__.py +7 -0
  26. web_fetch_mcp-0.1.0/src/web_fetch_mcp/service/escalation.py +69 -0
  27. web_fetch_mcp-0.1.0/src/web_fetch_mcp/service/fetcher.py +77 -0
  28. web_fetch_mcp-0.1.0/src/web_fetch_mcp/service/request.py +25 -0
  29. web_fetch_mcp-0.1.0/src/web_fetch_mcp/service/retry.py +78 -0
  30. web_fetch_mcp-0.1.0/src/web_fetch_mcp/service/strategies.py +97 -0
  31. web_fetch_mcp-0.1.0/tests/__init__.py +0 -0
  32. web_fetch_mcp-0.1.0/tests/fixtures/article.html +16 -0
  33. web_fetch_mcp-0.1.0/tests/fixtures/not_article.html +4 -0
  34. web_fetch_mcp-0.1.0/tests/fixtures/tiny.pdf +20 -0
  35. web_fetch_mcp-0.1.0/tests/test_fetch_enhancements.py +357 -0
@@ -0,0 +1,16 @@
1
+ # Virtualenv / caches
2
+ .venv/
3
+ __pycache__/
4
+ *.pyc
5
+ .pytest_cache/
6
+ .ruff_cache/
7
+
8
+ # Build artifacts (never commit or publish these)
9
+ dist/
10
+ build/
11
+ *.egg-info/
12
+
13
+ # Local editor/IDE config — must never be packaged or published
14
+ .cursor/
15
+ .idea/
16
+ .vscode/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,5 @@
1
+ web-fetch-mcp
2
+ Copyright 2026 Sandip Dutta
3
+
4
+ This product includes software developed by Sandip Dutta.
5
+ Licensed under the Apache License, Version 2.0.
@@ -0,0 +1,152 @@
1
+ Metadata-Version: 2.4
2
+ Name: web-fetch-mcp
3
+ Version: 0.1.0
4
+ Summary: Resilient web-fetch MCP server: 3-tier escalation (curl_cffi -> Patchright -> nodriver) that fails honestly, with article-extraction mode and automatic content-type handling (HTML/JSON/PDF/image).
5
+ Project-URL: Homepage, https://github.com/Dutta-SD/web-fetch-mcp
6
+ Project-URL: Source, https://github.com/Dutta-SD/web-fetch-mcp
7
+ Project-URL: Issues, https://github.com/Dutta-SD/web-fetch-mcp/issues
8
+ Author-email: Sandip Dutta <duttasandip11100@gmail.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ Keywords: anti-bot,curl-cffi,fetch,llm,mcp,model-context-protocol,nodriver,playwright,web-scraping
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Internet :: WWW/HTTP
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: beautifulsoup4>=4.12.0
23
+ Requires-Dist: curl-cffi>=0.7.0
24
+ Requires-Dist: lxml>=5.0.0
25
+ Requires-Dist: markdownify>=0.13.0
26
+ Requires-Dist: mcp[cli]>=1.2.0
27
+ Requires-Dist: nodriver>=0.40
28
+ Requires-Dist: patchright>=1.49.0
29
+ Requires-Dist: pypdf>=4.0.0
30
+ Requires-Dist: trafilatura>=1.8.0
31
+ Description-Content-Type: text/markdown
32
+
33
+ # web-fetch-mcp
34
+
35
+ **A web-fetch [MCP](https://modelcontextprotocol.io) server for LLM agents that
36
+ fails honestly — it raises `FetchBlocked` instead of silently handing your model
37
+ a CAPTCHA or login page as if it were the article.**
38
+
39
+ Naive fetchers poison an agent's context: when a site returns a JavaScript
40
+ interstitial or a login wall with HTTP 200, the agent reads the challenge page as
41
+ if it were content and reasons from garbage. `web-fetch-mcp` detects that and
42
+ either escalates to a stronger strategy or fails loudly.
43
+
44
+ > **Status:** early / alpha. The escalation logic and helpers are unit-tested,
45
+ > but real-world bypass rates are not yet benchmarked — see `assets/benchmarks.md`
46
+ > and the roadmap in `TODO.md`.
47
+
48
+ ## How it works
49
+
50
+ A cheapest-first escalation ladder. Each tier targets a different layer of
51
+ bot-detection, and the server only pays for the expensive ones when it has to:
52
+
53
+ | Tier | Engine | Targets | Speed |
54
+ |------|--------|---------|-------|
55
+ | 1 | `curl_cffi` (Chrome TLS/HTTP2 fingerprint) | TLS (JA3/JA4) + HTTP/2 fingerprinting | ~500 ms |
56
+ | 2 | Patchright (real headful Chrome) | JavaScript fingerprinting; renders SPAs | ~1–3 s |
57
+ | 3 | nodriver (custom CDP) | automation-protocol (CDP) detection | ~2–4 s |
58
+
59
+ Every tier's output is checked for **hard blocks** (403/429/503) and **soft
60
+ blocks** (HTTP-200 challenge or login bodies served in place of content).
61
+ Transient failures retry with exponential backoff + jitter (honoring
62
+ `Retry-After`) before escalating. If everything is blocked, it raises
63
+ `FetchBlocked` with a remedy hint — it never returns a block page as content.
64
+
65
+ ### Escalation path (`mode="auto"`)
66
+
67
+ ```mermaid
68
+ flowchart TD
69
+ A["fetch(url)"] --> B{dismiss_selector set?}
70
+ B -- "no" --> T1["Tier 1 · curl_cffi<br/>static fetch"]
71
+ B -- "yes (can't click)" --> T2
72
+
73
+ T1 --> C1{blocked or<br/>empty SPA shell?}
74
+ C1 -- "no" --> OK["render_by_type → return"]
75
+ C1 -- "yes, escalate" --> T2["Tier 2 · Patchright<br/>headful Chrome, JS render"]
76
+
77
+ T2 --> C2{blocked?}
78
+ C2 -- "no" --> OK
79
+ C2 -- "yes, escalate" --> T3["Tier 3 · nodriver<br/>custom-CDP stealth"]
80
+
81
+ T3 --> C3{blocked?}
82
+ C3 -- "no" --> OK
83
+ C3 -- "yes" --> X["raise FetchBlocked<br/>(suggest residential proxy)"]
84
+
85
+ OK:::done
86
+ X:::fail
87
+ classDef done fill:#1f7a1f,color:#fff,stroke:#0d4d0d;
88
+ classDef fail fill:#a11,color:#fff,stroke:#600;
89
+ ```
90
+
91
+ Each tier runs through `with_retry` (exponential backoff + jitter, honoring
92
+ `Retry-After`) before the chain escalates. Tier 1 must clear the **strict** check
93
+ (not blocked **and** not an unrendered SPA shell); Tiers 2–3 only need to be
94
+ not-blocked. The single-tier modes (`static`/`dynamic`/`stealth`) run exactly one
95
+ box and skip the chain.
96
+
97
+ ## Tools
98
+
99
+ - **`fetch`** — retrieve a page as `markdown` / `text` / `html` / `article`
100
+ (main-content extraction via trafilatura). Non-HTML URLs are auto-handled:
101
+ JSON is pretty-printed, PDFs are text-extracted, images return a note to use
102
+ `screenshot`.
103
+ - **`screenshot`** — render a page in real Chrome and return a PNG.
104
+
105
+ ## Architecture
106
+
107
+ A layered package (`src/web_fetch_mcp/`), dependencies pointing inward:
108
+
109
+ ```
110
+ controller (FastMCP tools, lifespan) controller/app.py
111
+ -> service (retry decorator, strategy registry, escalation, facade)
112
+ -> accessor (curl_cffi / Patchright / nodriver, BrowserManager)
113
+ -> core (models, config, detection, rendering, proxy, backoff)
114
+ ```
115
+
116
+ - **Strategy** — the three tiers are interchangeable `async (request) -> FetchResult`
117
+ callables in a registry (`service/strategies.py`).
118
+ - **Chain of Responsibility** (intent) — `auto` mode walks the tiers cheapest-first,
119
+ escalating until one yields usable content (`service/escalation.py`).
120
+ - **Decorator** — `with_retry` adds exponential-backoff + Retry-After to any tier
121
+ (`service/retry.py`), hand-rolled on the stdlib (no `tenacity`).
122
+ - **Manager** — `BrowserManager` owns one reused Chromium and closes it on the
123
+ FastMCP lifespan shutdown (`accessor/browser.py`).
124
+
125
+ ## Quickstart
126
+
127
+ ```bash
128
+ uv sync
129
+ uv pip install -e . # installs the `web-fetch-mcp` console command
130
+ web-fetch-mcp # run the stdio MCP server
131
+ ```
132
+
133
+ Register it with any MCP-compatible client as a stdio server that runs the
134
+ `web-fetch-mcp` command (or `python -m web_fetch_mcp.controller.app`).
135
+
136
+ ```python
137
+ fetch("https://example.com/article", output="article") # clean main content
138
+ fetch("https://api.site/data.json") # pretty-printed JSON
139
+ fetch("https://spa.example.com", mode="dynamic") # force a JS render
140
+ ```
141
+
142
+ ## Responsible use
143
+
144
+ This tool is for fetching content you are **authorized** to access. You are
145
+ solely responsible for complying with each site's Terms of Service, `robots.txt`,
146
+ and applicable law. It honors `Retry-After` and backs off by default; please
147
+ rate-limit responsibly. It does **not** solve CAPTCHAs or bypass authentication
148
+ you do not hold. Provided **as-is, without warranty**.
149
+
150
+ ## License
151
+
152
+ [Apache-2.0](LICENSE).
@@ -0,0 +1,120 @@
1
+ # web-fetch-mcp
2
+
3
+ **A web-fetch [MCP](https://modelcontextprotocol.io) server for LLM agents that
4
+ fails honestly — it raises `FetchBlocked` instead of silently handing your model
5
+ a CAPTCHA or login page as if it were the article.**
6
+
7
+ Naive fetchers poison an agent's context: when a site returns a JavaScript
8
+ interstitial or a login wall with HTTP 200, the agent reads the challenge page as
9
+ if it were content and reasons from garbage. `web-fetch-mcp` detects that and
10
+ either escalates to a stronger strategy or fails loudly.
11
+
12
+ > **Status:** early / alpha. The escalation logic and helpers are unit-tested,
13
+ > but real-world bypass rates are not yet benchmarked — see `assets/benchmarks.md`
14
+ > and the roadmap in `TODO.md`.
15
+
16
+ ## How it works
17
+
18
+ A cheapest-first escalation ladder. Each tier targets a different layer of
19
+ bot-detection, and the server only pays for the expensive ones when it has to:
20
+
21
+ | Tier | Engine | Targets | Speed |
22
+ |------|--------|---------|-------|
23
+ | 1 | `curl_cffi` (Chrome TLS/HTTP2 fingerprint) | TLS (JA3/JA4) + HTTP/2 fingerprinting | ~500 ms |
24
+ | 2 | Patchright (real headful Chrome) | JavaScript fingerprinting; renders SPAs | ~1–3 s |
25
+ | 3 | nodriver (custom CDP) | automation-protocol (CDP) detection | ~2–4 s |
26
+
27
+ Every tier's output is checked for **hard blocks** (403/429/503) and **soft
28
+ blocks** (HTTP-200 challenge or login bodies served in place of content).
29
+ Transient failures retry with exponential backoff + jitter (honoring
30
+ `Retry-After`) before escalating. If everything is blocked, it raises
31
+ `FetchBlocked` with a remedy hint — it never returns a block page as content.
32
+
33
+ ### Escalation path (`mode="auto"`)
34
+
35
+ ```mermaid
36
+ flowchart TD
37
+ A["fetch(url)"] --> B{dismiss_selector set?}
38
+ B -- "no" --> T1["Tier 1 · curl_cffi<br/>static fetch"]
39
+ B -- "yes (can't click)" --> T2
40
+
41
+ T1 --> C1{blocked or<br/>empty SPA shell?}
42
+ C1 -- "no" --> OK["render_by_type → return"]
43
+ C1 -- "yes, escalate" --> T2["Tier 2 · Patchright<br/>headful Chrome, JS render"]
44
+
45
+ T2 --> C2{blocked?}
46
+ C2 -- "no" --> OK
47
+ C2 -- "yes, escalate" --> T3["Tier 3 · nodriver<br/>custom-CDP stealth"]
48
+
49
+ T3 --> C3{blocked?}
50
+ C3 -- "no" --> OK
51
+ C3 -- "yes" --> X["raise FetchBlocked<br/>(suggest residential proxy)"]
52
+
53
+ OK:::done
54
+ X:::fail
55
+ classDef done fill:#1f7a1f,color:#fff,stroke:#0d4d0d;
56
+ classDef fail fill:#a11,color:#fff,stroke:#600;
57
+ ```
58
+
59
+ Each tier runs through `with_retry` (exponential backoff + jitter, honoring
60
+ `Retry-After`) before the chain escalates. Tier 1 must clear the **strict** check
61
+ (not blocked **and** not an unrendered SPA shell); Tiers 2–3 only need to be
62
+ not-blocked. The single-tier modes (`static`/`dynamic`/`stealth`) run exactly one
63
+ box and skip the chain.
64
+
65
+ ## Tools
66
+
67
+ - **`fetch`** — retrieve a page as `markdown` / `text` / `html` / `article`
68
+ (main-content extraction via trafilatura). Non-HTML URLs are auto-handled:
69
+ JSON is pretty-printed, PDFs are text-extracted, images return a note to use
70
+ `screenshot`.
71
+ - **`screenshot`** — render a page in real Chrome and return a PNG.
72
+
73
+ ## Architecture
74
+
75
+ A layered package (`src/web_fetch_mcp/`), dependencies pointing inward:
76
+
77
+ ```
78
+ controller (FastMCP tools, lifespan) controller/app.py
79
+ -> service (retry decorator, strategy registry, escalation, facade)
80
+ -> accessor (curl_cffi / Patchright / nodriver, BrowserManager)
81
+ -> core (models, config, detection, rendering, proxy, backoff)
82
+ ```
83
+
84
+ - **Strategy** — the three tiers are interchangeable `async (request) -> FetchResult`
85
+ callables in a registry (`service/strategies.py`).
86
+ - **Chain of Responsibility** (intent) — `auto` mode walks the tiers cheapest-first,
87
+ escalating until one yields usable content (`service/escalation.py`).
88
+ - **Decorator** — `with_retry` adds exponential-backoff + Retry-After to any tier
89
+ (`service/retry.py`), hand-rolled on the stdlib (no `tenacity`).
90
+ - **Manager** — `BrowserManager` owns one reused Chromium and closes it on the
91
+ FastMCP lifespan shutdown (`accessor/browser.py`).
92
+
93
+ ## Quickstart
94
+
95
+ ```bash
96
+ uv sync
97
+ uv pip install -e . # installs the `web-fetch-mcp` console command
98
+ web-fetch-mcp # run the stdio MCP server
99
+ ```
100
+
101
+ Register it with any MCP-compatible client as a stdio server that runs the
102
+ `web-fetch-mcp` command (or `python -m web_fetch_mcp.controller.app`).
103
+
104
+ ```python
105
+ fetch("https://example.com/article", output="article") # clean main content
106
+ fetch("https://api.site/data.json") # pretty-printed JSON
107
+ fetch("https://spa.example.com", mode="dynamic") # force a JS render
108
+ ```
109
+
110
+ ## Responsible use
111
+
112
+ This tool is for fetching content you are **authorized** to access. You are
113
+ solely responsible for complying with each site's Terms of Service, `robots.txt`,
114
+ and applicable law. It honors `Retry-After` and backs off by default; please
115
+ rate-limit responsibly. It does **not** solve CAPTCHAs or bypass authentication
116
+ you do not hold. Provided **as-is, without warranty**.
117
+
118
+ ## License
119
+
120
+ [Apache-2.0](LICENSE).
@@ -0,0 +1,140 @@
1
+ # web-fetch-mcp — TODO / Backlog
2
+
3
+ Future additions, roughly prioritized. Items in **In design** are actively
4
+ being specced; the rest are candidate ideas.
5
+
6
+ ## Done
7
+ - [x] **Article / readability mode** — `output="article"` via trafilatura.
8
+ - [x] **Retry-After honoring** — capped server-specified wait on 429/503.
9
+ - [x] **Content-type handling** — JSON pretty-print, PDF text, image note.
10
+
11
+ ## High value, not yet started
12
+ - [ ] **`web_search` tool** — completes the search → fetch → read loop the
13
+ `fetch` docstring already references. Pluggable backend:
14
+ - **DuckDuckGo** — free, keyless default (best-effort; unofficial scraping lib,
15
+ breaks periodically). No official web-results API.
16
+ - **Tavily** — LLM/agent-native search API. Returns cleaned, ranked content
17
+ (+ optional synthesized answer with sources) and a `/extract` endpoint, so it
18
+ minimizes post-fetch cleanup. Free tier ~1,000 credits/mo, no card; paid from
19
+ ~$30/mo. **Best fit for this MCP** — pairs naturally with `fetch`.
20
+ Activate via `TAVILY_API_KEY` when set. (Pricing approximate — verify.)
21
+ - **Brave Search API** — official, independent index, clean JSON SERP. Free
22
+ ~2k/mo (card required); paid ~$3–5 per 1k queries. Good general-purpose
23
+ keyed SERP backend.
24
+ - **Exa** — neural/semantic search ("find pages like this"). Best for research
25
+ discovery rather than plain top-N results.
26
+ - Design idea: keyless DDG default, upgrade to Tavily/Brave/Exa if an API key
27
+ is present.
28
+ - [ ] **Batch `fetch_many(urls)`** — concurrent multi-URL fetch reusing the
29
+ existing async browser.
30
+
31
+ ## Optional ML integrations (phase 2 — all optional extras, lazily imported)
32
+
33
+ **Design rule:** the tool serves two consumer modes — (a) a capable LLM agent
34
+ that already reads + judges content natively, and (b) a standalone server/library
35
+ in a non-LLM pipeline (scraper, RAG ingestion, monitor). A good ML feature helps
36
+ the *fetch mechanics* (something a downstream consumer can't do for itself); a bad
37
+ one duplicates judgment a capable caller already does. **Never a hard dependency**
38
+ (`pip install web-fetch-mcp[ml]`), lazily imported, pretrained CPU models, and it
39
+ must respect the "fail honestly / never silently drop content" contract.
40
+
41
+ Ranked by fit:
42
+
43
+ - [ ] **ML block/challenge detection (BEST FIT)** — second-stage *confirmer* on
44
+ top of `_is_blocked`'s substring list. The hand-maintained `_BLOCK_MARKERS`
45
+ list has a recall gap (a real soft-block gate was found by hand). A tiny text
46
+ classifier ("real content vs block/challenge/login/paywall shell") generalizes
47
+ to unseen gates. Helps BOTH consumer modes and deepens the project's crown
48
+ jewel (honest failure). Use only when a page is *ambiguous* (passed substring
49
+ check but suspiciously thin), not as a replacement — keeps the fast, zero-dep,
50
+ interpretable path as the default and limits false positives.
51
+ - **Recommended model: MiniLM-L6 fine-tuned → ONNX, INT8-quantized.** ~25MB
52
+ artifact, **~4–12ms/page CPU** (negligible vs the 500–4000ms fetch it guards).
53
+ Train/export with torch on the dev box; **ship torch-free** — runtime deps are
54
+ only `onnxruntime` + `tokenizers` + `numpy` (optional `[ml]` extra, lazily
55
+ imported, graceful fallback to substring-only when absent). Commit a `train/`
56
+ script so reviewers see the fine-tune (training code, not a runtime dep).
57
+ - **Design: structural/infra signals FIRST (language-neutral)** — short
58
+ visible-text length, high script-tag ratio, infra markers (`cf-chl`,
59
+ `datadome`, `px-captcha`, `/cdn-cgi/challenge-platform`), hard HTTP status —
60
+ these catch most foreign-language gates regardless of human language. The text
61
+ classifier is the second-stage confirmer for ambiguous cases only.
62
+ - **Multilingual:** lexical/TF-IDF approaches are English-centric; if
63
+ multilingual matters, start Option C from a multilingual base
64
+ (`microsoft/Multilingual-MiniLM-L12-H384` / `bge-m3` family) — ~50MB INT8,
65
+ ~10–25ms. Turns the weakness into a "shipped a torch-free multilingual
66
+ classifier" portfolio line.
67
+ - **Lighter fallback (Option A):** TF-IDF char-ngram + LogisticRegression,
68
+ <1MB, <1ms, scikit-learn only, interpretable — right tool if the signal stays
69
+ shallow/lexical and multilingual isn't a priority.
70
+ - [ ] **Embeddings / chunked RAG output** — a mode returning the page cleaned,
71
+ chunked, and optionally embedded (bi-encoder, contrastive-trained, e.g.
72
+ `BAAI/bge-small-en-v1.5`). Strong value for the standalone RAG-ingestion
73
+ consumer (this is what Jina Reader / Firecrawl monetize). Produces vectors,
74
+ never silently judges — ethos-safe. Good ML/RAG portfolio signal.
75
+ - [ ] **Relevance reranking** — gated on `web_search` existing. A cross-encoder
76
+ (`cross-encoder/ms-marco-MiniLM-L-6-v2`, ~22M, CPU, ~ms) ranks "which of N
77
+ search results to actually fetch" before paying browser cost. Valuable
78
+ precisely for the standalone consumer (no LLM to rank for it). Advisory only:
79
+ return scores, caller decides — never silently drop.
80
+ - [ ] **Page-type classification** (article/product/listing/forum) — minor;
81
+ trafilatura + content-type handling already cover most of the need. Skip unless
82
+ a consumer asks.
83
+ - [ ] **On-page summarization via Ollama/smol-LLM — SKIP.** Only helps the dumb
84
+ consumer, heavy (Ollama service or torch), quality-limited at 0.5–1B; the one
85
+ non-redundant case (non-LLM pipeline wanting a summary) is exactly where small
86
+ models disappoint. Not worth the "lightweight local-first" identity shift.
87
+
88
+ Model-choice note: prefer **pretrained off-the-shelf** (cross-encoder for
89
+ relevance, bi-encoder for embeddings). Cross-encoder > contrastive bi-encoder >
90
+ Ollama for relevance. Training a custom model needs labeled data and is overkill
91
+ for a general fetcher — see implementation notes if a custom block-detector is
92
+ ever pursued (must stay <50MB, CPU-only, e.g. ONNX-exported MiniLM or a
93
+ fastText/linear head over embeddings).
94
+
95
+ ## Robustness & open-source credibility (highest-leverage are NOT ML)
96
+
97
+ - [ ] **`robots.txt` awareness** — `respect_robots=True` option that checks
98
+ robots before fetching. The single best open-source-credibility move: signals a
99
+ responsible-scraping tool, backs the authorized-use README disclaimer, pre-empts
100
+ ToS criticism. Cheap, high-signal.
101
+ - [ ] **Structured failure taxonomy** — replace the single `FetchBlocked` with
102
+ subclasses: `CaptchaWall` / `LoginRequired` / `RateLimited` / `NotFound` /
103
+ `Timeout`. Lets programmatic consumers branch on the reason. Pairs with the ML
104
+ classifier below (which can *label* the block type).
105
+ - [ ] **Eval / benchmark harness** (`benchmarks/`) — runs the tiers against a
106
+ fixed URL set, reports tier-hit-rate + bypass success vs a naive fetch. Turns
107
+ the "defeats most anti-bot walls" claim into a demonstrated result, and is where
108
+ any ML classifier earns its precision/recall numbers. Directly answers the
109
+ assessment's "headline claim is unverified" weakness.
110
+ - [ ] **Per-domain adaptive tier memory** — remember which tier last succeeded
111
+ for a domain and start there (skip cheap tiers known to fail for it). Cuts
112
+ latency; light systems feature. Pairs with the TTL cache.
113
+ - [ ] **Language detection** (`fasttext-langid`, ~few MB, sub-ms) — tag each
114
+ fetch with detected language for RAG routing/filtering; also feeds the
115
+ multilingual block-detector. Low cost, real utility.
116
+ - [ ] **Near-duplicate detection** (MinHash/SimHash — statistical, no torch) —
117
+ detect when two URLs return substantially the same content (mirrors, tracking-
118
+ param variants). Useful for `fetch_many`/crawl; pairs with the TTL cache.
119
+ - [ ] **Multi-class page-state classifier (ELEGANT ML WIN)** — instead of a
120
+ binary block detector, make the ONNX model multi-class:
121
+ content / captcha / login / rate-limited / soft-404. ONE small model then powers
122
+ BOTH honest-failure detection AND the structured failure taxonomy above. Catches
123
+ HTTP-200 soft-404s (sites that return 200 for missing pages). Non-redundant with
124
+ the caller LLM, strong portfolio signal, and the eval harness gives it real
125
+ precision/recall. This is the recommended shape for the ML classifier.
126
+
127
+ Explicitly NOT doing: LLM summarization (redundant with caller, heavy); custom
128
+ content-extractor (trafilatura already wins); anything that silently drops or
129
+ transforms content (violates the honest-failure contract).
130
+
131
+ ## Nice to have
132
+ - [ ] **Metadata extraction** — title, description, OpenGraph, JSON-LD,
133
+ outbound links, without pulling the full body.
134
+ - [ ] **Response caching (TTL)** — avoid re-fetching the same URL within a
135
+ window; cuts latency and repeat-hit block risk.
136
+ - [ ] **Custom headers/cookies param** — let callers pass a cookie jar or auth
137
+ header for sites they have sessions on.
138
+ - [ ] **Optional managed-unblocker tier** — escalate to ScrapingBee / ScraperAPI
139
+ / Bright Data / Zyte after nodriver for CAPTCHA walls the local tiers can't
140
+ beat. (The `fetch` docstring already points users here for CAPTCHA-gated sites.)