|
1 | | -from typing import Annotated, Tuple |
| 1 | +import os |
| 2 | +from typing import TYPE_CHECKING, Annotated, Tuple |
2 | 3 | from importlib.metadata import version |
3 | 4 | from urllib.parse import urlparse, urlunparse |
4 | 5 |
|
|
21 | 22 | from protego import Protego |
22 | 23 | from pydantic import BaseModel, Field, AnyUrl |
23 | 24 |
|
| 25 | +if TYPE_CHECKING: |
| 26 | + from httpx import AsyncClient |
| 27 | + |
24 | 28 | # The version this server reports in serverInfo, read from the installed |
25 | 29 | # distribution's metadata (pyproject.toml) so it cannot drift from the |
26 | 30 | # published version (#360). Without it the SDK reports its own `mcp` version. |
@@ -76,18 +80,69 @@ def get_robots_txt_url(url: str) -> str: |
76 | 80 | return robots_url |
77 | 81 |
|
78 | 82 |
|
| 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 | + |
79 | 134 | async def check_may_autonomously_fetch_url( |
80 | 135 | url: str, user_agent: str, proxy_url: str | None = None |
81 | 136 | ) -> None: |
82 | 137 | """ |
83 | 138 | Check if the URL can be fetched by the user agent according to the robots.txt file. |
84 | 139 | Raises a McpError if not. |
85 | 140 | """ |
86 | | - from httpx import AsyncClient, HTTPError |
| 141 | + from httpx import HTTPError |
87 | 142 |
|
88 | 143 | robot_txt_url = get_robots_txt_url(url) |
89 | 144 |
|
90 | | - async with AsyncClient(proxy=proxy_url) as client: |
| 145 | + async with make_client(proxy_url) as client: |
91 | 146 | try: |
92 | 147 | response = await client.get( |
93 | 148 | robot_txt_url, |
@@ -135,9 +190,9 @@ async def fetch_url( |
135 | 190 | """ |
136 | 191 | Fetch the URL and return the content in a form ready for the LLM, as well as a prefix string with status information. |
137 | 192 | """ |
138 | | - from httpx import AsyncClient, HTTPError |
| 193 | + from httpx import HTTPError |
139 | 194 |
|
140 | | - async with AsyncClient(proxy=proxy_url) as client: |
| 195 | + async with make_client(proxy_url) as client: |
141 | 196 | try: |
142 | 197 | response = await client.get( |
143 | 198 | url, |
@@ -218,6 +273,9 @@ async def serve( |
218 | 273 | ignore_robots_txt: Whether to ignore robots.txt restrictions |
219 | 274 | proxy_url: Optional proxy URL to use for requests |
220 | 275 | """ |
| 276 | + if proxy_url: |
| 277 | + proxy_url = normalize_proxy_url(proxy_url) |
| 278 | + normalize_proxy_env() |
221 | 279 | server = Server("mcp-fetch", version=SERVER_VERSION) |
222 | 280 | user_agent_autonomous = custom_user_agent or DEFAULT_USER_AGENT_AUTONOMOUS |
223 | 281 | user_agent_manual = custom_user_agent or DEFAULT_USER_AGENT_MANUAL |
|
0 commit comments