Skip to content

Commit 4aac5e4

Browse files
authored
Merge pull request #5391 from modelcontextprotocol/v2/fix/5306-fetch-readability-subprocess
fix(fetch): run Readability.js under a bounded subprocess, off the event loop and stdout
2 parents 00389e1 + e4ce738 commit 4aac5e4

9 files changed

Lines changed: 924 additions & 70 deletions

File tree

‎.github/workflows/python.yml‎

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -142,24 +142,16 @@ jobs:
142142
working-directory: src/${{ matrix.package }}
143143
run: uv sync --locked --all-extras --dev
144144

145-
# fetch's tests pin readabilipy's Readability.js path, which needs Node
146-
# and readabilipy's JavaScript dependencies. readabilipy >= 0.3.0 ships
147-
# only their package.json and runs `npm install` on first use, but on
148-
# Windows its subprocess call cannot find npm (npm.cmd), so it falls back
149-
# to the pure-Python extractor. Install them here, as an operator would.
145+
# fetch's tests pin the Readability.js path, which needs Node and npm.
146+
# readabilipy >= 0.3.0 ships only its JavaScript's package.json, and the
147+
# server installs the dependencies on first use, resolving npm through
148+
# PATH so Windows' npm.cmd is found (#5313). Nothing is pre-installed
149+
# here, so this leg proves that install works on Windows.
150150
- uses: actions/setup-node@v7
151151
if: matrix.package == 'fetch'
152152
with:
153153
node-version: 24
154154

155-
- name: Install readabilipy's JavaScript dependencies
156-
if: matrix.package == 'fetch'
157-
working-directory: src/fetch
158-
shell: bash
159-
run: |
160-
jsdir=$(uv run --frozen python -c "import os, readabilipy; print(os.path.join(os.path.dirname(readabilipy.__file__), 'javascript'))")
161-
cd "$jsdir" && npm install --no-audit --no-fund
162-
163155
- name: Run pytest
164156
working-directory: src/${{ matrix.package }}
165157
run: uv run --frozen pytest

‎src/fetch/README.md‎

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ The server speaks both eras of the Model Context Protocol over stdio, with nothi
4646
## Installation
4747

4848
Optionally: Install node.js, this will cause the fetch server to use a different HTML simplifier that is more robust.
49+
Its JavaScript dependencies are then installed with npm on first use, which contacts the npm registry.
4950
To keep the server from ever starting Node.js, see [Customization - HTML extraction](#customization---html-extraction).
5051

5152
### Using uv (recommended)
@@ -213,11 +214,34 @@ installed with the server). A `socks://` proxy URL, as many desktop proxy settin
213214

214215
### Customization - HTML extraction
215216

216-
HTML is converted to Markdown by [readabilipy](https://github.com/alan-turing-institute/ReadabiliPy). When Node.js is
217-
on the `PATH`, readabilipy runs Mozilla's Readability.js in a Node.js subprocess; otherwise it uses its own
218-
pure-Python extractor, which keeps headings and text but drops link targets. The Node.js subprocess runs with no
219-
timeout, so a Node.js that hangs, or fails in a way readabilipy does not detect, stalls the tool call until the client
220-
gives up.
217+
HTML is converted to Markdown with [readabilipy](https://github.com/alan-turing-institute/ReadabiliPy). When Node.js 14
218+
or newer is on the `PATH`, the server runs Mozilla's Readability.js (readabilipy's `ExtractArticle.js`) in a Node.js
219+
subprocess; otherwise it uses readabilipy's pure-Python extractor, which keeps headings and text but drops link
220+
targets. The subprocess runs off the server's event loop, so other requests are answered while it works, and under a
221+
30 second timeout: a Node.js that hangs is killed, together with anything it started, and that page is extracted with
222+
the pure-Python extractor instead. If Readability.js fails in any other way, the same fallback is used. Every reason
223+
for a fallback is written to stderr (the server's log), never to stdout, which carries the protocol.
224+
225+
**Readability.js's dependencies are installed with npm on first use, which reaches the npm registry.** readabilipy
226+
ships only the `package.json` for its JavaScript (`@mozilla/readability`, `jsdom`, `minimist`). The first time the
227+
server extracts HTML with Node.js on the `PATH` and those packages missing, it runs `npm install` in readabilipy's
228+
`javascript` directory, inside that tool call, so:
229+
230+
- `registry.npmjs.org` belongs in the egress allowlist of a deployment that restricts outbound traffic, unless the
231+
packages are installed ahead of time (below) or Readability.js is turned off. Without it the install fails and the
232+
server uses the pure-Python extractor.
233+
- The JavaScript that runs is resolved from readabilipy's unpinned version ranges when it is installed, so pinning
234+
`mcp-server-fetch` does not pin it.
235+
- The install runs at most once per server process, under a 120 second timeout. Its output goes to stderr. If it
236+
fails, or Node.js is missing or older than 14, the server uses the pure-Python extractor until it is restarted.
237+
238+
To install the packages ahead of time (in a container image, say), run `npm install` in readabilipy's `javascript`
239+
directory from the Python environment the server runs in; the server then finds them and installs nothing:
240+
241+
```bash
242+
cd "$(python -c "import os, readabilipy; print(os.path.join(os.path.dirname(readabilipy.__file__), 'javascript'))")"
243+
npm install --no-audit --no-fund
244+
```
221245

222246
Readability.js discards hidden elements. Pages rendered progressively on the server often send a visible loading
223247
shell, then the real content in a container hidden (`display: none`, `visibility: hidden`, `hidden`) until scripts
@@ -226,7 +250,8 @@ Readability.js extracted, the server unhides it and runs Readability.js again, k
226250
text. Other pages are extracted once, exactly as before.
227251

228252
To always use the pure-Python extractor, add the argument `--no-readability-js` to the `args` list in the
229-
configuration. The server then never starts Node.js (or npm), whether or not it is installed.
253+
configuration. The server then never starts Node.js (or npm), whether or not it is installed, and never contacts the
254+
npm registry.
230255

231256
## Windows Configuration
232257

@@ -270,6 +295,10 @@ If you're experiencing timeout issues on Windows, you may need to set the `PYTHO
270295

271296
This addresses character encoding issues that can cause the server to timeout on Windows systems.
272297

298+
Readability.js works on Windows as it does elsewhere: the server finds Node.js and npm (`npm.cmd`) on the `PATH`, and
299+
installs Readability.js's dependencies on first use as described in
300+
[Customization - HTML extraction](#customization---html-extraction).
301+
273302
## Debugging
274303

275304
You can use the MCP inspector to debug the server. For uvx installations:
@@ -294,7 +323,7 @@ uv sync --frozen --all-extras --dev
294323
uv run --frozen pytest
295324
```
296325

297-
The tests drive `serve()` through an MCP `ClientSession` in-process (and, in `tests/test_eras.py`, through a `Client` as a 2026-07-28 and as a 2025-11-25 client), with HTTP mocked, so they need no network. The HTML extraction tests need Node.js on `PATH` (readabilipy uses Readability.js when Node is present and a pure-Python fallback when it is not).
326+
The tests drive `serve()` through an MCP `ClientSession` in-process (and, in `tests/test_eras.py`, through a `Client` as a 2026-07-28 and as a 2025-11-25 client), with HTTP mocked, so they need no network. The HTML extraction tests need Node.js and npm on `PATH` (the server uses Readability.js when Node is present and a pure-Python fallback when it is not), and the first run installs Readability.js's dependencies from the npm registry.
298327

299328
Coverage, measured per file with branch coverage:
300329

Lines changed: 274 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,274 @@
1+
# Runs Mozilla's Readability.js (readabilipy's `ExtractArticle.js`) under
2+
# Node.js in a subprocess the server controls, instead of through readabilipy's
3+
# own wrapper (`simple_json_from_html_string(use_readability=True)`).
4+
#
5+
# readabilipy's wrapper had four defects for a stdio MCP server, each fixed
6+
# here rather than worked around at the call site:
7+
#
8+
# - No timeout (#5306). Its `subprocess.run` calls wait forever, so a Node.js
9+
# or npm that hangs stalled the tool call. Every process here runs under a
10+
# timeout, and on timeout its whole process tree is killed (a process group
11+
# on POSIX, `taskkill /T` on Windows), so nothing is left running.
12+
# - Child output on fd 1 (#5310). Its `npm install` inherits the server's
13+
# stdout, which over stdio is the JSON-RPC channel, and it `print`s Node's
14+
# stderr to stdout on a failure. Here every child gets stdin from the null
15+
# device (it must never read the server's JSON-RPC input either) and pipes
16+
# for stdout and stderr; whatever a child prints is forwarded to stderr.
17+
# - npm not found on Windows (#5313). It runs a bare `npm`, which Windows'
18+
# `CreateProcess` does not resolve to `npm.cmd`. Here `node` and `npm` are
19+
# resolved with `shutil.which`, which honours `PATHEXT`.
20+
# - A failed Readability.js run raised out of the tool call. Here any failure
21+
# (no Node.js, an old one, no npm, a failed install, a timeout, a crash, bad
22+
# output) returns None, and the caller falls back to readabilipy's
23+
# pure-Python extractor, with the reason written to stderr.
24+
#
25+
# readabilipy >= 0.3.0 ships only `package.json` for its JavaScript and runs
26+
# `npm install` on first use, which reaches the npm registry during a tool call
27+
# (#4830). That stays the behaviour (the README states it), but the install now
28+
# runs at most once per process, under a lock and a timeout. It installs into
29+
# readabilipy's own `javascript` directory, so dependencies an operator
30+
# installed there ahead of time (the README says how) are found and nothing is
31+
# fetched.
32+
#
33+
# Everything here is synchronous: the caller runs extraction in a worker
34+
# thread (`asyncio.to_thread`), so the server's event loop never waits on it.
35+
36+
from __future__ import annotations
37+
38+
import json
39+
import os
40+
import shutil
41+
import signal
42+
import subprocess
43+
import sys
44+
import tempfile
45+
import threading
46+
from pathlib import Path
47+
48+
import readabilipy
49+
50+
# How long one Readability.js run may take before it is killed.
51+
EXTRACT_TIMEOUT_SECONDS = 30.0
52+
# How long the one-time `npm install` of readabilipy's JavaScript may take.
53+
INSTALL_TIMEOUT_SECONDS = 120.0
54+
# How long `node -v` may take.
55+
VERSION_TIMEOUT_SECONDS = 10.0
56+
# How long cleanup after a timeout may wait: for `taskkill`, and for the
57+
# killed child to be reaped.
58+
KILL_TIMEOUT_SECONDS = 5.0
59+
# readabilipy's `package.json` declares `"engines": {"node": ">=14.0.0"}`.
60+
MIN_NODE_MAJOR = 14
61+
# What `ExtractArticle.js` requires; all three present means installed.
62+
JS_DEPENDENCIES = ("@mozilla/readability", "jsdom", "minimist")
63+
64+
_probe_lock = threading.Lock()
65+
_probed = False
66+
_node: str | None = None
67+
68+
69+
def javascript_dir() -> Path:
70+
"""readabilipy's `javascript` directory: `ExtractArticle.js` and `node_modules`."""
71+
return Path(readabilipy.__file__).parent / "javascript"
72+
73+
74+
def _log(message: str) -> None:
75+
# stderr only: stdout is the JSON-RPC channel.
76+
print(f"mcp-server-fetch: {message}", file=sys.stderr, flush=True)
77+
78+
79+
def _forward(output: str) -> None:
80+
"""Copy a child's captured output to stderr, never to stdout."""
81+
if output:
82+
sys.stderr.write(output if output.endswith("\n") else output + "\n")
83+
sys.stderr.flush()
84+
85+
86+
def _kill_tree(proc: subprocess.Popen[str]) -> None:
87+
"""Kill ``proc`` and everything it started (npm runs node, `npm.cmd` runs cmd)."""
88+
if sys.platform == "win32":
89+
try:
90+
subprocess.run(
91+
["taskkill", "/F", "/T", "/PID", str(proc.pid)],
92+
stdin=subprocess.DEVNULL,
93+
stdout=subprocess.DEVNULL,
94+
stderr=subprocess.DEVNULL,
95+
check=False,
96+
timeout=KILL_TIMEOUT_SECONDS,
97+
)
98+
except (OSError, subprocess.SubprocessError):
99+
# taskkill could not start or did not finish: the direct child
100+
# is still killed below.
101+
pass
102+
else:
103+
try:
104+
# start_new_session made the child a process-group leader.
105+
os.killpg(proc.pid, signal.SIGKILL)
106+
except ProcessLookupError:
107+
pass
108+
# Whatever the tree kill did, the direct child is certainly gone after this.
109+
proc.kill()
110+
111+
112+
def _run(
113+
argv: list[str], timeout: float, cwd: Path | None = None
114+
) -> subprocess.CompletedProcess[str] | None:
115+
"""Run ``argv`` detached from the server's stdio, or None if it could not
116+
start or did not finish within ``timeout`` seconds (it is killed then)."""
117+
try:
118+
proc = subprocess.Popen(
119+
argv,
120+
cwd=cwd,
121+
stdin=subprocess.DEVNULL,
122+
stdout=subprocess.PIPE,
123+
stderr=subprocess.PIPE,
124+
text=True,
125+
encoding="utf-8",
126+
errors="replace",
127+
# POSIX only (ignored on Windows): its own process group, so a
128+
# timeout can kill the processes it starts as well.
129+
start_new_session=True,
130+
)
131+
except OSError as e:
132+
_log(f"could not start {argv[0]}: {e}")
133+
return None
134+
try:
135+
stdout, stderr = proc.communicate(timeout=timeout)
136+
except subprocess.TimeoutExpired:
137+
_kill_tree(proc)
138+
# Reap the child, but do not drain its pipes: a descendant that left
139+
# its process group (or survived taskkill) can hold them open forever.
140+
# The pipes close when `proc` is collected.
141+
try:
142+
proc.wait(timeout=KILL_TIMEOUT_SECONDS)
143+
except subprocess.TimeoutExpired:
144+
pass
145+
_log(f"{Path(argv[0]).name} did not finish within {timeout:g} s and was killed")
146+
return None
147+
return subprocess.CompletedProcess(argv, proc.returncode, stdout, stderr)
148+
149+
150+
def _node_major(version: str) -> int | None:
151+
"""The major version in `node -v` output (``v24.1.0``), or None."""
152+
head = version.strip().lstrip("v").split(".", 1)[0]
153+
return int(head) if head.isdigit() else None
154+
155+
156+
def _dependencies_installed(jsdir: Path) -> bool:
157+
modules = jsdir / "node_modules"
158+
return all((modules / name / "package.json").is_file() for name in JS_DEPENDENCIES)
159+
160+
161+
def _install_dependencies(jsdir: Path) -> bool:
162+
"""`npm install` readabilipy's JavaScript dependencies; whether it worked."""
163+
npm = shutil.which("npm")
164+
if npm is None:
165+
_log(
166+
"npm was not found on PATH, so Readability.js's dependencies cannot be "
167+
f"installed in {jsdir}; using the pure-Python extractor"
168+
)
169+
return False
170+
_log(
171+
f"installing Readability.js's dependencies with npm in {jsdir} (first use; "
172+
"this contacts the npm registry)"
173+
)
174+
done = _run(
175+
[npm, "install", "--no-audit", "--no-fund"],
176+
timeout=INSTALL_TIMEOUT_SECONDS,
177+
cwd=jsdir,
178+
)
179+
if done is None:
180+
return False
181+
_forward(done.stdout)
182+
_forward(done.stderr)
183+
if done.returncode != 0 or not _dependencies_installed(jsdir):
184+
_log(
185+
f"npm install failed (exit {done.returncode}); using the pure-Python extractor"
186+
)
187+
return False
188+
return True
189+
190+
191+
def _find_node() -> str | None:
192+
"""A Node.js ready to run `ExtractArticle.js`, installing its dependencies
193+
if they are missing, or None (the reason is logged)."""
194+
node = shutil.which("node")
195+
if node is None:
196+
_log("Node.js was not found on PATH; using the pure-Python extractor")
197+
return None
198+
done = _run([node, "-v"], timeout=VERSION_TIMEOUT_SECONDS)
199+
major = _node_major(done.stdout) if done and done.returncode == 0 else None
200+
if major is None or major < MIN_NODE_MAJOR:
201+
_log(
202+
f"Node.js >= {MIN_NODE_MAJOR} is needed for Readability.js "
203+
f"({node} did not report one); using the pure-Python extractor"
204+
)
205+
return None
206+
jsdir = javascript_dir()
207+
if not _dependencies_installed(jsdir) and not _install_dependencies(jsdir):
208+
return None
209+
return node
210+
211+
212+
def node_path() -> str | None:
213+
"""The Node.js to run Readability.js with, or None to use pure Python.
214+
215+
Probed once per process, under a lock, so concurrent first calls run one
216+
`npm install` between them. A failed probe is not retried until the server
217+
restarts, so a missing or broken Node.js costs one probe, not one per call.
218+
"""
219+
global _probed, _node
220+
with _probe_lock:
221+
if not _probed:
222+
_node = _find_node()
223+
_probed = True
224+
return _node
225+
226+
227+
def extract_article(html: str) -> str | None:
228+
"""Readability.js's article HTML for ``html`` ("" when it finds none), or
229+
None when Readability.js is unavailable or failed, to fall back on."""
230+
node = node_path()
231+
if node is None:
232+
return None
233+
jsdir = javascript_dir()
234+
with tempfile.TemporaryDirectory(
235+
prefix="mcp-server-fetch-", ignore_cleanup_errors=True
236+
) as tmp:
237+
page = Path(tmp, "page.html")
238+
result = Path(tmp, "article.json")
239+
page.write_text(html, encoding="utf-8")
240+
done = _run(
241+
[
242+
node,
243+
str(jsdir / "ExtractArticle.js"),
244+
"-i",
245+
str(page),
246+
"-o",
247+
str(result),
248+
],
249+
timeout=EXTRACT_TIMEOUT_SECONDS,
250+
cwd=jsdir,
251+
)
252+
if done is None:
253+
_log(
254+
"Readability.js was stopped; using the pure-Python extractor for this "
255+
"page. Start the server with --no-readability-js to never use it."
256+
)
257+
return None
258+
if done.returncode != 0 or not result.is_file():
259+
_forward(done.stderr)
260+
_log(
261+
f"Readability.js failed (exit {done.returncode}); using the "
262+
"pure-Python extractor for this page"
263+
)
264+
return None
265+
try:
266+
article = json.loads(result.read_text(encoding="utf-8"))
267+
except ValueError:
268+
_log(
269+
"Readability.js wrote unreadable output; using the pure-Python extractor"
270+
)
271+
return None
272+
# `Readability.parse()` returns null for a page with no article.
273+
content = article.get("content") if isinstance(article, dict) else None
274+
return content if isinstance(content, str) else ""

0 commit comments

Comments
 (0)