Skip to content

Commit fed94f8

Browse files
cliffhallclaude
andcommitted
feat(fetch): make the HTTP request timeout configurable
The page request's 30 s timeout was hard-coded. It can now be set per call with the fetch tool's timeout_ms argument (100 to 600000 ms, advertised with the server default as its default), server-wide with --timeout-ms or FETCH_TIMEOUT_MS, the most specific winning, and stays 30 s when none is given. A timed-out request says how long it waited. The robots.txt check keeps httpx's own default. Closes #4448 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: cliffhall <cliff@futurescale.com>
1 parent 446be48 commit fed94f8

6 files changed

Lines changed: 419 additions & 1 deletion

File tree

‎src/fetch/README.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ The fetch tool will truncate the response, but by using the `start_index` argume
2222
- `max_length` (integer, optional): Maximum number of characters to return (default: 5000)
2323
- `start_index` (integer, optional): Start content from this character index (default: 0)
2424
- `raw` (boolean, optional): Get raw content without markdown conversion (default: false)
25+
- `timeout_ms` (integer, optional): HTTP request timeout for this call, in milliseconds, from 100 to 600000 (default: the server's timeout, 30000 unless configured; see [Customization - Timeout](#customization---timeout))
2526
- Annotations: `readOnlyHint: true`, `destructiveHint: false`, `idempotentHint: true`, `openWorldHint: true` (it only reads, and it reaches arbitrary hosts on the internet)
2627

2728
### Prompts
@@ -202,6 +203,25 @@ ModelContextProtocol/1.0 (User-Specified; +https://github.com/modelcontextprotoc
202203

203204
This can be customized by adding the argument `--user-agent=YourUserAgent` to the `args` list in the configuration.
204205

206+
### Customization - Timeout
207+
208+
The HTTP request for the page waits up to 30 seconds (30000 ms) by default: to connect, and then for each read of the
209+
response. It bounds each of those separately, not the whole download, so a large page that keeps arriving is not cut
210+
off. A request that times out fails with a tool error saying how long it waited.
211+
212+
The timeout can be set at three levels, the most specific winning:
213+
214+
1. The `fetch` tool's `timeout_ms` argument, for one call (for example `120000` for a large download, or `5000` to
215+
fail fast).
216+
2. The argument `--timeout-ms=60000` in the `args` list in the configuration, for every call.
217+
3. The `FETCH_TIMEOUT_MS` environment variable (for example `"env": {"FETCH_TIMEOUT_MS": "60000"}` in the
218+
configuration), for every call when `--timeout-ms` is not given.
219+
220+
The server-wide value also applies to the `fetch` prompt, and is the default the tool advertises for `timeout_ms`.
221+
Every level takes a whole number of milliseconds from 100 to 600000 (10 minutes); the server refuses to start with a
222+
value outside that range, and the tool refuses such a `timeout_ms`. This is the HTTP request timeout only: the
223+
robots.txt check before an autonomous fetch keeps its own 5-second timeout, and HTML extraction is not covered.
224+
205225
### Customization - Proxy
206226

207227
The server can be configured to use a proxy by using the `--proxy-url` argument.

‎src/fetch/src/mcp_server_fetch/__init__.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,31 @@
11
from .server import serve
2+
from .timeout import (
3+
DEFAULT_TIMEOUT_MS,
4+
MAX_TIMEOUT_MS,
5+
MIN_TIMEOUT_MS,
6+
TIMEOUT_ENV,
7+
parse_timeout_ms,
8+
timeout_ms_from_env,
9+
)
210

311

412
def main():
513
"""MCP Fetch Server - HTTP fetching functionality for MCP"""
614
import argparse
715
import asyncio
16+
import os
817

918
parser = argparse.ArgumentParser(
1019
description="give a model the ability to make web requests"
1120
)
1221
parser.add_argument("--user-agent", type=str, help="Custom User-Agent string")
22+
parser.add_argument(
23+
"--timeout-ms",
24+
type=parse_timeout_ms,
25+
help=f"HTTP request timeout in milliseconds, {MIN_TIMEOUT_MS} to "
26+
f"{MAX_TIMEOUT_MS} (default: ${TIMEOUT_ENV}, else {DEFAULT_TIMEOUT_MS}); "
27+
"a tool call's timeout_ms argument overrides it",
28+
)
1329
parser.add_argument(
1430
"--ignore-robots-txt",
1531
action="store_true",
@@ -29,6 +45,14 @@ def main():
2945
)
3046

3147
args = parser.parse_args()
48+
# The server reads its timeout from the environment (see timeout.py), and
49+
# the flag outranks a value already there; a bad value stops it here.
50+
if args.timeout_ms is not None:
51+
os.environ[TIMEOUT_ENV] = str(args.timeout_ms)
52+
try:
53+
timeout_ms_from_env()
54+
except ValueError as e:
55+
parser.error(str(e))
3256
asyncio.run(
3357
serve(
3458
args.user_agent,

‎src/fetch/src/mcp_server_fetch/server.py‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,12 @@
3636
from mcp.server.context import CallNext, HandlerResult, ServerMiddleware
3737
from mcp.server.mcpserver.exceptions import ToolError
3838
from mcp.shared.exceptions import MCPError
39+
from .timeout import (
40+
DEFAULT_TIMEOUT_MS,
41+
MAX_TIMEOUT_MS,
42+
MIN_TIMEOUT_MS,
43+
timeout_ms_from_env,
44+
)
3945
from mcp.types import INVALID_PARAMS, ToolAnnotations
4046
from protego import Protego
4147
from pydantic import AnyUrl, Field
@@ -523,6 +529,7 @@ async def fetch_url(
523529
url: str,
524530
user_agent: str,
525531
force_raw: bool = False,
532+
timeout_ms: int = DEFAULT_TIMEOUT_MS,
526533
proxy_url: str | None = None,
527534
allow_private_ips: bool = False,
528535
check_robots_txt: bool = False,
@@ -562,7 +569,11 @@ async def _check_redirect_robots_txt(request: httpx.Request) -> None:
562569
url,
563570
follow_redirects=True,
564571
headers={"User-Agent": user_agent},
565-
timeout=30,
572+
timeout=timeout_ms / 1000,
573+
)
574+
except httpx.TimeoutException as e:
575+
raise ToolError(
576+
f"Failed to fetch {url}: timed out after {timeout_ms} ms: {e!r}"
566577
)
567578
except HTTPError as e:
568579
raise ToolError(f"Failed to fetch {url}: {e!r}")
@@ -650,6 +661,7 @@ def create_server(
650661
normalize_proxy_env()
651662
user_agent_autonomous = custom_user_agent or DEFAULT_USER_AGENT_AUTONOMOUS
652663
user_agent_manual = custom_user_agent or DEFAULT_USER_AGENT_MANUAL
664+
default_timeout_ms = timeout_ms_from_env()
653665

654666
# subscriptions=False: the tool and prompt lists never change and there are
655667
# no resources to watch, so `subscriptions/listen` is not served and the
@@ -703,6 +715,15 @@ async def fetch(
703715
strict=True,
704716
),
705717
] = False,
718+
timeout_ms: Annotated[
719+
int,
720+
Field(
721+
description="How long to wait, in milliseconds, to connect to the server and for each read of its response before giving up. Raise it for a slow server or a large download; lower it to fail fast.",
722+
ge=MIN_TIMEOUT_MS,
723+
le=MAX_TIMEOUT_MS,
724+
strict=True,
725+
),
726+
] = default_timeout_ms,
706727
) -> str:
707728
page_url = str(url)
708729

@@ -715,6 +736,7 @@ async def fetch(
715736
page_url,
716737
user_agent_autonomous,
717738
force_raw=raw,
739+
timeout_ms=timeout_ms,
718740
proxy_url=proxy_url,
719741
allow_private_ips=allow_private_ips,
720742
check_robots_txt=not ignore_robots_txt,
@@ -748,6 +770,7 @@ async def fetch_prompt(
748770
content, prefix = await fetch_url(
749771
url,
750772
user_agent_manual,
773+
timeout_ms=default_timeout_ms,
751774
proxy_url=proxy_url,
752775
allow_private_ips=allow_private_ips,
753776
use_readability_js=use_readability_js,
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# The fetch server's HTTP request timeout (#4448): its default, its bounds, and
2+
# how a configured value is read. It applies to the page request a `fetch` tool
3+
# call or prompt makes, and is set at three levels, the most specific winning:
4+
# the tool's `timeout_ms` argument, the `--timeout-ms` flag, the
5+
# `FETCH_TIMEOUT_MS` environment variable, and otherwise 30 s (the value the
6+
# server always used). It is httpx's per-phase timeout, so it bounds the
7+
# connect, each read and each write separately rather than the whole transfer.
8+
# The same bounds hold at every level, so a server default always satisfies the
9+
# tool argument's advertised minimum and maximum, and becomes its advertised
10+
# default. robots.txt checks are not covered: they keep httpx's own default.
11+
#
12+
# The server-wide value has one source, the environment variable:
13+
# `create_server` reads it, and `main()` copies `--timeout-ms` into it (the flag
14+
# outranks a value the environment already had). So the setting reaches the
15+
# server the same way whether it was given as a flag or as a variable, and
16+
# `serve()`'s positional signature is unchanged for its existing callers.
17+
18+
import argparse
19+
import os
20+
21+
DEFAULT_TIMEOUT_MS = 30_000
22+
MIN_TIMEOUT_MS = 100
23+
MAX_TIMEOUT_MS = 600_000
24+
TIMEOUT_ENV = "FETCH_TIMEOUT_MS"
25+
26+
27+
def parse_timeout_ms(value: str) -> int:
28+
"""Parse a timeout in milliseconds, as the ``--timeout-ms`` argparse type.
29+
30+
Raises ``argparse.ArgumentTypeError``, whose message argparse prints as is.
31+
"""
32+
try:
33+
timeout_ms = int(value.strip())
34+
except ValueError:
35+
raise argparse.ArgumentTypeError(
36+
f"{value!r} is not a whole number of milliseconds"
37+
)
38+
if not MIN_TIMEOUT_MS <= timeout_ms <= MAX_TIMEOUT_MS:
39+
raise argparse.ArgumentTypeError(
40+
f"{timeout_ms} ms is outside {MIN_TIMEOUT_MS}..{MAX_TIMEOUT_MS} ms"
41+
)
42+
return timeout_ms
43+
44+
45+
def timeout_ms_from_env() -> int:
46+
"""The server-wide timeout: ``FETCH_TIMEOUT_MS`` when set, else 30 s.
47+
48+
Raises ``ValueError`` for an unparseable or out-of-range value, so a bad
49+
setting stops the server at startup rather than failing every request.
50+
"""
51+
value = os.environ.get(TIMEOUT_ENV, "").strip()
52+
if not value:
53+
return DEFAULT_TIMEOUT_MS
54+
try:
55+
return parse_timeout_ms(value)
56+
except argparse.ArgumentTypeError as e:
57+
raise ValueError(f"{TIMEOUT_ENV}: {e}") from None

‎src/fetch/tests/test_protocol.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,15 @@ async def test_list_tools_wire_shape(web: FakeWeb) -> None:
187187
"title": "Raw",
188188
"type": "boolean",
189189
},
190+
# #4448: the server-wide timeout is the advertised default.
191+
"timeout_ms": {
192+
"default": 30000,
193+
"description": "How long to wait, in milliseconds, to connect to the server and for each read of its response before giving up. Raise it for a slow server or a large download; lower it to fail fast.",
194+
"maximum": 600000,
195+
"minimum": 100,
196+
"title": "Timeout Ms",
197+
"type": "integer",
198+
},
190199
},
191200
"required": ["url"],
192201
"title": "fetchArguments",

0 commit comments

Comments
 (0)