Delete fixed_mcp_gradio_app.py
Browse files- fixed_mcp_gradio_app.py +0 -703
fixed_mcp_gradio_app.py
DELETED
|
@@ -1,703 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
🏆 Fixed TopCoder MCP Agent - Enhanced Gradio Interface
|
| 4 |
-
Implements proper MCP integration with comprehensive error handling and debugging
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
import asyncio
|
| 8 |
-
import gradio as gr
|
| 9 |
-
import json
|
| 10 |
-
import logging
|
| 11 |
-
from datetime import datetime
|
| 12 |
-
import threading
|
| 13 |
-
import time
|
| 14 |
-
|
| 15 |
-
# Import our fixed MCP client
|
| 16 |
-
from fixed_mcp_client import FixedTopCoderMCPClient
|
| 17 |
-
|
| 18 |
-
# Configure logging
|
| 19 |
-
logging.basicConfig(level=logging.INFO)
|
| 20 |
-
logger = logging.getLogger(__name__)
|
| 21 |
-
|
| 22 |
-
class EnhancedMCPAgent:
|
| 23 |
-
"""
|
| 24 |
-
Enhanced MCP Agent with comprehensive debugging and error handling
|
| 25 |
-
"""
|
| 26 |
-
|
| 27 |
-
def __init__(self):
|
| 28 |
-
self.mcp_client = None
|
| 29 |
-
self.is_connected = False
|
| 30 |
-
self.connection_status = "Not Connected"
|
| 31 |
-
self.transport_method = "HTTP" # Start with HTTP
|
| 32 |
-
self.connection_log = []
|
| 33 |
-
self.stats = {
|
| 34 |
-
"connection_attempts": 0,
|
| 35 |
-
"successful_calls": 0,
|
| 36 |
-
"failed_calls": 0,
|
| 37 |
-
"total_queries": 0,
|
| 38 |
-
"endpoint_discovered": None,
|
| 39 |
-
"last_error": None
|
| 40 |
-
}
|
| 41 |
-
|
| 42 |
-
def log_message(self, message):
|
| 43 |
-
"""Add timestamped message to connection log"""
|
| 44 |
-
timestamp = datetime.now().strftime('%H:%M:%S')
|
| 45 |
-
log_entry = f"[{timestamp}] {message}"
|
| 46 |
-
self.connection_log.append(log_entry)
|
| 47 |
-
logger.info(message)
|
| 48 |
-
|
| 49 |
-
# Keep only last 50 entries
|
| 50 |
-
if len(self.connection_log) > 50:
|
| 51 |
-
self.connection_log = self.connection_log[-50:]
|
| 52 |
-
|
| 53 |
-
return "\n".join(self.connection_log)
|
| 54 |
-
|
| 55 |
-
async def initialize_mcp_connection(self):
|
| 56 |
-
"""Initialize MCP connection with enhanced error handling"""
|
| 57 |
-
try:
|
| 58 |
-
self.log_message(f"🔄 Starting MCP connection via {self.transport_method}")
|
| 59 |
-
self.stats["connection_attempts"] += 1
|
| 60 |
-
|
| 61 |
-
# Create new client
|
| 62 |
-
self.mcp_client = FixedTopCoderMCPClient()
|
| 63 |
-
self.mcp_client.transport_method = self.transport_method
|
| 64 |
-
|
| 65 |
-
# Initialize with endpoint discovery
|
| 66 |
-
success = await self.mcp_client.initialize()
|
| 67 |
-
|
| 68 |
-
if success:
|
| 69 |
-
self.is_connected = True
|
| 70 |
-
self.connection_status = f"Connected via {self.transport_method}"
|
| 71 |
-
self.stats["endpoint_discovered"] = self.mcp_client.working_endpoint
|
| 72 |
-
self.log_message(f"✅ MCP connected! Using endpoint: {self.mcp_client.working_endpoint}")
|
| 73 |
-
return True
|
| 74 |
-
else:
|
| 75 |
-
self.is_connected = False
|
| 76 |
-
self.connection_status = "Connection Failed"
|
| 77 |
-
self.stats["last_error"] = "Initialize failed"
|
| 78 |
-
self.log_message("❌ MCP connection failed")
|
| 79 |
-
return False
|
| 80 |
-
|
| 81 |
-
except Exception as e:
|
| 82 |
-
self.is_connected = False
|
| 83 |
-
self.connection_status = f"Error: {str(e)}"
|
| 84 |
-
self.stats["last_error"] = str(e)
|
| 85 |
-
self.log_message(f"❌ Connection error: {e}")
|
| 86 |
-
return False
|
| 87 |
-
|
| 88 |
-
def sync_initialize_mcp(self):
|
| 89 |
-
"""Synchronous wrapper for MCP initialization"""
|
| 90 |
-
try:
|
| 91 |
-
loop = asyncio.new_event_loop()
|
| 92 |
-
asyncio.set_event_loop(loop)
|
| 93 |
-
result = loop.run_until_complete(self.initialize_mcp_connection())
|
| 94 |
-
return result
|
| 95 |
-
except Exception as e:
|
| 96 |
-
self.log_message(f"❌ Sync initialize error: {e}")
|
| 97 |
-
return False
|
| 98 |
-
finally:
|
| 99 |
-
try:
|
| 100 |
-
loop.close()
|
| 101 |
-
except:
|
| 102 |
-
pass
|
| 103 |
-
|
| 104 |
-
async def test_connection_async(self):
|
| 105 |
-
"""Test MCP connection"""
|
| 106 |
-
try:
|
| 107 |
-
if not self.mcp_client:
|
| 108 |
-
return {"success": False, "error": "No MCP client"}
|
| 109 |
-
|
| 110 |
-
result = await self.mcp_client.test_connection()
|
| 111 |
-
|
| 112 |
-
if result.get("success"):
|
| 113 |
-
self.log_message(f"✅ Connection test passed")
|
| 114 |
-
else:
|
| 115 |
-
self.log_message(f"❌ Connection test failed: {result.get('error')}")
|
| 116 |
-
|
| 117 |
-
return result
|
| 118 |
-
|
| 119 |
-
except Exception as e:
|
| 120 |
-
self.log_message(f"❌ Test error: {e}")
|
| 121 |
-
return {"success": False, "error": str(e)}
|
| 122 |
-
|
| 123 |
-
def sync_test_connection(self):
|
| 124 |
-
"""Synchronous wrapper for connection test"""
|
| 125 |
-
try:
|
| 126 |
-
loop = asyncio.new_event_loop()
|
| 127 |
-
asyncio.set_event_loop(loop)
|
| 128 |
-
result = loop.run_until_complete(self.test_connection_async())
|
| 129 |
-
return result
|
| 130 |
-
except Exception as e:
|
| 131 |
-
return {"success": False, "error": str(e)}
|
| 132 |
-
finally:
|
| 133 |
-
try:
|
| 134 |
-
loop.close()
|
| 135 |
-
except:
|
| 136 |
-
pass
|
| 137 |
-
|
| 138 |
-
async def query_challenges_async(self, **params):
|
| 139 |
-
"""Query challenges via MCP"""
|
| 140 |
-
try:
|
| 141 |
-
if not self.is_connected or not self.mcp_client:
|
| 142 |
-
return {
|
| 143 |
-
"success": False,
|
| 144 |
-
"error": "Not connected to MCP server",
|
| 145 |
-
"data": None
|
| 146 |
-
}
|
| 147 |
-
|
| 148 |
-
self.stats["total_queries"] += 1
|
| 149 |
-
self.log_message(f"🔍 Querying challenges with params: {params}")
|
| 150 |
-
|
| 151 |
-
result = await self.mcp_client.query_challenges(**params)
|
| 152 |
-
|
| 153 |
-
if result.get("success"):
|
| 154 |
-
self.stats["successful_calls"] += 1
|
| 155 |
-
self.log_message("✅ Query successful")
|
| 156 |
-
else:
|
| 157 |
-
self.stats["failed_calls"] += 1
|
| 158 |
-
self.log_message(f"❌ Query failed: {result.get('error')}")
|
| 159 |
-
|
| 160 |
-
return result
|
| 161 |
-
|
| 162 |
-
except Exception as e:
|
| 163 |
-
self.stats["failed_calls"] += 1
|
| 164 |
-
self.log_message(f"❌ Query error: {e}")
|
| 165 |
-
return {"success": False, "error": str(e)}
|
| 166 |
-
|
| 167 |
-
def sync_query_challenges(self, **params):
|
| 168 |
-
"""Synchronous wrapper for challenge queries"""
|
| 169 |
-
try:
|
| 170 |
-
loop = asyncio.new_event_loop()
|
| 171 |
-
asyncio.set_event_loop(loop)
|
| 172 |
-
result = loop.run_until_complete(self.query_challenges_async(**params))
|
| 173 |
-
return result
|
| 174 |
-
except Exception as e:
|
| 175 |
-
return {"success": False, "error": str(e)}
|
| 176 |
-
finally:
|
| 177 |
-
try:
|
| 178 |
-
loop.close()
|
| 179 |
-
except:
|
| 180 |
-
pass
|
| 181 |
-
|
| 182 |
-
def switch_transport_method(self, method: str):
|
| 183 |
-
"""Switch transport method"""
|
| 184 |
-
try:
|
| 185 |
-
if method.upper() in ["SSE", "HTTP"]:
|
| 186 |
-
self.transport_method = method.upper()
|
| 187 |
-
|
| 188 |
-
if self.mcp_client:
|
| 189 |
-
self.mcp_client.switch_transport(method)
|
| 190 |
-
|
| 191 |
-
self.log_message(f"🔄 Switched to {self.transport_method} transport")
|
| 192 |
-
return True
|
| 193 |
-
else:
|
| 194 |
-
self.log_message(f"⚠️ Invalid transport: {method}")
|
| 195 |
-
return False
|
| 196 |
-
except Exception as e:
|
| 197 |
-
self.log_message(f"❌ Transport switch error: {e}")
|
| 198 |
-
return False
|
| 199 |
-
|
| 200 |
-
def get_connection_status(self):
|
| 201 |
-
"""Get comprehensive connection status"""
|
| 202 |
-
return {
|
| 203 |
-
"status": self.connection_status,
|
| 204 |
-
"is_connected": self.is_connected,
|
| 205 |
-
"transport": self.transport_method,
|
| 206 |
-
"working_endpoint": getattr(self.mcp_client, 'working_endpoint', None) if self.mcp_client else None,
|
| 207 |
-
"stats": self.stats.copy(),
|
| 208 |
-
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 209 |
-
"tools_available": len(getattr(self.mcp_client, 'available_tools', []))
|
| 210 |
-
}
|
| 211 |
-
|
| 212 |
-
def create_fixed_mcp_app():
|
| 213 |
-
"""
|
| 214 |
-
Create enhanced Gradio app with comprehensive debugging
|
| 215 |
-
"""
|
| 216 |
-
|
| 217 |
-
# Create agent instance
|
| 218 |
-
agent = EnhancedMCPAgent()
|
| 219 |
-
|
| 220 |
-
# Enhanced CSS
|
| 221 |
-
css = """
|
| 222 |
-
.status-connected {
|
| 223 |
-
background: linear-gradient(45deg, #28a745, #20c997) !important;
|
| 224 |
-
color: white !important; padding: 15px !important; border-radius: 8px !important;
|
| 225 |
-
margin: 10px 0 !important; font-weight: bold !important;
|
| 226 |
-
}
|
| 227 |
-
.status-error {
|
| 228 |
-
background: linear-gradient(45deg, #dc3545, #c82333) !important;
|
| 229 |
-
color: white !important; padding: 15px !important; border-radius: 8px !important;
|
| 230 |
-
margin: 10px 0 !important; font-weight: bold !important;
|
| 231 |
-
}
|
| 232 |
-
.status-testing {
|
| 233 |
-
background: linear-gradient(45deg, #ffc107, #ff8f00) !important;
|
| 234 |
-
color: white !important; padding: 15px !important; border-radius: 8px !important;
|
| 235 |
-
margin: 10px 0 !important; font-weight: bold !important;
|
| 236 |
-
}
|
| 237 |
-
.app-header {
|
| 238 |
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
|
| 239 |
-
color: white !important; padding: 30px !important; border-radius: 15px !important;
|
| 240 |
-
text-align: center !important; margin-bottom: 25px !important;
|
| 241 |
-
}
|
| 242 |
-
.transport-info {
|
| 243 |
-
background: linear-gradient(45deg, #17a2b8, #138496) !important;
|
| 244 |
-
color: white !important; padding: 12px !important; border-radius: 6px !important;
|
| 245 |
-
margin: 8px 0 !important; font-size: 14px !important;
|
| 246 |
-
}
|
| 247 |
-
.debug-section {
|
| 248 |
-
background: #f8f9fa !important; border: 1px solid #dee2e6 !important;
|
| 249 |
-
border-radius: 8px !important; padding: 15px !important; margin: 10px 0 !important;
|
| 250 |
-
}
|
| 251 |
-
"""
|
| 252 |
-
|
| 253 |
-
with gr.Blocks(css=css, title="🔧 Fixed TopCoder MCP Agent") as interface:
|
| 254 |
-
|
| 255 |
-
# Enhanced Header
|
| 256 |
-
gr.HTML("""
|
| 257 |
-
<div class="app-header">
|
| 258 |
-
<h1>🔧 Fixed TopCoder MCP Agent</h1>
|
| 259 |
-
<h2>Enhanced Debug Version with Endpoint Discovery</h2>
|
| 260 |
-
<p><strong>✅ Tests multiple endpoints automatically</strong></p>
|
| 261 |
-
<p><strong>✅ Enhanced error handling and diagnostics</strong></p>
|
| 262 |
-
<p><strong>✅ Real-time connection status monitoring</strong></p>
|
| 263 |
-
<p style="margin-top: 15px; font-size: 14px;">
|
| 264 |
-
<strong>Tested Endpoints:</strong><br>
|
| 265 |
-
https://api.topcoder-dev.com/v6/mcp<br>
|
| 266 |
-
https://api.topcoder-dev.com/v6/mcp/sse<br>
|
| 267 |
-
https://api.topcoder-dev.com/v6/mcp/mcp<br>
|
| 268 |
-
+ Production endpoints
|
| 269 |
-
</p>
|
| 270 |
-
</div>
|
| 271 |
-
""")
|
| 272 |
-
|
| 273 |
-
# Connection Control Section
|
| 274 |
-
with gr.Row():
|
| 275 |
-
with gr.Column(scale=1):
|
| 276 |
-
gr.Markdown("### 🚀 Connection Control")
|
| 277 |
-
|
| 278 |
-
transport_choice = gr.Radio(
|
| 279 |
-
choices=["HTTP", "SSE"],
|
| 280 |
-
value="HTTP",
|
| 281 |
-
label="Transport Method",
|
| 282 |
-
info="HTTP recommended for initial testing"
|
| 283 |
-
)
|
| 284 |
-
|
| 285 |
-
with gr.Row():
|
| 286 |
-
connect_btn = gr.Button("🔌 Connect & Discover", variant="primary", size="lg")
|
| 287 |
-
test_btn = gr.Button("🧪 Test Connection", variant="secondary")
|
| 288 |
-
refresh_btn = gr.Button("🔄 Refresh Status", variant="secondary")
|
| 289 |
-
|
| 290 |
-
with gr.Column(scale=1):
|
| 291 |
-
connection_display = gr.HTML(
|
| 292 |
-
value='<div class="status-error">🔴 Not Connected - Click Connect & Discover</div>',
|
| 293 |
-
label="Connection Status"
|
| 294 |
-
)
|
| 295 |
-
|
| 296 |
-
transport_info = gr.HTML(
|
| 297 |
-
value='<div class="transport-info">📡 Transport: HTTP<br>🔍 Endpoint Discovery: Ready</div>',
|
| 298 |
-
label="Transport & Endpoint Info"
|
| 299 |
-
)
|
| 300 |
-
|
| 301 |
-
# Enhanced Statistics and Diagnostics
|
| 302 |
-
with gr.Row():
|
| 303 |
-
with gr.Column():
|
| 304 |
-
connection_stats = gr.JSON(
|
| 305 |
-
label="📊 Connection Statistics",
|
| 306 |
-
value={
|
| 307 |
-
"status": "Ready",
|
| 308 |
-
"transport": "HTTP",
|
| 309 |
-
"endpoint_discovered": None,
|
| 310 |
-
"stats": {"connection_attempts": 0, "successful_calls": 0, "failed_calls": 0}
|
| 311 |
-
}
|
| 312 |
-
)
|
| 313 |
-
|
| 314 |
-
with gr.Column():
|
| 315 |
-
test_results = gr.JSON(
|
| 316 |
-
label="🧪 Last Test Results",
|
| 317 |
-
value={"ready": "Click Test Connection to see results"}
|
| 318 |
-
)
|
| 319 |
-
|
| 320 |
-
# Main Interface Tabs
|
| 321 |
-
with gr.Tabs():
|
| 322 |
-
# Challenge Query Tab
|
| 323 |
-
with gr.TabItem("📋 MCP Challenge Query"):
|
| 324 |
-
with gr.Row():
|
| 325 |
-
with gr.Column(scale=1):
|
| 326 |
-
gr.Markdown("### 🔍 Query Parameters")
|
| 327 |
-
gr.Markdown("*Enhanced with multiple fallback methods*")
|
| 328 |
-
|
| 329 |
-
status_filter = gr.Dropdown(
|
| 330 |
-
choices=["Any", "Active", "Completed", "Draft"],
|
| 331 |
-
value="Active",
|
| 332 |
-
label="Challenge Status",
|
| 333 |
-
info="Filter by challenge status"
|
| 334 |
-
)
|
| 335 |
-
|
| 336 |
-
track_filter = gr.Dropdown(
|
| 337 |
-
choices=["Any", "DEVELOP", "DESIGN", "DATA_SCIENCE"],
|
| 338 |
-
value="DEVELOP",
|
| 339 |
-
label="Track",
|
| 340 |
-
info="Filter by challenge track"
|
| 341 |
-
)
|
| 342 |
-
|
| 343 |
-
subtrack_filter = gr.Dropdown(
|
| 344 |
-
choices=["Any", "Code", "Algorithm", "Marathon", "UI Prototype", "Bug Hunt"],
|
| 345 |
-
value="Any",
|
| 346 |
-
label="Sub Track",
|
| 347 |
-
info="Optional sub-track filter"
|
| 348 |
-
)
|
| 349 |
-
|
| 350 |
-
with gr.Row():
|
| 351 |
-
per_page = gr.Number(
|
| 352 |
-
value=5,
|
| 353 |
-
minimum=1,
|
| 354 |
-
maximum=20,
|
| 355 |
-
label="Results per Page",
|
| 356 |
-
info="Number of results to return"
|
| 357 |
-
)
|
| 358 |
-
page = gr.Number(
|
| 359 |
-
value=1,
|
| 360 |
-
minimum=1,
|
| 361 |
-
label="Page Number",
|
| 362 |
-
info="Page number for pagination"
|
| 363 |
-
)
|
| 364 |
-
|
| 365 |
-
sort_order = gr.Dropdown(
|
| 366 |
-
choices=["Any", "asc", "desc"],
|
| 367 |
-
value="desc",
|
| 368 |
-
label="Sort Order",
|
| 369 |
-
info="Sort results ascending or descending"
|
| 370 |
-
)
|
| 371 |
-
|
| 372 |
-
query_btn = gr.Button("🔍 Query MCP Server", variant="primary", size="lg")
|
| 373 |
-
|
| 374 |
-
with gr.Column(scale=2):
|
| 375 |
-
gr.Markdown("### 📊 Query Results")
|
| 376 |
-
|
| 377 |
-
query_status = gr.HTML(
|
| 378 |
-
value='<div class="debug-section">Ready to query MCP server - Connect first</div>',
|
| 379 |
-
label="Query Status"
|
| 380 |
-
)
|
| 381 |
-
|
| 382 |
-
raw_results = gr.JSON(
|
| 383 |
-
label="Raw MCP Response",
|
| 384 |
-
value={},
|
| 385 |
-
info="Complete response from MCP server"
|
| 386 |
-
)
|
| 387 |
-
|
| 388 |
-
formatted_results = gr.Textbox(
|
| 389 |
-
label="Formatted Results",
|
| 390 |
-
lines=15,
|
| 391 |
-
interactive=False,
|
| 392 |
-
placeholder="Query results will appear here...",
|
| 393 |
-
info="Human-readable format of the results"
|
| 394 |
-
)
|
| 395 |
-
|
| 396 |
-
# Challenge Details Tab
|
| 397 |
-
with gr.TabItem("📄 Challenge Details"):
|
| 398 |
-
with gr.Row():
|
| 399 |
-
with gr.Column(scale=1):
|
| 400 |
-
gr.Markdown("### 📝 Get Challenge Details")
|
| 401 |
-
gr.Markdown("*Fetch detailed information for specific challenges*")
|
| 402 |
-
|
| 403 |
-
challenge_id_input = gr.Textbox(
|
| 404 |
-
label="Challenge ID",
|
| 405 |
-
placeholder="Enter challenge ID (e.g., 30377453)",
|
| 406 |
-
value="",
|
| 407 |
-
info="Get this from the challenge query results"
|
| 408 |
-
)
|
| 409 |
-
|
| 410 |
-
details_btn = gr.Button("📄 Get Details", variant="primary", size="lg")
|
| 411 |
-
|
| 412 |
-
with gr.Column(scale=2):
|
| 413 |
-
gr.Markdown("### 📋 Challenge Details")
|
| 414 |
-
|
| 415 |
-
details_status = gr.HTML(
|
| 416 |
-
value='<div class="debug-section">Enter challenge ID and click Get Details</div>'
|
| 417 |
-
)
|
| 418 |
-
|
| 419 |
-
details_raw = gr.JSON(
|
| 420 |
-
label="Raw Details Response",
|
| 421 |
-
value={}
|
| 422 |
-
)
|
| 423 |
-
|
| 424 |
-
details_formatted = gr.Textbox(
|
| 425 |
-
label="Formatted Details",
|
| 426 |
-
lines=15,
|
| 427 |
-
interactive=False,
|
| 428 |
-
placeholder="Challenge details will appear here..."
|
| 429 |
-
)
|
| 430 |
-
|
| 431 |
-
# Debug & Diagnostics Tab
|
| 432 |
-
with gr.TabItem("🔧 Debug & Diagnostics"):
|
| 433 |
-
with gr.Row():
|
| 434 |
-
with gr.Column():
|
| 435 |
-
gr.Markdown("### 🏥 Connection Health")
|
| 436 |
-
|
| 437 |
-
health_display = gr.JSON(
|
| 438 |
-
label="Connection Health Status",
|
| 439 |
-
value={"status": "Not tested"}
|
| 440 |
-
)
|
| 441 |
-
|
| 442 |
-
endpoint_discovery = gr.JSON(
|
| 443 |
-
label="Endpoint Discovery Results",
|
| 444 |
-
value={
|
| 445 |
-
"tested_endpoints": [],
|
| 446 |
-
"working_endpoints": [],
|
| 447 |
-
"failed_endpoints": []
|
| 448 |
-
}
|
| 449 |
-
)
|
| 450 |
-
|
| 451 |
-
with gr.Column():
|
| 452 |
-
gr.Markdown("### 📝 Live Connection Log")
|
| 453 |
-
|
| 454 |
-
connection_log = gr.Textbox(
|
| 455 |
-
label="Connection Log (Live Updates)",
|
| 456 |
-
lines=20,
|
| 457 |
-
interactive=False,
|
| 458 |
-
value="Enhanced MCP Agent ready\n✅ Multiple endpoint testing\n✅ Comprehensive error handling\n✅ Real-time diagnostics\n\nSelect transport method and click Connect & Discover to start",
|
| 459 |
-
info="Real-time log of all MCP operations"
|
| 460 |
-
)
|
| 461 |
-
|
| 462 |
-
# Event Handlers
|
| 463 |
-
def handle_transport_change(transport):
|
| 464 |
-
"""Handle transport method change with logging"""
|
| 465 |
-
try:
|
| 466 |
-
agent.switch_transport_method(transport)
|
| 467 |
-
|
| 468 |
-
transport_html = f'<div class="transport-info">📡 Transport: {transport}<br>🔍 Ready for endpoint discovery</div>'
|
| 469 |
-
log = agent.log_message(f"🔄 Transport changed to {transport}")
|
| 470 |
-
|
| 471 |
-
return transport_html, log
|
| 472 |
-
|
| 473 |
-
except Exception as e:
|
| 474 |
-
error_html = f'<div class="status-error">❌ Transport change failed: {str(e)}</div>'
|
| 475 |
-
log = agent.log_message(f"❌ Transport change error: {e}")
|
| 476 |
-
return error_html, log
|
| 477 |
-
|
| 478 |
-
def handle_connect():
|
| 479 |
-
"""Handle MCP server connection with endpoint discovery"""
|
| 480 |
-
try:
|
| 481 |
-
# Show connecting status
|
| 482 |
-
connecting_html = '<div class="status-testing">🔄 Connecting & Discovering Endpoints...</div>'
|
| 483 |
-
|
| 484 |
-
# Perform connection
|
| 485 |
-
success = agent.sync_initialize_mcp()
|
| 486 |
-
status = agent.get_connection_status()
|
| 487 |
-
|
| 488 |
-
if success:
|
| 489 |
-
endpoint = status.get("working_endpoint", "Unknown")
|
| 490 |
-
status_html = f'<div class="status-connected">✅ MCP Connected Successfully<br>🌐 Transport: {status["transport"]}<br>🔗 Endpoint: {endpoint}<br><small>Connected at {status["timestamp"]}</small></div>'
|
| 491 |
-
|
| 492 |
-
transport_html = f'<div class="transport-info">📡 Transport: {status["transport"]}<br>🔗 Working Endpoint: {endpoint}<br>🛠️ Tools Available: {status["tools_available"]}</div>'
|
| 493 |
-
else:
|
| 494 |
-
status_html = f'<div class="status-error">❌ Connection Failed<br><small>{status["status"]}</small><br><small>Last Error: {status["stats"].get("last_error", "Unknown")}</small></div>'
|
| 495 |
-
|
| 496 |
-
transport_html = f'<div class="status-error">❌ No working endpoint found<br>📡 Tried: {status["transport"]} transport</div>'
|
| 497 |
-
|
| 498 |
-
log = "\n".join(agent.connection_log[-30:])
|
| 499 |
-
|
| 500 |
-
return (
|
| 501 |
-
status_html,
|
| 502 |
-
transport_html,
|
| 503 |
-
status,
|
| 504 |
-
log
|
| 505 |
-
)
|
| 506 |
-
|
| 507 |
-
except Exception as e:
|
| 508 |
-
error_html = f'<div class="status-error">❌ Connection Error<br><small>{str(e)}</small></div>'
|
| 509 |
-
error_status = {"status": f"Error: {str(e)}", "is_connected": False}
|
| 510 |
-
log = agent.log_message(f"❌ Connect error: {e}")
|
| 511 |
-
return (error_html, error_html, error_status, log)
|
| 512 |
-
|
| 513 |
-
def handle_test_connection():
|
| 514 |
-
"""Handle connection test with detailed results"""
|
| 515 |
-
try:
|
| 516 |
-
result = agent.sync_test_connection()
|
| 517 |
-
log = "\n".join(agent.connection_log[-20:])
|
| 518 |
-
|
| 519 |
-
# Update health display based on test results
|
| 520 |
-
if result.get("success"):
|
| 521 |
-
health_status = {
|
| 522 |
-
"connection_healthy": True,
|
| 523 |
-
"transport": result.get("transport"),
|
| 524 |
-
"endpoint": result.get("endpoint"),
|
| 525 |
-
"tools_available": result.get("tools_available", 0),
|
| 526 |
-
"last_test": datetime.now().strftime('%H:%M:%S')
|
| 527 |
-
}
|
| 528 |
-
else:
|
| 529 |
-
health_status = {
|
| 530 |
-
"connection_healthy": False,
|
| 531 |
-
"error": result.get("error"),
|
| 532 |
-
"last_test": datetime.now().strftime('%H:%M:%S')
|
| 533 |
-
}
|
| 534 |
-
|
| 535 |
-
return result, health_status, log
|
| 536 |
-
|
| 537 |
-
except Exception as e:
|
| 538 |
-
error_result = {"success": False, "error": str(e)}
|
| 539 |
-
health_status = {"connection_healthy": False, "error": str(e)}
|
| 540 |
-
log = agent.log_message(f"❌ Test error: {e}")
|
| 541 |
-
return error_result, health_status, log
|
| 542 |
-
|
| 543 |
-
def handle_refresh_status():
|
| 544 |
-
"""Refresh connection status display"""
|
| 545 |
-
try:
|
| 546 |
-
status = agent.get_connection_status()
|
| 547 |
-
log = "\n".join(agent.connection_log[-20:])
|
| 548 |
-
|
| 549 |
-
return status, log
|
| 550 |
-
|
| 551 |
-
except Exception as e:
|
| 552 |
-
error_status = {"error": f"Failed to refresh: {e}"}
|
| 553 |
-
log = agent.log_message(f"❌ Refresh error: {e}")
|
| 554 |
-
return error_status, log
|
| 555 |
-
|
| 556 |
-
def handle_query_challenges(status, track, subtrack, per_page, page, sort_order):
|
| 557 |
-
"""Handle MCP challenge queries with enhanced error handling"""
|
| 558 |
-
try:
|
| 559 |
-
if not agent.is_connected:
|
| 560 |
-
error_html = '<div class="status-error">❌ Not Connected - Please connect first</div>'
|
| 561 |
-
return (
|
| 562 |
-
error_html,
|
| 563 |
-
{"error": "Not connected to MCP server"},
|
| 564 |
-
"Please connect to the MCP server first"
|
| 565 |
-
)
|
| 566 |
-
|
| 567 |
-
# Build query parameters
|
| 568 |
-
query_params = {}
|
| 569 |
-
if status and status != "Any":
|
| 570 |
-
query_params["status"] = status
|
| 571 |
-
if track and track != "Any":
|
| 572 |
-
query_params["track"] = track
|
| 573 |
-
if subtrack and subtrack != "Any":
|
| 574 |
-
query_params["subTrack"] = subtrack
|
| 575 |
-
if per_page:
|
| 576 |
-
query_params["perPage"] = int(per_page)
|
| 577 |
-
if page:
|
| 578 |
-
query_params["page"] = int(page)
|
| 579 |
-
if sort_order and sort_order != "Any":
|
| 580 |
-
query_params["sortOrder"] = sort_order
|
| 581 |
-
|
| 582 |
-
# Execute query
|
| 583 |
-
result = agent.sync_query_challenges(**query_params)
|
| 584 |
-
timestamp = datetime.now().strftime('%H:%M:%S')
|
| 585 |
-
|
| 586 |
-
if result.get("success"):
|
| 587 |
-
status_html = f'<div class="status-connected">✅ Query Successful<br>🌐 Transport: {result.get("transport", "Unknown")}<br><small>Query completed at {timestamp}</small></div>'
|
| 588 |
-
|
| 589 |
-
# Format results for display
|
| 590 |
-
data = result.get("data", {})
|
| 591 |
-
formatted_text = f"MCP Query Results:\n"
|
| 592 |
-
formatted_text += f"Transport: {result.get('transport', 'Unknown')}\n"
|
| 593 |
-
formatted_text += f"Format: {result.get('format', 'Unknown')}\n"
|
| 594 |
-
formatted_text += f"Time: {timestamp}\n\n"
|
| 595 |
-
|
| 596 |
-
# Try to extract and format challenge data
|
| 597 |
-
if isinstance(data, dict):
|
| 598 |
-
if "challenges" in data:
|
| 599 |
-
challenges = data["challenges"]
|
| 600 |
-
formatted_text += f"Found {len(challenges)} challenges:\n\n"
|
| 601 |
-
|
| 602 |
-
for i, challenge in enumerate(challenges[:10], 1):
|
| 603 |
-
name = challenge.get("name", "Unknown")
|
| 604 |
-
challenge_id = challenge.get("id", "Unknown")
|
| 605 |
-
track_name = challenge.get("track", "Unknown")
|
| 606 |
-
status_name = challenge.get("status", "Unknown")
|
| 607 |
-
prize = challenge.get("totalPrize", 0)
|
| 608 |
-
|
| 609 |
-
formatted_text += f"{i}. {name}\n"
|
| 610 |
-
formatted_text += f" ID: {challenge_id}\n"
|
| 611 |
-
formatted_text += f" Track: {track_name}\n"
|
| 612 |
-
formatted_text += f" Status: {status_name}\n"
|
| 613 |
-
formatted_text += f" Prize: ${prize}\n\n"
|
| 614 |
-
else:
|
| 615 |
-
# Format other types of responses
|
| 616 |
-
formatted_text += f"Response type: {type(data).__name__}\n"
|
| 617 |
-
formatted_text += f"Keys: {list(data.keys()) if isinstance(data, dict) else 'N/A'}\n\n"
|
| 618 |
-
formatted_text += f"Raw data preview:\n{str(data)[:500]}..."
|
| 619 |
-
else:
|
| 620 |
-
formatted_text += f"Non-dict response: {str(data)[:500]}..."
|
| 621 |
-
|
| 622 |
-
return (
|
| 623 |
-
status_html,
|
| 624 |
-
result,
|
| 625 |
-
formatted_text
|
| 626 |
-
)
|
| 627 |
-
else:
|
| 628 |
-
error_html = f'<div class="status-error">❌ Query Failed<br><small>{result.get("error", "Unknown error")}</small></div>'
|
| 629 |
-
return (
|
| 630 |
-
error_html,
|
| 631 |
-
result,
|
| 632 |
-
f"Query failed: {result.get('error', 'Unknown error')}"
|
| 633 |
-
)
|
| 634 |
-
|
| 635 |
-
except Exception as e:
|
| 636 |
-
error_html = f'<div class="status-error">❌ Query Error<br><small>{str(e)}</small></div>'
|
| 637 |
-
return (
|
| 638 |
-
error_html,
|
| 639 |
-
{"error": str(e)},
|
| 640 |
-
f"Query error: {str(e)}"
|
| 641 |
-
)
|
| 642 |
-
|
| 643 |
-
# Connect all event handlers
|
| 644 |
-
transport_choice.change(
|
| 645 |
-
fn=handle_transport_change,
|
| 646 |
-
inputs=[transport_choice],
|
| 647 |
-
outputs=[transport_info, connection_log]
|
| 648 |
-
)
|
| 649 |
-
|
| 650 |
-
connect_btn.click(
|
| 651 |
-
fn=handle_connect,
|
| 652 |
-
outputs=[connection_display, transport_info, connection_stats, connection_log]
|
| 653 |
-
)
|
| 654 |
-
|
| 655 |
-
test_btn.click(
|
| 656 |
-
fn=handle_test_connection,
|
| 657 |
-
outputs=[test_results, health_display, connection_log]
|
| 658 |
-
)
|
| 659 |
-
|
| 660 |
-
refresh_btn.click(
|
| 661 |
-
fn=handle_refresh_status,
|
| 662 |
-
outputs=[connection_stats, connection_log]
|
| 663 |
-
)
|
| 664 |
-
|
| 665 |
-
query_btn.click(
|
| 666 |
-
fn=handle_query_challenges,
|
| 667 |
-
inputs=[status_filter, track_filter, subtrack_filter, per_page, page, sort_order],
|
| 668 |
-
outputs=[query_status, raw_results, formatted_results]
|
| 669 |
-
)
|
| 670 |
-
|
| 671 |
-
# Initialize interface
|
| 672 |
-
interface.load(
|
| 673 |
-
fn=lambda: (
|
| 674 |
-
'<div class="status-error">🔴 Not Connected - Select transport and connect</div>',
|
| 675 |
-
{"status": "Ready to connect", "transport": "HTTP", "endpoint_discovered": None},
|
| 676 |
-
"Enhanced MCP Agent loaded - Ready for connection\nSelect transport method and click 'Connect & Discover'\n"
|
| 677 |
-
),
|
| 678 |
-
outputs=[connection_display, connection_stats, connection_log]
|
| 679 |
-
)
|
| 680 |
-
|
| 681 |
-
return interface
|
| 682 |
-
|
| 683 |
-
# Main execution
|
| 684 |
-
def main():
|
| 685 |
-
"""Main function for the enhanced MCP agent"""
|
| 686 |
-
print("🚀 Starting Enhanced TopCoder MCP Agent")
|
| 687 |
-
print("🔧 Multiple endpoint testing")
|
| 688 |
-
print("📊 Comprehensive diagnostics")
|
| 689 |
-
print("🌐 HTTP & SSE transport support")
|
| 690 |
-
print("=" * 60)
|
| 691 |
-
|
| 692 |
-
app = create_fixed_mcp_app()
|
| 693 |
-
|
| 694 |
-
# Launch with settings compatible with Hugging Face Spaces
|
| 695 |
-
app.launch(
|
| 696 |
-
server_name="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