import json
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("json-query")

@mcp.tool()
def query_json(data: str, path: str) -> str:
    """用键路径（如 user.name 或 items[0].id）查询 JSON 数据中的值。"""
    try:
        obj = json.loads(data)
    except json.JSONDecodeError as e:
        return f"JSON 解析失败: {e}"

    # 简单拆分路径（支持 a.b 和 a[0]）
    parts = path.replace('[', '.[').split('.')
    parts = [p for p in parts if p]
    
    current = obj
    try:
        for part in parts:
            if part.startswith('[') and part.endswith(']'):
                idx = int(part[1:-1])
                current = current[idx]
            else:
                current = current[part]
        return json.dumps(current, indent=2, ensure_ascii=False) if isinstance(current, (dict, list)) else str(current)
    except (KeyError, IndexError, TypeError) as e:
        return f"路径未找到或类型错误: {path} (错误: {str(e)})"

def main():
    mcp.run()

if __name__ == "__main__":
    main()
