Skip to content

Commit 0b7fb52

Browse files
authored
Merge pull request #5372 from modelcontextprotocol/v2/feat/4448-fetch-timeout
feat(fetch): make the HTTP request timeout configurable
2 parents 24a6484 + 3892d33 commit 0b7fb52

6 files changed

Lines changed: 425 additions & 4 deletions

File tree

‎src/fetch/README.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ The markdown of an HTML page opens with the page's title as a `#` heading (its `
2424
- `max_length` (integer, optional): Maximum number of characters to return (default: 5000)
2525
- `start_index` (integer, optional): Start content from this character index (default: 0)
2626
- `raw` (boolean, optional): Get raw content without markdown conversion (default: false)
27+
- `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))
2728
- Annotations: `readOnlyHint: true`, `destructiveHint: false`, `idempotentHint: true`, `openWorldHint: true` (it only reads, and it reaches arbitrary hosts on the internet)
2829

2930
### Prompts
@@ -237,6 +238,25 @@ ModelContextProtocol/1.0 (User-Specified; +https://github.com/modelcontextprotoc
237238

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

241+
### Customization - Timeout
242+
243+
The HTTP request for the page waits up to 30 seconds (30000 ms) by default: to connect, and then for each read of the
244+
response. It bounds each of those separately, not the whole download, so a large page that keeps arriving is not cut
245+
off. A request that times out fails with a tool error saying how long it waited.
246+
247+
The timeout can be set at three levels, the most specific winning:
248+
249+
1. The `fetch` tool's `timeout_ms` argument, for one call (for example `120000` for a large download, or `5000` to
250+
fail fast).
251+
2. The argument `--timeout-ms=60000` in the `args` list in the configuration, for every call.
252+
3. The `FETCH_TIMEOUT_MS` environment variable (for example `"env": {"FETCH_TIMEOUT_MS": "60000"}` in the
253+
configuration), for every call when `--timeout-ms` is not given.
254+
255+
The server-wide value also applies to the `fetch` prompt, and is the default the tool advertises for `timeout_ms`.
256+
Every level takes a whole number of milliseconds from 100 to 600000 (10 minutes); the server refuses to start with a
257+
value outside that range, and the tool refuses such a `timeout_ms`. This is the HTTP request timeout only: the
258+
robots.txt check before an autonomous fetch keeps its own 5-second timeout, and HTML extraction is not covered.
259+
240260
### Customization - Proxy
241261

242262
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,16 +1,32 @@
11
from .allowlist import parse_allowed_host
22
from .server import serve
3+
from .timeout import (
4+
DEFAULT_TIMEOUT_MS,
5+
MAX_TIMEOUT_MS,
6+
MIN_TIMEOUT_MS,
7+
TIMEOUT_ENV,
8+
parse_timeout_ms,
9+
timeout_ms_from_env,
10+
)
311

412

513
def main():
614
"""MCP Fetch Server - HTTP fetching functionality for MCP"""
715
import argparse
816
import asyncio
17+
import os
918

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

4157
args = parser.parse_args()
58+
# The server reads its timeout from the environment (see timeout.py), and
59+
# the flag outranks a value already there; a bad value stops it here.
60+
if args.timeout_ms is not None:
61+
os.environ[TIMEOUT_ENV] = str(args.timeout_ms)
62+
try:
63+
timeout_ms_from_env()
64+
except ValueError as e:
65+
parser.error(str(e))
4266
asyncio.run(
4367
serve(
4468
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
@@ -38,6 +38,12 @@
3838
from mcp.server.context import CallNext, HandlerResult, ServerMiddleware
3939
from mcp.server.mcpserver.exceptions import ToolError
4040
from mcp.shared.exceptions import MCPError
41+
from .timeout import (
42+
DEFAULT_TIMEOUT_MS,
43+
MAX_TIMEOUT_MS,
44+
MIN_TIMEOUT_MS,
45+
timeout_ms_from_env,
46+
)
4147
from mcp.types import INVALID_PARAMS, ToolAnnotations
4248
from protego import Protego
4349
from pydantic import AnyUrl, Field
@@ -547,6 +553,7 @@ async def fetch_url(
547553
url: str,
548554
user_agent: str,
549555
force_raw: bool = False,
556+
timeout_ms: int = DEFAULT_TIMEOUT_MS,
550557
proxy_url: str | None = None,
551558
allow_private_ips: bool = False,
552559
allowed_hosts: tuple[str, ...] = (),
@@ -589,7 +596,11 @@ async def _check_redirect_robots_txt(request: httpx.Request) -> None:
589596
url,
590597
follow_redirects=True,
591598
headers={"User-Agent": user_agent},
592-
timeout=30,
599+
timeout=timeout_ms / 1000,
600+
)
601+
except httpx.TimeoutException as e:
602+
raise ToolError(
603+
f"Failed to fetch {url}: timed out after {timeout_ms} ms: {e!r}"
593604
)
594605
except HTTPError as e:
595606
raise ToolError(f"Failed to fetch {url}: {e!r}")
@@ -682,6 +693,7 @@ def create_server(
682693
allowed = normalize_allowed_hosts(allowed_hosts)
683694
user_agent_autonomous = custom_user_agent or DEFAULT_USER_AGENT_AUTONOMOUS
684695
user_agent_manual = custom_user_agent or DEFAULT_USER_AGENT_MANUAL
696+
default_timeout_ms = timeout_ms_from_env()
685697

686698
# subscriptions=False: the tool and prompt lists never change and there are
687699
# no resources to watch, so `subscriptions/listen` is not served and the
@@ -735,6 +747,15 @@ async def fetch(
735747
strict=True,
736748
),
737749
] = False,
750+
timeout_ms: Annotated[
751+
int,
752+
Field(
753+
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.",
754+
ge=MIN_TIMEOUT_MS,
755+
le=MAX_TIMEOUT_MS,
756+
strict=True,
757+
),
758+
] = default_timeout_ms,
738759
) -> str:
739760
page_url = str(url)
740761

@@ -747,6 +768,7 @@ async def fetch(
747768
page_url,
748769
user_agent_autonomous,
749770
force_raw=raw,
771+
timeout_ms=timeout_ms,
750772
proxy_url=proxy_url,
751773
allow_private_ips=allow_private_ips,
752774
allowed_hosts=allowed,
@@ -781,6 +803,7 @@ async def fetch_prompt(
781803
content, prefix = await fetch_url(
782804
url,
783805
user_agent_manual,
806+
timeout_ms=default_timeout_ms,
784807
proxy_url=proxy_url,
785808
allow_private_ips=allow_private_ips,
786809
allowed_hosts=allowed,
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: 13 additions & 3 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",
@@ -999,9 +1008,10 @@ async def test_guard_uses_the_real_resolver() -> None:
9991008
)
10001009

10011010

1002-
async def test_timeouts_are_hard_coded(web: FakeWeb) -> None:
1003-
# Characterizes #4448: the page fetch uses a fixed 30s timeout and the
1004-
# robots.txt fetch uses httpx's 5s default; neither is configurable.
1011+
async def test_default_timeouts(web: FakeWeb) -> None:
1012+
# With nothing configured the page fetch waits 30s and the robots.txt
1013+
# fetch uses httpx's 5s default. Only the page timeout is configurable
1014+
# (#4448; tests/test_timeout.py).
10051015
web.add(ROBOTS, plain("", status=404))
10061016
web.add(PAGE, plain("ok"))
10071017
async with connect() as (session, _):

0 commit comments

Comments
 (0)