#!/usr/bin/env python3
"""
测试 MCP 工具的脚本
通过 MCP 协议调用工具，查看详细的请求日志
"""

import requests
import json
import time

def test_mcp_tools(base_url):
    """测试 MCP 工具调用"""
    print(f"🔌 测试 MCP 工具调用: {base_url}/mcp")
    
    # 1. 初始化 MCP 连接
    print("\n1️⃣ 初始化 MCP 连接...")
    init_request = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {
            "protocolVersion": "2024-11-05",
            "capabilities": {"tools": {}},
            "clientInfo": {"name": "test-client", "version": "1.0.0"}
        }
    }
    
    headers = {
        "Content-Type": "application/json",
        "User-Agent": "MCPStore-Test/1.0",
        "X-Test-Client": "nginx-debug"
    }
    
    try:
        response = requests.post(f"{base_url}/mcp", 
                               json=init_request, 
                               headers=headers,
                               timeout=10)
        
        print(f"   状态码: {response.status_code}")
        print(f"   响应头: {dict(response.headers)}")
        
        if response.status_code == 200:
            print("   ✅ MCP 初始化成功")
            init_result = response.json()
            print(f"   初始化响应: {json.dumps(init_result, indent=2, ensure_ascii=False)}")
        else:
            print(f"   ❌ MCP 初始化失败: {response.text}")
            return False
    except Exception as e:
        print(f"   ❌ MCP 初始化异常: {e}")
        return False
    
    # 2. 列出可用工具
    print("\n2️⃣ 列出可用工具...")
    list_tools_request = {
        "jsonrpc": "2.0",
        "id": 2,
        "method": "tools/list",
        "params": {}
    }
    
    try:
        response = requests.post(f"{base_url}/mcp", 
                               json=list_tools_request, 
                               headers=headers,
                               timeout=10)
        
        print(f"   状态码: {response.status_code}")
        
        if response.status_code == 200:
            tools_result = response.json()
            print("   ✅ 工具列表获取成功")
            print(f"   工具列表: {json.dumps(tools_result, indent=2, ensure_ascii=False)}")
            
            # 提取工具名称
            tools = []
            if 'result' in tools_result and 'tools' in tools_result['result']:
                tools = [tool['name'] for tool in tools_result['result']['tools']]
                print(f"   可用工具: {tools}")
        else:
            print(f"   ❌ 工具列表获取失败: {response.text}")
            return False
    except Exception as e:
        print(f"   ❌ 工具列表获取异常: {e}")
        return False
    
    # 3. 调用工具
    if tools:
        print("\n3️⃣ 调用工具...")
        
        # 测试天气查询工具
        if "get_current_weather" in tools:
            print("   🌤️ 测试 get_current_weather 工具...")
            call_tool_request = {
                "jsonrpc": "2.0",
                "id": 3,
                "method": "tools/call",
                "params": {
                    "name": "get_current_weather",
                    "arguments": {
                        "query": "北京"
                    }
                }
            }
            
            try:
                response = requests.post(f"{base_url}/mcp", 
                                       json=call_tool_request, 
                                       headers=headers,
                                       timeout=10)
                
                print(f"      状态码: {response.status_code}")
                
                if response.status_code == 200:
                    tool_result = response.json()
                    print("      ✅ 工具调用成功")
                    print(f"      工具结果: {json.dumps(tool_result, indent=2, ensure_ascii=False)}")
                else:
                    print(f"      ❌ 工具调用失败: {response.text}")
            except Exception as e:
                print(f"      ❌ 工具调用异常: {e}")
        
        # 测试请求信息工具
        if "get_request_info" in tools:
            print("   🔍 测试 get_request_info 工具...")
            call_tool_request = {
                "jsonrpc": "2.0",
                "id": 4,
                "method": "tools/call",
                "params": {
                    "name": "get_request_info",
                    "arguments": {}
                }
            }
            
            try:
                response = requests.post(f"{base_url}/mcp", 
                                       json=call_tool_request, 
                                       headers=headers,
                                       timeout=10)
                
                print(f"      状态码: {response.status_code}")
                
                if response.status_code == 200:
                    tool_result = response.json()
                    print("      ✅ 请求信息工具调用成功")
                    print(f"      请求信息结果: {json.dumps(tool_result, indent=2, ensure_ascii=False)}")
                else:
                    print(f"      ❌ 请求信息工具调用失败: {response.text}")
            except Exception as e:
                print(f"      ❌ 请求信息工具调用异常: {e}")
        
        # 测试调试工具（如果存在）
        if "get_debug_info" in tools:
            print("   🔍 测试 get_debug_info 工具...")
            call_tool_request = {
                "jsonrpc": "2.0",
                "id": 5,
                "method": "tools/call",
                "params": {
                    "name": "get_debug_info",
                    "arguments": {}
                }
            }
            
            try:
                response = requests.post(f"{base_url}/mcp", 
                                       json=call_tool_request, 
                                       headers=headers,
                                       timeout=10)
                
                print(f"      状态码: {response.status_code}")
                
                if response.status_code == 200:
                    tool_result = response.json()
                    print("      ✅ 调试信息工具调用成功")
                    print(f"      调试信息结果: {json.dumps(tool_result, indent=2, ensure_ascii=False)}")
                else:
                    print(f"      ❌ 调试信息工具调用失败: {response.text}")
            except Exception as e:
                print(f"      ❌ 调试信息工具调用异常: {e}")
    
    return True

def main():
    """主测试函数"""
    print("🧪 MCP 工具调用测试")
    print("=" * 60)
    
    # 测试不同的 URL
    test_urls = [
        "http://localhost:21923",
        "http://127.0.0.1:21923",
        # 如果您有域名，可以添加：
        # "https://your-domain.com",
    ]
    
    for base_url in test_urls:
        print(f"\n🎯 测试服务地址: {base_url}")
        print("-" * 40)
        
        success = test_mcp_tools(base_url)
        
        if success:
            print(f"\n🎉 {base_url} MCP 测试完成！")
        else:
            print(f"\n⚠️ {base_url} MCP 测试失败")
    
    print("\n" + "=" * 60)
    print("💡 查看服务日志以获取详细的请求信息:")
    print("   - mcpstorewiki.log (完整服务)")
    print("   - debug_service.log (调试服务)")

if __name__ == "__main__":
    main()
