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

mcp = FastMCP("jwt-decode")


@mcp.tool()
def decode_jwt(token: str) -> str:
    """解码 JWT Token，查看 header 和 payload（不验证签名）。"""
    parts = token.split(".")
    if len(parts) != 3:
        return "错误: 无效的 JWT 格式，应包含 3 个部分（header.payload.signature）"

    def decode_part(part: str) -> dict:
        padding = 4 - len(part) % 4
        if padding != 4:
            part += "=" * padding
        decoded = base64.urlsafe_b64decode(part)
        return json.loads(decoded)

    try:
        header = decode_part(parts[0])
        payload = decode_part(parts[1])
    except Exception as e:
        return f"解码失败: {e}"

    result = {"header": header, "payload": payload}
    return json.dumps(result, indent=2, ensure_ascii=False)


def main():
    mcp.run()


if __name__ == "__main__":
    main()
