import json
import ast
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("toml-parse")

# Standard library fallback for basic TOML-like structure parsing
# A full TOML parser would require tomllib (3.11+) or toml package.
# Since we require Python 3.11+, we can use tomllib!
import sys
if sys.version_info >= (3, 11):
    import tomllib
else:
    tomllib = None

@mcp.tool()
def parse_toml(text: str) -> str:
    """解析 TOML 文本为 JSON 格式（需要 Python >= 3.11）。"""
    if not tomllib:
        return "错误: 该工具依赖 Python 3.11+ 内置的 tomllib"
        
    try:
        data = tomllib.loads(text)
        return json.dumps(data, indent=2, ensure_ascii=False)
    except TypeError as e:
        # tomllib parses to python types, json dumps handles them mostly
        return f"JSON 序列化失败: {e}"
    except Exception as e:
        return f"TOML 解析失败: {e}"

def main():
    mcp.run()

if __name__ == "__main__":
    main()
