import urllib.request
import urllib.error
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("fetch")

@mcp.tool()
def fetch_url(url: str, timeout: int = 10) -> str:
    """抓取指定 URL 的网页内容并返回纯文本。"""
    if not url.startswith(('http://', 'https://')):
        url = 'http://' + url
        
    req = urllib.request.Request(
        url,
        headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
    )
    
    try:
        with urllib.request.urlopen(req, timeout=timeout) as response:
            charset = response.headers.get_content_charset() or 'utf-8'
            html = response.read().decode(charset, errors='replace')
            return html
    except urllib.error.URLError as e:
        return f"请求失败: {e}"
    except Exception as e:
        return f"未知错误: {e}"

def main():
    mcp.run()

if __name__ == "__main__":
    main()
