Spaces:
Sleeping
Sleeping
Download test_failure_analysis/sponge_mcp_server.py from VAH6002/Test_Failure_Analysis_Agent: direct link, hf CLI and curl.
- Browser
- Download file 18.2 kB
-
https://huggingface.co/spaces/VAH6002/Test_Failure_Analysis_Agent/resolve/main/test_failure_analysis/sponge_mcp_server.py
- Command line
-
hf download hf://spaces/VAH6002/Test_Failure_Analysis_Agent/test_failure_analysis/sponge_mcp_server.py
-
curl -L -o sponge_mcp_server.py https://huggingface.co/spaces/VAH6002/Test_Failure_Analysis_Agent/resolve/main/test_failure_analysis/sponge_mcp_server.py
18.2 kB
| """ | |
| Sponge MCP Server for Test Failure Analysis | |
| Provides 10 analysis tools as specified in the proposal | |
| """ | |
| import asyncio | |
| import json | |
| import logging | |
| import os | |
| import random | |
| from datetime import datetime, timedelta | |
| from typing import Dict, List, Any, Optional | |
| import mcp.server.stdio | |
| from dotenv import load_dotenv | |
| from google.adk.tools.function_tool import FunctionTool | |
| from google.adk.tools.mcp_tool.conversion_utils import adk_to_mcp_tool_type | |
| from mcp import types as mcp_types | |
| from mcp.server.lowlevel import NotificationOptions, Server | |
| from mcp.server.models import InitializationOptions | |
| load_dotenv() | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(levelname)s - %(message)s', | |
| handlers=[logging.StreamHandler()] | |
| ) | |
| app = Server("sponge-test-failure-analysis") | |
| # Mock data generators for demonstration | |
| def generate_mock_test_results(target_id: str, runs_count: int) -> List[Dict]: | |
| """Generate mock test results for demonstration""" | |
| results = [] | |
| base_time = datetime.now() - timedelta(days=30) | |
| for i in range(runs_count): | |
| # Simulate flaky behavior - some tests fail randomly | |
| is_flaky = "flaky" in target_id.lower() | |
| failure_rate = 0.4 if is_flaky else 0.1 | |
| status = "FAILED" if random.random() < failure_rate else "PASSED" | |
| results.append({ | |
| "invocation_id": f"inv_{target_id}_{i}", | |
| "target_id": target_id, | |
| "status": status, | |
| "timestamp": (base_time + timedelta(hours=i)).isoformat(), | |
| "duration_ms": random.randint(1000, 10000), | |
| "changelist": f"CL_{98000 + i}", | |
| "build_target": f"//service/{target_id.split(':')[0]}:test" | |
| }) | |
| return results | |
| def generate_mock_logs(invocation_id: str, build_target: str) -> List[str]: | |
| """Generate mock log entries""" | |
| logs = [ | |
| f"[INFO] Starting test execution for {build_target}", | |
| f"[INFO] Initializing test environment", | |
| f"[INFO] Loading test configuration", | |
| f"[DEBUG] Setting up database connections", | |
| f"[INFO] Running test cases", | |
| ] | |
| if "failed" in invocation_id.lower() or random.random() < 0.3: | |
| logs.extend([ | |
| f"[ERROR] Connection timeout to database service", | |
| f"[ERROR] java.sql.SQLException: Connection refused", | |
| f"[ERROR] Test failed: assertion error in line 142", | |
| f"[FATAL] Test execution terminated" | |
| ]) | |
| else: | |
| logs.extend([ | |
| f"[INFO] All test cases passed", | |
| f"[INFO] Cleaning up test environment", | |
| f"[INFO] Test execution completed successfully" | |
| ]) | |
| return logs | |
| # Analysis Tools Implementation | |
| def get_flaky_index(target_id: str, runs_count: int = 50) -> Dict[str, Any]: | |
| """Calculate pass/fail ratios to identify flaky tests""" | |
| results = generate_mock_test_results(target_id, runs_count) | |
| total_runs = len(results) | |
| failed_runs = len([r for r in results if r["status"] == "FAILED"]) | |
| flaky_ratio = failed_runs / total_runs if total_runs > 0 else 0 | |
| # Determine confidence based on sample size and consistency | |
| confidence = "high" if total_runs >= 30 else "medium" if total_runs >= 10 else "low" | |
| # Generate recommendation | |
| if flaky_ratio > 0.3: | |
| recommendation = f"High flakiness detected ({flaky_ratio:.1%}). Consider adding to flaky test list or improving stability." | |
| elif flaky_ratio > 0.1: | |
| recommendation = f"Moderate flakiness ({flaky_ratio:.1%}). Monitor for patterns and consider investigation." | |
| else: | |
| recommendation = f"Low flakiness ({flaky_ratio:.1%}). Test appears stable." | |
| return { | |
| "target_id": target_id, | |
| "flaky_ratio": flaky_ratio, | |
| "confidence": confidence, | |
| "total_runs": total_runs, | |
| "failed_runs": failed_runs, | |
| "recommendation": recommendation | |
| } | |
| def detect_regression_window(target_id: str, lookback_days: int = 7) -> Dict[str, Any]: | |
| """Find exact moments when tests went from green to red""" | |
| results = generate_mock_test_results(target_id, lookback_days * 4) # 4 runs per day | |
| # Find the first failure after a series of passes | |
| regression_point = None | |
| for i in range(1, len(results)): | |
| if results[i-1]["status"] == "PASSED" and results[i]["status"] == "FAILED": | |
| regression_point = results[i] | |
| break | |
| if regression_point: | |
| confidence = "high" | |
| analysis = f"Regression detected at {regression_point['timestamp']} with changelist {regression_point['changelist']}" | |
| else: | |
| confidence = "low" | |
| analysis = "No clear regression window found in the specified timeframe" | |
| return { | |
| "target_id": target_id, | |
| "regression_timestamp": regression_point["timestamp"] if regression_point else None, | |
| "changelist": regression_point["changelist"] if regression_point else None, | |
| "confidence": confidence, | |
| "analysis": analysis | |
| } | |
| def compare_log_diffs(failing_invocation_id: str, passing_invocation_id: str, build_target: str) -> Dict[str, Any]: | |
| """Identify divergence points between passing/failing runs""" | |
| failing_logs = generate_mock_logs(failing_invocation_id, build_target) | |
| passing_logs = generate_mock_logs("passing_test", build_target) | |
| # Find divergence point | |
| divergence_point = None | |
| new_errors = [] | |
| for i, (fail_log, pass_log) in enumerate(zip(failing_logs, passing_logs)): | |
| if fail_log != pass_log: | |
| divergence_point = i | |
| break | |
| # Extract new errors from failing logs | |
| new_errors = [log for log in failing_logs if "ERROR" in log or "FATAL" in log] | |
| analysis = f"Logs diverge at line {divergence_point + 1 if divergence_point else 'unknown'}" | |
| if new_errors: | |
| analysis += f". Found {len(new_errors)} new error(s) in failing run." | |
| return { | |
| "failing_invocation_id": failing_invocation_id, | |
| "passing_invocation_id": passing_invocation_id, | |
| "divergence_point": divergence_point, | |
| "new_errors": new_errors, | |
| "analysis": analysis | |
| } | |
| def locate_error_root(invocation_id: str, build_target: str) -> Dict[str, Any]: | |
| """Jump to first ERROR after last INFO message""" | |
| logs = generate_mock_logs(invocation_id, build_target) | |
| last_info_index = -1 | |
| first_error_index = -1 | |
| for i, log in enumerate(logs): | |
| if "[INFO]" in log: | |
| last_info_index = i | |
| elif "[ERROR]" in log and first_error_index == -1: | |
| first_error_index = i | |
| if first_error_index > last_info_index and first_error_index != -1: | |
| error_line = logs[first_error_index] | |
| context_lines = logs[max(0, first_error_index-2):first_error_index+3] | |
| else: | |
| error_line = "No error found after last INFO message" | |
| context_lines = logs[-5:] if logs else [] | |
| return { | |
| "invocation_id": invocation_id, | |
| "error_line": error_line, | |
| "error_line_number": first_error_index + 1 if first_error_index != -1 else None, | |
| "context_lines": context_lines, | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| def correlate_cross_service_logs(invocation_id: str, service_targets: List[str], time_window: int = 300) -> Dict[str, Any]: | |
| """Correlate logs across services using timestamps""" | |
| timeline = [] | |
| for service in service_targets: | |
| service_logs = generate_mock_logs(invocation_id, service) | |
| for i, log in enumerate(service_logs): | |
| timeline.append({ | |
| "service": service, | |
| "timestamp": (datetime.now() - timedelta(seconds=len(service_logs)-i)).isoformat(), | |
| "message": log, | |
| "severity": "ERROR" if "ERROR" in log else "INFO" | |
| }) | |
| # Sort by timestamp | |
| timeline.sort(key=lambda x: x["timestamp"]) | |
| # Analyze correlations | |
| error_services = [entry["service"] for entry in timeline if entry["severity"] == "ERROR"] | |
| correlation_analysis = f"Found errors in {len(set(error_services))} services: {', '.join(set(error_services))}" if error_services else "No cross-service errors detected" | |
| return { | |
| "invocation_id": invocation_id, | |
| "services": service_targets, | |
| "timeline": timeline, | |
| "correlation_analysis": correlation_analysis | |
| } | |
| def summarize_log_anomalies(invocation_id: str, build_target: str, min_occurrences: int = 2) -> Dict[str, Any]: | |
| """Reduce noise by grouping similar errors""" | |
| logs = generate_mock_logs(invocation_id, build_target) | |
| error_patterns = {} | |
| for log in logs: | |
| if "ERROR" in log or "FATAL" in log: | |
| # Simple pattern extraction - in real implementation would use regex | |
| pattern = log.split(":")[0] if ":" in log else log | |
| error_patterns[pattern] = error_patterns.get(pattern, 0) + 1 | |
| # Filter by minimum occurrences | |
| unique_errors = {pattern: count for pattern, count in error_patterns.items() | |
| if count >= min_occurrences} | |
| patterns = [f"{pattern} (occurred {count} times)" for pattern, count in unique_errors.items()] | |
| return { | |
| "invocation_id": invocation_id, | |
| "unique_errors": list(unique_errors.keys()), | |
| "occurrence_counts": unique_errors, | |
| "patterns": patterns, | |
| "total_error_types": len(unique_errors) | |
| } | |
| def fetch_stack_trace_context(invocation_id: str, build_target: str, context_lines: int = 5) -> Dict[str, Any]: | |
| """Provide code context around stack traces""" | |
| # Mock stack trace | |
| stack_trace = [ | |
| "java.lang.NullPointerException: null", | |
| " at com.example.service.AuthService.validateUser(AuthService.java:142)", | |
| " at com.example.controller.LoginController.login(LoginController.java:67)", | |
| " at com.example.test.LoginTest.testValidLogin(LoginTest.java:23)" | |
| ] | |
| # Mock code context | |
| code_context = { | |
| "AuthService.java:142": [ | |
| "139: public boolean validateUser(String username, String password) {", | |
| "140: User user = userRepository.findByUsername(username);", | |
| "141: if (user == null) {", | |
| "142: return user.getPassword().equals(password); // NPE here!", | |
| "143: }", | |
| "144: return false;", | |
| "145: }" | |
| ] | |
| } | |
| analysis = "Null pointer exception in AuthService.validateUser() - user object is null but code attempts to call getPassword()" | |
| return { | |
| "invocation_id": invocation_id, | |
| "stack_trace": stack_trace, | |
| "code_context": code_context, | |
| "analysis": analysis, | |
| "suggested_fix": "Add null check before accessing user.getPassword()" | |
| } | |
| def inspect_visual_state(invocation_id: str, build_target: str, action_name: str) -> Dict[str, Any]: | |
| """Return screenshots/videos with action context""" | |
| # Mock visual inspection data | |
| screenshots = [ | |
| f"screenshot_before_{action_name}.png", | |
| f"screenshot_after_{action_name}.png" | |
| ] | |
| videos = [f"test_execution_{action_name}.mp4"] | |
| visual_analysis = f"Visual inspection for action '{action_name}' shows UI elements are present but interaction failed" | |
| return { | |
| "invocation_id": invocation_id, | |
| "action_name": action_name, | |
| "screenshots": screenshots, | |
| "videos": videos, | |
| "visual_analysis": visual_analysis, | |
| "ui_elements_found": ["login_button", "username_field", "password_field"], | |
| "ui_elements_missing": [] | |
| } | |
| def compare_visual_baselines(failing_invocation_id: str, baseline_invocation_id: str, build_target: str) -> Dict[str, Any]: | |
| """Compare UI states between runs""" | |
| differences = [ | |
| { | |
| "element": "submit_button", | |
| "baseline": "visible, enabled", | |
| "current": "missing", | |
| "impact": "high" | |
| }, | |
| { | |
| "element": "error_message", | |
| "baseline": "not present", | |
| "current": "visible: 'Connection timeout'", | |
| "impact": "medium" | |
| } | |
| ] | |
| visual_regression_analysis = f"Found {len(differences)} visual differences. Critical: submit button is missing in current run." | |
| return { | |
| "failing_invocation_id": failing_invocation_id, | |
| "baseline_invocation_id": baseline_invocation_id, | |
| "differences": differences, | |
| "visual_regression_analysis": visual_regression_analysis, | |
| "regression_detected": True | |
| } | |
| def analyze_concurrency_drift(target_id: str, days_back: int = 30) -> Dict[str, Any]: | |
| """Detect environment aging through duration trends""" | |
| results = generate_mock_test_results(target_id, days_back) | |
| # Calculate duration trend | |
| durations = [r["duration_ms"] for r in results] | |
| avg_duration = sum(durations) / len(durations) if durations else 0 | |
| # Simple trend analysis - in real implementation would use statistical methods | |
| recent_avg = sum(durations[-7:]) / 7 if len(durations) >= 7 else avg_duration | |
| older_avg = sum(durations[:7]) / 7 if len(durations) >= 7 else avg_duration | |
| drift_percentage = ((recent_avg - older_avg) / older_avg * 100) if older_avg > 0 else 0 | |
| if abs(drift_percentage) > 20: | |
| drift_analysis = f"Significant duration drift detected: {drift_percentage:.1f}% change" | |
| recommendations = ["Consider environment refresh", "Check for resource contention", "Review recent infrastructure changes"] | |
| else: | |
| drift_analysis = f"Minimal duration drift: {drift_percentage:.1f}% change" | |
| recommendations = ["Environment appears stable"] | |
| return { | |
| "target_id": target_id, | |
| "duration_trend": { | |
| "average_duration_ms": avg_duration, | |
| "recent_average_ms": recent_avg, | |
| "older_average_ms": older_avg, | |
| "drift_percentage": drift_percentage | |
| }, | |
| "drift_analysis": drift_analysis, | |
| "recommendations": recommendations | |
| } | |
| # Create ADK Function Tools | |
| ADK_SPONGE_TOOLS = { | |
| "get_flaky_index": FunctionTool(func=get_flaky_index), | |
| "detect_regression_window": FunctionTool(func=detect_regression_window), | |
| "compare_log_diffs": FunctionTool(func=compare_log_diffs), | |
| "locate_error_root": FunctionTool(func=locate_error_root), | |
| "correlate_cross_service_logs": FunctionTool(func=correlate_cross_service_logs), | |
| "summarize_log_anomalies": FunctionTool(func=summarize_log_anomalies), | |
| "fetch_stack_trace_context": FunctionTool(func=fetch_stack_trace_context), | |
| "inspect_visual_state": FunctionTool(func=inspect_visual_state), | |
| "compare_visual_baselines": FunctionTool(func=compare_visual_baselines), | |
| "analyze_concurrency_drift": FunctionTool(func=analyze_concurrency_drift) | |
| } | |
| async def list_mcp_tools() -> List[mcp_types.Tool]: | |
| """MCP handler to list tools this server exposes""" | |
| logging.info("Sponge MCP Server: Received list_tools request") | |
| mcp_tools_list = [] | |
| for tool_name, adk_tool_instance in ADK_SPONGE_TOOLS.items(): | |
| if not adk_tool_instance.name: | |
| adk_tool_instance.name = tool_name | |
| mcp_tool_schema = adk_to_mcp_tool_type(adk_tool_instance) | |
| logging.info(f"Advertising tool: {mcp_tool_schema.name}") | |
| mcp_tools_list.append(mcp_tool_schema) | |
| return mcp_tools_list | |
| async def call_mcp_tool(name: str, arguments: dict) -> List[mcp_types.TextContent]: | |
| """MCP handler to execute a tool call""" | |
| logging.info(f"Sponge MCP Server: Executing tool '{name}' with args: {arguments}") | |
| if name in ADK_SPONGE_TOOLS: | |
| adk_tool_instance = ADK_SPONGE_TOOLS[name] | |
| try: | |
| result = await adk_tool_instance.run_async( | |
| args=arguments, | |
| tool_context=None | |
| ) | |
| logging.info(f"Tool '{name}' executed successfully") | |
| response_text = json.dumps(result, indent=2) | |
| return [mcp_types.TextContent(type="text", text=response_text)] | |
| except Exception as e: | |
| logging.error(f"Error executing tool '{name}': {e}", exc_info=True) | |
| error_payload = { | |
| "success": False, | |
| "message": f"Failed to execute tool '{name}': {str(e)}" | |
| } | |
| return [mcp_types.TextContent(type="text", text=json.dumps(error_payload))] | |
| else: | |
| logging.warning(f"Tool '{name}' not found") | |
| error_payload = { | |
| "success": False, | |
| "message": f"Tool '{name}' not implemented by this server" | |
| } | |
| return [mcp_types.TextContent(type="text", text=json.dumps(error_payload))] | |
| async def run_mcp_stdio_server(): | |
| """Run the MCP server over stdio""" | |
| async with mcp.server.stdio.stdio_server() as (read_stream, write_stream): | |
| logging.info("Sponge MCP Server: Starting...") | |
| await app.run( | |
| read_stream, | |
| write_stream, | |
| InitializationOptions( | |
| server_name=app.name, | |
| server_version="1.0.0", | |
| capabilities=app.get_capabilities( | |
| notification_options=NotificationOptions(), | |
| experimental_capabilities={} | |
| ) | |
| ) | |
| ) | |
| if __name__ == "__main__": | |
| logging.info("Starting Sponge MCP Server...") | |
| try: | |
| asyncio.run(run_mcp_stdio_server()) | |
| except KeyboardInterrupt: | |
| logging.info("Sponge MCP Server stopped by user") | |
| except Exception as e: | |
| logging.critical(f"Sponge MCP Server error: {e}", exc_info=True) |