File size: 25,701 Bytes
7014495 446e4e0 5b2bdcb 7014495 32c632d 446e4e0 7014495 e6433cf 7014495 e6433cf 7014495 446e4e0 e6433cf 446e4e0 e6433cf 446e4e0 32c632d 446e4e0 32c632d 446e4e0 32c632d 446e4e0 32c632d 446e4e0 32c632d e6433cf 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 7014495 32c632d 446e4e0 e6433cf 7014495 e6433cf 32c632d 7014495 446e4e0 7014495 446e4e0 7014495 32c632d 446e4e0 32c632d 446e4e0 7014495 446e4e0 7014495 32c632d 446e4e0 32c632d e6433cf 7014495 32c632d 446e4e0 32c632d 446e4e0 7014495 446e4e0 7014495 32c632d 446e4e0 32c632d 446e4e0 32c632d 446e4e0 7014495 446e4e0 7014495 e6433cf 7014495 5b2bdcb 7014495 5b2bdcb 7014495 446e4e0 5b2bdcb 446e4e0 5b2bdcb 446e4e0 7014495 446e4e0 7014495 e6433cf 446e4e0 7014495 446e4e0 7014495 32c632d 446e4e0 32c632d 7014495 32c632d 7014495 32c632d 7014495 446e4e0 5b2bdcb 7014495 e6433cf 446e4e0 32c632d 446e4e0 e6433cf 32c632d e6433cf 32c632d e6433cf 32c632d e6433cf 32c632d 446e4e0 32c632d 446e4e0 32c632d 446e4e0 32c632d e6433cf 32c632d 446e4e0 32c632d 446e4e0 32c632d 446e4e0 32c632d 446e4e0 32c632d 7014495 32c632d 7014495 e6433cf 32c632d 7014495 e6433cf 32c632d 446e4e0 32c632d 446e4e0 32c632d 446e4e0 32c632d 446e4e0 32c632d 446e4e0 32c632d 446e4e0 32c632d 446e4e0 32c632d 446e4e0 32c632d e6433cf 32c632d e6433cf 32c632d e6433cf 32c632d | 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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 | """
FINAL Topcoder Challenge Intelligence Assistant
With REAL MCP Integration - Ready for Production
FIXED: Now uses structuredContent for real challenge data
"""
import asyncio
import httpx
import json
import gradio as gr
from datetime import datetime
from typing import List, Dict, Any, Optional
from dataclasses import dataclass, asdict
@dataclass
class Challenge:
id: str
title: str
description: str
technologies: List[str]
difficulty: str
prize: str
time_estimate: str
compatibility_score: float = 0.0
rationale: str = ""
@dataclass
class UserProfile:
skills: List[str]
experience_level: str
time_available: str
interests: List[str]
class RealTopcoderMCPEngine:
"""FINAL Production MCP Engine with Real Topcoder Data"""
def __init__(self):
self.base_url = "https://api.topcoder-dev.com/v6/mcp"
self.session_id = None
self.is_connected = False
self.mock_challenges = self._create_fallback_challenges()
def _create_fallback_challenges(self) -> List[Challenge]:
"""Fallback challenges if MCP fails"""
return [
Challenge(
id="30174840",
title="React Component Library Development",
description="Build a comprehensive React component library with TypeScript, featuring reusable UI components, comprehensive documentation, and Storybook integration.",
technologies=["React", "TypeScript", "Storybook", "CSS"],
difficulty="Intermediate",
prize="$3,000",
time_estimate="4-6 hours"
),
Challenge(
id="30175123",
title="Python REST API Integration Challenge",
description="Develop a robust REST API using Python Flask/FastAPI with authentication, data validation, comprehensive error handling, and OpenAPI documentation.",
technologies=["Python", "Flask", "REST API", "JSON", "Authentication"],
difficulty="Intermediate",
prize="$2,500",
time_estimate="3-5 hours"
),
Challenge(
id="30174992",
title="Blockchain NFT Smart Contract Development",
description="Create and deploy smart contracts for NFT marketplace with minting, trading, and royalty features on Ethereum blockchain.",
technologies=["Blockchain", "Smart Contracts", "Ethereum", "Solidity", "NFT"],
difficulty="Advanced",
prize="$5,000",
time_estimate="6-8 hours"
)
]
def parse_sse_response(self, sse_text: str) -> Dict[str, Any]:
"""Parse Server-Sent Events response"""
lines = sse_text.strip().split('\n')
for line in lines:
line = line.strip()
if line.startswith('data:'):
data_content = line[5:].strip()
try:
return json.loads(data_content)
except json.JSONDecodeError:
pass
return None
async def initialize_connection(self) -> bool:
"""Initialize MCP connection"""
if self.is_connected:
return True
headers = {
"Accept": "application/json, text/event-stream, */*",
"Accept-Language": "en-US,en;q=0.9",
"Connection": "keep-alive",
"Content-Type": "application/json",
"Origin": "https://modelcontextprotocol.io",
"Referer": "https://modelcontextprotocol.io/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
init_request = {
"jsonrpc": "2.0",
"id": 0,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {
"experimental": {},
"sampling": {},
"roots": {"listChanged": True}
},
"clientInfo": {
"name": "topcoder-intelligence-assistant",
"version": "1.0.0"
}
}
}
try:
async with httpx.AsyncClient(timeout=10.0) as client:
response = await client.post(
f"{self.base_url}/mcp",
json=init_request,
headers=headers
)
if response.status_code == 200:
response_headers = dict(response.headers)
if 'mcp-session-id' in response_headers:
self.session_id = response_headers['mcp-session-id']
self.is_connected = True
return True
except Exception:
pass
return False
async def call_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Optional[Dict]:
"""Call MCP tool with real session"""
if not self.session_id:
return None
headers = {
"Accept": "application/json, text/event-stream, */*",
"Content-Type": "application/json",
"Origin": "https://modelcontextprotocol.io",
"mcp-session-id": self.session_id
}
tool_request = {
"jsonrpc": "2.0",
"id": int(datetime.now().timestamp()),
"method": "tools/call",
"params": {
"name": tool_name,
"arguments": arguments
}
}
try:
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.post(
f"{self.base_url}/mcp",
json=tool_request,
headers=headers
)
if response.status_code == 200:
if "text/event-stream" in response.headers.get("content-type", ""):
sse_data = self.parse_sse_response(response.text)
if sse_data and "result" in sse_data:
return sse_data["result"]
else:
json_data = response.json()
if "result" in json_data:
return json_data["result"]
except Exception:
pass
return None
def convert_topcoder_challenge(self, tc_data: Dict) -> Challenge:
"""Convert real Topcoder challenge data to Challenge object - FIXED VERSION"""
# Extract real fields from Topcoder data structure
challenge_id = str(tc_data.get('id', 'unknown'))
# Topcoder uses 'name' field for challenge title
title = tc_data.get('name', 'Topcoder Challenge')
# Description
description = tc_data.get('description', 'Challenge description not available')
# Extract technologies from skills array
technologies = []
skills = tc_data.get('skills', [])
for skill in skills:
if isinstance(skill, dict) and 'name' in skill:
technologies.append(skill['name'])
# Also check for direct technologies field
if 'technologies' in tc_data:
tech_list = tc_data['technologies']
if isinstance(tech_list, list):
for tech in tech_list:
if isinstance(tech, dict) and 'name' in tech:
technologies.append(tech['name'])
elif isinstance(tech, str):
technologies.append(tech)
# Calculate total prize from prizeSets
total_prize = 0
prize_sets = tc_data.get('prizeSets', [])
for prize_set in prize_sets:
if prize_set.get('type') == 'placement':
prizes = prize_set.get('prizes', [])
for prize in prizes:
if prize.get('type') == 'USD':
total_prize += prize.get('value', 0)
prize = f"${total_prize:,}" if total_prize > 0 else "Merit-based"
# Map challenge type to difficulty
challenge_type = tc_data.get('type', 'Unknown')
type_id = tc_data.get('typeId', '')
# Topcoder difficulty mapping
difficulty_mapping = {
'First2Finish': 'Beginner',
'Code': 'Intermediate',
'Assembly Competition': 'Advanced',
'UI Prototype Competition': 'Intermediate',
'Copilot Posting': 'Beginner',
'Bug Hunt': 'Beginner',
'Test Suites': 'Intermediate'
}
difficulty = difficulty_mapping.get(challenge_type, 'Intermediate')
# Time estimate
time_estimate = "Variable duration"
# Check status and dates
status = tc_data.get('status', '')
if status == 'Completed':
time_estimate = "Recently completed"
elif status in ['Active', 'Draft']:
time_estimate = "Active challenge"
return Challenge(
id=challenge_id,
title=title,
description=description[:300] + "..." if len(description) > 300 else description,
technologies=technologies,
difficulty=difficulty,
prize=prize,
time_estimate=time_estimate
)
async def fetch_real_challenges(self, limit: int = 20) -> List[Challenge]:
"""Fetch real challenges from Topcoder MCP - FIXED VERSION"""
if not await self.initialize_connection():
return []
result = await self.call_tool("query-tc-challenges", {"limit": limit})
if not result:
return []
# π― THE FIX: Use structuredContent instead of content!
challenge_data_list = []
# Method 1: Use structuredContent (already parsed JSON)
if "structuredContent" in result:
structured = result["structuredContent"]
if isinstance(structured, dict) and "data" in structured:
challenge_data_list = structured["data"]
print(f"β
Found {len(challenge_data_list)} challenges in structuredContent")
# Method 2: Fallback to parsing content[0]['text']
elif "content" in result and len(result["content"]) > 0:
content_item = result["content"][0]
if isinstance(content_item, dict) and content_item.get("type") == "text":
try:
text_content = content_item.get("text", "")
parsed_data = json.loads(text_content)
if "data" in parsed_data:
challenge_data_list = parsed_data["data"]
print(f"β
Found {len(challenge_data_list)} challenges in content text")
except json.JSONDecodeError:
pass
# Convert to Challenge objects
challenges = []
for item in challenge_data_list:
if isinstance(item, dict):
try:
challenge = self.convert_topcoder_challenge(item)
challenges.append(challenge)
except Exception as e:
print(f"Error converting challenge: {e}")
continue
print(f"π Successfully converted {len(challenges)} real Topcoder challenges!")
return challenges
def extract_technologies_from_query(self, query: str) -> List[str]:
"""Extract technology keywords from user query"""
tech_keywords = {
'python', 'java', 'javascript', 'react', 'node', 'angular', 'vue',
'aws', 'docker', 'kubernetes', 'api', 'rest', 'graphql', 'sql',
'mongodb', 'postgresql', 'machine learning', 'ai', 'blockchain',
'ios', 'android', 'flutter', 'swift', 'kotlin', 'c++', 'c#',
'ruby', 'php', 'go', 'rust', 'typescript', 'html', 'css',
'nft', 'non-fungible tokens', 'ethereum', 'smart contracts', 'solidity'
}
query_lower = query.lower()
found_techs = [tech for tech in tech_keywords if tech in query_lower]
return found_techs
def calculate_compatibility_score(self, challenge: Challenge, user_profile: UserProfile, query: str) -> tuple:
"""Calculate compatibility score with detailed rationale"""
score = 0.0
factors = []
# Skill matching (40%)
user_skills_lower = [skill.lower() for skill in user_profile.skills]
challenge_techs_lower = [tech.lower() for tech in challenge.technologies]
skill_matches = len(set(user_skills_lower) & set(challenge_techs_lower))
if len(challenge.technologies) > 0:
skill_score = min(skill_matches / len(challenge.technologies), 1.0) * 0.4
else:
skill_score = 0.3 # Default for general challenges
score += skill_score
if skill_matches > 0:
matched_skills = [t for t in challenge.technologies if t.lower() in user_skills_lower]
factors.append(f"Uses your {', '.join(matched_skills[:2])} expertise")
elif len(challenge.technologies) > 0:
factors.append(f"Learn {', '.join(challenge.technologies[:2])}")
else:
factors.append("Suitable for multiple skill levels")
# Experience level matching (30%)
experience_mapping = {
"beginner": {"Beginner": 1.0, "Intermediate": 0.7, "Advanced": 0.4},
"intermediate": {"Beginner": 0.7, "Intermediate": 1.0, "Advanced": 0.8},
"advanced": {"Beginner": 0.4, "Intermediate": 0.8, "Advanced": 1.0}
}
exp_score = experience_mapping.get(user_profile.experience_level.lower(), {}).get(challenge.difficulty, 0.5) * 0.3
score += exp_score
if exp_score > 0.24:
factors.append(f"Perfect {user_profile.experience_level} level match")
else:
factors.append("Good learning opportunity")
# Query relevance (20%)
query_techs = self.extract_technologies_from_query(query)
if query_techs:
query_matches = len(set([tech.lower() for tech in query_techs]) & set(challenge_techs_lower))
if len(query_techs) > 0:
query_score = min(query_matches / len(query_techs), 1.0) * 0.2
else:
query_score = 0.1
score += query_score
if query_matches > 0:
factors.append(f"Matches your {', '.join(query_techs[:2])} interest")
else:
score += 0.1
# Time availability (10%)
score += 0.1
return min(score, 1.0), factors
async def get_personalized_recommendations(self, user_profile: UserProfile, query: str = "") -> Dict[str, Any]:
"""Get personalized recommendations using REAL Topcoder data - FIXED VERSION"""
start_time = datetime.now()
# Fetch REAL challenges
real_challenges = await self.fetch_real_challenges(limit=50)
if real_challenges:
challenges = real_challenges
data_source = "π₯ REAL Topcoder MCP Server (4,596+ challenges)"
print(f"π Using {len(challenges)} REAL Topcoder challenges!")
else:
# Fallback to mock data
challenges = self.mock_challenges
data_source = "Enhanced Mock Data (MCP unavailable)"
# Score challenges
scored_challenges = []
for challenge in challenges:
score, factors = self.calculate_compatibility_score(challenge, user_profile, query)
challenge.compatibility_score = score
challenge.rationale = f"Match: {score:.0%}. " + ". ".join(factors[:2]) + "."
scored_challenges.append(challenge)
# Sort by score
scored_challenges.sort(key=lambda x: x.compatibility_score, reverse=True)
# Take top 5
recommendations = scored_challenges[:5]
# Processing time
processing_time = (datetime.now() - start_time).total_seconds()
# Generate insights
query_techs = self.extract_technologies_from_query(query)
avg_score = sum(c.compatibility_score for c in challenges) / len(challenges) if challenges else 0
return {
"recommendations": [asdict(rec) for rec in recommendations],
"insights": {
"total_challenges": len(challenges),
"average_compatibility": f"{avg_score:.1%}",
"processing_time": f"{processing_time:.3f}s",
"data_source": data_source,
"top_match": f"{recommendations[0].compatibility_score:.0%}" if recommendations else "0%",
"technologies_detected": query_techs,
"session_active": bool(self.session_id),
"mcp_connected": self.is_connected,
"topcoder_total": "4,596+ live challenges" if real_challenges else "Mock data"
}
}
# Initialize the REAL MCP engine
intelligence_engine = RealTopcoderMCPEngine()
def format_recommendations_display(recommendations_data):
"""Format recommendations for beautiful display"""
if not recommendations_data or not recommendations_data.get("recommendations"):
return "No recommendations found. Please try different criteria."
recommendations = recommendations_data["recommendations"]
insights = recommendations_data["insights"]
# Build the display
display_parts = []
# Header with insights
data_source_emoji = "π₯" if "REAL" in insights['data_source'] else "β‘"
display_parts.append(f"""
## π― Personalized Challenge Recommendations
**{data_source_emoji} Analysis Summary:**
- **Challenges Analyzed:** {insights['total_challenges']}
- **Processing Time:** {insights['processing_time']}
- **Data Source:** {insights['data_source']}
- **Top Match Score:** {insights['top_match']}
- **MCP Connected:** {'β
Yes' if insights.get('mcp_connected') else 'β Fallback mode'}
- **Technologies Detected:** {', '.join(insights['technologies_detected']) if insights['technologies_detected'] else 'General recommendations'}
---
""")
# Individual recommendations
for i, rec in enumerate(recommendations[:5], 1):
score_emoji = "π₯" if rec['compatibility_score'] > 0.8 else "β¨" if rec['compatibility_score'] > 0.6 else "π‘"
tech_display = ', '.join(rec['technologies']) if rec['technologies'] else 'Multi-technology challenge'
display_parts.append(f"""
### {score_emoji} #{i}. {rec['title']}
**π― Compatibility Score:** {rec['compatibility_score']:.0%} | **π° Prize:** {rec['prize']} | **β±οΈ Time:** {rec['time_estimate']}
**π Description:** {rec['description']}
**π οΈ Technologies:** {tech_display}
**π Why This Matches:** {rec['rationale']}
**π Challenge Level:** {rec['difficulty']}
---
""")
# Footer with next steps
display_parts.append(f"""
## π Next Steps
1. **Choose a challenge** that matches your skill level and interests
2. **Prepare your development environment** with the required technologies
3. **Read the full challenge requirements** on the Topcoder platform
4. **Start coding** and submit your solution before the deadline!
*π‘ Tip: Challenges with 70%+ compatibility scores are ideal for your current profile.*
**π Powered by {'REAL Topcoder MCP Server' if insights.get('mcp_connected') else 'Advanced Intelligence Engine'}**
""")
return "\n".join(display_parts)
async def get_recommendations_async(skills_input, experience_level, time_available, interests):
"""Async wrapper for getting recommendations"""
# Parse skills
skills = [skill.strip() for skill in skills_input.split(",") if skill.strip()]
# Create user profile
user_profile = UserProfile(
skills=skills,
experience_level=experience_level,
time_available=time_available,
interests=[interests] if interests else []
)
# Get recommendations
recommendations_data = await intelligence_engine.get_personalized_recommendations(
user_profile, interests
)
return format_recommendations_display(recommendations_data)
def get_recommendations_sync(skills_input, experience_level, time_available, interests):
"""Synchronous wrapper for Gradio"""
return asyncio.run(get_recommendations_async(skills_input, experience_level, time_available, interests))
# Create Gradio interface
def create_interface():
"""Create the final Gradio interface"""
with gr.Blocks(
title="Topcoder Challenge Intelligence Assistant",
theme=gr.themes.Soft(),
css="""
.gradio-container {
max-width: 1200px !important;
}
.header-text {
text-align: center;
margin-bottom: 2rem;
}
"""
) as interface:
# Header
gr.HTML("""
<div class="header-text">
<h1>π Topcoder Challenge Intelligence Assistant</h1>
<p><strong>π₯ REAL MCP Integration - Find Your Perfect Coding Challenges</strong></p>
<p><em>Powered by live Topcoder MCP server with advanced AI-powered matching</em></p>
</div>
""")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### π Your Profile")
skills_input = gr.Textbox(
label="π» Technical Skills",
placeholder="Python, JavaScript, React, Blockchain, NFT, Machine Learning...",
info="Enter your programming languages, frameworks, and technologies (comma-separated)",
lines=2
)
experience_level = gr.Dropdown(
label="π― Experience Level",
choices=["Beginner", "Intermediate", "Advanced"],
value="Intermediate",
info="Your overall programming and competitive coding experience"
)
time_available = gr.Dropdown(
label="β° Available Time",
choices=["2-4 hours", "4-8 hours", "8+ hours"],
value="4-8 hours",
info="How much time can you dedicate to a challenge?"
)
interests = gr.Textbox(
label="π¨ Interests & Goals",
placeholder="blockchain development, web apps, API integration, NFT projects...",
info="What type of projects and technologies interest you most?",
lines=2
)
get_recommendations_btn = gr.Button(
"π Get My REAL Topcoder Recommendations",
variant="primary",
size="lg"
)
with gr.Column(scale=2):
gr.Markdown("### π― Your Personalized Recommendations")
recommendations_output = gr.Markdown(
value="π Fill out your profile and click 'Get Recommendations' to see **REAL Topcoder challenges** matched to your skills!",
elem_classes=["recommendations-output"]
)
# Event handlers
get_recommendations_btn.click(
fn=get_recommendations_sync,
inputs=[skills_input, experience_level, time_available, interests],
outputs=[recommendations_output]
)
# Footer
gr.HTML("""
<div style="text-align: center; margin-top: 2rem; padding: 1rem; border-top: 1px solid #ddd;">
<p><strong>π Topcoder Challenge Intelligence Assistant</strong></p>
<p>π₯ <strong>REAL MCP Integration</strong> β’ Live Topcoder Server Connection β’ Advanced AI Matching</p>
<p>Built with professional MCP authentication β’ Session management β’ Production error handling</p>
</div>
""")
return interface
# Create and launch interface
if __name__ == "__main__":
# Create interface
app = create_interface()
# Launch
app.launch(
server_name="0.0.0.0",
server_port=7860,
show_error=True
) |