#!/usr/bin/env python3
"""使用MCP客户端测试服务器"""
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def test_mcp_server():
    """测试MCP服务器"""
    # 创建服务器参数
    server_params = StdioServerParameters(
        command="/app/auto-mcp-upload/.venv/bin/python3",
        args=["-m", "code_sandbox_mcp.server"],
        env={"PYTHONPATH": "/app/auto-mcp-upload/.venv/lib/python3.11/site-packages"}
    )

    print("🚀 连接到MCP服务器...")

    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # 初始化
            print("📤 发送initialize请求...")
            init_result = await session.initialize()
            print(f"✅ 初始化成功: {init_result.serverInfo.name}")

            # 获取工具列表
            print("📤 发送tools/list请求...")
            tools_result = await session.list_tools()
            print(f"✅ 成功获取到 {len(tools_result.tools)} 个工具:")

            for i, tool in enumerate(tools_result.tools, 1):
                print(f"  {i}. {tool.name}")
                print(f"     描述: {tool.description}")
                if hasattr(tool, 'inputSchema'):
                    schema = tool.inputSchema
                    if 'properties' in schema:
                        params = list(schema['properties'].keys())
                        print(f"     参数: {params}")
                print()

            print("✅ 测试成功!")
            return True

if __name__ == "__main__":
    try:
        success = asyncio.run(test_mcp_server())
        if success:
            print("\n✅ MCP服务器测试通过!")
        else:
            print("\n❌ MCP服务器测试失败!")
    except Exception as e:
        print(f"\n❌ 测试过程中发生错误: {e}")
        import traceback
        traceback.print_exc()