diff --git a/src/fetch/README.md b/src/fetch/README.md index ffdd01b0..d7ecb6d4 100644 --- a/src/fetch/README.md +++ b/src/fetch/README.md @@ -2,20 +2,27 @@ 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. +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 - - Argument: `url` (string, required): URL to fetch + - 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 diff --git a/src/fetch/pyproject.toml b/src/fetch/pyproject.toml index 25eac8d8..d9015e69 100644 --- a/src/fetch/pyproject.toml +++ b/src/fetch/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "mcp-server-fetch" -version = "0.1.2" +version = "0.1.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" diff --git a/src/fetch/src/mcp_server_fetch/server.py b/src/fetch/src/mcp_server_fetch/server.py index 04ecad3c..a3c0f95b 100644 --- a/src/fetch/src/mcp_server_fetch/server.py +++ b/src/fetch/src/mcp_server_fetch/server.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Optional, Tuple from urllib.parse import urlparse, urlunparse import markdownify @@ -17,26 +17,44 @@ INTERNAL_ERROR, ) from protego import Protego -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, AnyUrl, conint DEFAULT_USER_AGENT_AUTONOMOUS = "ModelContextProtocol/1.0 (Autonomous; +https://github.com/modelcontextprotocol/servers)" DEFAULT_USER_AGENT_MANUAL = "ModelContextProtocol/1.0 (User-Specified; +https://github.com/modelcontextprotocol/servers)" -def extract_content(html: str) -> str: - ret = readabilipy.simple_json.simple_json_from_html_string(html) - if not ret["plain_content"]: +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 "Page failed to be simplified from HTML" content = markdownify.markdownify( - ret["plain_content"], + ret["content"], heading_style=markdownify.ATX, ) return content -def get_robots_txt_url(url: str) -> str: +def get_robots_txt_url(url: AnyUrl | 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) + parsed = urlparse(str(url)) # Reconstruct the base URL with just scheme, netloc, and /robots.txt path robots_url = urlunparse((parsed.scheme, parsed.netloc, "/robots.txt", "", "", "")) @@ -44,7 +62,7 @@ def get_robots_txt_url(url: str) -> str: return robots_url -async def check_may_autonomously_fetch_url(url: str, user_agent: str): +async def check_may_autonomously_fetch_url(url: AnyUrl | str, user_agent: str) -> None: """ Check if the URL can be fetched by the user agent according to the robots.txt file. Raises a McpError if not. @@ -87,34 +105,72 @@ async def check_may_autonomously_fetch_url(url: str, user_agent: str): ) -async def fetch_url(url: str, user_agent: str) -> str: +async def fetch_url( + url: AnyUrl | str, user_agent: str, force_raw: bool = False +) -> 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() as client: try: response = await client.get( - url, follow_redirects=True, headers={"User-Agent": user_agent} + str(url), + follow_redirects=True, + headers={"User-Agent": user_agent}, + timeout=30, ) - except HTTPError: - raise McpError(INTERNAL_ERROR, f"Failed to fetch {url}") + except HTTPError as e: + raise McpError(INTERNAL_ERROR, f"Failed to fetch {url}: {e!r}") if response.status_code >= 400: raise McpError( INTERNAL_ERROR, f"Failed to fetch {url} - status code {response.status_code}", ) - page_html = response.text + page_raw = response.text - return extract_content(page_html) + content_type = response.headers.get("content-type", "") + is_page_html = ( + " None: + """Run the fetch MCP server. + + Args: + custom_user_agent: Optional custom User-Agent string to use for requests + ignore_robots_txt: Whether to ignore robots.txt restrictions + """ 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 @@ -124,7 +180,7 @@ async def list_tools() -> list[Tool]: return [ Tool( name="fetch", - description="""Fetches a URL from the internet and extracts its contents as markdown. + 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(), @@ -147,15 +203,25 @@ async def list_prompts() -> list[Prompt]: @server.call_tool() async def call_tool(name, arguments: dict) -> list[TextContent]: - url = arguments.get("url") + try: + args = Fetch(**arguments) + except ValueError as e: + raise McpError(INVALID_PARAMS, str(e)) + + url = args.url if not url: raise McpError(INVALID_PARAMS, "URL is required") if not ignore_robots_txt: await check_may_autonomously_fetch_url(url, user_agent_autonomous) - content = await fetch_url(url, user_agent_autonomous) - return [TextContent(type="text", text=f"Contents of {url}:\n{content}")] + content, prefix = await fetch_url( + url, user_agent_autonomous, force_raw=args.raw + ) + if len(content) > args.max_length: + content = content[args.start_index : args.start_index + args.max_length] + content += f"\n\nContent truncated. Call the fetch tool with a start_index of {args.start_index + args.max_length} to get more content." + 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: @@ -165,7 +231,7 @@ async def get_prompt(name: str, arguments: dict | None) -> GetPromptResult: url = arguments["url"] try: - content = await fetch_url(url, user_agent_manual) + content, prefix = await fetch_url(url, user_agent_manual) # TODO: after SDK bug is addressed, don't catch the exception except McpError as e: return GetPromptResult( @@ -181,7 +247,7 @@ async def get_prompt(name: str, arguments: dict | None) -> GetPromptResult: description=f"Contents of {url}", messages=[ PromptMessage( - role="user", content=TextContent(type="text", text=content) + role="user", content=TextContent(type="text", text=prefix + content) ) ], )