Spaces:
Sleeping
Sleeping
| # ///////////////////////////////////////////// | |
| # Xyizko - MCH Hackathon 2025 Skeleton | |
| # x.com/xyizko | |
| # ///////////////////////////////////////////// | |
| # --- Imports Section --- | |
| import datetime | |
| import gradio as gr | |
| # Try importing SmolAgents with proper 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 (UPDATED with MCP info) | |
| def app_intro(): | |
| intro_text = """ | |
| # Xyizko - MCP Hackathon 2025 Submission - Smart Contract Analyzer | |
| 1. This gradio app serves as a skeleton for the MCP Hackathon 2025 project. | |
| 2. As components are developed they will be added to this app. | |
| 3. https://huggingface.co/Agents-MCP-Hackathon - Official Hackathon Announcement | |
| # 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) | |
| # --- Existing Analysis Functions (Unchanged) --- | |
| 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 (Unchanged) --- | |
| 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 | |
| - **microsoft/DialoGPT-medium** (Reliable, good balance) | |
| - **microsoft/DialoGPT-large** (More detailed responses) | |
| - **google/flan-t5-base** (Good instruction following) | |
| - **facebook/blenderbot-400M-distill** (Lightweight, fast) | |
| """ | |
| 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.Ocean(), | |
| title="Xyizko - Smart Contract Analyzer" | |
| ) as demo: | |
| with gr.Tab("π Introduction"): | |
| app_intro() | |
| with gr.Tab("π Contract Analyzer"): | |
| 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, # π KEY FIX: Enable MCP server | |
| share=False, | |
| server_name="0.0.0.0", | |
| show_error=True | |
| ) | |