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
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
# /////////////////////////////////////////////
# Xyizko - MCH Hackathon 2025 Skeleton
# x.com/xyizko
# /////////////////////////////////////////////

# --- Imports Section ---

import datetime

import gradio as gr

# Importing Smolagents with error handling
try:
    from smolagents import CodeAgent, HfApiModel
    SMOLAGENTS_AVAILABLE = True
except ImportError:
    SMOLAGENTS_AVAILABLE = False
    print("⚠️ SmolAgents not available, using direct HF API")

# Fallback to HuggingFace Hub
from huggingface_hub import InferenceClient

# --- Demo UI Component Functions ---

# App Introduction Function


def demo_vid():
    gr.Markdown("# Video Demo")
    gr.HTML("""
            <iframe width="560" height="315" 
                src="https://www.youtube.com/embed/Ttj49yTI46w?si=1FZeoSNivLxozQy0" 
                title="YouTube video player" 
                frameborder="0" 
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" 
                referrerpolicy="strict-origin-when-cross-origin" 
                allowfullscreen>
            </iframe>
        """)


def app_intro():
    intro_text = """
    # πŸ€– Xyizko - MCP Hackathon 2025 Submission - Web3-Security-Auditor
    1. This is a submission for the Gradio MCP Hackathon Project.
    2. This submision is for **Track 1 (MCP Tool / Server)** and **Track3 (Agentic Demo Showcase)**
    3. https://huggingface.co/Agents-MCP-Hackathon - Official Hackathon Announcement.
    4. Project is both Agentic and a MCP Server uisng HugginFace an Gradio Libraries.


    # βš™οΈ App Description
    **AI-Powered Smart Contract Security Analysis Platform**
    1. This tool leverages AI to analyze smart contracts for vulnerabilities, 
    anti-patterns, and security issues. Upload your contract code and get comprehensive 
    security analysis powered by Hugging Face models.
    2. https://github.com/RareSkills/Buggy-ERC-20 - Test Buggy ERC-20 Contracts Source
    """

    ai_system_info = f"""
    ## πŸ€– AI Analysis System
    **SmolAgents Status**: {'βœ… Available' if SMOLAGENTS_AVAILABLE else '❌ Not Available - Using Direct HF API'}
    
    ### What Our AI System Does:
    
    #### 🧠 **Intelligent Code Analysis**
    {'- SmolAgents CodeAgent for specialized code analysis' if SMOLAGENTS_AVAILABLE else '- Direct HuggingFace Inference API calls'}
    - Multi-step security vulnerability detection
    - Risk assessment and scoring
    - Code quality evaluation
    - Actionable security recommendations
    
    #### 🎯 **Analysis Capabilities**
    1. **Security Vulnerability Detection**: Identifies reentrancy, overflow, access control issues
    2. **Risk Assessment**: Intelligent risk scoring and prioritization
    3. **Code Quality Analysis**: Best practices and optimization evaluation
    4. **Pattern Recognition**: Detects anti-patterns and security smells
    5. **Actionable Recommendations**: Generates specific improvement suggestions
    
    #### πŸš€ **System Features**
    - **Reliable**: Robust error handling with fallback mechanisms
    - **Flexible**: Works with various HuggingFace models
    - **Comprehensive**: Multi-dimensional analysis approach
    - **Practical**: Provides actionable, implementable recommendations
    """

    # NEW MCP Integration Info
    mcp_integration_info = """
    ## πŸ”Œ Model Context Protocol (MCP) Integration
    
    **πŸš€ This app is now MCP-enabled!** AI assistants like Claude can use it as a specialized security tool.
    
    ### πŸ› οΈ Available MCP Tool:
    
    #### πŸ›‘οΈ `analyze_smart_contract`
    - **Purpose**: Complete smart contract security analysis
    - **Features**: Security vulnerabilities + Risk scoring + Code quality assessment
    - **AI-Powered**: Uses HuggingFace models with intelligent rule-based fallback
    - **Input**: Just paste your Solidity contract code
    - **Output**: Comprehensive security report with actionable recommendations
    - **Reliability**: Always works - even without API tokens (fallback analysis)
    
    ### πŸ€– How AI Assistants Use This:
    
    **Claude Desktop Integration:**
    ```json
    {
      "mcpServers": {
        "smart-contract-analyzer": {
          "command": "npx",
          "args": ["-y", "@modelcontextprotocol/server-gradio", "YOUR_HF_SPACE_URL"]
        }
      }
    }
    ```
    
    **Example AI Conversation:**
    ```
    User: "Analyze this smart contract for security issues: [paste contract]"
    
    Claude: [Uses analyze_smart_contract tool] 
    "I've analyzed your contract and found 3 critical vulnerabilities..."
    ```
    
    ### ✨ Key Benefits:
    - **One-Click Security**: AI assistants can instantly analyze any contract
    - **Always Available**: Hosted on reliable HuggingFace infrastructure  
    - **No Setup Required**: AI assistants connect directly to your public space
    - **Professional Reports**: Detailed analysis with specific remediation steps
    """

    part3 = """
    ## Development Progress 
    > Changelog - Fri Jun  6 08:14:02 PM UTC 2025
    1. βœ… Implement robust AI analysis system
    2. βœ… SmolAgents integration with proper error handling
    3. βœ… Direct HF API fallback for maximum compatibility
    4. βœ… Enhanced analysis with multiple approaches
    5. βœ… Comprehensive security assessment capabilities
    6. βœ… **NEW: Model Context Protocol (MCP) Integration**
    7. βœ… **NEW: Single powerful MCP tool for AI assistants**
    8. βœ… **NEW: Lightweight deployment (no transformers/torch dependencies)**
    9. βœ… **NEW: Proper Gradio MCP server setup with mcp_server=True**

    ### About Author
    1. X - https://x.com/xyizko 
    2. Project Acknowledgements - https://x.com/Gradio/status/1930951866935910753
    """

    gr.Markdown(intro_text)
    gr.Markdown(ai_system_info)
    gr.Markdown(mcp_integration_info)
    gr.Markdown(
        value="""  
        ```mermaid  
        flowchart LR
            A[Smart Contract Code] -->|Upload/MCP| B{AI Analysis System}
            B -->|SmolAgents Available| C[CodeAgent Analysis]
            B -->|Fallback| D[Direct HF API]
            C --> E[Multi-Step Analysis]
            D --> E
            E --> F[Security Assessment]
            E --> G[Risk Scoring]
            E --> H[Quality Review]
            F --> I[Comprehensive Report]
            G --> I
            H --> I
            I --> J[Gradio UI Output]
            I --> K[MCP Tool Response]
            K --> L[AI Assistant Integration]
            J --> M[Downloadable Analysis]
        ```  
        """)
    gr.Markdown(part3)


# --- Smart Contract Agent ---


def create_smart_contract_analyzer(hf_token, model_name):
    """Create AI analyzer using SmolAgents or direct HF API"""
    if SMOLAGENTS_AVAILABLE:
        try:
            model = HfApiModel(model_id=model_name, token=hf_token)
            agent = CodeAgent(tools=[], model=model)
            return {"type": "smolagent", "instance": agent, "model": model_name}
        except Exception as e:
            print(f"SmolAgents creation failed: {e}")

    try:
        client = InferenceClient(token=hf_token)
        test_response = client.text_generation(
            prompt="Test prompt",
            model=model_name,
            max_new_tokens=5
        )
        return {"type": "direct_api", "instance": client, "model": model_name}
    except Exception as e:
        raise Exception(f"Failed to create AI analyzer: {str(e)}")


def run_ai_analysis(analyzer, contract_code, analysis_type):
    """Run AI analysis using available method"""
    prompts = {
        "security": f"""Analyze this Solidity smart contract for security vulnerabilities:

```solidity
{contract_code[:3000]}
```

Identify:
1. Security vulnerabilities (reentrancy, overflow, access control)
2. Risk level for each issue (Critical/High/Medium/Low)
3. Specific remediation steps

Be concise and practical.""",

        "risk": f"""Assess the risk level of this smart contract (scale 1-10):

```solidity
{contract_code[:3000]}
```

Provide:
1. Overall risk score (1-10)
2. Main risk factors
3. Top 3 recommendations

Be specific and actionable.""",

        "quality": f"""Review the code quality of this smart contract:

```solidity
{contract_code[:3000]}
```

Evaluate:
1. Solidity best practices
2. Gas optimization opportunities
3. Code organization

Provide specific improvement suggestions."""
    }

    prompt = prompts.get(analysis_type, prompts["security"])

    try:
        if analyzer["type"] == "smolagent":
            result = analyzer["instance"].run(prompt)
            return str(result)
        else:
            response = analyzer["instance"].text_generation(
                prompt=prompt,
                model=analyzer["model"],
                max_new_tokens=600,
                temperature=0.5,
                do_sample=True
            )

            if isinstance(response, str):
                return response.strip()
            elif hasattr(response, 'generated_text'):
                return response.generated_text.strip()
            else:
                return str(response)

    except Exception as e:
        error_msg = str(e).lower()
        if "not found" in error_msg or "404" in error_msg:
            return f"❌ Model '{analyzer.get('model', 'unknown')}' not found. Try: microsoft/DialoGPT-medium"
        elif "unauthorized" in error_msg or "403" in error_msg:
            return "❌ Invalid API token or insufficient permissions"
        elif "rate limit" in error_msg:
            return "❌ Rate limit exceeded. Please wait and try again"
        else:
            return f"❌ Analysis failed: {str(e)}"


def enhanced_fallback_analysis(content, analysis_type):
    """Comprehensive fallback analysis when AI fails"""
    lines = content.splitlines()
    functions = content.count('function')

    if analysis_type == "security":
        vulnerabilities = []
        risk_score = 0

        if 'call.value' in content or '.call(' in content:
            vulnerabilities.append(
                "πŸ”΄ **CRITICAL**: Potential reentrancy vulnerability (call.value/.call usage)")
            risk_score += 4

        if 'tx.origin' in content:
            vulnerabilities.append(
                "🟑 **MEDIUM**: Authentication bypass risk (tx.origin usage)")
            risk_score += 2

        if 'block.timestamp' in content or 'now' in content:
            vulnerabilities.append("🟑 **MEDIUM**: Timestamp manipulation risk")
            risk_score += 1

        if not any(word in content.lower() for word in ['require', 'assert', 'revert']):
            vulnerabilities.append("🟠 **HIGH**: Missing input validation")
            risk_score += 3

        if 'selfdestruct' in content:
            vulnerabilities.append(
                "πŸ”΄ **CRITICAL**: Contract can be destroyed (selfdestruct)")
            risk_score += 4

        if 'delegatecall' in content:
            vulnerabilities.append("🟠 **HIGH**: Dangerous delegate call usage")
            risk_score += 3

        if functions > 20:
            vulnerabilities.append(
                "🟑 **MEDIUM**: High complexity (many functions)")
            risk_score += 1

        return f"""**Security Analysis Results:**

**Vulnerabilities Found:** {len(vulnerabilities)}
**Risk Score:** {min(risk_score, 10)}/10

{chr(10).join(vulnerabilities) if vulnerabilities else "βœ… No major vulnerabilities detected in static analysis"}

**Recommendations:**
- Implement reentrancy guards for external calls
- Use msg.sender instead of tx.origin
- Add comprehensive input validation
- Consider formal verification for critical functions"""

    elif analysis_type == "risk":
        risk_factors = []
        score = 0

        if 'call.value' in content:
            score += 3
            risk_factors.append("External call risks")
        if len(lines) > 500:
            score += 1
            risk_factors.append("Large codebase")
        if functions > 15:
            score += 1
            risk_factors.append("High complexity")
        if 'owner' in content.lower():
            score += 1
            risk_factors.append("Centralized control")
        if content.count('mapping') > 5:
            score += 1
            risk_factors.append("Complex state")

        risk_level = "Critical" if score >= 6 else "High" if score >= 4 else "Medium" if score >= 2 else "Low"

        return f"""**Risk Assessment:**

**Overall Risk Score:** {score}/10
**Risk Level:** {risk_level}

**Risk Factors:**
{chr(10).join([f"- {factor}" for factor in risk_factors]) if risk_factors else "- Minimal risk factors identified"}

**Priority Actions:**
1. {"Immediate security review required" if score >= 4 else "Standard review recommended"}
2. {"Implement emergency pause mechanism" if score >= 6 else "Add comprehensive testing"}
3. {"Consider professional audit" if score >= 3 else "Document all functions"}"""

    elif analysis_type == "quality":
        quality_issues = []
        score = 100

        if content.count('pragma') == 0:
            quality_issues.append("❌ Missing pragma statement (-10 points)")
            score -= 10

        if content.count('//') < functions / 2:
            quality_issues.append("⚠️ Insufficient documentation (-15 points)")
            score -= 15

        if len(lines) > 1000:
            quality_issues.append(
                "⚠️ Contract too large, consider splitting (-10 points)")
            score -= 10

        if 'TODO' in content or 'FIXME' in content:
            quality_issues.append(
                "⚠️ Unfinished code markers found (-5 points)")
            score -= 5

        if not any(modifier in content for modifier in ['public', 'private', 'internal', 'external']):
            quality_issues.append(
                "❌ Missing function visibility specifiers (-20 points)")
            score -= 20

        return f"""**Code Quality Assessment:**

**Quality Score:** {max(score, 0)}/100

**Issues Found:**
{chr(10).join(quality_issues) if quality_issues else "βœ… No major quality issues detected"}

**Improvement Suggestions:**
- Add comprehensive NatSpec documentation
- Implement consistent naming conventions
- Use latest Solidity version with appropriate pragma
- Add function visibility specifiers
- Consider gas optimization patterns"""

# --- MCP Tool Function ---


def analyze_smart_contract(contract_code: str, hf_token: str = "", hf_model: str = "microsoft/DialoGPT-medium"):
    """
    MCP Tool: Comprehensive smart contract security analysis

    This function will be automatically exposed as an MCP tool when mcp_server=True

    Args:
        contract_code: Solidity smart contract source code
        hf_token: Optional HuggingFace API token for AI analysis
        hf_model: HuggingFace model name (default: microsoft/DialoGPT-medium)

    Returns:
        Complete security analysis report with vulnerabilities, risk assessment, and recommendations
    """
    try:
        # Initialize analyzer if token provided
        analyzer = None
        analysis_method = "Enhanced Rule-Based Fallback"

        if hf_token.strip():
            try:
                analyzer = create_smart_contract_analyzer(hf_token, hf_model)
                analysis_method = f"AI-Powered ({analyzer['type']})"
            except Exception as e:
                # Continue with fallback analysis
                analysis_method = f"Rule-Based Fallback (AI failed: {str(e)[:50]}...)"

        # Perform comprehensive analysis
        if analyzer:
            # Try AI analysis first
            security_result = run_ai_analysis(
                analyzer, contract_code, "security")
            if security_result.startswith("❌"):
                security_result = enhanced_fallback_analysis(
                    contract_code, "security")

            risk_result = run_ai_analysis(analyzer, contract_code, "risk")
            if risk_result.startswith("❌"):
                risk_result = enhanced_fallback_analysis(contract_code, "risk")

            quality_result = run_ai_analysis(
                analyzer, contract_code, "quality")
            if quality_result.startswith("❌"):
                quality_result = enhanced_fallback_analysis(
                    contract_code, "quality")
        else:
            # Use enhanced fallback analysis
            security_result = enhanced_fallback_analysis(
                contract_code, "security")
            risk_result = enhanced_fallback_analysis(contract_code, "risk")
            quality_result = enhanced_fallback_analysis(
                contract_code, "quality")

        # Contract statistics
        lines = contract_code.splitlines()
        function_count = contract_code.count('function')
        modifier_count = contract_code.count('modifier')
        pragma_count = contract_code.count('pragma')

        # Generate comprehensive report
        report = f"""# πŸ›‘οΈ Smart Contract Security Analysis Report

## πŸ“Š Analysis Overview
**Analysis Method**: {analysis_method}
**Model Used**: {hf_model if analyzer else 'Rule-Based Analysis Engine'}
**Timestamp**: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}
**Analysis Tool**: Xyizko Smart Contract Analyzer (MCP-Enabled)

## πŸ“ˆ Contract Metrics
- **Lines of Code**: {len(lines)}
- **Functions**: {function_count}
- **Modifiers**: {modifier_count}
- **Pragma Statements**: {pragma_count}
- **Code Size**: {len(contract_code)} characters

## πŸ›‘οΈ Security Vulnerability Assessment
{security_result}

## 🎯 Risk Assessment & Scoring
{risk_result}

## πŸ“Š Code Quality Analysis
{quality_result}

## πŸ“‹ Executive Summary & Recommendations

### 🚨 Immediate Actions Required:
- Review and address any CRITICAL or HIGH severity vulnerabilities
- Implement recommended security improvements
- Add missing input validations and access controls

### πŸ”§ Development Best Practices:
- Follow Solidity security patterns and conventions
- Implement comprehensive testing including edge cases
- Consider formal verification for critical functions

### πŸ—οΈ Deployment Readiness:
- {"⚠️ NOT READY: Address critical issues before deployment" if "CRITICAL" in security_result else "βœ… Ready for thorough testing and audit review"}
- Professional security audit recommended before mainnet deployment
- Implement emergency pause mechanisms for production contracts

---
**Analysis powered by Xyizko Smart Contract Analyzer**  
*MCP-enabled AI tool for comprehensive smart contract security assessment*
"""

        return report

    except Exception as e:
        return f"""# ❌ Smart Contract Analysis Failed

**Error**: {str(e)}
**Timestamp**: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}

## Troubleshooting:
- Ensure contract code is valid Solidity
- Check HuggingFace token if using AI analysis
- Try with a different model name
- Contact support if the issue persists

---
*Xyizko Smart Contract Analyzer - MCP Tool*
"""

# --- Smart Contract Analysis Tab ---


def upload_tab():
    system_status = "SmolAgents + HF API" if SMOLAGENTS_AVAILABLE else "Direct HF API"

    upload_description = f"""
    # Smart Contract AI Analysis
    > Upload your smart contract and get comprehensive AI-powered security analysis.
    
    **Current System**: {system_status}
    
    ## How it works:
    1. **Upload**: Select your smart contract (.txt, .sol files)
    2. **Configure**: Enter your Hugging Face API token and model
    3. **AI Analysis**: {'SmolAgents or' if SMOLAGENTS_AVAILABLE else ''} Direct API analysis with fallback
    4. **Download**: Get detailed analysis reports with actionable recommendations
    """

    analysis_info = """
    ## Analysis Features
    - **πŸ›‘οΈ Security Analysis**: Comprehensive vulnerability detection
    - **🎯 Risk Assessment**: Intelligent risk scoring (1-10 scale)
    - **πŸ“Š Code Quality Review**: Best practices evaluation
    - **πŸ”§ Fallback Analysis**: Robust rule-based analysis when AI fails
    - **πŸ“ Actionable Reports**: Specific, implementable recommendations
    
    ## Recommended Models
    - **Qwen/Qwen3-235B-A22B**
    - **mistralai/Mistral-7B-Instruct-v0.3**
    - **google/flan-t5-base** 
    - **meta-llama/Llama-3.3-70B-Instruct** 
    - Note premium and frontier models provide the highest quality
    """

    def analyze_contract_ui(file, hf_token, hf_model, progress=gr.Progress()):
        if file is None:
            return "❌ No file uploaded.", "", gr.update(visible=False)

        if not hf_token.strip():
            return "❌ Please provide a valid Hugging Face API token.", "", gr.update(visible=False)

        if not hf_model.strip():
            return "❌ Please specify a Hugging Face model name.", "", gr.update(visible=False)

        try:
            progress(0.1, desc="πŸ“– Reading contract file...")

            # Read file content
            if hasattr(file, 'read'):
                content = file.read().decode("utf-8")
            else:
                with open(file.name, 'r', encoding='utf-8') as f:
                    content = f.read()

            # Limit content size
            if len(content) > 10000:
                content = content[:10000] + "\n// ... (truncated for analysis)"

            progress(0.3, desc="πŸ€– Running comprehensive analysis...")

            # Use the MCP function for consistency
            analysis_result = analyze_smart_contract(
                content, hf_token, hf_model)

            progress(0.9, desc="πŸ’Ύ Creating downloadable report...")

            # Create downloadable report
            timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
            report_content = f"""# Smart Contract Security Analysis Report
**Generated by**: Xyizko Smart Contract Analyzer
**Date**: {datetime.datetime.now().strftime("%Y-%m-%d at %H:%M:%S")}

{analysis_result}

---
*Report generated by Xyizko Smart Contract Analyzer - MCH Hackathon 2025*
"""

            progress(1.0, desc="βœ… Analysis complete!")

            # Create downloadable file
            report_filename = f"contract_analysis_{timestamp}.md"
            try:
                with open(report_filename, 'w', encoding='utf-8') as f:
                    f.write(report_content)

                return (
                    "βœ… Analysis completed successfully!",
                    analysis_result,
                    gr.update(visible=True, value=report_filename)
                )
            except Exception:
                return (
                    "βœ… Analysis completed! (Download creation failed)",
                    analysis_result,
                    gr.update(visible=False)
                )

        except Exception as e:
            return f"❌ Analysis error: {str(e)}", "", gr.update(visible=False)

    with gr.Column():
        gr.Markdown(upload_description)
        gr.Markdown(analysis_info)

        with gr.Row():
            with gr.Column(scale=2):
                file_input = gr.File(
                    label="πŸ“ Upload Smart Contract",
                    file_types=[".txt", ".sol"],
                    height=120
                )
                hf_token_input = gr.Textbox(
                    label="πŸ”‘ Hugging Face API Token",
                    placeholder="hf_xxxxxxxxxxxxxxxxxxxxxxxxx",
                    type="password",
                    info="Get your token from https://huggingface.co/settings/tokens"
                )
                hf_model_input = gr.Textbox(
                    label="πŸ€– Hugging Face Model",
                    placeholder="microsoft/DialoGPT-medium",
                    value="microsoft/DialoGPT-medium",
                    info="Recommended: microsoft/DialoGPT-medium (Lightweight & Reliable)"
                )

            with gr.Column(scale=1):
                analyze_btn = gr.Button(
                    "πŸš€ Start Analysis",
                    variant="primary",
                    size="lg",
                    scale=2
                )

        gr.Markdown("---")

        status_output = gr.Textbox(
            label="πŸ“Š Analysis Status",
            lines=2,
            interactive=False,
            show_copy_button=True
        )

        analysis_output = gr.Textbox(
            label="πŸ“‹ Analysis Results",
            lines=20,
            max_lines=25,
            show_copy_button=True
        )

        download_file = gr.File(
            label="πŸ“₯ Download Analysis Report (Markdown)",
            visible=False
        )

        analyze_btn.click(
            fn=analyze_contract_ui,
            inputs=[file_input, hf_token_input, hf_model_input],
            outputs=[status_output, analysis_output, download_file]
        )

# --- MCP Integration Tab ---


def mcp_integration_tab():
    """Simple MCP Integration and Testing Tab"""

    mcp_info = """
    # πŸ”Œ MCP Integration - One Powerful Tool
    
    This Smart Contract Analyzer provides **one comprehensive MCP tool** that AI assistants can use.
    
    ## πŸ›‘οΈ `analyze_smart_contract` - The Complete Security Tool
    
    **What it does:**
    - βœ… **Security Vulnerability Detection** (reentrancy, access control, etc.)
    - βœ… **Risk Assessment & Scoring** (1-10 scale with detailed factors)
    - βœ… **Code Quality Analysis** (best practices, optimization opportunities)
    - βœ… **Actionable Recommendations** (specific steps to fix issues)
    - βœ… **Always Works** (AI-powered with intelligent fallback)
    
    **Parameters:**
    - `contract_code` (required): Your Solidity smart contract code
    - `hf_token` (optional): HuggingFace API token for AI analysis
    - `hf_model` (optional): Model name (default: microsoft/DialoGPT-medium)
    
    ## πŸš€ For AI Assistants (Claude, etc.):
    
    **Claude Desktop Config:**
    ```json
    {
      "mcpServers": {
        "smart-contract-analyzer": {
          "command": "npx",
          "args": ["-y", "@modelcontextprotocol/server-gradio", "YOUR_HF_SPACE_URL"]
        }
      }
    }
    ```
    
    **Example Usage:**
    ```
    "Analyze this smart contract for security issues:
    
    pragma solidity ^0.8.0;
    contract MyContract {
        // Your contract code here
    }"
    ```
    
    **Benefits:**
    - 🎯 **Simple**: One tool does everything
    - πŸ›‘οΈ **Reliable**: Always works (even without API tokens)
    - πŸš€ **Fast**: Lightweight dependencies
    - πŸ“Š **Comprehensive**: Complete security assessment
    """

    def test_mcp_tool(contract_code, hf_token, hf_model):
        """Test the MCP tool directly"""
        if not contract_code.strip():
            return "❌ Please provide contract code to test the MCP tool"

        try:
            result = analyze_smart_contract(contract_code, hf_token, hf_model)
            return result
        except Exception as e:
            return f"❌ MCP Tool Error: {str(e)}"

    def generate_claude_config(hf_space_url):
        """Generate Claude Desktop configuration"""
        if not hf_space_url.strip():
            hf_space_url = "https://your-username-smart-contract-analyzer.hf.space"

        config = f'''{{\n  "mcpServers": {{\n    "smart-contract-analyzer": {{\n      "command": "npx",\n      "args": [\n        "-y", \n        "@modelcontextprotocol/server-gradio",\n        "{hf_space_url}"\n      ]\n    }}\n  }}\n}}'''
        return config

    with gr.Column():
        gr.Markdown(mcp_info)

        gr.Markdown("## πŸ§ͺ Test the MCP Tool")

        with gr.Row():
            with gr.Column(scale=2):
                test_contract = gr.Textbox(
                    label="πŸ“ Contract Code",
                    placeholder="""pragma solidity ^0.8.0;

contract TestContract {
    address owner;
    mapping(address => uint) balances;
    
    function withdraw() public {
        uint amount = balances[msg.sender];
        (bool success, ) = msg.sender.call{value: amount}("");
        balances[msg.sender] = 0;
    }
}""",
                    lines=12
                )

                test_token = gr.Textbox(
                    label="πŸ”‘ HF Token (Optional)",
                    placeholder="hf_xxxxxxxxx (leave empty for rule-based analysis)",
                    type="password"
                )

                test_model = gr.Textbox(
                    label="πŸ€– Model (Optional)",
                    placeholder="microsoft/DialoGPT-medium",
                    value="microsoft/DialoGPT-medium"
                )

            with gr.Column(scale=1):
                test_btn = gr.Button(
                    "πŸ§ͺ Test MCP Tool",
                    variant="primary",
                    size="lg"
                )

                gr.Markdown("### πŸ“‹ Generate Config")

                space_url = gr.Textbox(
                    label="🌐 Your HF Space URL",
                    placeholder="https://your-space.hf.space"
                )

                config_btn = gr.Button(
                    "πŸ“‹ Generate Claude Config",
                    variant="secondary"
                )

        test_output = gr.Textbox(
            label="πŸ” MCP Tool Test Results",
            lines=25,
            show_copy_button=True
        )

        claude_config = gr.Textbox(
            label="πŸ“„ Claude Desktop Configuration",
            lines=12,
            show_copy_button=True
        )

        test_btn.click(
            fn=test_mcp_tool,
            inputs=[test_contract, test_token, test_model],
            outputs=[test_output]
        )

        config_btn.click(
            fn=generate_claude_config,
            inputs=[space_url],
            outputs=[claude_config]
        )

# /////////////////////////////////////////////////////////////////////////////////
# --- Main Demo UI Function ---


with gr.Blocks(
    theme=gr.themes.Soft(),
    title="Xyizko - Smart Contract Analyzer"
) as demo:

    with gr.Tab("🏠 Docs"):
        demo_vid()
        app_intro()

    with gr.Tab("πŸ” Analyzer Agent"):
        upload_tab()

    with gr.Tab("πŸ”Œ MCP Integration"):
        mcp_integration_tab()

if __name__ == "__main__":
    print("🌐 Starting Xyizko Smart Contract Analyzer...")
    print("πŸ”Œ MCP Integration: ENABLED (mcp_server=True)")
    print("πŸ€– AI Analysis: SmolAgents + HF API with Fallback")
    print("⚑ Lightweight: No transformers/torch dependencies")
    print("πŸ’‘ Deploy to HuggingFace Spaces for public MCP access!")

    demo.launch(
        mcp_server=True,  
        share=False,
        server_name="0.0.0.0",
        show_error=True
    )