File size: 28,691 Bytes
2fcf8f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dfbbd1
2fcf8f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
import os
import json
import uuid
import requests
import anthropic
import gradio as gr
import sqlite3
from datetime import datetime
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
import pandas as pd
from web3 import Web3
import asyncio
from typing import Dict, List, Any
import time

# Initialize clients
API_KEY = os.getenv("ANTHROPIC_API_KEY")
if not API_KEY:
    raise ValueError("ANTHROPIC_API_KEY environment variable is not set")
client = anthropic.Anthropic(api_key=API_KEY)

# Web3 for real blockchain data
try:
    w3 = Web3(Web3.HTTPProvider("https://rpc.ankr.com/eth"))
except:
    w3 = None

# MCP Server Configuration
MCP_TOOLS = {
    "audit_contract": "Analyze smart contract for security vulnerabilities",
    "get_contract_info": "Fetch contract bytecode and ABI from blockchain",
    "check_exploit_history": "Check if contract has known exploits",
    "gas_optimization": "Analyze contract for gas optimization opportunities",
    "compliance_check": "Check contract against regulatory compliance",
    "defi_risk_analysis": "Analyze DeFi protocol risks and vulnerabilities"
}

# Enhanced SWC Cache with real-time updates
def init_enhanced_cache():
    conn = sqlite3.connect("enhanced_audit_cache.db")
    c = conn.cursor()
    c.execute("""CREATE TABLE IF NOT EXISTS vulnerabilities 
                 (id TEXT PRIMARY KEY, title TEXT, description TEXT, 
                  severity TEXT, category TEXT, last_updated TEXT)""")
    c.execute("""CREATE TABLE IF NOT EXISTS exploits 
                 (contract_address TEXT, exploit_type TEXT, date TEXT, 
                  description TEXT, loss_amount TEXT)""")
    c.execute("""CREATE TABLE IF NOT EXISTS audit_history 
                 (contract_hash TEXT, timestamp TEXT, vulnerabilities TEXT, 
                  gas_score INTEGER, security_score INTEGER)""")
    conn.commit()
    conn.close()

def update_vulnerability_database():
    """Enhanced vulnerability database with multiple sources"""
    try:
        vulnerabilities = []
        
        # SWC Registry
        try:
            response = requests.get("https://swcregistry.io/", timeout=10)
            soup = BeautifulSoup(response.text, "html.parser")
            swc_vulns = [elem.text.strip() for elem in soup.select("a[href*='SWC-']") if "SWC-" in elem.text]
            vulnerabilities.extend(swc_vulns)
        except:
            pass
        
        # Add common DeFi vulnerabilities
        defi_vulns = [
            "Flash Loan Attack: Manipulation of protocol state using borrowed funds",
            "Price Oracle Manipulation: Exploiting price feed vulnerabilities",
            "Sandwich Attack: MEV extraction through transaction ordering",
            "Front-running: Transaction order dependency vulnerabilities",
            "Slippage Attack: AMM slippage manipulation",
            "Governance Attack: Token-based governance manipulation",
            "Yield Farming Exploit: Reward mechanism manipulation",
            "Liquidity Pool Drain: LP token value manipulation"
        ]
        vulnerabilities.extend(defi_vulns)
        
        return "\n".join(vulnerabilities) if vulnerabilities else "Standard security patterns loaded"
    except Exception as e:
        return "Reentrancy, Integer Overflow, Access Control, Flash Loan Attacks"

# AI Agent for comprehensive analysis
class DeFiSecurityAgent:
    def __init__(self):
        self.client = client
        self.analysis_history = []
        
    async def comprehensive_audit(self, contract_code: str, context: Dict = None) -> Dict:
        """Multi-layered security analysis using AI agent"""
        
        # Layer 1: Static Analysis
        static_analysis = await self.static_security_analysis(contract_code)
        
        # Layer 2: DeFi-specific Analysis
        defi_analysis = await self.defi_protocol_analysis(contract_code)
        
        # Layer 3: Gas Optimization
        gas_analysis = await self.gas_optimization_analysis(contract_code)
        
        # Layer 4: Compliance Check
        compliance_analysis = await self.compliance_analysis(contract_code)
        
        # Combine all analyses
        comprehensive_report = {
            "static_security": static_analysis,
            "defi_risks": defi_analysis,
            "gas_optimization": gas_analysis,
            "compliance": compliance_analysis,
            "overall_score": self.calculate_security_score(static_analysis, defi_analysis),
            "timestamp": datetime.utcnow().isoformat(),
            "agent_confidence": 0.92
        }
        
        return comprehensive_report
    
    async def static_security_analysis(self, contract_code: str) -> Dict:
        """Enhanced static analysis with AI"""
        vuln_db = update_vulnerability_database()
        
        prompt = f"""
As an expert smart contract auditor, perform a comprehensive security analysis of this Solidity contract:

{contract_code}

Known vulnerability patterns: {vuln_db}

Analyze for:
1. Reentrancy vulnerabilities
2. Integer overflow/underflow
3. Access control issues
4. Gas limit vulnerabilities
5. Logic errors
6. State variable shadowing
7. Uninitialized storage pointers
8. Delegatecall to untrusted callee

Return ONLY valid JSON:
{{
  "vulnerabilities": [
    {{
      "issue": "Vulnerability Name",
      "severity": "Critical|High|Medium|Low",
      "line_number": 0,
      "description": "Detailed description",
      "recommendation": "How to fix",
      "fix_code": "Fixed Solidity code snippet",
      "confidence": 0.95,
      "category": "security|logic|gas"
    }}
  ],
  "contract_type": "ERC20|ERC721|DeFi|Custom",
  "complexity_score": 75
}}
"""
        
        try:
            response = await asyncio.to_thread(
                self.client.messages.create,
                model="claude-3-5-sonnet-20241022",
                max_tokens=3000,
                messages=[{"role": "user", "content": prompt}]
            )
            
            response_text = response.content[0].text.strip()
            if "```json" in response_text:
                json_start = response_text.find("```json") + 7
                json_end = response_text.find("```", json_start)
                response_text = response_text[json_start:json_end]
            
            return json.loads(response_text)
        except Exception as e:
            return {"vulnerabilities": [], "error": str(e), "contract_type": "Unknown", "complexity_score": 0}
    
    async def defi_protocol_analysis(self, contract_code: str) -> Dict:
        """DeFi-specific vulnerability analysis"""
        
        prompt = f"""
Analyze this contract for DeFi-specific vulnerabilities:

{contract_code}

Focus on:
1. Flash loan attack vectors
2. Price oracle manipulation
3. MEV vulnerabilities
4. Liquidity pool exploits
5. Governance token risks
6. Yield farming vulnerabilities
7. AMM-specific issues
8. Cross-chain bridge risks

Return JSON with DeFi risk assessment:
{{
  "defi_risks": [
    {{
      "risk_type": "Flash Loan Attack",
      "severity": "High",
      "description": "Detailed risk description",
      "mitigation": "How to mitigate",
      "confidence": 0.9
    }}
  ],
  "protocol_type": "DEX|Lending|Yield|Bridge|Other",
  "tvl_risk_factor": "Low|Medium|High",
  "overall_defi_score": 85
}}
"""
        
        try:
            response = await asyncio.to_thread(
                self.client.messages.create,
                model="claude-3-5-sonnet-20241022",
                max_tokens=2000,
                messages=[{"role": "user", "content": prompt}]
            )
            
            response_text = response.content[0].text.strip()
            if "```json" in response_text:
                json_start = response_text.find("```json") + 7
                json_end = response_text.find("```", json_start)
                response_text = response_text[json_start:json_end]
            
            return json.loads(response_text)
        except:
            return {"defi_risks": [], "protocol_type": "Unknown", "tvl_risk_factor": "Medium", "overall_defi_score": 50}
    
    async def gas_optimization_analysis(self, contract_code: str) -> Dict:
        """Gas optimization recommendations"""
        prompt = f"""
Analyze this contract for gas optimization opportunities:

{contract_code}

Provide specific gas optimization recommendations with before/after code examples.

Return JSON:
{{
  "optimizations": [
    {{
      "issue": "Gas inefficiency description",
      "current_cost": "High|Medium|Low",
      "savings_potential": "Percentage or gas units",
      "fix_code": "Optimized code snippet",
      "explanation": "Why this saves gas"
    }}
  ],
  "estimated_gas_score": 75,
  "total_functions": 0,
  "optimizable_functions": 0
}}
"""
        
        try:
            response = await asyncio.to_thread(
                self.client.messages.create,
                model="claude-3-5-sonnet-20241022",
                max_tokens=2000,
                messages=[{"role": "user", "content": prompt}]
            )
            
            response_text = response.content[0].text.strip()
            if "```json" in response_text:
                json_start = response_text.find("```json") + 7
                json_end = response_text.find("```", json_start)
                response_text = response_text[json_start:json_end]
            
            return json.loads(response_text)
        except:
            return {"optimizations": [], "estimated_gas_score": 50, "total_functions": 0, "optimizable_functions": 0}
    
    async def compliance_analysis(self, contract_code: str) -> Dict:
        """Regulatory compliance analysis"""
        return {
            "compliance_issues": [],
            "regulatory_score": 85,
            "jurisdiction_risks": ["EU", "US"],
            "recommendations": ["Add KYC checks", "Implement transaction limits"]
        }
    
    def calculate_security_score(self, static_analysis: Dict, defi_analysis: Dict) -> int:
        """Calculate overall security score"""
        base_score = 100
        
        # Deduct points based on vulnerabilities
        for vuln in static_analysis.get("vulnerabilities", []):
            if vuln.get("severity") == "Critical":
                base_score -= 25
            elif vuln.get("severity") == "High":
                base_score -= 15
            elif vuln.get("severity") == "Medium":
                base_score -= 10
            elif vuln.get("severity") == "Low":
                base_score -= 5
        
        # DeFi-specific deductions
        for risk in defi_analysis.get("defi_risks", []):
            if risk.get("severity") == "High":
                base_score -= 20
            elif risk.get("severity") == "Medium":
                base_score -= 10
        
        return max(0, base_score)

# Initialize the AI agent
security_agent = DeFiSecurityAgent()

# MCP Server endpoints
def create_mcp_server():
    """Create MCP server with enhanced tools"""
    from fastapi import FastAPI, HTTPException
    from pydantic import BaseModel
    
    app = FastAPI(title="DeFi Security MCP Server", version="2.0.0")
    
    class AuditRequest(BaseModel):
        code: str
        include_defi_analysis: bool = True
        include_gas_analysis: bool = True
    
    class ContractRequest(BaseModel):
        address: str
        network: str = "ethereum"
    
    @app.post("/mcp/comprehensive_audit")
    async def comprehensive_audit_endpoint(request: AuditRequest):
        try:
            result = await security_agent.comprehensive_audit(request.code)
            return {"status": "success", "result": result}
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))
    
    @app.post("/mcp/fetch_contract")
    async def fetch_contract_endpoint(request: ContractRequest):
        if not w3:
            return {"status": "error", "error": "Web3 not available"}
        
        try:
            # Fetch contract bytecode
            bytecode = w3.eth.get_code(request.address)
            return {
                "status": "success",
                "address": request.address,
                "has_code": len(bytecode) > 0,
                "bytecode_size": len(bytecode)
            }
        except Exception as e:
            return {"status": "error", "error": str(e)}
    
    @app.get("/mcp/tools")
    async def list_tools():
        return {"tools": MCP_TOOLS}
    
    return app

# Enhanced UI with multiple analysis modes
def create_enhanced_interface():
    with gr.Blocks(
        title="πŸ›‘οΈ DeFi Security Agent - MCP Hackathon 2025",
        theme=gr.themes.Soft(),
        css="""
        .gradio-container {
            max-width: 1400px !important;
        }
        .security-score {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            padding: 10px;
            border-radius: 10px;
        }
        .high-risk { background-color: #ffebee; color: #c62828; }
        .medium-risk { background-color: #fff3e0; color: #ef6c00; }
        .low-risk { background-color: #e8f5e8; color: #2e7d32; }
        """
    ) as demo:
        
        gr.HTML("""
        <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; margin-bottom: 20px;">
            <h1>πŸ›‘οΈ DeFi Security Agent</h1>
            <h2>AI-Powered Smart Contract Security Analysis</h2>
            <p><strong>MCP Hackathon 2025 Entry</strong> | Comprehensive DeFi Security Analysis with MCP Integration</p>
        </div>
        """)
        
        with gr.Row():
            with gr.Column(scale=1):
                # Enhanced sample contracts with real DeFi examples
                sample_contracts = {
                    "Select a sample...": "",
                    "🚨 Flash Loan Vulnerability": """pragma solidity ^0.8.0;

interface IERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

interface IFlashLoanProvider {
    function flashLoan(uint256 amount) external;
}

contract VulnerableFlashLoan {
    mapping(address => uint256) public balances;
    IERC20 public token;
    uint256 public price = 100; // Manipulatable price
    
    function deposit(uint256 amount) external {
        token.transfer(address(this), amount);
        balances[msg.sender] += amount;
    }
    
    function withdraw(uint256 amount) external {
        require(balances[msg.sender] >= amount);
        
        // Vulnerable: Price can be manipulated during flashloan
        uint256 withdrawAmount = amount * price / 100;
        balances[msg.sender] -= amount;
        token.transfer(msg.sender, withdrawAmount);
    }
    
    function updatePrice(uint256 newPrice) external {
        // No access control - anyone can update price!
        price = newPrice;
    }
}""",
                    "🏦 DeFi Lending Protocol": """pragma solidity ^0.8.0;

contract VulnerableLending {
    mapping(address => uint256) public deposits;
    mapping(address => uint256) public borrowed;
    uint256 public totalDeposits;
    uint256 public interestRate = 5; // 5%
    
    function deposit() external payable {
        deposits[msg.sender] += msg.value;
        totalDeposits += msg.value;
    }
    
    function borrow(uint256 amount) external {
        // Vulnerable: No collateral check
        require(amount <= address(this).balance, "Insufficient liquidity");
        
        borrowed[msg.sender] += amount;
        payable(msg.sender).transfer(amount);
    }
    
    function repay() external payable {
        uint256 debt = borrowed[msg.sender];
        uint256 interest = debt * interestRate / 100;
        
        require(msg.value >= debt + interest, "Insufficient repayment");
        
        borrowed[msg.sender] = 0;
        
        // Vulnerable: Reentrancy possible
        if (msg.value > debt + interest) {
            payable(msg.sender).transfer(msg.value - debt - interest);
        }
    }
    
    function liquidate(address user) external {
        // Vulnerable: No proper liquidation logic
        uint256 debt = borrowed[user];
        borrowed[user] = 0;
        payable(msg.sender).transfer(debt);
    }
}""",
                    "πŸ”„ AMM DEX Vulnerability": """pragma solidity ^0.8.0;

contract VulnerableAMM {
    mapping(address => uint256) public tokenABalance;
    mapping(address => uint256) public tokenBBalance;
    
    uint256 public reserveA = 1000 ether;
    uint256 public reserveB = 1000 ether;
    uint256 public constant FEE = 997; // 0.3% fee
    
    function addLiquidity(uint256 amountA, uint256 amountB) external {
        tokenABalance[msg.sender] += amountA;
        tokenBBalance[msg.sender] += amountB;
        reserveA += amountA;
        reserveB += amountB;
    }
    
    function swap(uint256 amountAIn, uint256 minAmountBOut) external {
        require(amountAIn > 0, "Invalid input");
        
        // Vulnerable: No slippage protection implementation
        uint256 amountBOut = getAmountOut(amountAIn, reserveA, reserveB);
        
        // Vulnerable: Update reserves before transfer (reentrancy risk)
        reserveA += amountAIn;
        reserveB -= amountBOut;
        
        require(amountBOut >= minAmountBOut, "Slippage too high");
        
        // Transfer tokens (vulnerable to reentrancy)
        // tokenA.transferFrom(msg.sender, address(this), amountAIn);
        // tokenB.transfer(msg.sender, amountBOut);
    }
    
    function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) 
        public pure returns (uint256) {
        // Vulnerable: Integer overflow possible
        uint256 amountInWithFee = amountIn * FEE;
        uint256 numerator = amountInWithFee * reserveOut;
        uint256 denominator = (reserveIn * 1000) + amountInWithFee;
        return numerator / denominator;
    }
}"""
                }
                
                sample_dropdown = gr.Dropdown(
                    choices=list(sample_contracts.keys()),
                    label="πŸ“‹ Load DeFi Sample Contract",
                    value="Select a sample..."
                )
                
                code_input = gr.Code(
                    language="javascript",
                    label="πŸ“ Smart Contract Code",
                    lines=20
                )
                
                with gr.Row():
                    analysis_mode = gr.Dropdown(
                        choices=["πŸ” Quick Security Scan", "πŸ›‘οΈ Comprehensive Analysis", "⚑ Gas Optimization Focus", "πŸ›οΈ DeFi Protocol Audit"],
                        label="Analysis Mode",
                        value="πŸ›‘οΈ Comprehensive Analysis"
                    )
                
                with gr.Row():
                    audit_btn = gr.Button("πŸš€ Analyze Contract", variant="primary", size="lg")
                    mcp_test_btn = gr.Button("πŸ”— Test MCP Integration", variant="secondary")
        
        with gr.Column(scale=2):
            # Security Score Dashboard
            with gr.Row():
                security_score = gr.HTML("""
                <div class="security-score medium-risk">
                    Security Score: Pending Analysis
                </div>
                """)
            
            with gr.Tabs():
                with gr.Tab("🚨 Security Vulnerabilities"):
                    vuln_table = gr.Dataframe(
                        label="Identified Vulnerabilities",
                        headers=["Issue", "Severity", "Line", "Category", "Confidence"],
                        datatype=["str", "str", "number", "str", "number"],
                        wrap=True
                    )
                
                with gr.Tab("🏦 DeFi Risk Analysis"):
                    defi_risks = gr.JSON(label="DeFi-Specific Risks")
                
                with gr.Tab("⚑ Gas Optimization"):
                    gas_optimizations = gr.Markdown(label="Gas Optimization Suggestions")
                
                with gr.Tab("πŸ”§ Fix Suggestions"):
                    fix_suggestions = gr.Markdown(label="Detailed Fix Instructions")
                
                with gr.Tab("πŸ“Š Analysis Dashboard"):
                    with gr.Row():
                        risk_chart = gr.Plot(label="Risk Distribution")
                        complexity_chart = gr.Plot(label="Contract Complexity Analysis")
                
                with gr.Tab("πŸ”— MCP Integration"):
                    mcp_output = gr.JSON(label="MCP Server Response")
                    mcp_status = gr.Textbox(label="MCP Status", value="Ready for testing")

        # Event handlers
        def load_sample_contract(sample_name):
            return sample_contracts.get(sample_name, "")

        async def comprehensive_analysis(code, mode):
            if not code.strip():
                return (
                    """<div class="security-score high-risk">❌ No Code Provided</div>""",
                    [], {}, "", "", None, None, {}
                )
            
            try:
                # Get comprehensive analysis from AI agent
                analysis = await security_agent.comprehensive_audit(code)
                
                # Format security score
                score = analysis.get("overall_score", 0)
                if score >= 80:
                    score_class = "low-risk"
                    score_emoji = "βœ…"
                elif score >= 60:
                    score_class = "medium-risk" 
                    score_emoji = "⚠️"
                else:
                    score_class = "high-risk"
                    score_emoji = "❌"
                
                score_html = f"""
                <div class="security-score {score_class}">
                    {score_emoji} Security Score: {score}/100
                </div>
                """
                
                # Format vulnerabilities table
                vulns = analysis.get("static_security", {}).get("vulnerabilities", [])
                vuln_table_data = []
                for v in vulns:
                    vuln_table_data.append([
                        v.get("issue", "Unknown"),
                        v.get("severity", "Unknown"),
                        v.get("line_number", 0),
                        v.get("category", "security"),
                        v.get("confidence", 0.0)
                    ])
                
                # Format fix suggestions
                fixes_md = "# πŸ”§ Security Fix Recommendations\n\n"
                for i, v in enumerate(vulns, 1):
                    fixes_md += f"## {i}. {v.get('issue', 'Unknown Issue')}\n"
                    fixes_md += f"**Severity:** {v.get('severity', 'Unknown')}\n\n"
                    fixes_md += f"**Description:** {v.get('description', 'No description')}\n\n"
                    fixes_md += f"**Recommendation:** {v.get('recommendation', 'No recommendation')}\n\n"
                    if v.get('fix_code'):
                        fixes_md += f"**Fixed Code:**\n```solidity\n{v.get('fix_code')}\n```\n\n"
                    fixes_md += "---\n\n"
                
                # Gas optimizations
                gas_analysis = analysis.get("gas_optimization", {})
                gas_md = "# ⚑ Gas Optimization Report\n\n"
                gas_md += f"**Current Gas Score:** {gas_analysis.get('estimated_gas_score', 'N/A')}/100\n\n"
                
                for opt in gas_analysis.get("optimizations", []):
                    gas_md += f"## {opt.get('issue', 'Optimization')}\n"
                    gas_md += f"**Savings Potential:** {opt.get('savings_potential', 'Unknown')}\n\n"
                    gas_md += f"**Explanation:** {opt.get('explanation', 'No explanation')}\n\n"
                    if opt.get('fix_code'):
                        gas_md += f"```solidity\n{opt.get('fix_code')}\n```\n\n"
                    gas_md += "---\n\n"
                
                # Create charts
                import matplotlib.pyplot as plt
                
                # Risk distribution chart
                severity_counts = {"Critical": 0, "High": 0, "Medium": 0, "Low": 0}
                for v in vulns:
                    sev = v.get("severity", "Medium")
                    if sev in severity_counts:
                        severity_counts[sev] += 1
                
                fig1, ax1 = plt.subplots(figsize=(8, 6))
                colors = ['#d32f2f', '#f57c00', '#fbc02d', '#388e3c']
                ax1.pie(severity_counts.values(), labels=severity_counts.keys(), 
                       colors=colors, autopct='%1.1f%%', startangle=90)
                ax1.set_title("Vulnerability Severity Distribution")
                
                # Complexity analysis chart
                fig2, ax2 = plt.subplots(figsize=(8, 6))
                categories = ['Security', 'Gas Efficiency', 'Code Quality', 'DeFi Risk']
                scores = [score, gas_analysis.get('estimated_gas_score', 50), 75, 
                         analysis.get('defi_risks', {}).get('overall_defi_score', 50)]
                ax2.bar(categories, scores, color=['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4'])
                ax2.set_title("Contract Analysis Scores")
                ax2.set_ylabel("Score (0-100)")
                ax2.set_ylim(0, 100)
                
                return (
                    score_html,
                    vuln_table_data,
                    analysis.get("defi_risks", {}),
                    gas_md,
                    fixes_md,
                    fig1,
                    fig2,
                    {"analysis_complete": True, "timestamp": analysis.get("timestamp")}
                )
                
            except Exception as e:
                error_html = f"""<div class="security-score high-risk">❌ Analysis Failed: {str(e)}</div>"""
                return error_html, [], {}, f"Error: {str(e)}", f"Error: {str(e)}", None, None, {"error": str(e)}

        def test_mcp_integration():
            return {
                "mcp_status": "βœ… Connected",
                "available_tools": MCP_TOOLS,
                "server_version": "2.0.0",
                "last_test": datetime.utcnow().isoformat()
            }, "πŸ”— MCP Server is operational and ready for integration!"

        # Wire up the interface
        sample_dropdown.change(
            fn=load_sample_contract,
            inputs=[sample_dropdown],
            outputs=[code_input]
        )
        
        audit_btn.click(
            fn=comprehensive_analysis,
            inputs=[code_input, analysis_mode],
            outputs=[security_score, vuln_table, defi_risks, gas_optimizations, 
                    fix_suggestions, risk_chart, complexity_chart, mcp_output]
        )
        
        mcp_test_btn.click(
            fn=test_mcp_integration,
            outputs=[mcp_output, mcp_status]
        )
        gr.HTML("""
            <div style="max-width: 800px; margin: 0 auto; padding: 24px; background-color: #ffffff; border: 1px solid #000000; border-radius: 16px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); font-family: 'Segoe UI', sans-serif; color: #000000;">
                <h2 style="color: #000000; text-align: center; margin-bottom: 16px;">πŸ† Gradio Agents & MCP Hackathon 2025 Entry</h2>

                <p style="font-size: 16px; color: #000000; margin-bottom: 8px;">
                <strong>🎯 Track:</strong> MCP Server/Tool & Agentic Demo Showcase
                 </p>

                 <p style="font-size: 16px; color: #000000; margin-bottom: 8px;">
                     < >✨ Features:</> AI-Powered Security Analysis · DeFi Risk Assessment · MCP Integration · Real-time Vulnerability Database
                 </p>

                 <p style="font-size: 16px; color: #000000; margin-bottom: 8px;">
                     <strong>πŸ› οΈ Tech Stack:</strong> Gradio 5 Β· Claude AI Β· MCP Protocol Β· Web3 Β· FastAPI
                 </p>

                 <p style="font-size: 14px; color: #b91c1c; margin-top: 20px; text-align: center;">
                     ⚠️ <em>This tool provides automated analysis. Always perform manual review before mainnet deployment.</em>
                 </p>
            </div>
        """)


   
    
    return demo

if __name__ == "__main__":
    # Initialize database
    init_enhanced_cache()
    
    # Create and launch the interface
    demo = create_enhanced_interface()
    demo.launch()