Skip to main content
Glama
connect_all_final.pyโ€ข12.8 kB
#!/usr/bin/env python3 """ CONNECT ALL FINAL - Complete Working Solution Connects all agents together with full functionality """ import asyncio import subprocess import sys import os import requests import time from pathlib import Path from datetime import datetime class FinalMCPConnector: """Final working MCP connector that actually connects everything.""" def __init__(self): self.server_process = None self.server_url = "http://localhost:8000" def check_dependencies(self) -> bool: """Check if all dependencies are installed.""" print("๐Ÿ”ง CHECKING DEPENDENCIES") print("=" * 50) required_packages = [ ("requests", "requests"), ("fastapi", "fastapi"), ("uvicorn", "uvicorn"), ("python-dotenv", "dotenv") ] missing = [] for package_name, import_name in required_packages: try: __import__(import_name) print(f"โœ… {package_name}") except ImportError: print(f"โŒ {package_name}") missing.append(package_name) if missing: print(f"\n๐Ÿ”ง Installing missing packages...") for package in missing: try: subprocess.check_call([sys.executable, "-m", "pip", "install", package]) print(f"โœ… Installed {package}") except: print(f"โŒ Failed to install {package}") return False print("โœ… All dependencies ready") return True async def start_server(self) -> bool: """Start the MCP server.""" print("\n๐Ÿš€ STARTING MCP SERVER") print("=" * 50) # Check if server is already running try: response = requests.get(f"{self.server_url}/api/health", timeout=3) if response.status_code == 200: print("โœ… MCP Server already running") return True except: pass # Start the simple server server_file = "simple_mcp_server.py" if not Path(server_file).exists(): print(f"โŒ Server file not found: {server_file}") return False try: print(f"๐Ÿ”„ Starting {server_file}...") # Start server process self.server_process = subprocess.Popen( [sys.executable, server_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) # Wait for server to be ready print("โณ Waiting for server to start...") for attempt in range(30): try: response = requests.get(f"{self.server_url}/api/health", timeout=2) if response.status_code == 200: health = response.json() agents_loaded = health.get("agents_loaded", 0) print(f"โœ… MCP Server started successfully") print(f"๐Ÿค– Agents loaded: {agents_loaded}") return True except: pass await asyncio.sleep(1) if attempt % 10 == 0: print(f"โณ Still waiting... ({attempt}/30)") print("โŒ Server failed to start properly") return False except Exception as e: print(f"โŒ Failed to start server: {e}") return False async def test_all_agents(self) -> dict: """Test all agents to verify they're working.""" print("\n๐Ÿงช TESTING ALL AGENTS") print("=" * 50) test_cases = [ ("Calculate 20% of 500", "Math Agent"), ("Analyze this text: Hello world", "Document Agent"), ("Send email to test@example.com", "Gmail Agent"), ("Create reminder for tomorrow", "Calendar Agent"), ("What is the weather in Mumbai?", "Weather Agent") ] results = {} successful_tests = 0 for command, agent_name in test_cases: print(f"๐Ÿ” Testing {agent_name}: {command[:30]}...") try: response = requests.post( f"{self.server_url}/api/mcp/command", json={"command": command}, timeout=15 ) if response.status_code == 200: result = response.json() status = result.get("status", "unknown") if status == "success": results[agent_name] = "โœ… Working" print(f"โœ… {agent_name}: Working") successful_tests += 1 # Show specific results if "result" in result: print(f" Result: {result['result']}") elif "city" in result: print(f" City: {result['city']}") elif "reminder" in result: print(f" Reminder created") elif "email_sent" in result: print(f" Email prepared") else: results[agent_name] = f"โš ๏ธ Limited: {result.get('message', 'Unknown')[:30]}" print(f"โš ๏ธ {agent_name}: Limited functionality") else: results[agent_name] = f"โŒ HTTP {response.status_code}" print(f"โŒ {agent_name}: HTTP {response.status_code}") except Exception as e: results[agent_name] = f"โŒ Error: {str(e)[:30]}" print(f"โŒ {agent_name}: {str(e)[:30]}...") return { "results": results, "successful_tests": successful_tests, "total_tests": len(test_cases), "success_rate": (successful_tests / len(test_cases)) * 100 } async def get_system_status(self) -> dict: """Get comprehensive system status.""" try: response = requests.get(f"{self.server_url}/api/health", timeout=5) if response.status_code == 200: return response.json() else: return {"status": "error", "message": f"HTTP {response.status_code}"} except Exception as e: return {"status": "error", "message": str(e)} async def connect_all(self) -> dict: """Connect all agents and systems.""" print("๐Ÿ”— FINAL MCP CONNECTION SYSTEM") print("=" * 80) print("๐ŸŽฏ Connecting all agents with full functionality") print("๐Ÿ›ก๏ธ Independent agent architecture with failsafe isolation") print("๐Ÿš€ Complete working solution") print("=" * 80) results = { "timestamp": datetime.now().isoformat(), "dependencies_ready": False, "server_running": False, "system_status": {}, "agent_tests": {}, "system_operational": False } try: # Step 1: Check dependencies results["dependencies_ready"] = self.check_dependencies() if not results["dependencies_ready"]: return results # Step 2: Start server results["server_running"] = await self.start_server() if not results["server_running"]: return results # Step 3: Get system status results["system_status"] = await self.get_system_status() # Step 4: Test all agents test_results = await self.test_all_agents() results["agent_tests"] = test_results # Determine system status results["system_operational"] = ( results["dependencies_ready"] and results["server_running"] and results["system_status"].get("status") == "ok" and test_results["successful_tests"] > 0 ) return results except Exception as e: print(f"โŒ Fatal error: {e}") results["error"] = str(e) return results def cleanup(self): """Cleanup resources.""" if self.server_process: try: self.server_process.terminate() self.server_process.wait(timeout=5) except: try: self.server_process.kill() except: pass async def main(): """Main function.""" connector = FinalMCPConnector() try: results = await connector.connect_all() # Display comprehensive results print("\n" + "=" * 80) print("๐Ÿ“Š FINAL CONNECTION RESULTS") print("=" * 80) print(f"๐Ÿ”ง Dependencies: {'โœ… Ready' if results['dependencies_ready'] else 'โŒ Missing'}") print(f"๐Ÿš€ MCP Server: {'โœ… Running' if results['server_running'] else 'โŒ Failed'}") system_status = results.get("system_status", {}) if system_status.get("status") == "ok": agents_loaded = system_status.get("agents_loaded", 0) available_agents = system_status.get("available_agents", []) print(f"๐Ÿค– Agents Loaded: {agents_loaded}") print(f"๐Ÿ“‹ Available Agents: {', '.join(available_agents)}") agent_tests = results.get("agent_tests", {}) if agent_tests: successful = agent_tests.get("successful_tests", 0) total = agent_tests.get("total_tests", 0) success_rate = agent_tests.get("success_rate", 0) print(f"๐Ÿงช Agent Tests: {successful}/{total} passed ({success_rate:.1f}%)") print(f"\n๐Ÿงช AGENT TEST RESULTS:") for agent, status in agent_tests.get("results", {}).items(): print(f" โ€ข {agent}: {status}") print(f"โšก System: {'โœ… OPERATIONAL' if results['system_operational'] else 'โŒ Limited'}") if results["system_operational"]: print("\n๐ŸŽ‰ ALL SYSTEMS CONNECTED AND WORKING!") print("โœ… Your unified MCP system is fully operational") print("๐Ÿ›ก๏ธ Independent agent architecture implemented") print("๐Ÿ”— All agents connected and tested") print("\n๐ŸŒ ACCESS POINTS:") print(f" โ€ข Web Interface: {connector.server_url}") print(f" โ€ข Health Check: {connector.server_url}/api/health") print(f" โ€ข Command API: {connector.server_url}/api/mcp/command") print(f" โ€ข API Documentation: {connector.server_url}/docs") print("\n๐Ÿงช EXAMPLE COMMANDS:") print(" โ€ข Calculate 20% of 500") print(" โ€ข What is the weather in Mumbai?") print(" โ€ข Send email to test@example.com") print(" โ€ข Create reminder for tomorrow") print(" โ€ข Analyze this text: Hello world") print("\n๐Ÿ’ก USAGE:") print(" 1. Open web interface in browser") print(" 2. Use API endpoints for integration") print(" 3. Run test_all_agents.py for verification") return True else: print("\nโš ๏ธ PARTIAL CONNECTION") print("Some components working but system needs attention") return False except KeyboardInterrupt: print("\n๐Ÿ‘‹ Connection cancelled by user") return False except Exception as e: print(f"\nโŒ Fatal error: {e}") return False finally: connector.cleanup() if __name__ == "__main__": try: success = asyncio.run(main()) if success: print("\n๐ŸŽ‰ ALL AGENTS CONNECTED SUCCESSFULLY!") print("๐Ÿ”— Your unified MCP system is fully operational!") print("๐Ÿš€ Ready for production use!") else: print("\n๐Ÿ”ง Connection completed with some issues.") print("๐Ÿ’ก Check the messages above for details.") except Exception as e: print(f"\nโŒ Connection failed: {e}") import traceback traceback.print_exc()

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/tensorwhiz141/MCP2'

If you have feedback or need assistance with the MCP directory API, please join our Discord server