Skip to content

Commit 08314e7

Browse files
authored
Merge pull request #5024 from modelcontextprotocol/v2/fix/767-fetch-socks-proxy
fix(fetch): support SOCKS proxies and report bad proxy settings as tool errors
2 parents 8def287 + 36f57bc commit 08314e7

6 files changed

Lines changed: 151 additions & 15 deletions

File tree

‎src/fetch/README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,11 @@ This can be customized by adding the argument `--user-agent=YourUserAgent` to th
174174

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

177+
Without `--proxy-url`, the server uses the proxy in the standard `HTTP_PROXY`, `HTTPS_PROXY` and `ALL_PROXY`
178+
environment variables (honoring `NO_PROXY`). Both `http(s)://` and SOCKS5 proxies are supported (SOCKS support is
179+
installed with the server). A `socks://` proxy URL, as many desktop proxy settings export it, is treated as
180+
`socks5://`. A proxy setting the server cannot use makes each fetch fail with a tool error that says so.
181+
177182
## Windows Configuration
178183

179184
If you're experiencing timeout issues on Windows, you may need to set the `PYTHONIOENCODING` environment variable to ensure proper character encoding:

‎src/fetch/pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ classifiers = [
1616
"Programming Language :: Python :: 3.10",
1717
]
1818
dependencies = [
19-
"httpx>=0.27",
19+
"httpx[socks]>=0.27",
2020
"markdownify>=0.13.1",
2121
"mcp>=1.29.0,<2",
2222
"protego>=0.3.1",

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

Lines changed: 63 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from typing import Annotated, Tuple
1+
import os
2+
from typing import TYPE_CHECKING, Annotated, Tuple
23
from importlib.metadata import version
34
from urllib.parse import urlparse, urlunparse
45

@@ -21,6 +22,9 @@
2122
from protego import Protego
2223
from pydantic import BaseModel, Field, AnyUrl
2324

25+
if TYPE_CHECKING:
26+
from httpx import AsyncClient
27+
2428
# The version this server reports in serverInfo, read from the installed
2529
# distribution's metadata (pyproject.toml) so it cannot drift from the
2630
# published version (#360). Without it the SDK reports its own `mcp` version.
@@ -76,18 +80,69 @@ def get_robots_txt_url(url: str) -> str:
7680
return robots_url
7781

7882

83+
PROXY_ENV_VARS = (
84+
"HTTP_PROXY",
85+
"http_proxy",
86+
"HTTPS_PROXY",
87+
"https_proxy",
88+
"ALL_PROXY",
89+
"all_proxy",
90+
)
91+
92+
93+
def normalize_proxy_url(proxy_url: str) -> str:
94+
"""Rewrite the ``socks://`` alias, which httpx rejects, to ``socks5://``.
95+
96+
Desktop proxy settings often export ``socks://host:port``; httpx only
97+
accepts ``socks5://``. Every other value is returned unchanged.
98+
"""
99+
if proxy_url.lower().startswith("socks://"):
100+
return "socks5://" + proxy_url[len("socks://") :]
101+
return proxy_url
102+
103+
104+
def normalize_proxy_env() -> None:
105+
"""Apply ``normalize_proxy_url`` to the proxy variables httpx reads."""
106+
for name in PROXY_ENV_VARS:
107+
value = os.environ.get(name)
108+
if value:
109+
os.environ[name] = normalize_proxy_url(value)
110+
111+
112+
def make_client(proxy_url: str | None) -> "AsyncClient":
113+
"""Build the httpx client, turning a bad proxy setting into a tool error.
114+
115+
httpx validates the proxy (``--proxy-url`` or the proxy environment
116+
variables) when the client is constructed, before any request, so this
117+
failure is not an ``HTTPError``.
118+
"""
119+
from httpx import AsyncClient
120+
121+
try:
122+
return AsyncClient(proxy=proxy_url)
123+
except (ValueError, ImportError) as e:
124+
raise McpError(
125+
ErrorData(
126+
code=INTERNAL_ERROR,
127+
message=f"Failed to set up the HTTP client, check the proxy "
128+
f"configuration (--proxy-url or the HTTP_PROXY, HTTPS_PROXY and "
129+
f"ALL_PROXY environment variables): {e}",
130+
)
131+
)
132+
133+
79134
async def check_may_autonomously_fetch_url(
80135
url: str, user_agent: str, proxy_url: str | None = None
81136
) -> None:
82137
"""
83138
Check if the URL can be fetched by the user agent according to the robots.txt file.
84139
Raises a McpError if not.
85140
"""
86-
from httpx import AsyncClient, HTTPError
141+
from httpx import HTTPError
87142

88143
robot_txt_url = get_robots_txt_url(url)
89144

90-
async with AsyncClient(proxy=proxy_url) as client:
145+
async with make_client(proxy_url) as client:
91146
try:
92147
response = await client.get(
93148
robot_txt_url,
@@ -135,9 +190,9 @@ async def fetch_url(
135190
"""
136191
Fetch the URL and return the content in a form ready for the LLM, as well as a prefix string with status information.
137192
"""
138-
from httpx import AsyncClient, HTTPError
193+
from httpx import HTTPError
139194

140-
async with AsyncClient(proxy=proxy_url) as client:
195+
async with make_client(proxy_url) as client:
141196
try:
142197
response = await client.get(
143198
url,
@@ -218,6 +273,9 @@ async def serve(
218273
ignore_robots_txt: Whether to ignore robots.txt restrictions
219274
proxy_url: Optional proxy URL to use for requests
220275
"""
276+
if proxy_url:
277+
proxy_url = normalize_proxy_url(proxy_url)
278+
normalize_proxy_env()
221279
server = Server("mcp-fetch", version=SERVER_VERSION)
222280
user_agent_autonomous = custom_user_agent or DEFAULT_USER_AGENT_AUTONOMOUS
223281
user_agent_manual = custom_user_agent or DEFAULT_USER_AGENT_MANUAL

‎src/fetch/tests/test_protocol.py‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -686,12 +686,23 @@ async def test_no_proxy_by_default(web: FakeWeb) -> None:
686686
assert web.client_kwargs == [{"proxy": None}]
687687

688688

689-
# KNOWN BUG #767, #1401: pins current (wrong) behavior; the fix changes this assertion.
689+
async def test_socks_alias_proxy_url_is_passed_as_socks5(web: FakeWeb) -> None:
690+
# #767: httpx rejects the common socks:// alias, so it reaches the client
691+
# as socks5:// (supported through httpx[socks], #1401).
692+
web.add(ROBOTS, plain("", status=404))
693+
web.add(PAGE, plain("ok"))
694+
async with connect(proxy_url="socks://127.0.0.1:2080") as (session, _):
695+
result = await call(session, {"url": PAGE})
696+
assert wire(result)["isError"] is False
697+
socks5 = "socks5://127.0.0.1:2080"
698+
assert web.client_kwargs == [{"proxy": socks5}, {"proxy": socks5}]
699+
700+
690701
@pytest.mark.parametrize("ignore_robots_txt", [False, True])
691-
async def test_bad_proxy_config_surfaces_as_bare_text(ignore_robots_txt: bool) -> None:
692-
# Characterizes #767 and #1401: a bad proxy URL makes httpx.AsyncClient()
693-
# raise at construction, outside the `except HTTPError`, so the client gets
694-
# httpx's bare exception text with no mention of fetch or the proxy flag.
702+
async def test_bad_proxy_config_is_a_tool_error(ignore_robots_txt: bool) -> None:
703+
# #767 and #1401: a proxy httpx cannot use makes httpx.AsyncClient() raise
704+
# at construction, before any request. The client gets an isError result
705+
# that names the proxy settings, not httpx's bare exception text.
695706
# No `web` fixture: the real AsyncClient fails before any request is made.
696707
async with connect(
697708
proxy_url="ftp://proxy.example.com", ignore_robots_txt=ignore_robots_txt
@@ -701,7 +712,10 @@ async def test_bad_proxy_config_surfaces_as_bare_text(ignore_robots_txt: bool) -
701712
"content": [
702713
{
703714
"type": "text",
704-
"text": "Unknown scheme for proxy URL URL('ftp://proxy.example.com')",
715+
"text": "Failed to set up the HTTP client, check the proxy "
716+
"configuration (--proxy-url or the HTTP_PROXY, HTTPS_PROXY and "
717+
"ALL_PROXY environment variables): "
718+
"Unknown scheme for proxy URL URL('ftp://proxy.example.com')",
705719
}
706720
],
707721
"isError": True,
@@ -823,7 +837,7 @@ async def test_get_prompt_does_not_validate_the_url(
823837
# a "Failed to fetch" prompt message rather than a validation error.
824838
# No `web` fixture: the real transport rejects the URL before any I/O.
825839
# Proxy variables are cleared so the real client cannot pick up one from
826-
# the environment (a socks:// proxy would fail on the missing socksio).
840+
# the environment and send the request through it.
827841
for name in list(os.environ):
828842
if name.lower() in ("http_proxy", "https_proxy", "all_proxy"):
829843
monkeypatch.delenv(name)

‎src/fetch/tests/test_server.py‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,17 @@
44
test_protocol.py.
55
"""
66

7+
import os
8+
9+
import httpx
710
import pytest
811

912
from mcp_server_fetch.server import (
13+
PROXY_ENV_VARS,
1014
extract_content_from_html,
1115
get_robots_txt_url,
16+
normalize_proxy_env,
17+
normalize_proxy_url,
1218
)
1319

1420

@@ -86,3 +92,42 @@ def test_empty_content_returns_error(self):
8692
html = ""
8793
result = extract_content_from_html(html)
8894
assert "<error>" in result
95+
96+
97+
class TestNormalizeProxyUrl:
98+
"""Tests for normalize_proxy_url and normalize_proxy_env (#767)."""
99+
100+
@pytest.mark.parametrize(
101+
("given", "expected"),
102+
[
103+
("socks://127.0.0.1:2080/", "socks5://127.0.0.1:2080/"),
104+
("SOCKS://127.0.0.1:2080", "socks5://127.0.0.1:2080"),
105+
("socks5://127.0.0.1:2080", "socks5://127.0.0.1:2080"),
106+
("http://proxy.example.com:8080", "http://proxy.example.com:8080"),
107+
("ftp://proxy.example.com", "ftp://proxy.example.com"),
108+
],
109+
)
110+
def test_only_the_socks_alias_is_rewritten(self, given, expected):
111+
assert normalize_proxy_url(given) == expected
112+
113+
def test_environment_socks_alias_is_rewritten(self, monkeypatch):
114+
for name in PROXY_ENV_VARS:
115+
monkeypatch.delenv(name, raising=False)
116+
monkeypatch.setenv("ALL_PROXY", "socks://127.0.0.1:2080/")
117+
monkeypatch.setenv("https_proxy", "http://proxy.example.com:8080")
118+
normalize_proxy_env()
119+
assert os.environ["ALL_PROXY"] == "socks5://127.0.0.1:2080/"
120+
assert os.environ["https_proxy"] == "http://proxy.example.com:8080"
121+
assert "HTTP_PROXY" not in os.environ
122+
123+
def test_normalized_socks_environment_builds_a_client(self, monkeypatch):
124+
# #767 and #1401 together: httpx rejects socks:// outright, and a
125+
# socks5:// proxy needs socksio, which httpx[socks] now installs.
126+
for name in PROXY_ENV_VARS:
127+
monkeypatch.delenv(name, raising=False)
128+
monkeypatch.setenv("ALL_PROXY", "socks://127.0.0.1:2080/")
129+
with pytest.raises(ValueError, match="Unknown scheme for proxy URL"):
130+
httpx.AsyncClient()
131+
normalize_proxy_env()
132+
httpx.AsyncClient()
133+
httpx.AsyncClient(proxy="socks5://127.0.0.1:2080/")

‎src/fetch/uv.lock‎

Lines changed: 16 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)