xyizko commited on
Commit
bd7764e
Β·
verified Β·
1 Parent(s): a62cd5a

xyizko-Cleanup

Browse files

xyizko - Cleanup and braakdown

Files changed (1) hide show
  1. app.py +832 -8
app.py CHANGED
@@ -1,24 +1,848 @@
1
  # /////////////////////////////////////////////
2
- # Xyizko - MCH Hackathon 2025 Main App
3
  # x.com/xyizko
4
  # /////////////////////////////////////////////
5
 
 
 
 
 
6
  import gradio as gr
7
- from intro_tab import intro_tab
8
- from analyzer_tab import analyzer_tab
9
- from mcp_tab import mcp_integration_tab
10
 
11
- # Main Demo UI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  with gr.Blocks(
13
  theme=gr.themes.Ocean(),
14
  title="Xyizko - Smart Contract Analyzer"
15
  ) as demo:
16
 
17
  with gr.Tab("🏠 Introduction"):
18
- intro_tab()
19
 
20
  with gr.Tab("πŸ” Contract Analyzer"):
21
- analyzer_tab()
22
 
23
  with gr.Tab("πŸ”Œ MCP Integration"):
24
  mcp_integration_tab()
@@ -31,7 +855,7 @@ if __name__ == "__main__":
31
  print("πŸ’‘ Deploy to HuggingFace Spaces for public MCP access!")
32
 
33
  demo.launch(
34
- mcp_server=True,
35
  share=False,
36
  server_name="0.0.0.0",
37
  show_error=True
 
1
  # /////////////////////////////////////////////
2
+ # Xyizko - MCH Hackathon 2025 Skeleton
3
  # x.com/xyizko
4
  # /////////////////////////////////////////////
5
 
6
+ # --- Imports Section ---
7
+
8
+ import datetime
9
+
10
  import gradio as gr
 
 
 
11
 
12
+ # Try importing SmolAgents with proper error handling
13
+ try:
14
+ from smolagents import CodeAgent, HfApiModel
15
+ SMOLAGENTS_AVAILABLE = True
16
+ except ImportError:
17
+ SMOLAGENTS_AVAILABLE = False
18
+ print("⚠️ SmolAgents not available, using direct HF API")
19
+
20
+ # Fallback to HuggingFace Hub
21
+ from huggingface_hub import InferenceClient
22
+
23
+ # --- Demo UI Component Functions ---
24
+
25
+ # App Introduction Function (UPDATED with MCP info)
26
+
27
+
28
+ def app_intro():
29
+ intro_text = """
30
+ # Xyizko - MCP Hackathon 2025 Submission - Smart Contract Analyzer
31
+ 1. This gradio app serves as a skeleton for the MCP Hackathon 2025 project.
32
+ 2. As components are developed they will be added to this app.
33
+ 3. https://huggingface.co/Agents-MCP-Hackathon - Official Hackathon Announcement
34
+
35
+ # App Description
36
+ **AI-Powered Smart Contract Security Analysis Platform**
37
+ 1. This tool leverages AI to analyze smart contracts for vulnerabilities,
38
+ anti-patterns, and security issues. Upload your contract code and get comprehensive
39
+ security analysis powered by Hugging Face models.
40
+ 2. https://github.com/RareSkills/Buggy-ERC-20 - Test Buggy ERC-20 Contracts Source
41
+ """
42
+
43
+ ai_system_info = f"""
44
+ ## πŸ€– AI Analysis System
45
+ **SmolAgents Status**: {'βœ… Available' if SMOLAGENTS_AVAILABLE else '❌ Not Available - Using Direct HF API'}
46
+
47
+ ### What Our AI System Does:
48
+
49
+ #### 🧠 **Intelligent Code Analysis**
50
+ {'- SmolAgents CodeAgent for specialized code analysis' if SMOLAGENTS_AVAILABLE else '- Direct HuggingFace Inference API calls'}
51
+ - Multi-step security vulnerability detection
52
+ - Risk assessment and scoring
53
+ - Code quality evaluation
54
+ - Actionable security recommendations
55
+
56
+ #### 🎯 **Analysis Capabilities**
57
+ 1. **Security Vulnerability Detection**: Identifies reentrancy, overflow, access control issues
58
+ 2. **Risk Assessment**: Intelligent risk scoring and prioritization
59
+ 3. **Code Quality Analysis**: Best practices and optimization evaluation
60
+ 4. **Pattern Recognition**: Detects anti-patterns and security smells
61
+ 5. **Actionable Recommendations**: Generates specific improvement suggestions
62
+
63
+ #### πŸš€ **System Features**
64
+ - **Reliable**: Robust error handling with fallback mechanisms
65
+ - **Flexible**: Works with various HuggingFace models
66
+ - **Comprehensive**: Multi-dimensional analysis approach
67
+ - **Practical**: Provides actionable, implementable recommendations
68
+ """
69
+
70
+ # NEW MCP Integration Info
71
+ mcp_integration_info = """
72
+ ## πŸ”Œ Model Context Protocol (MCP) Integration
73
+
74
+ **πŸš€ This app is now MCP-enabled!** AI assistants like Claude can use it as a specialized security tool.
75
+
76
+ ### πŸ› οΈ Available MCP Tool:
77
+
78
+ #### πŸ›‘οΈ `analyze_smart_contract`
79
+ - **Purpose**: Complete smart contract security analysis
80
+ - **Features**: Security vulnerabilities + Risk scoring + Code quality assessment
81
+ - **AI-Powered**: Uses HuggingFace models with intelligent rule-based fallback
82
+ - **Input**: Just paste your Solidity contract code
83
+ - **Output**: Comprehensive security report with actionable recommendations
84
+ - **Reliability**: Always works - even without API tokens (fallback analysis)
85
+
86
+ ### πŸ€– How AI Assistants Use This:
87
+
88
+ **Claude Desktop Integration:**
89
+ ```json
90
+ {
91
+ "mcpServers": {
92
+ "smart-contract-analyzer": {
93
+ "command": "npx",
94
+ "args": ["-y", "@modelcontextprotocol/server-gradio", "YOUR_HF_SPACE_URL"]
95
+ }
96
+ }
97
+ }
98
+ ```
99
+
100
+ **Example AI Conversation:**
101
+ ```
102
+ User: "Analyze this smart contract for security issues: [paste contract]"
103
+
104
+ Claude: [Uses analyze_smart_contract tool]
105
+ "I've analyzed your contract and found 3 critical vulnerabilities..."
106
+ ```
107
+
108
+ ### ✨ Key Benefits:
109
+ - **One-Click Security**: AI assistants can instantly analyze any contract
110
+ - **Always Available**: Hosted on reliable HuggingFace infrastructure
111
+ - **No Setup Required**: AI assistants connect directly to your public space
112
+ - **Professional Reports**: Detailed analysis with specific remediation steps
113
+ """
114
+
115
+ part3 = """
116
+ ## Development Progress
117
+ > Changelog - Fri Jun 6 08:14:02 PM UTC 2025
118
+ 1. βœ… Implement robust AI analysis system
119
+ 2. βœ… SmolAgents integration with proper error handling
120
+ 3. βœ… Direct HF API fallback for maximum compatibility
121
+ 4. βœ… Enhanced analysis with multiple approaches
122
+ 5. βœ… Comprehensive security assessment capabilities
123
+ 6. βœ… **NEW: Model Context Protocol (MCP) Integration**
124
+ 7. βœ… **NEW: Single powerful MCP tool for AI assistants**
125
+ 8. βœ… **NEW: Lightweight deployment (no transformers/torch dependencies)**
126
+ 9. βœ… **NEW: Proper Gradio MCP server setup with mcp_server=True**
127
+
128
+ ### About Author
129
+ 1. X - https://x.com/xyizko
130
+ 2. Project Acknowledgements - https://x.com/Gradio/status/1930951866935910753
131
+ """
132
+
133
+ gr.Markdown(intro_text)
134
+ gr.Markdown(ai_system_info)
135
+ gr.Markdown(mcp_integration_info)
136
+ gr.Markdown(
137
+ value="""
138
+ ```mermaid
139
+ flowchart LR
140
+ A[Smart Contract Code] -->|Upload/MCP| B{AI Analysis System}
141
+ B -->|SmolAgents Available| C[CodeAgent Analysis]
142
+ B -->|Fallback| D[Direct HF API]
143
+ C --> E[Multi-Step Analysis]
144
+ D --> E
145
+ E --> F[Security Assessment]
146
+ E --> G[Risk Scoring]
147
+ E --> H[Quality Review]
148
+ F --> I[Comprehensive Report]
149
+ G --> I
150
+ H --> I
151
+ I --> J[Gradio UI Output]
152
+ I --> K[MCP Tool Response]
153
+ K --> L[AI Assistant Integration]
154
+ J --> M[Downloadable Analysis]
155
+ ```
156
+ """)
157
+ gr.Markdown(part3)
158
+
159
+ # --- Existing Analysis Functions (Unchanged) ---
160
+
161
+
162
+ def create_smart_contract_analyzer(hf_token, model_name):
163
+ """Create AI analyzer using SmolAgents or direct HF API"""
164
+ if SMOLAGENTS_AVAILABLE:
165
+ try:
166
+ model = HfApiModel(model_id=model_name, token=hf_token)
167
+ agent = CodeAgent(tools=[], model=model)
168
+ return {"type": "smolagent", "instance": agent, "model": model_name}
169
+ except Exception as e:
170
+ print(f"SmolAgents creation failed: {e}")
171
+
172
+ try:
173
+ client = InferenceClient(token=hf_token)
174
+ test_response = client.text_generation(
175
+ prompt="Test prompt",
176
+ model=model_name,
177
+ max_new_tokens=5
178
+ )
179
+ return {"type": "direct_api", "instance": client, "model": model_name}
180
+ except Exception as e:
181
+ raise Exception(f"Failed to create AI analyzer: {str(e)}")
182
+
183
+
184
+ def run_ai_analysis(analyzer, contract_code, analysis_type):
185
+ """Run AI analysis using available method"""
186
+ prompts = {
187
+ "security": f"""Analyze this Solidity smart contract for security vulnerabilities:
188
+
189
+ ```solidity
190
+ {contract_code[:3000]}
191
+ ```
192
+
193
+ Identify:
194
+ 1. Security vulnerabilities (reentrancy, overflow, access control)
195
+ 2. Risk level for each issue (Critical/High/Medium/Low)
196
+ 3. Specific remediation steps
197
+
198
+ Be concise and practical.""",
199
+
200
+ "risk": f"""Assess the risk level of this smart contract (scale 1-10):
201
+
202
+ ```solidity
203
+ {contract_code[:3000]}
204
+ ```
205
+
206
+ Provide:
207
+ 1. Overall risk score (1-10)
208
+ 2. Main risk factors
209
+ 3. Top 3 recommendations
210
+
211
+ Be specific and actionable.""",
212
+
213
+ "quality": f"""Review the code quality of this smart contract:
214
+
215
+ ```solidity
216
+ {contract_code[:3000]}
217
+ ```
218
+
219
+ Evaluate:
220
+ 1. Solidity best practices
221
+ 2. Gas optimization opportunities
222
+ 3. Code organization
223
+
224
+ Provide specific improvement suggestions."""
225
+ }
226
+
227
+ prompt = prompts.get(analysis_type, prompts["security"])
228
+
229
+ try:
230
+ if analyzer["type"] == "smolagent":
231
+ result = analyzer["instance"].run(prompt)
232
+ return str(result)
233
+ else:
234
+ response = analyzer["instance"].text_generation(
235
+ prompt=prompt,
236
+ model=analyzer["model"],
237
+ max_new_tokens=600,
238
+ temperature=0.5,
239
+ do_sample=True
240
+ )
241
+
242
+ if isinstance(response, str):
243
+ return response.strip()
244
+ elif hasattr(response, 'generated_text'):
245
+ return response.generated_text.strip()
246
+ else:
247
+ return str(response)
248
+
249
+ except Exception as e:
250
+ error_msg = str(e).lower()
251
+ if "not found" in error_msg or "404" in error_msg:
252
+ return f"❌ Model '{analyzer.get('model', 'unknown')}' not found. Try: microsoft/DialoGPT-medium"
253
+ elif "unauthorized" in error_msg or "403" in error_msg:
254
+ return "❌ Invalid API token or insufficient permissions"
255
+ elif "rate limit" in error_msg:
256
+ return "❌ Rate limit exceeded. Please wait and try again"
257
+ else:
258
+ return f"❌ Analysis failed: {str(e)}"
259
+
260
+
261
+ def enhanced_fallback_analysis(content, analysis_type):
262
+ """Comprehensive fallback analysis when AI fails"""
263
+ lines = content.splitlines()
264
+ functions = content.count('function')
265
+
266
+ if analysis_type == "security":
267
+ vulnerabilities = []
268
+ risk_score = 0
269
+
270
+ if 'call.value' in content or '.call(' in content:
271
+ vulnerabilities.append(
272
+ "πŸ”΄ **CRITICAL**: Potential reentrancy vulnerability (call.value/.call usage)")
273
+ risk_score += 4
274
+
275
+ if 'tx.origin' in content:
276
+ vulnerabilities.append(
277
+ "🟑 **MEDIUM**: Authentication bypass risk (tx.origin usage)")
278
+ risk_score += 2
279
+
280
+ if 'block.timestamp' in content or 'now' in content:
281
+ vulnerabilities.append("🟑 **MEDIUM**: Timestamp manipulation risk")
282
+ risk_score += 1
283
+
284
+ if not any(word in content.lower() for word in ['require', 'assert', 'revert']):
285
+ vulnerabilities.append("🟠 **HIGH**: Missing input validation")
286
+ risk_score += 3
287
+
288
+ if 'selfdestruct' in content:
289
+ vulnerabilities.append(
290
+ "πŸ”΄ **CRITICAL**: Contract can be destroyed (selfdestruct)")
291
+ risk_score += 4
292
+
293
+ if 'delegatecall' in content:
294
+ vulnerabilities.append("🟠 **HIGH**: Dangerous delegate call usage")
295
+ risk_score += 3
296
+
297
+ if functions > 20:
298
+ vulnerabilities.append(
299
+ "🟑 **MEDIUM**: High complexity (many functions)")
300
+ risk_score += 1
301
+
302
+ return f"""**Security Analysis Results:**
303
+
304
+ **Vulnerabilities Found:** {len(vulnerabilities)}
305
+ **Risk Score:** {min(risk_score, 10)}/10
306
+
307
+ {chr(10).join(vulnerabilities) if vulnerabilities else "βœ… No major vulnerabilities detected in static analysis"}
308
+
309
+ **Recommendations:**
310
+ - Implement reentrancy guards for external calls
311
+ - Use msg.sender instead of tx.origin
312
+ - Add comprehensive input validation
313
+ - Consider formal verification for critical functions"""
314
+
315
+ elif analysis_type == "risk":
316
+ risk_factors = []
317
+ score = 0
318
+
319
+ if 'call.value' in content:
320
+ score += 3
321
+ risk_factors.append("External call risks")
322
+ if len(lines) > 500:
323
+ score += 1
324
+ risk_factors.append("Large codebase")
325
+ if functions > 15:
326
+ score += 1
327
+ risk_factors.append("High complexity")
328
+ if 'owner' in content.lower():
329
+ score += 1
330
+ risk_factors.append("Centralized control")
331
+ if content.count('mapping') > 5:
332
+ score += 1
333
+ risk_factors.append("Complex state")
334
+
335
+ risk_level = "Critical" if score >= 6 else "High" if score >= 4 else "Medium" if score >= 2 else "Low"
336
+
337
+ return f"""**Risk Assessment:**
338
+
339
+ **Overall Risk Score:** {score}/10
340
+ **Risk Level:** {risk_level}
341
+
342
+ **Risk Factors:**
343
+ {chr(10).join([f"- {factor}" for factor in risk_factors]) if risk_factors else "- Minimal risk factors identified"}
344
+
345
+ **Priority Actions:**
346
+ 1. {"Immediate security review required" if score >= 4 else "Standard review recommended"}
347
+ 2. {"Implement emergency pause mechanism" if score >= 6 else "Add comprehensive testing"}
348
+ 3. {"Consider professional audit" if score >= 3 else "Document all functions"}"""
349
+
350
+ elif analysis_type == "quality":
351
+ quality_issues = []
352
+ score = 100
353
+
354
+ if content.count('pragma') == 0:
355
+ quality_issues.append("❌ Missing pragma statement (-10 points)")
356
+ score -= 10
357
+
358
+ if content.count('//') < functions / 2:
359
+ quality_issues.append("⚠️ Insufficient documentation (-15 points)")
360
+ score -= 15
361
+
362
+ if len(lines) > 1000:
363
+ quality_issues.append(
364
+ "⚠️ Contract too large, consider splitting (-10 points)")
365
+ score -= 10
366
+
367
+ if 'TODO' in content or 'FIXME' in content:
368
+ quality_issues.append(
369
+ "⚠️ Unfinished code markers found (-5 points)")
370
+ score -= 5
371
+
372
+ if not any(modifier in content for modifier in ['public', 'private', 'internal', 'external']):
373
+ quality_issues.append(
374
+ "❌ Missing function visibility specifiers (-20 points)")
375
+ score -= 20
376
+
377
+ return f"""**Code Quality Assessment:**
378
+
379
+ **Quality Score:** {max(score, 0)}/100
380
+
381
+ **Issues Found:**
382
+ {chr(10).join(quality_issues) if quality_issues else "βœ… No major quality issues detected"}
383
+
384
+ **Improvement Suggestions:**
385
+ - Add comprehensive NatSpec documentation
386
+ - Implement consistent naming conventions
387
+ - Use latest Solidity version with appropriate pragma
388
+ - Add function visibility specifiers
389
+ - Consider gas optimization patterns"""
390
+
391
+ # --- MCP Tool Function ---
392
+
393
+
394
+ def analyze_smart_contract(contract_code: str, hf_token: str = "", hf_model: str = "microsoft/DialoGPT-medium"):
395
+ """
396
+ MCP Tool: Comprehensive smart contract security analysis
397
+
398
+ This function will be automatically exposed as an MCP tool when mcp_server=True
399
+
400
+ Args:
401
+ contract_code: Solidity smart contract source code
402
+ hf_token: Optional HuggingFace API token for AI analysis
403
+ hf_model: HuggingFace model name (default: microsoft/DialoGPT-medium)
404
+
405
+ Returns:
406
+ Complete security analysis report with vulnerabilities, risk assessment, and recommendations
407
+ """
408
+ try:
409
+ # Initialize analyzer if token provided
410
+ analyzer = None
411
+ analysis_method = "Enhanced Rule-Based Fallback"
412
+
413
+ if hf_token.strip():
414
+ try:
415
+ analyzer = create_smart_contract_analyzer(hf_token, hf_model)
416
+ analysis_method = f"AI-Powered ({analyzer['type']})"
417
+ except Exception as e:
418
+ # Continue with fallback analysis
419
+ analysis_method = f"Rule-Based Fallback (AI failed: {str(e)[:50]}...)"
420
+
421
+ # Perform comprehensive analysis
422
+ if analyzer:
423
+ # Try AI analysis first
424
+ security_result = run_ai_analysis(
425
+ analyzer, contract_code, "security")
426
+ if security_result.startswith("❌"):
427
+ security_result = enhanced_fallback_analysis(
428
+ contract_code, "security")
429
+
430
+ risk_result = run_ai_analysis(analyzer, contract_code, "risk")
431
+ if risk_result.startswith("❌"):
432
+ risk_result = enhanced_fallback_analysis(contract_code, "risk")
433
+
434
+ quality_result = run_ai_analysis(
435
+ analyzer, contract_code, "quality")
436
+ if quality_result.startswith("❌"):
437
+ quality_result = enhanced_fallback_analysis(
438
+ contract_code, "quality")
439
+ else:
440
+ # Use enhanced fallback analysis
441
+ security_result = enhanced_fallback_analysis(
442
+ contract_code, "security")
443
+ risk_result = enhanced_fallback_analysis(contract_code, "risk")
444
+ quality_result = enhanced_fallback_analysis(
445
+ contract_code, "quality")
446
+
447
+ # Contract statistics
448
+ lines = contract_code.splitlines()
449
+ function_count = contract_code.count('function')
450
+ modifier_count = contract_code.count('modifier')
451
+ pragma_count = contract_code.count('pragma')
452
+
453
+ # Generate comprehensive report
454
+ report = f"""# πŸ›‘οΈ Smart Contract Security Analysis Report
455
+
456
+ ## πŸ“Š Analysis Overview
457
+ **Analysis Method**: {analysis_method}
458
+ **Model Used**: {hf_model if analyzer else 'Rule-Based Analysis Engine'}
459
+ **Timestamp**: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}
460
+ **Analysis Tool**: Xyizko Smart Contract Analyzer (MCP-Enabled)
461
+
462
+ ## πŸ“ˆ Contract Metrics
463
+ - **Lines of Code**: {len(lines)}
464
+ - **Functions**: {function_count}
465
+ - **Modifiers**: {modifier_count}
466
+ - **Pragma Statements**: {pragma_count}
467
+ - **Code Size**: {len(contract_code)} characters
468
+
469
+ ## πŸ›‘οΈ Security Vulnerability Assessment
470
+ {security_result}
471
+
472
+ ## 🎯 Risk Assessment & Scoring
473
+ {risk_result}
474
+
475
+ ## πŸ“Š Code Quality Analysis
476
+ {quality_result}
477
+
478
+ ## πŸ“‹ Executive Summary & Recommendations
479
+
480
+ ### 🚨 Immediate Actions Required:
481
+ - Review and address any CRITICAL or HIGH severity vulnerabilities
482
+ - Implement recommended security improvements
483
+ - Add missing input validations and access controls
484
+
485
+ ### πŸ”§ Development Best Practices:
486
+ - Follow Solidity security patterns and conventions
487
+ - Implement comprehensive testing including edge cases
488
+ - Consider formal verification for critical functions
489
+
490
+ ### πŸ—οΈ Deployment Readiness:
491
+ - {"⚠️ NOT READY: Address critical issues before deployment" if "CRITICAL" in security_result else "βœ… Ready for thorough testing and audit review"}
492
+ - Professional security audit recommended before mainnet deployment
493
+ - Implement emergency pause mechanisms for production contracts
494
+
495
+ ---
496
+ **Analysis powered by Xyizko Smart Contract Analyzer**
497
+ *MCP-enabled AI tool for comprehensive smart contract security assessment*
498
+ """
499
+
500
+ return report
501
+
502
+ except Exception as e:
503
+ return f"""# ❌ Smart Contract Analysis Failed
504
+
505
+ **Error**: {str(e)}
506
+ **Timestamp**: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}
507
+
508
+ ## Troubleshooting:
509
+ - Ensure contract code is valid Solidity
510
+ - Check HuggingFace token if using AI analysis
511
+ - Try with a different model name
512
+ - Contact support if the issue persists
513
+
514
+ ---
515
+ *Xyizko Smart Contract Analyzer - MCP Tool*
516
+ """
517
+
518
+ # --- Smart Contract Analysis Tab (Unchanged) ---
519
+
520
+
521
+ def upload_tab():
522
+ system_status = "SmolAgents + HF API" if SMOLAGENTS_AVAILABLE else "Direct HF API"
523
+
524
+ upload_description = f"""
525
+ # Smart Contract AI Analysis
526
+ > Upload your smart contract and get comprehensive AI-powered security analysis.
527
+
528
+ **Current System**: {system_status}
529
+
530
+ ## How it works:
531
+ 1. **Upload**: Select your smart contract (.txt, .sol files)
532
+ 2. **Configure**: Enter your Hugging Face API token and model
533
+ 3. **AI Analysis**: {'SmolAgents or' if SMOLAGENTS_AVAILABLE else ''} Direct API analysis with fallback
534
+ 4. **Download**: Get detailed analysis reports with actionable recommendations
535
+ """
536
+
537
+ analysis_info = """
538
+ ## Analysis Features
539
+ - **πŸ›‘οΈ Security Analysis**: Comprehensive vulnerability detection
540
+ - **🎯 Risk Assessment**: Intelligent risk scoring (1-10 scale)
541
+ - **πŸ“Š Code Quality Review**: Best practices evaluation
542
+ - **πŸ”§ Fallback Analysis**: Robust rule-based analysis when AI fails
543
+ - **πŸ“ Actionable Reports**: Specific, implementable recommendations
544
+
545
+ ## Recommended Models
546
+ - **microsoft/DialoGPT-medium** (Reliable, good balance)
547
+ - **microsoft/DialoGPT-large** (More detailed responses)
548
+ - **google/flan-t5-base** (Good instruction following)
549
+ - **facebook/blenderbot-400M-distill** (Lightweight, fast)
550
+ """
551
+
552
+ def analyze_contract_ui(file, hf_token, hf_model, progress=gr.Progress()):
553
+ if file is None:
554
+ return "❌ No file uploaded.", "", gr.update(visible=False)
555
+
556
+ if not hf_token.strip():
557
+ return "❌ Please provide a valid Hugging Face API token.", "", gr.update(visible=False)
558
+
559
+ if not hf_model.strip():
560
+ return "❌ Please specify a Hugging Face model name.", "", gr.update(visible=False)
561
+
562
+ try:
563
+ progress(0.1, desc="πŸ“– Reading contract file...")
564
+
565
+ # Read file content
566
+ if hasattr(file, 'read'):
567
+ content = file.read().decode("utf-8")
568
+ else:
569
+ with open(file.name, 'r', encoding='utf-8') as f:
570
+ content = f.read()
571
+
572
+ # Limit content size
573
+ if len(content) > 10000:
574
+ content = content[:10000] + "\n// ... (truncated for analysis)"
575
+
576
+ progress(0.3, desc="πŸ€– Running comprehensive analysis...")
577
+
578
+ # Use the MCP function for consistency
579
+ analysis_result = analyze_smart_contract(
580
+ content, hf_token, hf_model)
581
+
582
+ progress(0.9, desc="πŸ’Ύ Creating downloadable report...")
583
+
584
+ # Create downloadable report
585
+ timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
586
+ report_content = f"""# Smart Contract Security Analysis Report
587
+ **Generated by**: Xyizko Smart Contract Analyzer
588
+ **Date**: {datetime.datetime.now().strftime("%Y-%m-%d at %H:%M:%S")}
589
+
590
+ {analysis_result}
591
+
592
+ ---
593
+ *Report generated by Xyizko Smart Contract Analyzer - MCH Hackathon 2025*
594
+ """
595
+
596
+ progress(1.0, desc="βœ… Analysis complete!")
597
+
598
+ # Create downloadable file
599
+ report_filename = f"contract_analysis_{timestamp}.md"
600
+ try:
601
+ with open(report_filename, 'w', encoding='utf-8') as f:
602
+ f.write(report_content)
603
+
604
+ return (
605
+ "βœ… Analysis completed successfully!",
606
+ analysis_result,
607
+ gr.update(visible=True, value=report_filename)
608
+ )
609
+ except Exception:
610
+ return (
611
+ "βœ… Analysis completed! (Download creation failed)",
612
+ analysis_result,
613
+ gr.update(visible=False)
614
+ )
615
+
616
+ except Exception as e:
617
+ return f"❌ Analysis error: {str(e)}", "", gr.update(visible=False)
618
+
619
+ with gr.Column():
620
+ gr.Markdown(upload_description)
621
+ gr.Markdown(analysis_info)
622
+
623
+ with gr.Row():
624
+ with gr.Column(scale=2):
625
+ file_input = gr.File(
626
+ label="πŸ“ Upload Smart Contract",
627
+ file_types=[".txt", ".sol"],
628
+ height=120
629
+ )
630
+ hf_token_input = gr.Textbox(
631
+ label="πŸ”‘ Hugging Face API Token",
632
+ placeholder="hf_xxxxxxxxxxxxxxxxxxxxxxxxx",
633
+ type="password",
634
+ info="Get your token from https://huggingface.co/settings/tokens"
635
+ )
636
+ hf_model_input = gr.Textbox(
637
+ label="πŸ€– Hugging Face Model",
638
+ placeholder="microsoft/DialoGPT-medium",
639
+ value="microsoft/DialoGPT-medium",
640
+ info="Recommended: microsoft/DialoGPT-medium (Lightweight & Reliable)"
641
+ )
642
+
643
+ with gr.Column(scale=1):
644
+ analyze_btn = gr.Button(
645
+ "πŸš€ Start Analysis",
646
+ variant="primary",
647
+ size="lg",
648
+ scale=2
649
+ )
650
+
651
+ gr.Markdown("---")
652
+
653
+ status_output = gr.Textbox(
654
+ label="πŸ“Š Analysis Status",
655
+ lines=2,
656
+ interactive=False,
657
+ show_copy_button=True
658
+ )
659
+
660
+ analysis_output = gr.Textbox(
661
+ label="πŸ“‹ Analysis Results",
662
+ lines=20,
663
+ max_lines=25,
664
+ show_copy_button=True
665
+ )
666
+
667
+ download_file = gr.File(
668
+ label="πŸ“₯ Download Analysis Report (Markdown)",
669
+ visible=False
670
+ )
671
+
672
+ analyze_btn.click(
673
+ fn=analyze_contract_ui,
674
+ inputs=[file_input, hf_token_input, hf_model_input],
675
+ outputs=[status_output, analysis_output, download_file]
676
+ )
677
+
678
+ # --- MCP Integration Tab ---
679
+
680
+
681
+ def mcp_integration_tab():
682
+ """Simple MCP Integration and Testing Tab"""
683
+
684
+ mcp_info = """
685
+ # πŸ”Œ MCP Integration - One Powerful Tool
686
+
687
+ This Smart Contract Analyzer provides **one comprehensive MCP tool** that AI assistants can use.
688
+
689
+ ## πŸ›‘οΈ `analyze_smart_contract` - The Complete Security Tool
690
+
691
+ **What it does:**
692
+ - βœ… **Security Vulnerability Detection** (reentrancy, access control, etc.)
693
+ - βœ… **Risk Assessment & Scoring** (1-10 scale with detailed factors)
694
+ - βœ… **Code Quality Analysis** (best practices, optimization opportunities)
695
+ - βœ… **Actionable Recommendations** (specific steps to fix issues)
696
+ - βœ… **Always Works** (AI-powered with intelligent fallback)
697
+
698
+ **Parameters:**
699
+ - `contract_code` (required): Your Solidity smart contract code
700
+ - `hf_token` (optional): HuggingFace API token for AI analysis
701
+ - `hf_model` (optional): Model name (default: microsoft/DialoGPT-medium)
702
+
703
+ ## πŸš€ For AI Assistants (Claude, etc.):
704
+
705
+ **Claude Desktop Config:**
706
+ ```json
707
+ {
708
+ "mcpServers": {
709
+ "smart-contract-analyzer": {
710
+ "command": "npx",
711
+ "args": ["-y", "@modelcontextprotocol/server-gradio", "YOUR_HF_SPACE_URL"]
712
+ }
713
+ }
714
+ }
715
+ ```
716
+
717
+ **Example Usage:**
718
+ ```
719
+ "Analyze this smart contract for security issues:
720
+
721
+ pragma solidity ^0.8.0;
722
+ contract MyContract {
723
+ // Your contract code here
724
+ }"
725
+ ```
726
+
727
+ **Benefits:**
728
+ - 🎯 **Simple**: One tool does everything
729
+ - πŸ›‘οΈ **Reliable**: Always works (even without API tokens)
730
+ - πŸš€ **Fast**: Lightweight dependencies
731
+ - πŸ“Š **Comprehensive**: Complete security assessment
732
+ """
733
+
734
+ def test_mcp_tool(contract_code, hf_token, hf_model):
735
+ """Test the MCP tool directly"""
736
+ if not contract_code.strip():
737
+ return "❌ Please provide contract code to test the MCP tool"
738
+
739
+ try:
740
+ result = analyze_smart_contract(contract_code, hf_token, hf_model)
741
+ return result
742
+ except Exception as e:
743
+ return f"❌ MCP Tool Error: {str(e)}"
744
+
745
+ def generate_claude_config(hf_space_url):
746
+ """Generate Claude Desktop configuration"""
747
+ if not hf_space_url.strip():
748
+ hf_space_url = "https://your-username-smart-contract-analyzer.hf.space"
749
+
750
+ 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}}'''
751
+ return config
752
+
753
+ with gr.Column():
754
+ gr.Markdown(mcp_info)
755
+
756
+ gr.Markdown("## πŸ§ͺ Test the MCP Tool")
757
+
758
+ with gr.Row():
759
+ with gr.Column(scale=2):
760
+ test_contract = gr.Textbox(
761
+ label="πŸ“ Contract Code",
762
+ placeholder="""pragma solidity ^0.8.0;
763
+
764
+ contract TestContract {
765
+ address owner;
766
+ mapping(address => uint) balances;
767
+
768
+ function withdraw() public {
769
+ uint amount = balances[msg.sender];
770
+ (bool success, ) = msg.sender.call{value: amount}("");
771
+ balances[msg.sender] = 0;
772
+ }
773
+ }""",
774
+ lines=12
775
+ )
776
+
777
+ test_token = gr.Textbox(
778
+ label="πŸ”‘ HF Token (Optional)",
779
+ placeholder="hf_xxxxxxxxx (leave empty for rule-based analysis)",
780
+ type="password"
781
+ )
782
+
783
+ test_model = gr.Textbox(
784
+ label="πŸ€– Model (Optional)",
785
+ placeholder="microsoft/DialoGPT-medium",
786
+ value="microsoft/DialoGPT-medium"
787
+ )
788
+
789
+ with gr.Column(scale=1):
790
+ test_btn = gr.Button(
791
+ "πŸ§ͺ Test MCP Tool",
792
+ variant="primary",
793
+ size="lg"
794
+ )
795
+
796
+ gr.Markdown("### πŸ“‹ Generate Config")
797
+
798
+ space_url = gr.Textbox(
799
+ label="🌐 Your HF Space URL",
800
+ placeholder="https://your-space.hf.space"
801
+ )
802
+
803
+ config_btn = gr.Button(
804
+ "πŸ“‹ Generate Claude Config",
805
+ variant="secondary"
806
+ )
807
+
808
+ test_output = gr.Textbox(
809
+ label="πŸ” MCP Tool Test Results",
810
+ lines=25,
811
+ show_copy_button=True
812
+ )
813
+
814
+ claude_config = gr.Textbox(
815
+ label="πŸ“„ Claude Desktop Configuration",
816
+ lines=12,
817
+ show_copy_button=True
818
+ )
819
+
820
+ test_btn.click(
821
+ fn=test_mcp_tool,
822
+ inputs=[test_contract, test_token, test_model],
823
+ outputs=[test_output]
824
+ )
825
+
826
+ config_btn.click(
827
+ fn=generate_claude_config,
828
+ inputs=[space_url],
829
+ outputs=[claude_config]
830
+ )
831
+
832
+ # /////////////////////////////////////////////////////////////////////////////////
833
+ # --- Main Demo UI Function ---
834
+
835
+
836
  with gr.Blocks(
837
  theme=gr.themes.Ocean(),
838
  title="Xyizko - Smart Contract Analyzer"
839
  ) as demo:
840
 
841
  with gr.Tab("🏠 Introduction"):
842
+ app_intro()
843
 
844
  with gr.Tab("πŸ” Contract Analyzer"):
845
+ upload_tab()
846
 
847
  with gr.Tab("πŸ”Œ MCP Integration"):
848
  mcp_integration_tab()
 
855
  print("πŸ’‘ Deploy to HuggingFace Spaces for public MCP access!")
856
 
857
  demo.launch(
858
+ mcp_server=True, # πŸ”‘ KEY FIX: Enable MCP server
859
  share=False,
860
  server_name="0.0.0.0",
861
  show_error=True