#!/usr/bin/env python3
import subprocess
import json
import sys
import time

# 启动MCP服务器
proc = subprocess.Popen(
    ["/app/auto-mcp-upload/.venv/bin/python", "-m", "code_sandbox_mcp.server"],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True,
    cwd="/app/auto-mcp-upload/data/5139"
)

# 发送initialize请求
init_request = {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
        "protocolVersion": "2024-11-05",
        "capabilities": {},
        "clientInfo": {
            "name": "test-client",
            "version": "1.0.0"
        }
    }
}

try:
    print("发送initialize请求...")
    proc.stdin.write(json.dumps(init_request) + "\n")
    proc.stdin.flush()

    # 读取响应
    response = ""
    start_time = time.time()
    while time.time() - start_time < 5:
        try:
            line = proc.stdout.readline()
            if line:
                response += line
                if "}" in line:
                    break
        except:
            break

    print(f"收到响应: {response[:500]}")

    # 发送tools/list请求
    tools_request = {
        "jsonrpc": "2.0",
        "id": 2,
        "method": "tools/list"
    }

    print("发送tools/list请求...")
    proc.stdin.write(json.dumps(tools_request) + "\n")
    proc.stdin.flush()

    # 读取响应
    response = ""
    start_time = time.time()
    while time.time() - start_time < 10:
        try:
            line = proc.stdout.readline()
            if line:
                response += line
                if "}" in line:
                    break
        except:
            break

    print(f"收到响应: {response[:1000]}")

    # 解析响应以获取工具数量
    try:
        data = json.loads(response)
        if "result" in data and "tools" in data["result"]:
            tools = data["result"]["tools"]
            print(f"✅ 成功! 工具数量: {len(tools)}")
            for tool in tools:
                print(f"  - {tool.get('name', 'unknown')}")
        else:
            print(f"❌ 响应格式不正确: {response}")
    except json.JSONDecodeError as e:
        print(f"❌ JSON解析失败: {e}")
        print(f"响应内容: {response}")

finally:
    proc.terminate()
    proc.wait(timeout=2)