Spaces:
Sleeping
Sleeping
xyizko-Fix
Browse filesxyizko - Syntax and AgentCalls Fixes
- app.py +397 -125
- requirements.txt +3 -3
app.py
CHANGED
|
@@ -22,7 +22,7 @@ from huggingface_hub import InferenceClient
|
|
| 22 |
|
| 23 |
# --- Demo UI Component Functions ---
|
| 24 |
|
| 25 |
-
# App Introduction Function
|
| 26 |
|
| 27 |
|
| 28 |
def app_intro():
|
|
@@ -34,7 +34,7 @@ def app_intro():
|
|
| 34 |
|
| 35 |
# App Description
|
| 36 |
**AI-Powered Smart Contract Security Analysis Platform**
|
| 37 |
-
1.
|
| 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
|
|
@@ -67,6 +67,51 @@ def app_intro():
|
|
| 67 |
- **Practical**: Provides actionable, implementable recommendations
|
| 68 |
"""
|
| 69 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
part3 = """
|
| 71 |
## Development Progress
|
| 72 |
> Changelog - Fri Jun 6 07:15:00 PM UTC 2025
|
|
@@ -75,19 +120,23 @@ def app_intro():
|
|
| 75 |
3. β
Direct HF API fallback for maximum compatibility
|
| 76 |
4. β
Enhanced analysis with multiple approaches
|
| 77 |
5. β
Comprehensive security assessment capabilities
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
### About Author
|
| 80 |
1. X - https://x.com/xyizko
|
| 81 |
-
2.
|
| 82 |
"""
|
| 83 |
|
| 84 |
gr.Markdown(intro_text)
|
| 85 |
gr.Markdown(ai_system_info)
|
|
|
|
| 86 |
gr.Markdown(
|
| 87 |
value="""
|
| 88 |
```mermaid
|
| 89 |
flowchart LR
|
| 90 |
-
A[Smart Contract Code] -->|Upload| B{AI Analysis System}
|
| 91 |
B -->|SmolAgents Available| C[CodeAgent Analysis]
|
| 92 |
B -->|Fallback| D[Direct HF API]
|
| 93 |
C --> E[Multi-Step Analysis]
|
|
@@ -98,37 +147,29 @@ def app_intro():
|
|
| 98 |
F --> I[Comprehensive Report]
|
| 99 |
G --> I
|
| 100 |
H --> I
|
| 101 |
-
I --> J[
|
|
|
|
|
|
|
|
|
|
| 102 |
```
|
| 103 |
""")
|
| 104 |
gr.Markdown(part3)
|
| 105 |
|
| 106 |
-
#
|
| 107 |
|
| 108 |
|
| 109 |
def create_smart_contract_analyzer(hf_token, model_name):
|
| 110 |
"""Create AI analyzer using SmolAgents or direct HF API"""
|
| 111 |
-
|
| 112 |
if SMOLAGENTS_AVAILABLE:
|
| 113 |
try:
|
| 114 |
-
# Try SmolAgents approach
|
| 115 |
model = HfApiModel(model_id=model_name, token=hf_token)
|
| 116 |
-
|
| 117 |
-
# Create CodeAgent with correct parameters based on SmolAgents API
|
| 118 |
-
agent = CodeAgent(
|
| 119 |
-
tools=[], # Empty tools list
|
| 120 |
-
model=model,
|
| 121 |
-
# Note: system_prompt might not be supported, check SmolAgents docs
|
| 122 |
-
)
|
| 123 |
-
|
| 124 |
return {"type": "smolagent", "instance": agent, "model": model_name}
|
| 125 |
except Exception as e:
|
| 126 |
print(f"SmolAgents creation failed: {e}")
|
| 127 |
|
| 128 |
-
# Fallback to direct HF API
|
| 129 |
try:
|
| 130 |
client = InferenceClient(token=hf_token)
|
| 131 |
-
# Test the connection
|
| 132 |
test_response = client.text_generation(
|
| 133 |
prompt="Test prompt",
|
| 134 |
model=model_name,
|
|
@@ -141,8 +182,6 @@ def create_smart_contract_analyzer(hf_token, model_name):
|
|
| 141 |
|
| 142 |
def run_ai_analysis(analyzer, contract_code, analysis_type):
|
| 143 |
"""Run AI analysis using available method"""
|
| 144 |
-
|
| 145 |
-
# Define analysis prompts
|
| 146 |
prompts = {
|
| 147 |
"security": f"""Analyze this Solidity smart contract for security vulnerabilities:
|
| 148 |
|
|
@@ -188,11 +227,9 @@ Provide specific improvement suggestions."""
|
|
| 188 |
|
| 189 |
try:
|
| 190 |
if analyzer["type"] == "smolagent":
|
| 191 |
-
# Use SmolAgents
|
| 192 |
result = analyzer["instance"].run(prompt)
|
| 193 |
return str(result)
|
| 194 |
else:
|
| 195 |
-
# Use direct HF API
|
| 196 |
response = analyzer["instance"].text_generation(
|
| 197 |
prompt=prompt,
|
| 198 |
model=analyzer["model"],
|
|
@@ -219,12 +256,9 @@ Provide specific improvement suggestions."""
|
|
| 219 |
else:
|
| 220 |
return f"β Analysis failed: {str(e)}"
|
| 221 |
|
| 222 |
-
# Enhanced fallback analysis
|
| 223 |
-
|
| 224 |
|
| 225 |
def enhanced_fallback_analysis(content, analysis_type):
|
| 226 |
"""Comprehensive fallback analysis when AI fails"""
|
| 227 |
-
|
| 228 |
lines = content.splitlines()
|
| 229 |
functions = content.count('function')
|
| 230 |
|
|
@@ -232,7 +266,6 @@ def enhanced_fallback_analysis(content, analysis_type):
|
|
| 232 |
vulnerabilities = []
|
| 233 |
risk_score = 0
|
| 234 |
|
| 235 |
-
# Check for specific vulnerabilities
|
| 236 |
if 'call.value' in content or '.call(' in content:
|
| 237 |
vulnerabilities.append(
|
| 238 |
"π΄ **CRITICAL**: Potential reentrancy vulnerability (call.value/.call usage)")
|
|
@@ -354,7 +387,132 @@ def enhanced_fallback_analysis(content, analysis_type):
|
|
| 354 |
- Add function visibility specifiers
|
| 355 |
- Consider gas optimization patterns"""
|
| 356 |
|
| 357 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
|
| 359 |
|
| 360 |
def upload_tab():
|
|
@@ -412,99 +570,11 @@ def upload_tab():
|
|
| 412 |
if len(content) > 10000:
|
| 413 |
content = content[:10000] + "\n// ... (truncated for analysis)"
|
| 414 |
|
| 415 |
-
progress(0.
|
| 416 |
-
|
| 417 |
-
# Create analyzer
|
| 418 |
-
analyzer = None
|
| 419 |
-
ai_method = "fallback"
|
| 420 |
-
|
| 421 |
-
try:
|
| 422 |
-
analyzer = create_smart_contract_analyzer(hf_token, hf_model)
|
| 423 |
-
ai_method = analyzer["type"]
|
| 424 |
-
progress(0.25, desc=f"β
AI analyzer ready ({ai_method})!")
|
| 425 |
-
except Exception as e:
|
| 426 |
-
progress(0.25, desc="β οΈ AI failed, using enhanced fallback...")
|
| 427 |
-
print(f"AI analyzer creation failed: {e}")
|
| 428 |
-
|
| 429 |
-
progress(0.3, desc="π‘οΈ Running security analysis...")
|
| 430 |
-
|
| 431 |
-
if analyzer:
|
| 432 |
-
security_result = run_ai_analysis(
|
| 433 |
-
analyzer, content, "security")
|
| 434 |
-
if security_result.startswith("β"):
|
| 435 |
-
security_result = enhanced_fallback_analysis(
|
| 436 |
-
content, "security")
|
| 437 |
-
else:
|
| 438 |
-
security_result = enhanced_fallback_analysis(
|
| 439 |
-
content, "security")
|
| 440 |
-
|
| 441 |
-
progress(0.5, desc="π― Performing risk assessment...")
|
| 442 |
-
|
| 443 |
-
if analyzer:
|
| 444 |
-
risk_result = run_ai_analysis(analyzer, content, "risk")
|
| 445 |
-
if risk_result.startswith("β"):
|
| 446 |
-
risk_result = enhanced_fallback_analysis(content, "risk")
|
| 447 |
-
else:
|
| 448 |
-
risk_result = enhanced_fallback_analysis(content, "risk")
|
| 449 |
-
|
| 450 |
-
progress(0.7, desc="π Analyzing code quality...")
|
| 451 |
-
|
| 452 |
-
if analyzer:
|
| 453 |
-
quality_result = run_ai_analysis(analyzer, content, "quality")
|
| 454 |
-
if quality_result.startswith("β"):
|
| 455 |
-
quality_result = enhanced_fallback_analysis(
|
| 456 |
-
content, "quality")
|
| 457 |
-
else:
|
| 458 |
-
quality_result = enhanced_fallback_analysis(content, "quality")
|
| 459 |
-
|
| 460 |
-
progress(0.8, desc="π Generating comprehensive report...")
|
| 461 |
-
|
| 462 |
-
# Contract statistics
|
| 463 |
-
lines = content.splitlines()
|
| 464 |
-
function_count = content.count('function')
|
| 465 |
-
modifier_count = content.count('modifier')
|
| 466 |
-
pragma_count = content.count('pragma')
|
| 467 |
|
| 468 |
-
#
|
| 469 |
-
analysis_result =
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
## π€ Analysis Configuration
|
| 473 |
-
**Method**: {ai_method.upper() if analyzer else 'ENHANCED FALLBACK'}
|
| 474 |
-
**Model**: {hf_model if analyzer else 'Rule-based Analysis'}
|
| 475 |
-
**Timestamp**: {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
| 476 |
-
|
| 477 |
-
## π Contract Statistics
|
| 478 |
-
- **Lines of Code**: {len(lines)}
|
| 479 |
-
- **Functions**: {function_count}
|
| 480 |
-
- **Modifiers**: {modifier_count}
|
| 481 |
-
- **Pragma Statements**: {pragma_count}
|
| 482 |
-
- **File Size**: {len(content)} characters
|
| 483 |
-
|
| 484 |
-
## π‘οΈ Security Analysis
|
| 485 |
-
{security_result}
|
| 486 |
-
|
| 487 |
-
## π― Risk Assessment
|
| 488 |
-
{risk_result}
|
| 489 |
-
|
| 490 |
-
## π Code Quality Analysis
|
| 491 |
-
{quality_result}
|
| 492 |
-
|
| 493 |
-
## π Executive Summary
|
| 494 |
-
- β
{'AI-powered' if analyzer else 'Rule-based'} security analysis completed
|
| 495 |
-
- β
Risk assessment with actionable recommendations
|
| 496 |
-
- β
Code quality evaluation with improvement suggestions
|
| 497 |
-
- β
Comprehensive report generated successfully
|
| 498 |
-
|
| 499 |
-
## π― Next Steps
|
| 500 |
-
1. **Immediate**: Address any Critical or High severity issues
|
| 501 |
-
2. **Short-term**: Implement recommended security improvements
|
| 502 |
-
3. **Medium-term**: Optimize gas usage and code quality
|
| 503 |
-
4. **Long-term**: Consider professional audit for production deployment
|
| 504 |
-
|
| 505 |
-
---
|
| 506 |
-
*Analysis powered by {'SmolAgents/HF API' if analyzer else 'Enhanced Rule-based System'} - Comprehensive Security Assessment*
|
| 507 |
-
"""
|
| 508 |
|
| 509 |
progress(0.9, desc="πΎ Creating downloadable report...")
|
| 510 |
|
|
@@ -513,8 +583,6 @@ def upload_tab():
|
|
| 513 |
report_content = f"""# Smart Contract Security Analysis Report
|
| 514 |
**Generated by**: Xyizko Smart Contract Analyzer
|
| 515 |
**Date**: {datetime.datetime.now().strftime("%Y-%m-%d at %H:%M:%S")}
|
| 516 |
-
**Analysis Method**: {ai_method.upper() if analyzer else 'ENHANCED FALLBACK'}
|
| 517 |
-
**Model**: {hf_model if analyzer else 'Rule-based Analysis'}
|
| 518 |
|
| 519 |
{analysis_result}
|
| 520 |
|
|
@@ -531,7 +599,7 @@ def upload_tab():
|
|
| 531 |
f.write(report_content)
|
| 532 |
|
| 533 |
return (
|
| 534 |
-
|
| 535 |
analysis_result,
|
| 536 |
gr.update(visible=True, value=report_filename)
|
| 537 |
)
|
|
@@ -566,7 +634,7 @@ def upload_tab():
|
|
| 566 |
label="π€ Hugging Face Model",
|
| 567 |
placeholder="microsoft/DialoGPT-medium",
|
| 568 |
value="microsoft/DialoGPT-medium",
|
| 569 |
-
info="Recommended: microsoft/DialoGPT-medium (
|
| 570 |
)
|
| 571 |
|
| 572 |
with gr.Column(scale=1):
|
|
@@ -604,10 +672,201 @@ def upload_tab():
|
|
| 604 |
outputs=[status_output, analysis_output, download_file]
|
| 605 |
)
|
| 606 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 607 |
|
| 608 |
# /////////////////////////////////////////////////////////////////////////////////
|
| 609 |
# --- Main Demo UI Function ---
|
| 610 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 611 |
|
| 612 |
with gr.Tab("π Introduction"):
|
| 613 |
app_intro()
|
|
@@ -615,5 +874,18 @@ with gr.Blocks(theme=gr.themes.Ocean(), title="Xyizko - Smart Contract Analyzer"
|
|
| 615 |
with gr.Tab("π Contract Analyzer"):
|
| 616 |
upload_tab()
|
| 617 |
|
|
|
|
|
|
|
|
|
|
| 618 |
if __name__ == "__main__":
|
| 619 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
# --- Demo UI Component Functions ---
|
| 24 |
|
| 25 |
+
# App Introduction Function (UPDATED with MCP info)
|
| 26 |
|
| 27 |
|
| 28 |
def app_intro():
|
|
|
|
| 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
|
|
|
|
| 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 07:15:00 PM UTC 2025
|
|
|
|
| 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 |
|
| 127 |
### About Author
|
| 128 |
1. X - https://x.com/xyizko
|
| 129 |
+
2. Project Acknowledgements - https://x.com/Gradio/status/1930951866935910753
|
| 130 |
"""
|
| 131 |
|
| 132 |
gr.Markdown(intro_text)
|
| 133 |
gr.Markdown(ai_system_info)
|
| 134 |
+
gr.Markdown(mcp_integration_info)
|
| 135 |
gr.Markdown(
|
| 136 |
value="""
|
| 137 |
```mermaid
|
| 138 |
flowchart LR
|
| 139 |
+
A[Smart Contract Code] -->|Upload/MCP| B{AI Analysis System}
|
| 140 |
B -->|SmolAgents Available| C[CodeAgent Analysis]
|
| 141 |
B -->|Fallback| D[Direct HF API]
|
| 142 |
C --> E[Multi-Step Analysis]
|
|
|
|
| 147 |
F --> I[Comprehensive Report]
|
| 148 |
G --> I
|
| 149 |
H --> I
|
| 150 |
+
I --> J[Gradio UI Output]
|
| 151 |
+
I --> K[MCP Tool Response]
|
| 152 |
+
K --> L[AI Assistant Integration]
|
| 153 |
+
J --> M[Downloadable Analysis]
|
| 154 |
```
|
| 155 |
""")
|
| 156 |
gr.Markdown(part3)
|
| 157 |
|
| 158 |
+
# --- Existing Analysis Functions (Unchanged) ---
|
| 159 |
|
| 160 |
|
| 161 |
def create_smart_contract_analyzer(hf_token, model_name):
|
| 162 |
"""Create AI analyzer using SmolAgents or direct HF API"""
|
|
|
|
| 163 |
if SMOLAGENTS_AVAILABLE:
|
| 164 |
try:
|
|
|
|
| 165 |
model = HfApiModel(model_id=model_name, token=hf_token)
|
| 166 |
+
agent = CodeAgent(tools=[], model=model)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
return {"type": "smolagent", "instance": agent, "model": model_name}
|
| 168 |
except Exception as e:
|
| 169 |
print(f"SmolAgents creation failed: {e}")
|
| 170 |
|
|
|
|
| 171 |
try:
|
| 172 |
client = InferenceClient(token=hf_token)
|
|
|
|
| 173 |
test_response = client.text_generation(
|
| 174 |
prompt="Test prompt",
|
| 175 |
model=model_name,
|
|
|
|
| 182 |
|
| 183 |
def run_ai_analysis(analyzer, contract_code, analysis_type):
|
| 184 |
"""Run AI analysis using available method"""
|
|
|
|
|
|
|
| 185 |
prompts = {
|
| 186 |
"security": f"""Analyze this Solidity smart contract for security vulnerabilities:
|
| 187 |
|
|
|
|
| 227 |
|
| 228 |
try:
|
| 229 |
if analyzer["type"] == "smolagent":
|
|
|
|
| 230 |
result = analyzer["instance"].run(prompt)
|
| 231 |
return str(result)
|
| 232 |
else:
|
|
|
|
| 233 |
response = analyzer["instance"].text_generation(
|
| 234 |
prompt=prompt,
|
| 235 |
model=analyzer["model"],
|
|
|
|
| 256 |
else:
|
| 257 |
return f"β Analysis failed: {str(e)}"
|
| 258 |
|
|
|
|
|
|
|
| 259 |
|
| 260 |
def enhanced_fallback_analysis(content, analysis_type):
|
| 261 |
"""Comprehensive fallback analysis when AI fails"""
|
|
|
|
| 262 |
lines = content.splitlines()
|
| 263 |
functions = content.count('function')
|
| 264 |
|
|
|
|
| 266 |
vulnerabilities = []
|
| 267 |
risk_score = 0
|
| 268 |
|
|
|
|
| 269 |
if 'call.value' in content or '.call(' in content:
|
| 270 |
vulnerabilities.append(
|
| 271 |
"π΄ **CRITICAL**: Potential reentrancy vulnerability (call.value/.call usage)")
|
|
|
|
| 387 |
- Add function visibility specifiers
|
| 388 |
- Consider gas optimization patterns"""
|
| 389 |
|
| 390 |
+
# --- Single Powerful MCP Tool ---
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def analyze_smart_contract_mcp(contract_code: str, hf_token: str = "", hf_model: str = "microsoft/DialoGPT-medium"):
|
| 394 |
+
"""
|
| 395 |
+
Single comprehensive MCP tool for smart contract analysis
|
| 396 |
+
|
| 397 |
+
Args:
|
| 398 |
+
contract_code: Solidity smart contract source code
|
| 399 |
+
hf_token: Optional HuggingFace API token for AI analysis
|
| 400 |
+
hf_model: HuggingFace model name (default: microsoft/DialoGPT-medium)
|
| 401 |
+
|
| 402 |
+
Returns:
|
| 403 |
+
Complete security analysis report with vulnerabilities, risk assessment, and recommendations
|
| 404 |
+
"""
|
| 405 |
+
try:
|
| 406 |
+
# Initialize analyzer if token provided
|
| 407 |
+
analyzer = None
|
| 408 |
+
analysis_method = "Enhanced Rule-Based Fallback"
|
| 409 |
+
|
| 410 |
+
if hf_token.strip():
|
| 411 |
+
try:
|
| 412 |
+
analyzer = create_smart_contract_analyzer(hf_token, hf_model)
|
| 413 |
+
analysis_method = f"AI-Powered ({analyzer['type']})"
|
| 414 |
+
except Exception as e:
|
| 415 |
+
# Continue with fallback analysis
|
| 416 |
+
analysis_method = f"Rule-Based Fallback (AI failed: {str(e)[:50]}...)"
|
| 417 |
+
|
| 418 |
+
# Perform comprehensive analysis
|
| 419 |
+
if analyzer:
|
| 420 |
+
# Try AI analysis first
|
| 421 |
+
security_result = run_ai_analysis(
|
| 422 |
+
analyzer, contract_code, "security")
|
| 423 |
+
if security_result.startswith("β"):
|
| 424 |
+
security_result = enhanced_fallback_analysis(
|
| 425 |
+
contract_code, "security")
|
| 426 |
+
|
| 427 |
+
risk_result = run_ai_analysis(analyzer, contract_code, "risk")
|
| 428 |
+
if risk_result.startswith("β"):
|
| 429 |
+
risk_result = enhanced_fallback_analysis(contract_code, "risk")
|
| 430 |
+
|
| 431 |
+
quality_result = run_ai_analysis(
|
| 432 |
+
analyzer, contract_code, "quality")
|
| 433 |
+
if quality_result.startswith("β"):
|
| 434 |
+
quality_result = enhanced_fallback_analysis(
|
| 435 |
+
contract_code, "quality")
|
| 436 |
+
else:
|
| 437 |
+
# Use enhanced fallback analysis
|
| 438 |
+
security_result = enhanced_fallback_analysis(
|
| 439 |
+
contract_code, "security")
|
| 440 |
+
risk_result = enhanced_fallback_analysis(contract_code, "risk")
|
| 441 |
+
quality_result = enhanced_fallback_analysis(
|
| 442 |
+
contract_code, "quality")
|
| 443 |
+
|
| 444 |
+
# Contract statistics
|
| 445 |
+
lines = contract_code.splitlines()
|
| 446 |
+
function_count = contract_code.count('function')
|
| 447 |
+
modifier_count = contract_code.count('modifier')
|
| 448 |
+
pragma_count = contract_code.count('pragma')
|
| 449 |
+
|
| 450 |
+
# Generate comprehensive report
|
| 451 |
+
report = f"""# π‘οΈ Smart Contract Security Analysis Report
|
| 452 |
+
|
| 453 |
+
## π Analysis Overview
|
| 454 |
+
**Analysis Method**: {analysis_method}
|
| 455 |
+
**Model Used**: {hf_model if analyzer else 'Rule-Based Analysis Engine'}
|
| 456 |
+
**Timestamp**: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}
|
| 457 |
+
**Analysis Tool**: Xyizko Smart Contract Analyzer (MCP-Enabled)
|
| 458 |
+
|
| 459 |
+
## π Contract Metrics
|
| 460 |
+
- **Lines of Code**: {len(lines)}
|
| 461 |
+
- **Functions**: {function_count}
|
| 462 |
+
- **Modifiers**: {modifier_count}
|
| 463 |
+
- **Pragma Statements**: {pragma_count}
|
| 464 |
+
- **Code Size**: {len(contract_code)} characters
|
| 465 |
+
|
| 466 |
+
## π‘οΈ Security Vulnerability Assessment
|
| 467 |
+
{security_result}
|
| 468 |
+
|
| 469 |
+
## π― Risk Assessment & Scoring
|
| 470 |
+
{risk_result}
|
| 471 |
+
|
| 472 |
+
## π Code Quality Analysis
|
| 473 |
+
{quality_result}
|
| 474 |
+
|
| 475 |
+
## π Executive Summary & Recommendations
|
| 476 |
+
|
| 477 |
+
### π¨ Immediate Actions Required:
|
| 478 |
+
- Review and address any CRITICAL or HIGH severity vulnerabilities
|
| 479 |
+
- Implement recommended security improvements
|
| 480 |
+
- Add missing input validations and access controls
|
| 481 |
+
|
| 482 |
+
### π§ Development Best Practices:
|
| 483 |
+
- Follow Solidity security patterns and conventions
|
| 484 |
+
- Implement comprehensive testing including edge cases
|
| 485 |
+
- Consider formal verification for critical functions
|
| 486 |
+
|
| 487 |
+
### ποΈ Deployment Readiness:
|
| 488 |
+
- {"β οΈ NOT READY: Address critical issues before deployment" if "CRITICAL" in security_result else "β
Ready for thorough testing and audit review"}
|
| 489 |
+
- Professional security audit recommended before mainnet deployment
|
| 490 |
+
- Implement emergency pause mechanisms for production contracts
|
| 491 |
+
|
| 492 |
+
---
|
| 493 |
+
**Analysis powered by Xyizko Smart Contract Analyzer**
|
| 494 |
+
*MCP-enabled AI tool for comprehensive smart contract security assessment*
|
| 495 |
+
"""
|
| 496 |
+
|
| 497 |
+
return report
|
| 498 |
+
|
| 499 |
+
except Exception as e:
|
| 500 |
+
return f"""# β Smart Contract Analysis Failed
|
| 501 |
+
|
| 502 |
+
**Error**: {str(e)}
|
| 503 |
+
**Timestamp**: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}
|
| 504 |
+
|
| 505 |
+
## Troubleshooting:
|
| 506 |
+
- Ensure contract code is valid Solidity
|
| 507 |
+
- Check HuggingFace token if using AI analysis
|
| 508 |
+
- Try with a different model name
|
| 509 |
+
- Contact support if the issue persists
|
| 510 |
+
|
| 511 |
+
---
|
| 512 |
+
*Xyizko Smart Contract Analyzer - MCP Tool*
|
| 513 |
+
"""
|
| 514 |
+
|
| 515 |
+
# --- Smart Contract Analysis Tab (Unchanged) ---
|
| 516 |
|
| 517 |
|
| 518 |
def upload_tab():
|
|
|
|
| 570 |
if len(content) > 10000:
|
| 571 |
content = content[:10000] + "\n// ... (truncated for analysis)"
|
| 572 |
|
| 573 |
+
progress(0.3, desc="π€ Running comprehensive analysis...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 574 |
|
| 575 |
+
# Use the same MCP function for consistency
|
| 576 |
+
analysis_result = analyze_smart_contract_mcp(
|
| 577 |
+
content, hf_token, hf_model)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 578 |
|
| 579 |
progress(0.9, desc="πΎ Creating downloadable report...")
|
| 580 |
|
|
|
|
| 583 |
report_content = f"""# Smart Contract Security Analysis Report
|
| 584 |
**Generated by**: Xyizko Smart Contract Analyzer
|
| 585 |
**Date**: {datetime.datetime.now().strftime("%Y-%m-%d at %H:%M:%S")}
|
|
|
|
|
|
|
| 586 |
|
| 587 |
{analysis_result}
|
| 588 |
|
|
|
|
| 599 |
f.write(report_content)
|
| 600 |
|
| 601 |
return (
|
| 602 |
+
"β
Analysis completed successfully!",
|
| 603 |
analysis_result,
|
| 604 |
gr.update(visible=True, value=report_filename)
|
| 605 |
)
|
|
|
|
| 634 |
label="π€ Hugging Face Model",
|
| 635 |
placeholder="microsoft/DialoGPT-medium",
|
| 636 |
value="microsoft/DialoGPT-medium",
|
| 637 |
+
info="Recommended: microsoft/DialoGPT-medium (Lightweight & Reliable)"
|
| 638 |
)
|
| 639 |
|
| 640 |
with gr.Column(scale=1):
|
|
|
|
| 672 |
outputs=[status_output, analysis_output, download_file]
|
| 673 |
)
|
| 674 |
|
| 675 |
+
# --- MCP Integration Tab ---
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def mcp_integration_tab():
|
| 679 |
+
"""Simple MCP Integration and Testing Tab"""
|
| 680 |
+
|
| 681 |
+
mcp_info = """
|
| 682 |
+
# π MCP Integration - One Powerful Tool
|
| 683 |
+
|
| 684 |
+
This Smart Contract Analyzer provides **one comprehensive MCP tool** that AI assistants can use.
|
| 685 |
+
|
| 686 |
+
## π‘οΈ `analyze_smart_contract` - The Complete Security Tool
|
| 687 |
+
|
| 688 |
+
**What it does:**
|
| 689 |
+
- β
**Security Vulnerability Detection** (reentrancy, access control, etc.)
|
| 690 |
+
- β
**Risk Assessment & Scoring** (1-10 scale with detailed factors)
|
| 691 |
+
- β
**Code Quality Analysis** (best practices, optimization opportunities)
|
| 692 |
+
- β
**Actionable Recommendations** (specific steps to fix issues)
|
| 693 |
+
- β
**Always Works** (AI-powered with intelligent fallback)
|
| 694 |
+
|
| 695 |
+
**Parameters:**
|
| 696 |
+
- `contract_code` (required): Your Solidity smart contract code
|
| 697 |
+
- `hf_token` (optional): HuggingFace API token for AI analysis
|
| 698 |
+
- `hf_model` (optional): Model name (default: microsoft/DialoGPT-medium)
|
| 699 |
+
|
| 700 |
+
## π For AI Assistants (Claude, etc.):
|
| 701 |
+
|
| 702 |
+
**Claude Desktop Config:**
|
| 703 |
+
```json
|
| 704 |
+
{
|
| 705 |
+
"mcpServers": {
|
| 706 |
+
"smart-contract-analyzer": {
|
| 707 |
+
"command": "npx",
|
| 708 |
+
"args": ["-y", "@modelcontextprotocol/server-gradio", "YOUR_HF_SPACE_URL"]
|
| 709 |
+
}
|
| 710 |
+
}
|
| 711 |
+
}
|
| 712 |
+
```
|
| 713 |
+
|
| 714 |
+
**Example Usage:**
|
| 715 |
+
```
|
| 716 |
+
"Analyze this smart contract for security issues:
|
| 717 |
+
|
| 718 |
+
pragma solidity ^0.8.0;
|
| 719 |
+
contract MyContract {
|
| 720 |
+
// Your contract code here
|
| 721 |
+
}"
|
| 722 |
+
```
|
| 723 |
+
|
| 724 |
+
**Benefits:**
|
| 725 |
+
- π― **Simple**: One tool does everything
|
| 726 |
+
- π‘οΈ **Reliable**: Always works (even without API tokens)
|
| 727 |
+
- π **Fast**: Lightweight dependencies
|
| 728 |
+
- π **Comprehensive**: Complete security assessment
|
| 729 |
+
"""
|
| 730 |
+
|
| 731 |
+
def test_mcp_tool(contract_code, hf_token, hf_model):
|
| 732 |
+
"""Test the MCP tool directly"""
|
| 733 |
+
if not contract_code.strip():
|
| 734 |
+
return "β Please provide contract code to test the MCP tool"
|
| 735 |
+
|
| 736 |
+
try:
|
| 737 |
+
result = analyze_smart_contract_mcp(
|
| 738 |
+
contract_code, hf_token, hf_model)
|
| 739 |
+
return result
|
| 740 |
+
except Exception as e:
|
| 741 |
+
return f"β MCP Tool Error: {str(e)}"
|
| 742 |
+
|
| 743 |
+
def generate_claude_config(hf_space_url):
|
| 744 |
+
"""Generate Claude Desktop configuration"""
|
| 745 |
+
if not hf_space_url.strip():
|
| 746 |
+
hf_space_url = "https://your-username-smart-contract-analyzer.hf.space"
|
| 747 |
+
|
| 748 |
+
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}}'''
|
| 749 |
+
return config
|
| 750 |
+
|
| 751 |
+
with gr.Column():
|
| 752 |
+
gr.Markdown(mcp_info)
|
| 753 |
+
|
| 754 |
+
gr.Markdown("## π§ͺ Test the MCP Tool")
|
| 755 |
+
|
| 756 |
+
with gr.Row():
|
| 757 |
+
with gr.Column(scale=2):
|
| 758 |
+
test_contract = gr.Textbox(
|
| 759 |
+
label="π Contract Code",
|
| 760 |
+
placeholder="""pragma solidity ^0.8.0;
|
| 761 |
+
|
| 762 |
+
contract TestContract {
|
| 763 |
+
address owner;
|
| 764 |
+
mapping(address => uint) balances;
|
| 765 |
+
|
| 766 |
+
function withdraw() public {
|
| 767 |
+
uint amount = balances[msg.sender];
|
| 768 |
+
(bool success, ) = msg.sender.call{value: amount}("");
|
| 769 |
+
balances[msg.sender] = 0;
|
| 770 |
+
}
|
| 771 |
+
}""",
|
| 772 |
+
lines=12
|
| 773 |
+
)
|
| 774 |
+
|
| 775 |
+
test_token = gr.Textbox(
|
| 776 |
+
label="π HF Token (Optional)",
|
| 777 |
+
placeholder="hf_xxxxxxxxx (leave empty for rule-based analysis)",
|
| 778 |
+
type="password"
|
| 779 |
+
)
|
| 780 |
+
|
| 781 |
+
test_model = gr.Textbox(
|
| 782 |
+
label="π€ Model (Optional)",
|
| 783 |
+
placeholder="microsoft/DialoGPT-medium",
|
| 784 |
+
value="microsoft/DialoGPT-medium"
|
| 785 |
+
)
|
| 786 |
+
|
| 787 |
+
with gr.Column(scale=1):
|
| 788 |
+
test_btn = gr.Button(
|
| 789 |
+
"π§ͺ Test MCP Tool",
|
| 790 |
+
variant="primary",
|
| 791 |
+
size="lg"
|
| 792 |
+
)
|
| 793 |
+
|
| 794 |
+
gr.Markdown("### π Generate Config")
|
| 795 |
+
|
| 796 |
+
space_url = gr.Textbox(
|
| 797 |
+
label="π Your HF Space URL",
|
| 798 |
+
placeholder="https://your-space.hf.space"
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
config_btn = gr.Button(
|
| 802 |
+
"π Generate Claude Config",
|
| 803 |
+
variant="secondary"
|
| 804 |
+
)
|
| 805 |
+
|
| 806 |
+
test_output = gr.Textbox(
|
| 807 |
+
label="π MCP Tool Test Results",
|
| 808 |
+
lines=25,
|
| 809 |
+
show_copy_button=True
|
| 810 |
+
)
|
| 811 |
+
|
| 812 |
+
claude_config = gr.Textbox(
|
| 813 |
+
label="π Claude Desktop Configuration",
|
| 814 |
+
lines=12,
|
| 815 |
+
show_copy_button=True
|
| 816 |
+
)
|
| 817 |
+
|
| 818 |
+
test_btn.click(
|
| 819 |
+
fn=test_mcp_tool,
|
| 820 |
+
inputs=[test_contract, test_token, test_model],
|
| 821 |
+
outputs=[test_output]
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
config_btn.click(
|
| 825 |
+
fn=generate_claude_config,
|
| 826 |
+
inputs=[space_url],
|
| 827 |
+
outputs=[claude_config]
|
| 828 |
+
)
|
| 829 |
+
|
| 830 |
+
# --- Simple MCP Metadata ---
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
def add_mcp_metadata():
|
| 834 |
+
"""Simple MCP metadata for the single tool"""
|
| 835 |
+
return {
|
| 836 |
+
"mcp_tools": [
|
| 837 |
+
{
|
| 838 |
+
"name": "analyze_smart_contract",
|
| 839 |
+
"description": "Comprehensive smart contract security analysis with vulnerability detection, risk assessment, and code quality evaluation",
|
| 840 |
+
"parameters": {
|
| 841 |
+
"contract_code": {
|
| 842 |
+
"type": "string",
|
| 843 |
+
"required": True,
|
| 844 |
+
"description": "Solidity smart contract source code to analyze"
|
| 845 |
+
},
|
| 846 |
+
"hf_token": {
|
| 847 |
+
"type": "string",
|
| 848 |
+
"default": "",
|
| 849 |
+
"description": "Optional HuggingFace API token for AI-powered analysis"
|
| 850 |
+
},
|
| 851 |
+
"hf_model": {
|
| 852 |
+
"type": "string",
|
| 853 |
+
"default": "microsoft/DialoGPT-medium",
|
| 854 |
+
"description": "HuggingFace model name for AI analysis"
|
| 855 |
+
}
|
| 856 |
+
}
|
| 857 |
+
}
|
| 858 |
+
]
|
| 859 |
+
}
|
| 860 |
|
| 861 |
# /////////////////////////////////////////////////////////////////////////////////
|
| 862 |
# --- Main Demo UI Function ---
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
with gr.Blocks(
|
| 866 |
+
theme=gr.themes.Ocean(),
|
| 867 |
+
title="Xyizko - Smart Contract Analyzer",
|
| 868 |
+
**add_mcp_metadata()
|
| 869 |
+
) as demo:
|
| 870 |
|
| 871 |
with gr.Tab("π Introduction"):
|
| 872 |
app_intro()
|
|
|
|
| 874 |
with gr.Tab("π Contract Analyzer"):
|
| 875 |
upload_tab()
|
| 876 |
|
| 877 |
+
with gr.Tab("π MCP Integration"):
|
| 878 |
+
mcp_integration_tab()
|
| 879 |
+
|
| 880 |
if __name__ == "__main__":
|
| 881 |
+
print("π Starting Xyizko Smart Contract Analyzer...")
|
| 882 |
+
print("π MCP Integration: ENABLED (Single Powerful Tool)")
|
| 883 |
+
print("π€ AI Analysis: SmolAgents + HF API with Fallback")
|
| 884 |
+
print("β‘ Lightweight: No transformers/torch dependencies")
|
| 885 |
+
print("π‘ Deploy to HuggingFace Spaces for public MCP access!")
|
| 886 |
+
|
| 887 |
+
demo.launch(
|
| 888 |
+
share=False,
|
| 889 |
+
server_name="0.0.0.0",
|
| 890 |
+
show_error=True
|
| 891 |
+
)
|
requirements.txt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
-
|
| 2 |
-
huggingface_hub
|
| 3 |
-
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
huggingface_hub
|
| 3 |
+
smolagents
|