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

mcp = FastMCP("headers")

@mcp.tool()
def get_headers(url: str, timeout: int = 10) -> str:
    """获取 URL 的 HTTP 响应头信息。"""
    if not url.startswith(('http://', 'https://')):
        url = 'http://' + url
        
    req = urllib.request.Request(
        url, method="HEAD",
        headers={'User-Agent': 'Mozilla/5.0'}
    )
    
    try:
        with urllib.request.urlopen(req, timeout=timeout) as response:
            headers = response.info()
            lines = [f"Status: {response.status} {response.reason}"]
            for k, v in headers.items():
                lines.append(f"{k}: {v}")
            return "\n".join(lines)
    except urllib.error.URLError as e:
        return f"请求失败: {e}"
    except Exception as e:
        return f"未知错误: {e}"

def main():
    mcp.run()

if __name__ == "__main__":
    main()
