Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fetch URL Server #29

Merged
merged 10 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ A collection of reference implementations and community-contributed servers for
- **[Puppeteer](src/puppeteer)** - Browser automation and web scraping
- **[Brave Search](src/brave-search)** - Web and local search using Brave's Search API
- **[Google Maps](src/google-maps)** - Location services, directions, and place details
- **[Fetch](src/fetch)** - Web content fetching and conversion for efficient LLM usage

## 🚀 Getting Started

Expand Down
2 changes: 2 additions & 0 deletions src/fetch/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
__pycache__
.venv
jackadamson marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions src/fetch/.python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.11
7 changes: 7 additions & 0 deletions src/fetch/LICENSE
Original file line number Diff line number Diff line change
@@ -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.
126 changes: 126 additions & 0 deletions src/fetch/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
# Fetch MCP Server

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.

Presently the server only supports fetching HTML content.

### Available Tools

- `fetch` - Fetches a URL from the internet and extracts its contents as markdown.

### Prompts

- **fetch**
- Fetch a URL and extract its contents as markdown
- Argument: `url` (string, required): URL to fetch

## Installation

### 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 pip installation</summary>

```json
"mcpServers": {
"fetch": {
"command": "python",
"args": ["-m", "mcp_server_fetch"]
}
}
```
</details>

### Configure for Zed

Add to your Zed settings.json:

<details>
<summary>Using uvx</summary>

```json
"context_servers": [
"mcp-server-fetch": {
"command": "uvx",
"args": ["mcp-server-fetch"]
}
],
```
</details>

<details>
<summary>Using pip installation</summary>

```json
"context_servers": {
"mcp-server-fetch": {
"command": "python",
"args": ["-m", "mcp_server_fetch"]
}
},
```
</details>

## 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.
34 changes: 34 additions & 0 deletions src/fetch/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
[project]
name = "mcp-server-fetch"
version = "0.1.1"
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 = "[email protected]" }]
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 = [
"markdownify>=0.13.1",
"mcp>=0.6.0",
jackadamson marked this conversation as resolved.
Show resolved Hide resolved
"pydantic>=2.0.0",
"readabilipy>=0.2.0",
"requests>=2.32.3",
]

[project.scripts]
mcp-server-fetch = "mcp_server_fetch:main"

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.uv]
dev-dependencies = ["pyright>=1.1.389", "ruff>=0.7.3"]
12 changes: 12 additions & 0 deletions src/fetch/src/mcp_server_fetch/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from .server import serve


def main():
"""MCP Fetch Server - HTTP fetching functionality for MCP"""
import asyncio

asyncio.run(serve())


if __name__ == "__main__":
main()
5 changes: 5 additions & 0 deletions src/fetch/src/mcp_server_fetch/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# __main__.py

from mcp_server_fetch import main

main()
119 changes: 119 additions & 0 deletions src/fetch/src/mcp_server_fetch/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import markdownify
import readabilipy.simple_json
from mcp.shared.exceptions import McpError
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import (
GetPromptResult,
Prompt,
PromptArgument,
PromptMessage,
TextContent,
Tool,
INVALID_PARAMS,
INTERNAL_ERROR,
)
from pydantic import BaseModel, Field


def extract_content(html: str) -> str:
ret = readabilipy.simple_json.simple_json_from_html_string(html)
if not ret["plain_content"]:
return "<error>Page failed to be simplified from HTML</error>"
content = markdownify.markdownify(
ret["plain_content"],
heading_style=markdownify.ATX,
)
return content


async def fetch_url(url: str) -> str:
from httpx import AsyncClient, HTTPError

async with AsyncClient() as client:
try:
response = await client.get(url, follow_redirects=True)
except HTTPError:
raise McpError(INTERNAL_ERROR, f"Failed to fetch {url}")
if response.status_code >= 400:
raise McpError(INTERNAL_ERROR, f"Failed to fetch {url} - status code {response.status_code}")

page_html = response.text

return extract_content(page_html)


class Fetch(BaseModel):
url: str = Field(..., description="URL to fetch")


async def serve() -> None:
server = Server("mcp-fetch")

@server.list_tools()
async def list_tools() -> list[Tool]:
return [
Tool(
name="fetch",
description="""Fetches a URL from the internet and 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]:
url = arguments.get("url")
if not url:
raise McpError(INVALID_PARAMS, "URL is required")

content = await fetch_url(url)
return [TextContent(type="text", text=f"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(INVALID_PARAMS, "URL is required")

url = arguments["url"]

try:
content = await fetch_url(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=content)
)
],
)

options = server.create_initialization_options()
async with stdio_server() as (read_stream, write_stream):
await server.run(read_stream, write_stream, options, raise_exceptions=True)
Loading