Upload app.py
Browse files337 unmodified lines338339340341341342343344343344346345346347348349349350351352353352353354355356355356358359357358361362363364365366367368369370371372373374375376377378379380381382383384385386387388359360361362390391392393394395396397398399400401402403404405406407363364409410411412413414415416417418419420421422423424365366367368369370371372373374375376377378379380381382383384426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462385386387388389390391392393394395396397398399400401402403404405406407408409410411412464413414415416417418419420466467421422423424425337 unmodified lines sort_by: str = None,
sort_order: str = None,
) -> List[Challenge]:
"""FIXED: Debug version - shows exactly what MCP is doing"""
"""FIXED: Guaranteed to return real challenges when MCP works"""
# Always try to connect
print(f"π Attempting to fetch REAL challenges (limit: {limit})")
print(f"π Fetching REAL challenges (limit: {limit})")
print(f"π― Query: '{query}' | Skills: {user_profile.skills}")
connection_success = await self.initialize_connection()
# Always try to connect
connection_success = await self.initialize_connection()
if not connection_success:
print("β Could not establish MCP connection, using fallback")
print("β Could not establish MCP connection")
return []
# Try multiple query strategies to see what works
query_strategies = []
# Build simple query that we KNOW works from debug
mcp_query = {"perPage": min(limit, 20)}
# Strategy 1: Simple query with minimal parameters
simple_query = {"perPage": min(limit, 20)}
# Add search term if provided
if query.strip():
simple_query["search"] = query.strip()
query_strategies.append(("Simple Search", simple_query))
mcp_query["search"] = query.strip()
# Strategy 2: Skills-based query
skill_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 skills
query_strategies.append(("Skills Query", skills_query))
# Strategy 3: Your comprehensive query
comprehensive_query = {"perPage": min(limit, 20)}
if status:
comprehensive_query["status"] = status
if query.strip():
comprehensive_query["search"] = query.strip()
if sort_by:
comprehensive_query["sortBy"] = sort_by
if sort_order:
comprehensive_query["sortOrder"] = sort_order
query_strategies.append(("Comprehensive", comprehensive_query))
# Try each strategy until one works
for strategy_name, mcp_query in query_strategies:
print(f"\nπ§ͺ Trying {strategy_name} strategy:")
print(f"π§ Query parameters: {mcp_query}")
# Call the MCP tool
result = await self.call_tool("query-tc-challenges", mcp_query)
# Add status filter
if status and status != "":
mcp_query["status"] = status
if not result:
print(f"β {strategy_name} failed - no result")
continue
print(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 debugging
for 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)}")
print(f"π§ MCP Query: {mcp_query}")
# Try to parse the response
challenge_data_list = []
# Check all possible data locations
data_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 = data
print(f"β
Found {len(challenge_data_list)} challenges in {source_name}")
break
# 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.data
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.data")
# Special handling for content field
if 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 challenges
challenges = []
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 details
print(f"π First challenge: {challenge.title} | {challenge.prize} | {challenge.technologies}")
except Exception as e:
print(f"β Error converting challenge {i}: {e}")
continue
if challenges:
print(f"π SUCCESS with {strategy_name}! Converted {len(challenges)} REAL challenges")
return challenges
else:
print(f"β {strategy_name} - no challenges converted")
# Fallback: direct data field
elif "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 objects
challenges = []
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 challenge
if 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 everything
continue
else:
print(f"β {strategy_name} - no challenge data found")
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 all
if len(challenges) > 0:
return challenges
else:
print("β All strategies failed - no real MCP data retrieved")
return []
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.0app.py+68-113