from mcp.server.fastmcp import FastMCP

mcp = FastMCP("unit")

# 参考基础单位及换算系数
CONVERSIONS = {
    "length": {
        "m": 1.0, "km": 1000.0, "cm": 0.01, "mm": 0.001,
        "inch": 0.0254, "foot": 0.3048, "yard": 0.9144, "mile": 1609.344
    },
    "weight": {
        "kg": 1.0, "g": 0.001, "mg": 1e-6, "ton": 1000.0,
        "lb": 0.45359237, "oz": 0.02834952
    }
}

@mcp.tool()
def convert_unit(value: float, from_unit: str, to_unit: str) -> str:
    """常用物理量单位转换（如长度 m->inch, 重量 kg->lb）。支持温度 c/f/k。"""
    fr = from_unit.lower().strip()
    to = to_unit.lower().strip()
    
    # 温度特殊处理
    temps = ("c", "f", "k")
    if fr in temps and to in temps:
        celsius = value
        if fr == "f": celsius = (value - 32) * 5/9
        elif fr == "k": celsius = value - 273.15
        
        result = celsius
        if to == "f": result = (celsius * 9/5) + 32
        elif to == "k": result = celsius + 273.15
        return f"{value} {from_unit} = {result:.4f} {to_unit}"

    # 其他按基础单位转换
    for category, units in CONVERSIONS.items():
        if fr in units and to in units:
            base_val = value * units[fr]
            result = base_val / units[to]
            return f"{value} {from_unit} = {result:.6g} {to_unit}"
            
    return f"不支持的转换: {from_unit} 到 {to_unit}"

def main():
    mcp.run()

if __name__ == "__main__":
    main()
