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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
"""

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)
}

@app.list_tools()
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

@app.call_tool()
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)