Added fetch module
This commit is contained in:
1
mcpServer/modules/fetch/.python-version
Normal file
1
mcpServer/modules/fetch/.python-version
Normal file
@@ -0,0 +1 @@
|
||||
3.11
|
||||
33
mcpServer/modules/fetch/Dockerfile
Normal file
33
mcpServer/modules/fetch/Dockerfile
Normal file
@@ -0,0 +1,33 @@
|
||||
# Use a Python image with uv pre-installed
|
||||
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS uv
|
||||
|
||||
# Install the project into `/app`
|
||||
WORKDIR /app
|
||||
|
||||
# Enable bytecode compilation
|
||||
ENV UV_COMPILE_BYTECODE=1
|
||||
|
||||
# Copy from the cache instead of linking since it's a mounted volume
|
||||
ENV UV_LINK_MODE=copy
|
||||
|
||||
# Install the project's dependencies using the lockfile and settings
|
||||
ADD . /app
|
||||
RUN uv lock
|
||||
RUN uv sync --locked --no-install-project --no-dev --no-editable
|
||||
|
||||
# Then, add the rest of the project source code and install it
|
||||
# Installing separately from its dependencies allows optimal layer caching
|
||||
RUN uv sync --locked --no-dev --no-editable
|
||||
|
||||
FROM python:3.12-slim-bookworm
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=uv /root/.local /root/.local
|
||||
COPY --from=uv --chown=app:app /app/.venv /app/.venv
|
||||
|
||||
# Place executables in the environment at the front of the path
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
|
||||
# Bind to 0.0.0.0 so the SSE server is reachable from outside the container
|
||||
ENTRYPOINT ["mcp-server-fetch", "--host", "0.0.0.0"]
|
||||
7
mcpServer/modules/fetch/LICENSE
Normal file
7
mcpServer/modules/fetch/LICENSE
Normal file
@@ -0,0 +1,7 @@
|
||||
Copyright (c) 2024 Anthropic, PBC.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
241
mcpServer/modules/fetch/README.md
Normal file
241
mcpServer/modules/fetch/README.md
Normal file
@@ -0,0 +1,241 @@
|
||||
# Fetch MCP Server
|
||||
|
||||
<!-- mcp-name: io.github.modelcontextprotocol/server-fetch -->
|
||||
|
||||
A Model Context Protocol server that provides web content fetching capabilities. This server enables LLMs to retrieve and process content from web pages, converting HTML to markdown for easier consumption.
|
||||
|
||||
> [!CAUTION]
|
||||
> This server can access local/internal IP addresses and may represent a security risk. Exercise caution when using this MCP server to ensure this does not expose any sensitive data.
|
||||
|
||||
The fetch tool will truncate the response, but by using the `start_index` argument, you can specify where to start the content extraction. This lets models read a webpage in chunks, until they find the information they need.
|
||||
|
||||
### Available Tools
|
||||
|
||||
- `fetch` - Fetches a URL from the internet and extracts its contents as markdown.
|
||||
- `url` (string, required): URL to fetch
|
||||
- `max_length` (integer, optional): Maximum number of characters to return (default: 5000)
|
||||
- `start_index` (integer, optional): Start content from this character index (default: 0)
|
||||
- `raw` (boolean, optional): Get raw content without markdown conversion (default: false)
|
||||
|
||||
### Prompts
|
||||
|
||||
- **fetch**
|
||||
- Fetch a URL and extract its contents as markdown
|
||||
- Arguments:
|
||||
- `url` (string, required): URL to fetch
|
||||
|
||||
## Installation
|
||||
|
||||
Optionally: Install node.js, this will cause the fetch server to use a different HTML simplifier that is more robust.
|
||||
|
||||
### Using uv (recommended)
|
||||
|
||||
When using [`uv`](https://docs.astral.sh/uv/) no specific installation is needed. We will
|
||||
use [`uvx`](https://docs.astral.sh/uv/guides/tools/) to directly run *mcp-server-fetch*.
|
||||
|
||||
### Using PIP
|
||||
|
||||
Alternatively you can install `mcp-server-fetch` via pip:
|
||||
|
||||
```
|
||||
pip install mcp-server-fetch
|
||||
```
|
||||
|
||||
After installation, you can run it as a script using:
|
||||
|
||||
```
|
||||
python -m mcp_server_fetch
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Configure for Claude.app
|
||||
|
||||
Add to your Claude settings:
|
||||
|
||||
<details>
|
||||
<summary>Using uvx</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"fetch": {
|
||||
"command": "uvx",
|
||||
"args": ["mcp-server-fetch"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Using docker</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"fetch": {
|
||||
"command": "docker",
|
||||
"args": ["run", "-i", "--rm", "mcp/fetch"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Using pip installation</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"fetch": {
|
||||
"command": "python",
|
||||
"args": ["-m", "mcp_server_fetch"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
### Configure for VS Code
|
||||
|
||||
For quick installation, use one of the one-click install buttons below...
|
||||
|
||||
[](https://insiders.vscode.dev/redirect/mcp/install?name=fetch&config=%7B%22command%22%3A%22uvx%22%2C%22args%22%3A%5B%22mcp-server-fetch%22%5D%7D) [](https://insiders.vscode.dev/redirect/mcp/install?name=fetch&config=%7B%22command%22%3A%22uvx%22%2C%22args%22%3A%5B%22mcp-server-fetch%22%5D%7D&quality=insiders)
|
||||
|
||||
[](https://insiders.vscode.dev/redirect/mcp/install?name=fetch&config=%7B%22command%22%3A%22docker%22%2C%22args%22%3A%5B%22run%22%2C%22-i%22%2C%22--rm%22%2C%22mcp%2Ffetch%22%5D%7D) [](https://insiders.vscode.dev/redirect/mcp/install?name=fetch&config=%7B%22command%22%3A%22docker%22%2C%22args%22%3A%5B%22run%22%2C%22-i%22%2C%22--rm%22%2C%22mcp%2Ffetch%22%5D%7D&quality=insiders)
|
||||
|
||||
For manual installation, add the following JSON block to your User Settings (JSON) file in VS Code. You can do this by pressing `Ctrl + Shift + P` and typing `Preferences: Open User Settings (JSON)`.
|
||||
|
||||
Optionally, you can add it to a file called `.vscode/mcp.json` in your workspace. This will allow you to share the configuration with others.
|
||||
|
||||
> Note that the `mcp` key is needed when using the `mcp.json` file.
|
||||
|
||||
<details>
|
||||
<summary>Using uvx</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"mcp": {
|
||||
"servers": {
|
||||
"fetch": {
|
||||
"command": "uvx",
|
||||
"args": ["mcp-server-fetch"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Using Docker</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"mcp": {
|
||||
"servers": {
|
||||
"fetch": {
|
||||
"command": "docker",
|
||||
"args": ["run", "-i", "--rm", "mcp/fetch"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
### Customization - robots.txt
|
||||
|
||||
By default, the server will obey a websites robots.txt file if the request came from the model (via a tool), but not if
|
||||
the request was user initiated (via a prompt). This can be disabled by adding the argument `--ignore-robots-txt` to the
|
||||
`args` list in the configuration.
|
||||
|
||||
### Customization - User-agent
|
||||
|
||||
By default, depending on if the request came from the model (via a tool), or was user initiated (via a prompt), the
|
||||
server will use either the user-agent
|
||||
```
|
||||
ModelContextProtocol/1.0 (Autonomous; +https://github.com/modelcontextprotocol/servers)
|
||||
```
|
||||
or
|
||||
```
|
||||
ModelContextProtocol/1.0 (User-Specified; +https://github.com/modelcontextprotocol/servers)
|
||||
```
|
||||
|
||||
This can be customized by adding the argument `--user-agent=YourUserAgent` to the `args` list in the configuration.
|
||||
|
||||
### Customization - Proxy
|
||||
|
||||
The server can be configured to use a proxy by using the `--proxy-url` argument.
|
||||
|
||||
## Windows Configuration
|
||||
|
||||
If you're experiencing timeout issues on Windows, you may need to set the `PYTHONIOENCODING` environment variable to ensure proper character encoding:
|
||||
|
||||
<details>
|
||||
<summary>Windows configuration (uvx)</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"fetch": {
|
||||
"command": "uvx",
|
||||
"args": ["mcp-server-fetch"],
|
||||
"env": {
|
||||
"PYTHONIOENCODING": "utf-8"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Windows configuration (pip)</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"fetch": {
|
||||
"command": "python",
|
||||
"args": ["-m", "mcp_server_fetch"],
|
||||
"env": {
|
||||
"PYTHONIOENCODING": "utf-8"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
This addresses character encoding issues that can cause the server to timeout on Windows systems.
|
||||
|
||||
## Debugging
|
||||
|
||||
You can use the MCP inspector to debug the server. For uvx installations:
|
||||
|
||||
```
|
||||
npx @modelcontextprotocol/inspector uvx mcp-server-fetch
|
||||
```
|
||||
|
||||
Or if you've installed the package in a specific directory or are developing on it:
|
||||
|
||||
```
|
||||
cd path/to/servers/src/fetch
|
||||
npx @modelcontextprotocol/inspector uv run mcp-server-fetch
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
We encourage contributions to help expand and improve mcp-server-fetch. Whether you want to add new tools, enhance existing functionality, or improve documentation, your input is valuable.
|
||||
|
||||
For examples of other MCP servers and implementation patterns, see:
|
||||
https://github.com/modelcontextprotocol/servers
|
||||
|
||||
Pull requests are welcome! Feel free to contribute new ideas, bug fixes, or enhancements to make mcp-server-fetch even more powerful and useful.
|
||||
|
||||
## License
|
||||
|
||||
mcp-server-fetch is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.
|
||||
42
mcpServer/modules/fetch/pyproject.toml
Normal file
42
mcpServer/modules/fetch/pyproject.toml
Normal file
@@ -0,0 +1,42 @@
|
||||
[project]
|
||||
name = "mcp-server-fetch"
|
||||
version = "0.6.3"
|
||||
description = "A Model Context Protocol server providing tools to fetch and convert web content for usage by LLMs"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
authors = [{ name = "Anthropic, PBC." }]
|
||||
maintainers = [{ name = "Jack Adamson", email = "jadamson@anthropic.com" }]
|
||||
keywords = ["http", "mcp", "llm", "automation"]
|
||||
license = { text = "MIT" }
|
||||
classifiers = [
|
||||
"Development Status :: 4 - Beta",
|
||||
"Intended Audience :: Developers",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
]
|
||||
dependencies = [
|
||||
"httpx<0.28",
|
||||
"markdownify>=0.13.1",
|
||||
"mcp>=1.1.3",
|
||||
"protego>=0.3.1",
|
||||
"pydantic>=2.0.0",
|
||||
"readabilipy>=0.2.0",
|
||||
"requests>=2.32.3",
|
||||
"starlette>=0.38.0",
|
||||
"uvicorn>=0.30.0",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
mcp-server-fetch = "mcp_server_fetch:main"
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[depencency-groups]
|
||||
dev = ["pyright>=1.1.389", "ruff>=0.7.3", "pytest>=8.0.0", "pytest-asyncio>=0.21.0"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
asyncio_mode = "auto"
|
||||
49
mcpServer/modules/fetch/src/mcp_server_fetch/__init__.py
Normal file
49
mcpServer/modules/fetch/src/mcp_server_fetch/__init__.py
Normal file
@@ -0,0 +1,49 @@
|
||||
from .server import serve
|
||||
|
||||
|
||||
def main():
|
||||
"""MCP Fetch Server - HTTP fetching functionality for MCP"""
|
||||
import argparse
|
||||
import asyncio
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description="give a model the ability to make web requests"
|
||||
)
|
||||
parser.add_argument("--user-agent", type=str, help="Custom User-Agent string")
|
||||
parser.add_argument(
|
||||
"--ignore-robots-txt",
|
||||
action="store_true",
|
||||
help="Ignore robots.txt restrictions",
|
||||
)
|
||||
parser.add_argument("--proxy-url", type=str, help="Proxy URL to use for requests")
|
||||
parser.add_argument(
|
||||
"--port",
|
||||
type=int,
|
||||
default=None,
|
||||
help="Port for SSE server (default: from MCP_PORT or SSE_PORT env, else 3000)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--host",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Host to bind the SSE server to (default: MCP_HOST env or 127.0.0.1)",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
import os
|
||||
|
||||
port = args.port
|
||||
if port is None:
|
||||
port = int(os.environ.get("MCP_PORT") or os.environ.get("SSE_PORT") or "3000")
|
||||
host = args.host or os.environ.get("MCP_HOST") or "127.0.0.1"
|
||||
serve(
|
||||
custom_user_agent=args.user_agent,
|
||||
ignore_robots_txt=args.ignore_robots_txt,
|
||||
proxy_url=args.proxy_url,
|
||||
port=port,
|
||||
host=host,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
5
mcpServer/modules/fetch/src/mcp_server_fetch/__main__.py
Normal file
5
mcpServer/modules/fetch/src/mcp_server_fetch/__main__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
# __main__.py
|
||||
|
||||
from mcp_server_fetch import main
|
||||
|
||||
main()
|
||||
350
mcpServer/modules/fetch/src/mcp_server_fetch/server.py
Normal file
350
mcpServer/modules/fetch/src/mcp_server_fetch/server.py
Normal file
@@ -0,0 +1,350 @@
|
||||
from typing import Annotated, Tuple
|
||||
from urllib.parse import urlparse, urlunparse
|
||||
|
||||
import markdownify
|
||||
import readabilipy.simple_json
|
||||
from mcp.shared.exceptions import McpError
|
||||
from mcp.server import Server
|
||||
from mcp.server.sse import SseServerTransport
|
||||
from mcp.types import (
|
||||
ErrorData,
|
||||
GetPromptResult,
|
||||
Prompt,
|
||||
PromptArgument,
|
||||
PromptMessage,
|
||||
TextContent,
|
||||
Tool,
|
||||
INVALID_PARAMS,
|
||||
INTERNAL_ERROR,
|
||||
)
|
||||
from protego import Protego
|
||||
from pydantic import BaseModel, Field, AnyUrl
|
||||
|
||||
DEFAULT_USER_AGENT_AUTONOMOUS = "Cariddi/1.0 (Autonomous; +https://git.andreagordanelli.com/Schrody/CariddiCTF)"
|
||||
DEFAULT_USER_AGENT_MANUAL = "Cariddi/1.0 (User-Specified; +https://git.andreagordanelli.com/Schrody/CariddiCTF)"
|
||||
|
||||
|
||||
def extract_content_from_html(html: str) -> str:
|
||||
"""Extract and convert HTML content to Markdown format.
|
||||
|
||||
Args:
|
||||
html: Raw HTML content to process
|
||||
|
||||
Returns:
|
||||
Simplified markdown version of the content
|
||||
"""
|
||||
ret = readabilipy.simple_json.simple_json_from_html_string(
|
||||
html, use_readability=True
|
||||
)
|
||||
if not ret["content"]:
|
||||
return "<error>Page failed to be simplified from HTML</error>"
|
||||
content = markdownify.markdownify(
|
||||
ret["content"],
|
||||
heading_style=markdownify.ATX,
|
||||
)
|
||||
return content
|
||||
|
||||
|
||||
def get_robots_txt_url(url: str) -> str:
|
||||
"""Get the robots.txt URL for a given website URL.
|
||||
|
||||
Args:
|
||||
url: Website URL to get robots.txt for
|
||||
|
||||
Returns:
|
||||
URL of the robots.txt file
|
||||
"""
|
||||
# Parse the URL into components
|
||||
parsed = urlparse(url)
|
||||
|
||||
# Reconstruct the base URL with just scheme, netloc, and /robots.txt path
|
||||
robots_url = urlunparse((parsed.scheme, parsed.netloc, "/robots.txt", "", "", ""))
|
||||
|
||||
return robots_url
|
||||
|
||||
|
||||
async def check_may_autonomously_fetch_url(url: str, user_agent: str, proxy_url: str | None = None) -> None:
|
||||
"""
|
||||
Check if the URL can be fetched by the user agent according to the robots.txt file.
|
||||
Raises a McpError if not.
|
||||
"""
|
||||
from httpx import AsyncClient, HTTPError
|
||||
|
||||
robot_txt_url = get_robots_txt_url(url)
|
||||
|
||||
async with AsyncClient(proxies=proxy_url) as client:
|
||||
try:
|
||||
response = await client.get(
|
||||
robot_txt_url,
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": user_agent},
|
||||
)
|
||||
except HTTPError:
|
||||
raise McpError(ErrorData(
|
||||
code=INTERNAL_ERROR,
|
||||
message=f"Failed to fetch robots.txt {robot_txt_url} due to a connection issue",
|
||||
))
|
||||
if response.status_code in (401, 403):
|
||||
raise McpError(ErrorData(
|
||||
code=INTERNAL_ERROR,
|
||||
message=f"When fetching robots.txt ({robot_txt_url}), received status {response.status_code} so assuming that autonomous fetching is not allowed, the user can try manually fetching by using the fetch prompt",
|
||||
))
|
||||
elif 400 <= response.status_code < 500:
|
||||
return
|
||||
robot_txt = response.text
|
||||
processed_robot_txt = "\n".join(
|
||||
line for line in robot_txt.splitlines() if not line.strip().startswith("#")
|
||||
)
|
||||
robot_parser = Protego.parse(processed_robot_txt)
|
||||
if not robot_parser.can_fetch(str(url), user_agent):
|
||||
raise McpError(ErrorData(
|
||||
code=INTERNAL_ERROR,
|
||||
message=f"The sites robots.txt ({robot_txt_url}), specifies that autonomous fetching of this page is not allowed, "
|
||||
f"<useragent>{user_agent}</useragent>\n"
|
||||
f"<url>{url}</url>"
|
||||
f"<robots>\n{robot_txt}\n</robots>\n"
|
||||
f"The assistant must let the user know that it failed to view the page. The assistant may provide further guidance based on the above information.\n"
|
||||
f"The assistant can tell the user that they can try manually fetching the page by using the fetch prompt within their UI.",
|
||||
))
|
||||
|
||||
|
||||
async def fetch_url(
|
||||
url: str, user_agent: str, force_raw: bool = False, proxy_url: str | None = None
|
||||
) -> Tuple[str, str]:
|
||||
"""
|
||||
Fetch the URL and return the content in a form ready for the LLM, as well as a prefix string with status information.
|
||||
"""
|
||||
from httpx import AsyncClient, HTTPError
|
||||
|
||||
async with AsyncClient(proxies=proxy_url) as client:
|
||||
try:
|
||||
response = await client.get(
|
||||
url,
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": user_agent},
|
||||
timeout=30,
|
||||
)
|
||||
except HTTPError as e:
|
||||
raise McpError(ErrorData(code=INTERNAL_ERROR, message=f"Failed to fetch {url}: {e!r}"))
|
||||
if response.status_code >= 400:
|
||||
raise McpError(ErrorData(
|
||||
code=INTERNAL_ERROR,
|
||||
message=f"Failed to fetch {url} - status code {response.status_code}",
|
||||
))
|
||||
|
||||
page_raw = response.text
|
||||
|
||||
content_type = response.headers.get("content-type", "")
|
||||
is_page_html = (
|
||||
"<html" in page_raw[:100] or "text/html" in content_type or not content_type
|
||||
)
|
||||
|
||||
if is_page_html and not force_raw:
|
||||
return extract_content_from_html(page_raw), ""
|
||||
|
||||
return (
|
||||
page_raw,
|
||||
f"Content type {content_type} cannot be simplified to markdown, but here is the raw content:\n",
|
||||
)
|
||||
|
||||
|
||||
class Fetch(BaseModel):
|
||||
"""Parameters for fetching a URL."""
|
||||
|
||||
url: Annotated[AnyUrl, Field(description="URL to fetch")]
|
||||
max_length: Annotated[
|
||||
int,
|
||||
Field(
|
||||
default=5000,
|
||||
description="Maximum number of characters to return.",
|
||||
gt=0,
|
||||
lt=1000000,
|
||||
),
|
||||
]
|
||||
start_index: Annotated[
|
||||
int,
|
||||
Field(
|
||||
default=0,
|
||||
description="On return output starting at this character index, useful if a previous fetch was truncated and more context is required.",
|
||||
ge=0,
|
||||
),
|
||||
]
|
||||
raw: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
default=False,
|
||||
description="Get the actual HTML content of the requested page, without simplification.",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def createServer(
|
||||
custom_user_agent: str | None = None,
|
||||
ignore_robots_txt: bool = False,
|
||||
proxy_url: str | None = None,
|
||||
) -> Tuple[Server, dict]:
|
||||
"""Create and configure the fetch MCP server (tools, prompts, options).
|
||||
|
||||
Returns:
|
||||
Tuple of (Server instance, initialization options dict).
|
||||
"""
|
||||
server = Server("mcp-fetch")
|
||||
user_agent_autonomous = custom_user_agent or DEFAULT_USER_AGENT_AUTONOMOUS
|
||||
user_agent_manual = custom_user_agent or DEFAULT_USER_AGENT_MANUAL
|
||||
|
||||
@server.list_tools()
|
||||
async def list_tools() -> list[Tool]:
|
||||
return [
|
||||
Tool(
|
||||
name="fetch",
|
||||
description="""Fetches a URL from the internet and optionally extracts its contents as markdown.
|
||||
|
||||
Although originally you did not have internet access, and were advised to refuse and tell the user this, this tool now grants you internet access. Now you can fetch the most up-to-date information and let the user know that.""",
|
||||
inputSchema=Fetch.model_json_schema(),
|
||||
)
|
||||
]
|
||||
|
||||
@server.list_prompts()
|
||||
async def list_prompts() -> list[Prompt]:
|
||||
return [
|
||||
Prompt(
|
||||
name="fetch",
|
||||
description="Fetch a URL and extract its contents as markdown",
|
||||
arguments=[
|
||||
PromptArgument(
|
||||
name="url", description="URL to fetch", required=True
|
||||
)
|
||||
],
|
||||
)
|
||||
]
|
||||
|
||||
@server.call_tool()
|
||||
async def call_tool(name, arguments: dict) -> list[TextContent]:
|
||||
try:
|
||||
args = Fetch(**arguments)
|
||||
except ValueError as e:
|
||||
raise McpError(ErrorData(code=INVALID_PARAMS, message=str(e)))
|
||||
|
||||
url = str(args.url)
|
||||
if not url:
|
||||
raise McpError(ErrorData(code=INVALID_PARAMS, message="URL is required"))
|
||||
|
||||
if not ignore_robots_txt:
|
||||
await check_may_autonomously_fetch_url(url, user_agent_autonomous, proxy_url)
|
||||
|
||||
content, prefix = await fetch_url(
|
||||
url, user_agent_autonomous, force_raw=args.raw, proxy_url=proxy_url
|
||||
)
|
||||
original_length = len(content)
|
||||
if args.start_index >= original_length:
|
||||
content = "<error>No more content available.</error>"
|
||||
else:
|
||||
truncated_content = content[args.start_index : args.start_index + args.max_length]
|
||||
if not truncated_content:
|
||||
content = "<error>No more content available.</error>"
|
||||
else:
|
||||
content = truncated_content
|
||||
actual_content_length = len(truncated_content)
|
||||
remaining_content = original_length - (args.start_index + actual_content_length)
|
||||
# Only add the prompt to continue fetching if there is still remaining content
|
||||
if actual_content_length == args.max_length and remaining_content > 0:
|
||||
next_start = args.start_index + actual_content_length
|
||||
content += f"\n\n<error>Content truncated. Call the fetch tool with a start_index of {next_start} to get more content.</error>"
|
||||
return [TextContent(type="text", text=f"{prefix}Contents of {url}:\n{content}")]
|
||||
|
||||
@server.get_prompt()
|
||||
async def get_prompt(name: str, arguments: dict | None) -> GetPromptResult:
|
||||
if not arguments or "url" not in arguments:
|
||||
raise McpError(ErrorData(code=INVALID_PARAMS, message="URL is required"))
|
||||
|
||||
url = arguments["url"]
|
||||
|
||||
try:
|
||||
content, prefix = await fetch_url(url, user_agent_manual, proxy_url=proxy_url)
|
||||
# TODO: after SDK bug is addressed, don't catch the exception
|
||||
except McpError as e:
|
||||
return GetPromptResult(
|
||||
description=f"Failed to fetch {url}",
|
||||
messages=[
|
||||
PromptMessage(
|
||||
role="user",
|
||||
content=TextContent(type="text", text=str(e)),
|
||||
)
|
||||
],
|
||||
)
|
||||
return GetPromptResult(
|
||||
description=f"Contents of {url}",
|
||||
messages=[
|
||||
PromptMessage(
|
||||
role="user", content=TextContent(type="text", text=prefix + content)
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
return server, server.create_initialization_options()
|
||||
|
||||
|
||||
def serve(
|
||||
custom_user_agent: str | None = None,
|
||||
ignore_robots_txt: bool = False,
|
||||
proxy_url: str | None = None,
|
||||
port: int = 3000,
|
||||
host: str = "0.0.0.0",
|
||||
) -> None:
|
||||
"""Run the fetch MCP server over SSE.
|
||||
|
||||
Args:
|
||||
custom_user_agent: Optional custom User-Agent string to use for requests
|
||||
ignore_robots_txt: Whether to ignore robots.txt restrictions
|
||||
proxy_url: Optional proxy URL to use for requests
|
||||
port: Port for the SSE HTTP server
|
||||
host: Host to bind the SSE server to
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
from starlette.applications import Starlette
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
from starlette.routing import Mount, Route
|
||||
|
||||
def buildApp():
|
||||
server, options = createServer(
|
||||
custom_user_agent, ignore_robots_txt, proxy_url
|
||||
)
|
||||
sse = SseServerTransport("/messages/")
|
||||
|
||||
async def handleSse(request: Request) -> Response:
|
||||
async with sse.connect_sse(
|
||||
request.scope, request.receive, request._send
|
||||
) as streams:
|
||||
await server.run(
|
||||
streams[0], streams[1], options, raise_exceptions=True
|
||||
)
|
||||
return Response()
|
||||
|
||||
routes = [
|
||||
Route("/sse", endpoint=handleSse, methods=["GET"]),
|
||||
Route("/", endpoint=handleSse, methods=["GET"]),
|
||||
Mount("/messages/", app=sse.handle_post_message),
|
||||
]
|
||||
return Starlette(routes=routes)
|
||||
|
||||
async def run():
|
||||
app = buildApp()
|
||||
import uvicorn
|
||||
|
||||
config = uvicorn.Config(app, host=host, port=port, log_level="info")
|
||||
server_uv = uvicorn.Server(config)
|
||||
await server_uv.serve()
|
||||
|
||||
import sys
|
||||
|
||||
sys.stderr.write(
|
||||
f"MCP Fetch Server running on SSE at http://{host}:{port}\n"
|
||||
)
|
||||
sys.stderr.write(" GET /sse or / – open SSE stream\n")
|
||||
sys.stderr.write(
|
||||
" POST /messages/?session_id=<id> – send MCP messages\n"
|
||||
)
|
||||
sys.stderr.flush()
|
||||
asyncio.run(run())
|
||||
0
mcpServer/modules/fetch/tests/__init__.py
Normal file
0
mcpServer/modules/fetch/tests/__init__.py
Normal file
326
mcpServer/modules/fetch/tests/test_server.py
Normal file
326
mcpServer/modules/fetch/tests/test_server.py
Normal file
@@ -0,0 +1,326 @@
|
||||
"""Tests for the fetch MCP server."""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, patch, MagicMock
|
||||
from mcp.shared.exceptions import McpError
|
||||
|
||||
from mcp_server_fetch.server import (
|
||||
extract_content_from_html,
|
||||
get_robots_txt_url,
|
||||
check_may_autonomously_fetch_url,
|
||||
fetch_url,
|
||||
DEFAULT_USER_AGENT_AUTONOMOUS,
|
||||
)
|
||||
|
||||
|
||||
class TestGetRobotsTxtUrl:
|
||||
"""Tests for get_robots_txt_url function."""
|
||||
|
||||
def test_simple_url(self):
|
||||
"""Test with a simple URL."""
|
||||
result = get_robots_txt_url("https://example.com/page")
|
||||
assert result == "https://example.com/robots.txt"
|
||||
|
||||
def test_url_with_path(self):
|
||||
"""Test with URL containing path."""
|
||||
result = get_robots_txt_url("https://example.com/some/deep/path/page.html")
|
||||
assert result == "https://example.com/robots.txt"
|
||||
|
||||
def test_url_with_query_params(self):
|
||||
"""Test with URL containing query parameters."""
|
||||
result = get_robots_txt_url("https://example.com/page?foo=bar&baz=qux")
|
||||
assert result == "https://example.com/robots.txt"
|
||||
|
||||
def test_url_with_port(self):
|
||||
"""Test with URL containing port number."""
|
||||
result = get_robots_txt_url("https://example.com:8080/page")
|
||||
assert result == "https://example.com:8080/robots.txt"
|
||||
|
||||
def test_url_with_fragment(self):
|
||||
"""Test with URL containing fragment."""
|
||||
result = get_robots_txt_url("https://example.com/page#section")
|
||||
assert result == "https://example.com/robots.txt"
|
||||
|
||||
def test_http_url(self):
|
||||
"""Test with HTTP URL."""
|
||||
result = get_robots_txt_url("http://example.com/page")
|
||||
assert result == "http://example.com/robots.txt"
|
||||
|
||||
|
||||
class TestExtractContentFromHtml:
|
||||
"""Tests for extract_content_from_html function."""
|
||||
|
||||
def test_simple_html(self):
|
||||
"""Test with simple HTML content."""
|
||||
html = """
|
||||
<html>
|
||||
<head><title>Test Page</title></head>
|
||||
<body>
|
||||
<article>
|
||||
<h1>Hello World</h1>
|
||||
<p>This is a test paragraph.</p>
|
||||
</article>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
result = extract_content_from_html(html)
|
||||
# readabilipy may extract different parts depending on the content
|
||||
assert "test paragraph" in result
|
||||
|
||||
def test_html_with_links(self):
|
||||
"""Test that links are converted to markdown."""
|
||||
html = """
|
||||
<html>
|
||||
<body>
|
||||
<article>
|
||||
<p>Visit <a href="https://example.com">Example</a> for more.</p>
|
||||
</article>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
result = extract_content_from_html(html)
|
||||
assert "Example" in result
|
||||
|
||||
def test_empty_content_returns_error(self):
|
||||
"""Test that empty/invalid HTML returns error message."""
|
||||
html = ""
|
||||
result = extract_content_from_html(html)
|
||||
assert "<error>" in result
|
||||
|
||||
|
||||
class TestCheckMayAutonomouslyFetchUrl:
|
||||
"""Tests for check_may_autonomously_fetch_url function."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_allows_when_robots_txt_404(self):
|
||||
"""Test that fetching is allowed when robots.txt returns 404."""
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 404
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_class:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_class.return_value.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client_class.return_value.__aexit__ = AsyncMock(return_value=None)
|
||||
|
||||
# Should not raise
|
||||
await check_may_autonomously_fetch_url(
|
||||
"https://example.com/page",
|
||||
DEFAULT_USER_AGENT_AUTONOMOUS
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_blocks_when_robots_txt_401(self):
|
||||
"""Test that fetching is blocked when robots.txt returns 401."""
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 401
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_class:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_class.return_value.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client_class.return_value.__aexit__ = AsyncMock(return_value=None)
|
||||
|
||||
with pytest.raises(McpError):
|
||||
await check_may_autonomously_fetch_url(
|
||||
"https://example.com/page",
|
||||
DEFAULT_USER_AGENT_AUTONOMOUS
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_blocks_when_robots_txt_403(self):
|
||||
"""Test that fetching is blocked when robots.txt returns 403."""
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 403
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_class:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_class.return_value.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client_class.return_value.__aexit__ = AsyncMock(return_value=None)
|
||||
|
||||
with pytest.raises(McpError):
|
||||
await check_may_autonomously_fetch_url(
|
||||
"https://example.com/page",
|
||||
DEFAULT_USER_AGENT_AUTONOMOUS
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_allows_when_robots_txt_allows_all(self):
|
||||
"""Test that fetching is allowed when robots.txt allows all."""
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.text = "User-agent: *\nAllow: /"
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_class:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_class.return_value.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client_class.return_value.__aexit__ = AsyncMock(return_value=None)
|
||||
|
||||
# Should not raise
|
||||
await check_may_autonomously_fetch_url(
|
||||
"https://example.com/page",
|
||||
DEFAULT_USER_AGENT_AUTONOMOUS
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_blocks_when_robots_txt_disallows_all(self):
|
||||
"""Test that fetching is blocked when robots.txt disallows all."""
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.text = "User-agent: *\nDisallow: /"
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_class:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_class.return_value.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client_class.return_value.__aexit__ = AsyncMock(return_value=None)
|
||||
|
||||
with pytest.raises(McpError):
|
||||
await check_may_autonomously_fetch_url(
|
||||
"https://example.com/page",
|
||||
DEFAULT_USER_AGENT_AUTONOMOUS
|
||||
)
|
||||
|
||||
|
||||
class TestFetchUrl:
|
||||
"""Tests for fetch_url function."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fetch_html_page(self):
|
||||
"""Test fetching an HTML page returns markdown content."""
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.text = """
|
||||
<html>
|
||||
<body>
|
||||
<article>
|
||||
<h1>Test Page</h1>
|
||||
<p>Hello World</p>
|
||||
</article>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
mock_response.headers = {"content-type": "text/html"}
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_class:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_class.return_value.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client_class.return_value.__aexit__ = AsyncMock(return_value=None)
|
||||
|
||||
content, prefix = await fetch_url(
|
||||
"https://example.com/page",
|
||||
DEFAULT_USER_AGENT_AUTONOMOUS
|
||||
)
|
||||
|
||||
# HTML is processed, so we check it returns something
|
||||
assert isinstance(content, str)
|
||||
assert prefix == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fetch_html_page_raw(self):
|
||||
"""Test fetching an HTML page with raw=True returns original HTML."""
|
||||
html_content = "<html><body><h1>Test</h1></body></html>"
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.text = html_content
|
||||
mock_response.headers = {"content-type": "text/html"}
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_class:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_class.return_value.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client_class.return_value.__aexit__ = AsyncMock(return_value=None)
|
||||
|
||||
content, prefix = await fetch_url(
|
||||
"https://example.com/page",
|
||||
DEFAULT_USER_AGENT_AUTONOMOUS,
|
||||
force_raw=True
|
||||
)
|
||||
|
||||
assert content == html_content
|
||||
assert "cannot be simplified" in prefix
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fetch_json_returns_raw(self):
|
||||
"""Test fetching JSON content returns raw content."""
|
||||
json_content = '{"key": "value"}'
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.text = json_content
|
||||
mock_response.headers = {"content-type": "application/json"}
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_class:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_class.return_value.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client_class.return_value.__aexit__ = AsyncMock(return_value=None)
|
||||
|
||||
content, prefix = await fetch_url(
|
||||
"https://api.example.com/data",
|
||||
DEFAULT_USER_AGENT_AUTONOMOUS
|
||||
)
|
||||
|
||||
assert content == json_content
|
||||
assert "cannot be simplified" in prefix
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fetch_404_raises_error(self):
|
||||
"""Test that 404 response raises McpError."""
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 404
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_class:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_class.return_value.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client_class.return_value.__aexit__ = AsyncMock(return_value=None)
|
||||
|
||||
with pytest.raises(McpError):
|
||||
await fetch_url(
|
||||
"https://example.com/notfound",
|
||||
DEFAULT_USER_AGENT_AUTONOMOUS
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fetch_500_raises_error(self):
|
||||
"""Test that 500 response raises McpError."""
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 500
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_class:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_class.return_value.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client_class.return_value.__aexit__ = AsyncMock(return_value=None)
|
||||
|
||||
with pytest.raises(McpError):
|
||||
await fetch_url(
|
||||
"https://example.com/error",
|
||||
DEFAULT_USER_AGENT_AUTONOMOUS
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fetch_with_proxy(self):
|
||||
"""Test that proxy URL is passed to client."""
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.text = '{"data": "test"}'
|
||||
mock_response.headers = {"content-type": "application/json"}
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_class:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_class.return_value.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client_class.return_value.__aexit__ = AsyncMock(return_value=None)
|
||||
|
||||
await fetch_url(
|
||||
"https://example.com/data",
|
||||
DEFAULT_USER_AGENT_AUTONOMOUS,
|
||||
proxy_url="http://proxy.example.com:8080"
|
||||
)
|
||||
|
||||
# Verify AsyncClient was called with proxy
|
||||
mock_client_class.assert_called_once_with(proxies="http://proxy.example.com:8080")
|
||||
1285
mcpServer/modules/fetch/uv.lock
generated
Normal file
1285
mcpServer/modules/fetch/uv.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user