#!/usr/bin/env python3
"""
IP Geolocation MCP Server
Uses ip-api.com free API for IP geolocation queries
"""

import json
import requests
from fastmcp import FastMCP

# Create MCP server
mcp = FastMCP("IP Geolocation")

def _get_ip_location_data(ip_address: str = None):
    """Internal function: Get IP address geolocation info"""
    # If no IP address provided, get current IP
    if ip_address:
        url = f"http://ip-api.com/json/{ip_address}"
    else:
        url = "http://ip-api.com/json/"
    
    # Add all available fields
    params = {
        "fields": "66846719"  # Numeric value for all fields
    }
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        if data.get("status") == "success":
            return {
                "ip": data.get("query"),
                "country": data.get("country"),
                "country_code": data.get("countryCode"),
                "region": data.get("regionName"),
                "region_code": data.get("region"),
                "city": data.get("city"),
                "zip_code": data.get("zip"),
                "latitude": data.get("lat"),
                "longitude": data.get("lon"),
                "timezone": data.get("timezone"),
                "isp": data.get("isp"),
                "organization": data.get("org"),
                "as_number": data.get("as"),
                "continent": data.get("continent"),
                "continent_code": data.get("continentCode"),
                "currency": data.get("currency"),
                "mobile": data.get("mobile"),
                "proxy": data.get("proxy"),
                "hosting": data.get("hosting")
            }
        else:
            return {"error": data.get("message", "Failed to get location")}
    except Exception as e:
        return {"error": str(e)}

@mcp.tool()
def get_ip_location(ip_address: str = None):
    """Get/FetchIP地址的地理位置Info/Information"""
    return _get_ip_location_data(ip_address)

@mcp.tool()
def get_multiple_ip_locations(ip_addresses: list):
    """批量Get/Fetch多个IP地址的地理位置Info/Information"""
    if len(ip_addresses) > 100:
        return {"error": "At mostSupport100个IP地址"}
    
    results = []
    for ip in ip_addresses:
        location = _get_ip_location_data(ip.strip())
        results.append({
            "ip": ip.strip(),
            "location": location
        })
    
    return {"results": results, "total": len(results)}

@mcp.tool()
def get_current_ip():
    """Get/Fetch当前公网IP地址"""
    try:
        response = requests.get("http://ip-api.com/json/", timeout=10)
        data = response.json()
        
        if data.get("status") == "success":
            return {
                "ip": data.get("query"),
                "location_summary": f"{data.get('city')}, {data.get('regionName')}, {data.get('country')}"
            }
        else:
            return {"error": "无法Get/Fetch当前IP"}
    except Exception as e:
        return {"error": f"Get/FetchIPFailed: {str(e)}"}

@mcp.tool()
def check_ip_details(ip_address: str):
    """检查IP地址的DetailedInfo/Information，包括安全Info/Information"""
    url = f"http://ip-api.com/json/{ip_address}"
    params = {
        "fields": "66846719"  # 所有字段
    }
    
    try:
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        if data.get("status") == "success":
            return {
                "basic_info": {
                    "ip": data.get("query"),
                    "type": "IPv4" if "." in ip_address else "IPv6",
                    "country": data.get("country"),
                    "city": data.get("city"),
                    "timezone": data.get("timezone")
                },
                "network_info": {
                    "isp": data.get("isp"),
                    "organization": data.get("org"),
                    "as_number": data.get("as"),
                    "reverse_dns": data.get("reverse", "N/A")
                },
                "security_info": {
                    "is_mobile": data.get("mobile", False),
                    "is_proxy": data.get("proxy", False),
                    "is_hosting": data.get("hosting", False)
                },
                "location": {
                    "latitude": data.get("lat"),
                    "longitude": data.get("lon"),
                    "accuracy_radius": "City level",
                    "zip_code": data.get("zip")
                }
            }
        else:
            return {"error": data.get("message", "IPQueryFailed")}
    except Exception as e:
        return {"error": f"QueryFailed: {str(e)}"}

@mcp.tool()
def get_api_info():
    """Get/FetchIP-API服务Info/Information"""
    return {
        "service": "ip-api.com",
        "type": "FreeIP地理位置API",
        "rate_limit": "45次Request/分钟",
        "features": [
            "IPv4和IPv6Support",
            "地理位置Info/Information",
            "ISP和组织Info/Information",
            "时区Info/Information",
            "基础安全检测",
            "无需API密钥"
        ],
        "accuracy": "城市级别",
        "data_sources": "多个地理位置Data库",
        "note": "Free服务，商业Use/Using请考虑付费版本"
    }

if __name__ == "__main__":
    mcp.run() 