Skip to content

Commit

Permalink
add fetch MCP server
Browse files Browse the repository at this point in the history
  • Loading branch information
jackadamson committed Nov 22, 2024
1 parent 8e63b5e commit 781571b
Show file tree
Hide file tree
Showing 8 changed files with 967 additions and 0 deletions.
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
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.0"
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",
"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()
92 changes: 92 additions & 0 deletions src/fetch/src/mcp_server_fetch/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import markdownify
import readabilipy.simple_json
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import (
TextContent,
Tool,
Prompt,
PromptArgument,
GetPromptResult,
PromptMessage,
)
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

async with AsyncClient() as client:
response = await client.get(url)
response.raise_for_status()
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["url"]
content = await fetch_url(url)
return [TextContent(type="text", text=f"Contents of {url}:\n{content}")]

@server.get_prompt()
async def get_prompt(name, arguments: dict) -> GetPromptResult:
url = arguments["url"]
content = await fetch_url(url)
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

0 comments on commit 781571b

Please sign in to comment.