import urllib.parse
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("url-parse")

@mcp.tool()
def parse_url(url: str) -> str:
    """解析 URL 的各个组成部分。"""
    try:
        parsed = urllib.parse.urlparse(url)
        query = urllib.parse.parse_qs(parsed.query)
        
        info = [
            f"协议 (Scheme): {parsed.scheme}",
            f"域名 (Netloc): {parsed.hostname}",
            f"端口 (Port): {parsed.port}",
            f"用户 (Username): {parsed.username}",
            f"密码 (Password): {parsed.password}",
            f"路径 (Path): {parsed.path}",
            f"参数 (Params): {parsed.params}",
            f"查询 (Query): {parsed.query}",
            f"解析后的查询: {query}",
            f"片段 (Fragment): {parsed.fragment}"
        ]
        
        return "\n".join([i for i in info if "None" not in i and i.split(": ")[1] != ""])
    except Exception as e:
        return f"URL 解析失败: {e}"

def main():
    mcp.run()

if __name__ == "__main__":
    main()
