Upload app.py
Browse files337 unmodified lines338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470337 unmodified linessort_by: str = None,sort_order: str = None,) -> List[Challenge]:"""FIXED: Debug version - shows exactly what MCP is doing"""# Always try to connectprint(f"π Attempting to fetch REAL challenges (limit: {limit})")print(f"π― Query: '{query}' | Skills: {user_profile.skills}")connection_success = await self.initialize_connection()if not connection_success:print("β Could not establish MCP connection, using fallback")return []# Try multiple query strategies to see what worksquery_strategies = []# Strategy 1: Simple query with minimal parameterssimple_query = {"perPage": min(limit, 20)}if query.strip():simple_query["search"] = query.strip()query_strategies.append(("Simple Search", simple_query))# Strategy 2: Skills-based queryskill_keywords = self.extract_technologies_from_query(query + " " + " ".join(user_profile.skills + user_profile.interests))if skill_keywords:skills_query = {"perPage": min(limit, 20)}skills_query["tags"] = skill_keywords[:3] # Limit to 3 skillsquery_strategies.append(("Skills Query", skills_query))# Strategy 3: Your comprehensive querycomprehensive_query = {"perPage": min(limit, 20)}if status:comprehensive_query["status"] = statusif query.strip():comprehensive_query["search"] = query.strip()if sort_by:comprehensive_query["sortBy"] = sort_byif sort_order:comprehensive_query["sortOrder"] = sort_orderquery_strategies.append(("Comprehensive", comprehensive_query))# Try each strategy until one worksfor strategy_name, mcp_query in query_strategies:print(f"\nπ§ͺ Trying {strategy_name} strategy:")print(f"π§ Query parameters: {mcp_query}")# Call the MCP toolresult = await self.call_tool("query-tc-challenges", mcp_query)if not result:print(f"β {strategy_name} failed - no result")continueprint(f"π {strategy_name} result type: {type(result)}")if isinstance(result, dict):print(f"π Result keys: {list(result.keys())}")# Show first few characters of each field for debuggingfor key, value in result.items():if isinstance(value, str):print(f" {key}: {str(value)[:100]}...")elif isinstance(value, dict):print(f" {key}: dict with keys {list(value.keys())}")elif isinstance(value, list):print(f" {key}: list with {len(value)} items")else:print(f" {key}: {type(value)}")# Try to parse the responsechallenge_data_list = []# Check all possible data locationsdata_sources = [("structuredContent.data", result.get("structuredContent", {}).get("data", [])),("data", result.get("data", [])),("content[0].text", None), # Will handle separately("result", result if isinstance(result, list) else [])]for source_name, data in data_sources:if data and isinstance(data, list) and len(data) > 0:challenge_data_list = dataprint(f"β Found {len(challenge_data_list)} challenges in {source_name}")break# Special handling for content fieldif not challenge_data_list and "content" in result:content = result["content"]if isinstance(content, list) and len(content) > 0:content_item = content[0]if isinstance(content_item, dict) and content_item.get("type") == "text":try:text_content = content_item.get("text", "")print(f"π Content text preview: {text_content[:200]}...")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 parsed content")except json.JSONDecodeError as e:print(f"β Failed to parse content JSON: {e}")if challenge_data_list:print(f"π― Sample challenge data keys: {list(challenge_data_list[0].keys()) if challenge_data_list else 'None'}")# Convert challengeschallenges = []for i, item in enumerate(challenge_data_list):if isinstance(item, dict):try:challenge = self.convert_topcoder_challenge(item)challenges.append(challenge)if i == 0: # Show first challenge detailsprint(f"π First challenge: {challenge.title} | {challenge.prize} | {challenge.technologies}")except Exception as e:print(f"β Error converting challenge {i}: {e}")continueif challenges:print(f"π SUCCESS with {strategy_name}! Converted {len(challenges)} REAL challenges")return challengeselse:print(f"β {strategy_name} - no challenges converted")else:print(f"β {strategy_name} - no challenge data found")print("β All strategies failed - no real MCP data retrieved")return []def calculate_advanced_compatibility_score(self, challenge: Challenge, user_profile: UserProfile, query: str) -> tuple:score = 0.0337 unmodified lines338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425337 unmodified linessort_by: str = None,sort_order: str = None,) -> List[Challenge]:"""FIXED: Guaranteed to return real challenges when MCP works"""print(f"π Fetching REAL challenges (limit: {limit})")print(f"π― Query: '{query}' | Skills: {user_profile.skills}")# Always try to connectconnection_success = await self.initialize_connection()if not connection_success:print("β Could not establish MCP connection")return []# Build simple query that we KNOW works from debugmcp_query = {"perPage": min(limit, 20)}# Add search term if providedif query.strip():mcp_query["search"] = query.strip()# Add status filterif status and status != "":mcp_query["status"] = statusprint(f"π§ MCP Query: {mcp_query}")# Call the MCP tool (we know this works from debug)result = await self.call_tool("query-tc-challenges", mcp_query)if not result:print("β No result from MCP tool call")return []print(f"π Got MCP result with keys: {list(result.keys()) if isinstance(result, dict) else 'Not dict'}")# Extract challenge data (we know it's in structuredContent.data from debug)challenge_data_list = []if isinstance(result, dict):# Primary location: structuredContent.dataif "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.data")# Fallback: direct data fieldelif "data" in result:challenge_data_list = result["data"]print(f"β Found {len(challenge_data_list)} challenges in data field")if not challenge_data_list:print("β No challenge data found in response")return []print(f"π― Processing {len(challenge_data_list)} raw challenges...")# Convert to Challenge objectschallenges = []for i, item in enumerate(challenge_data_list):if isinstance(item, dict):try:challenge = self.convert_topcoder_challenge(item)challenges.append(challenge)# Show details for first challengeif i == 0:print(f"π Sample: {challenge.title} | {challenge.prize} | {challenge.technologies}")except Exception as e:print(f"β οΈ Error converting challenge {i}: {e}")# Don't let one bad challenge break everythingcontinueelse:print(f"β οΈ Unexpected challenge format at index {i}: {type(item)}")print(f"π SUCCESSFULLY converted {len(challenges)} REAL challenges!")# IMPORTANT: Always return challenges if we got any data at allif len(challenges) > 0:return challengeselse:print("β No challenges could be converted from raw data")return []def calculate_advanced_compatibility_score(self, challenge: Challenge, user_profile: UserProfile, query: str) -> tuple:score = 0.0
app.py+68-113