File size: 8,405 Bytes
188e027
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
#!/usr/bin/env python3
"""
Test script to diagnose GNS3 connection and MCP server issues
"""

import os
import sys
import time
import requests
import subprocess
import json

# Colors for terminal output
GREEN = '\033[92m'
RED = '\033[91m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
RESET = '\033[0m'

def test_env_vars():
    """Test environment variables"""
    print(f"\n{BLUE}=== Testing Environment Variables ==={RESET}")
    
    gns3_server = os.getenv('GNS3_SERVER', 'NOT SET')
    project_name = os.getenv('GNS3_PROJECT_NAME', 'NOT SET')
    
    print(f"GNS3_SERVER: {gns3_server}")
    print(f"GNS3_PROJECT_NAME: {project_name}")
    
    if gns3_server == 'NOT SET':
        print(f"{RED}❌ GNS3_SERVER not set in environment{RESET}")
        return False
    
    print(f"{GREEN}βœ… Environment variables configured{RESET}")
    return True

def test_gns3_connection():
    """Test direct HTTP connection to GNS3 server"""
    print(f"\n{BLUE}=== Testing GNS3 Server Connection ==={RESET}")
    
    server = os.getenv('GNS3_SERVER', 'http://localhost:3080')
    
    try:
        print(f"Connecting to: {server}/v2/version")
        start_time = time.time()
        response = requests.get(f"{server}/v2/version", timeout=10)
        elapsed = time.time() - start_time
        
        print(f"Response time: {elapsed:.2f}s")
        print(f"Status code: {response.status_code}")
        
        if response.status_code == 200:
            data = response.json()
            print(f"GNS3 version: {data.get('version', 'unknown')}")
            print(f"{GREEN}βœ… GNS3 server is reachable{RESET}")
            return True
        else:
            print(f"{RED}❌ GNS3 server returned error: {response.status_code}{RESET}")
            return False
            
    except requests.exceptions.Timeout:
        print(f"{RED}❌ Connection timed out after 10 seconds{RESET}")
        print(f"{YELLOW}This suggests network connectivity issues{RESET}")
        return False
    except requests.exceptions.ConnectionError as e:
        print(f"{RED}❌ Connection failed: {e}{RESET}")
        return False
    except Exception as e:
        print(f"{RED}❌ Unexpected error: {e}{RESET}")
        return False

def test_gns3_projects():
    """Test fetching GNS3 projects"""
    print(f"\n{BLUE}=== Testing GNS3 Projects API ==={RESET}")
    
    server = os.getenv('GNS3_SERVER', 'http://localhost:3080')
    
    try:
        print(f"Fetching projects from: {server}/v2/projects")
        start_time = time.time()
        response = requests.get(f"{server}/v2/projects", timeout=10)
        elapsed = time.time() - start_time
        
        print(f"Response time: {elapsed:.2f}s")
        
        if response.status_code == 200:
            projects = response.json()
            print(f"Found {len(projects)} projects")
            
            # Look for overgrowth project
            overgrowth = [p for p in projects if 'overgrowth' in p['name'].lower()]
            if overgrowth:
                print(f"{GREEN}βœ… Found overgrowth project: {overgrowth[0]['name']}{RESET}")
                print(f"   Project ID: {overgrowth[0]['project_id']}")
                print(f"   Status: {overgrowth[0].get('status', 'unknown')}")
                return True
            else:
                print(f"{YELLOW}⚠️  overgrowth project not found{RESET}")
                return False
        else:
            print(f"{RED}❌ Failed to fetch projects: {response.status_code}{RESET}")
            return False
            
    except Exception as e:
        print(f"{RED}❌ Error: {e}{RESET}")
        return False

def test_mcp_server():
    """Test MCP server directly"""
    print(f"\n{BLUE}=== Testing MCP Server ==={RESET}")
    
    # Check if server file exists
    server_path = "mcp-server/server.py"
    python_path = "/home/gpaasch/overgrowth-mcp-server/venv/bin/python"
    
    if not os.path.exists(server_path):
        print(f"{RED}❌ MCP server not found at: {server_path}{RESET}")
        return False
    
    if not os.path.exists(python_path):
        print(f"{YELLOW}⚠️  Venv python not found, using system python{RESET}")
        python_path = sys.executable
    
    print(f"Server: {server_path}")
    print(f"Python: {python_path}")
    
    # Prepare MCP request
    init_request = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {
            "protocolVersion": "2024-11-05",
            "capabilities": {},
            "clientInfo": {"name": "test", "version": "1.0"}
        }
    }
    
    projects_request = {
        "jsonrpc": "2.0",
        "id": 2,
        "method": "tools/call",
        "params": {
            "name": "get_projects",
            "arguments": {}
        }
    }
    
    input_data = json.dumps(init_request) + "\n" + json.dumps(projects_request) + "\n"
    
    try:
        print("Calling MCP server...")
        start_time = time.time()
        
        result = subprocess.run(
            [python_path, server_path],
            input=input_data,
            capture_output=True,
            text=True,
            timeout=30
        )
        
        elapsed = time.time() - start_time
        print(f"Response time: {elapsed:.2f}s")
        print(f"Exit code: {result.returncode}")
        
        # Parse response
        lines = result.stdout.strip().split('\n')
        found_response = False
        
        for line in lines:
            if line.startswith('INFO:') or line.startswith('WARNING:'):
                continue
            
            try:
                response = json.loads(line)
                if response.get('id') == 2:
                    found_response = True
                    if 'error' in response:
                        print(f"{RED}❌ MCP server returned error: {response['error']}{RESET}")
                        return False
                    
                    content = response.get('result', {}).get('content', [])
                    if content:
                        text = content[0].get('text', '')
                        projects = json.loads(text)
                        print(f"{GREEN}βœ… MCP server working! Found {len(projects)} projects{RESET}")
                        return True
            except json.JSONDecodeError:
                continue
        
        if not found_response:
            print(f"{RED}❌ No valid response from MCP server{RESET}")
            if result.stderr:
                print(f"Stderr: {result.stderr[:500]}")
            return False
            
    except subprocess.TimeoutExpired:
        print(f"{RED}❌ MCP server timed out after 30 seconds{RESET}")
        return False
    except Exception as e:
        print(f"{RED}❌ Error: {e}{RESET}")
        return False

def main():
    print(f"{BLUE}{'='*60}")
    print("Overgrowth GNS3 Connection Diagnostic Tool")
    print(f"{'='*60}{RESET}")
    
    # Load .env if available
    try:
        from dotenv import load_dotenv
        load_dotenv()
        print(f"{GREEN}βœ… Loaded .env file{RESET}")
    except ImportError:
        print(f"{YELLOW}⚠️  python-dotenv not installed{RESET}")
    
    results = []
    
    # Run tests
    results.append(("Environment Variables", test_env_vars()))
    results.append(("GNS3 Connection", test_gns3_connection()))
    results.append(("GNS3 Projects", test_gns3_projects()))
    results.append(("MCP Server", test_mcp_server()))
    
    # Summary
    print(f"\n{BLUE}=== Test Summary ==={RESET}")
    passed = sum(1 for _, result in results if result)
    total = len(results)
    
    for name, result in results:
        status = f"{GREEN}βœ… PASS{RESET}" if result else f"{RED}❌ FAIL{RESET}"
        print(f"{name:.<40} {status}")
    
    print(f"\n{passed}/{total} tests passed")
    
    if passed == total:
        print(f"\n{GREEN}πŸŽ‰ All tests passed! Your setup is working correctly.{RESET}")
    else:
        print(f"\n{RED}❌ Some tests failed. Check the output above for details.{RESET}")
        print(f"\n{YELLOW}Common fixes:{RESET}")
        print("1. Ensure GNS3 server is running at lab.grahampaasch.com:3080")
        print("2. Check network connectivity (firewall, VPN, etc.)")
        print("3. Verify .env file has correct GNS3_SERVER URL")
        print("4. Check that overgrowth project exists in GNS3")

if __name__ == "__main__":
    main()