#!/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()