The Complete AI Coding Safety Net - Verify, Enforce, Remember
Project description
CodeShield
An intelligent security layer for AI-generated code. CodeShield validates, formats, and secures code before it enters your production environment, acting as a firewall for your development workflow.
Built for AI Vibe Coding Hackathon 2026 โ Stop getting betrayed by 90% correct code.
๐ฏ What CodeShield Does
CodeShield intercepts AI-generated code and ensures it's:
- Safe โ No malicious imports, infinite loops, or dangerous operations
- Correct โ Syntax validated, missing imports detected and auto-fixed
- Consistent โ Matches your codebase's naming conventions
- Efficient โ Optimized token usage with caching and local processing
๐๏ธ Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CodeShield โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โ
โ โ TrustGate โ โ StyleForge โ โ ContextVault โ โ
โ โ (Security) โ โ (Style) โ โ (Memory) โ โ
โ โโโโโโโโฌโโโโโโโโ โโโโโโโโฌโโโโโโโโ โโโโโโโโโโฌโโโโโโโโโโ โ
โ โ โ โ โ
โ โโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โโโโโโโโโโผโโโโโโโโโ โ
โ โ LLM Client โ โ
โ โ (Multi-Provider)โ โ
โ โโโโโโโโโโฌโโโโโโโโโ โ
โ โ โ
โ โโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโ โ
โ โ โ โ โ
โ โโโโโโผโโโโโ โโโโโโโผโโโโโโ โโโโโโโผโโโโโโ โ
โ โCometAPI โ โ Novita.ai โ โ AIML API โ โ
โ โ(Primary)โ โ(Secondary)โ โ(Fallback) โ โ
โ โโโโโโโโโโโ โโโโโโโโโโโโโ โโโโโโโโโโโโโ โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Token Optimizer โ Metrics Collector โ LeanMCP โ Daytona โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โจ Core Features
๐ก๏ธ TrustGate โ Security Verification
Validates generated code in an isolated sandbox environment:
| Feature | Description |
|---|---|
| Syntax Validation | AST parsing to catch syntax errors before execution |
| Import Detection | Identifies missing imports with auto-fix capability |
| Undefined Names | Detects potentially undefined variables |
| Sandbox Execution | Runs code in Daytona's isolated environment |
| Confidence Scoring | 0-100% confidence score based on issue severity |
| Auto-Fix | Automatically adds missing imports |
from codeshield.trustgate.checker import verify_code
code = """
def fetch_data(url):
return requests.get(url).json()
"""
result = verify_code(code, auto_fix=True)
print(f"Valid: {result.is_valid}") # False (missing import)
print(f"Confidence: {result.confidence_score:.0%}") # 80%
print(result.fixed_code) # Includes 'import requests'
Detection Capabilities:
- โ Missing standard library imports (os, json, re, etc.)
- โ Missing third-party imports (requests, numpy, pandas, etc.)
- โ Syntax errors (missing colons, unmatched brackets)
- โ Indentation errors
- โ Undefined variable usage
๐จ StyleForge โ Convention Enforcement
Analyzes your codebase to detect and enforce naming conventions:
| Feature | Description |
|---|---|
| Pattern Detection | Automatically detects snake_case, camelCase, PascalCase |
| Codebase Analysis | Scans up to 50 files to determine dominant style |
| Auto-Correction | Converts names to match project conventions |
| Typo Detection | Finds similar existing names that might be typos |
from codeshield.styleforge.corrector import check_style
code = """
def GetUserData(userName):
totalValue = calculateTotal(userName)
return totalValue
"""
result = check_style(code, codebase_path="./src")
print(result.conventions_detected) # {'functions': 'snake_case', ...}
print(result.corrected_code) # Uses snake_case throughout
Supported Conventions:
snake_caseโ Python standard (PEP 8)camelCaseโ JavaScript/Java stylePascalCaseโ Class namesSCREAMING_SNAKE_CASEโ Constants
๐พ ContextVault โ State Persistence
Saves your development state like a game save file:
| Feature | Description |
|---|---|
| State Capture | Saves open files, cursor position, notes |
| SQLite Storage | Persistent local database |
| Instant Restore | One-click context restoration |
| AI Briefing | LLM-generated summary when restoring |
from codeshield.contextvault.capture import save_context, list_contexts
from codeshield.contextvault.restore import restore_context
# Save current state
save_context(
name="auth-refactor",
files=["src/auth.py", "tests/test_auth.py"],
cursor={"file": "src/auth.py", "line": 42, "column": 10},
notes="Fixing token expiration logic"
)
# List all contexts
contexts = list_contexts()
# Restore with AI briefing
result = restore_context("auth-refactor")
print(result["briefing"]) # "You were working on auth token logic..."
โก Token Efficiency โ Up to 90% Savings
Advanced optimization system to minimize LLM token usage:
| Optimization | Savings | How It Works |
|---|---|---|
| Local Processing | 100% | Fix common imports without LLM calls |
| Prompt Compression | 40-60% | Shorter prompts, same results |
| Dynamic max_tokens | 50-75% | Adaptive limits based on task |
| Model Tiering | 30-50% | Cheap models for simple tasks |
| Response Caching | 100% | SQLite cache for repeated requests |
from codeshield.utils.token_optimizer import LocalProcessor, get_token_optimizer
# Local fix (0 tokens!)
code = "x = json.loads(data)"
issues = ["Missing import: json"]
if LocalProcessor.can_fix_locally(code, issues):
fixed = LocalProcessor.fix_locally(code, issues)
# Result: "import json\nx = json.loads(data)"
# Tokens used: 0
# Check efficiency stats
optimizer = get_token_optimizer()
stats = optimizer.get_stats()
print(f"Cache hit rate: {stats['cache_hit_rate']}%")
print(f"Tokens saved: {stats['tokens_saved_by_cache']}")
Supported Local Fixes (35+ imports):
json, os, sys, re, math, random, datetime, time, pathlib, typing, dataclasses, collections, itertools, functools, requests, httpx, asyncio, logging, subprocess, tempfile, shutil, glob, csv, sqlite3, hashlib, base64, copy, io, threading, uuid, enum, abc, contextlib, pydantic, fastapi, flask, numpy, pandas, pytest
๐ Metrics & Observability
Real-time, transparent statistics tracking:
from codeshield.utils.metrics import get_metrics
metrics = get_metrics()
summary = metrics.get_summary()
# TrustGate metrics
print(f"Detection rate: {summary['trustgate']['detection_rate']}%")
print(f"Fix success rate: {summary['trustgate']['fix_success_rate']}%")
print(f"Sandbox success rate: {summary['trustgate']['sandbox_success_rate']}%")
# Token metrics
print(f"Token efficiency: {summary['tokens']['token_efficiency']}")
print(f"Estimated cost: ${summary['tokens']['estimated_cost_usd']}")
Tracked Metrics:
- TrustGate: verifications, detections, fixes, sandbox results
- StyleForge: checks, conventions detected, corrections
- ContextVault: saves, restores, success rates
- Tokens: input/output, efficiency ratio, cost estimates
๐ Integrations
CodeShield requires these services for full functionality:
| Service | Purpose | Environment Variable |
|---|---|---|
| CometAPI | Primary LLM (100+ models) | COMETAPI_KEY |
| Novita.ai | Secondary LLM (cost-effective) | NOVITA_API_KEY |
| AIML API | Fallback LLM | AIML_API_KEY |
| Daytona | Sandbox execution | DAYTONA_API_KEY, DAYTONA_API_URL |
| LeanMCP | MCP deployment & observability | See LeanMCP Deployment |
๐ LeanMCP Deployment
CodeShield can be deployed to LeanMCP Platform for production-grade MCP infrastructure with built-in observability.
Quick Deploy
# Install LeanMCP CLI
npm install -g @leanmcp/cli
# Login to LeanMCP
leanmcp login
# Deploy CodeShield MCP Server
cd leanmcp
npm install
leanmcp deploy .
Your MCP server will be live at https://codeshield.leanmcp.link/mcp
What You Get
| Feature | Description |
|---|---|
| Edge Deployment | Auto-scaling across 30+ global regions |
| Built-in Monitoring | Tool analytics, latency metrics, error tracking |
| Zero DevOps | No infrastructure to manage |
| MCP Protocol | Full support for Claude, Cursor, Windsurf, etc. |
Architecture
MCP Clients โ LeanMCP Platform โ CodeShield TypeScript MCP โ Python Backend
(Edge Deployment) (leanmcp/ folder) (api_server.py)
Connect Your MCP Client
Claude Desktop (claude_desktop_config.json):
{
"mcpServers": {
"codeshield": {
"url": "https://codeshield.leanmcp.link/mcp"
}
}
}
See leanmcp/README.md for full deployment documentation
๐ Installation
Prerequisites
- Python 3.9+
- Node.js 18+ (for frontend)
Setup
# Clone repository
git clone https://github.com/Erebuzzz/CodeShield.git
cd CodeShield
# Install Python dependencies
pip install -e .
# Configure environment
cp .env.example .env
# Edit .env with your API keys
# (Optional) Install frontend dependencies
cd frontend && npm install
Environment Variables
# .env
COMETAPI_KEY=sk-your-cometapi-key
NOVITA_API_KEY=sk_your-novita-key
AIML_API_KEY=your-aiml-key
DAYTONA_API_KEY=dtn_your-daytona-key
DAYTONA_API_URL=https://app.daytona.io/api
LEANMCP_KEY=leanmcp_your-key
๐ Usage
Python API
# Security verification
from codeshield.trustgate.checker import verify_code
result = verify_code("print('hello')", auto_fix=True)
# Full sandbox verification
from codeshield.trustgate.sandbox import full_verification
result = full_verification("print('hello')")
# Style checking
from codeshield.styleforge.corrector import check_style
result = check_style("def MyFunc(): pass", "./src")
# Context management
from codeshield.contextvault.capture import save_context
save_context(name="my-task", files=["main.py"])
REST API
# Start server
python -m uvicorn codeshield.api_server:app --reload
# Verify code
curl -X POST http://localhost:8000/api/verify \
-H "Content-Type: application/json" \
-d '{"code": "print(x)", "auto_fix": true}'
# Check style
curl -X POST http://localhost:8000/api/style \
-H "Content-Type: application/json" \
-d '{"code": "def MyFunc(): pass", "codebase_path": "."}'
# Get metrics
curl http://localhost:8000/api/metrics
# Get token efficiency
curl http://localhost:8000/api/tokens/efficiency
MCP Server (Claude/Cursor)
Add to your MCP settings:
{
"mcpServers": {
"codeshield": {
"command": "python",
"args": ["-m", "codeshield.mcp.server"],
"cwd": "${workspaceFolder}",
"env": {
"PYTHONPATH": "${workspaceFolder}/src"
}
}
}
}
Available MCP Tools:
| Tool | Description |
|---|---|
verify_code |
Fast static analysis |
full_verify |
Static + sandbox execution |
check_style |
Convention enforcement |
save_context |
Save coding state |
restore_context |
Restore with AI briefing |
list_contexts |
List saved contexts |
mcp_health |
Server health check |
test_llm_connection |
Test LLM providers |
๐งช Testing
# Run all tests (70 tests)
pytest tests/ -v
# Run specific test suites
pytest tests/test_trustgate.py -v
pytest tests/test_styleforge.py -v
pytest tests/test_comprehensive.py -v
# Quick demo
python test_quick.py
# Token efficiency demo
python demo_token_efficiency.py
๐ Project Structure
CodeShield/
โโโ src/codeshield/
โ โโโ trustgate/ # Security verification
โ โ โโโ checker.py # Syntax, import, undefined detection
โ โ โโโ sandbox.py # Daytona sandbox integration
โ โโโ styleforge/ # Style enforcement
โ โ โโโ corrector.py # Convention detection & correction
โ โโโ contextvault/ # State persistence
โ โ โโโ capture.py # Save context
โ โ โโโ restore.py # Restore with briefing
โ โโโ mcp/ # MCP server (Python)
โ โ โโโ server.py # FastMCP implementation
โ โโโ utils/
โ โ โโโ llm.py # Multi-provider LLM client
โ โ โโโ metrics.py # Statistics tracking
โ โ โโโ token_optimizer.py # Token efficiency
โ โ โโโ daytona.py # Sandbox client
โ โ โโโ leanmcp.py # Observability client
โ โโโ api_server.py # FastAPI HTTP server
โ โโโ cli.py # Command-line interface
โโโ leanmcp/ # LeanMCP TypeScript MCP Server
โ โโโ main.ts # Entry point
โ โโโ leanmcp.config.js # Deployment config
โ โโโ mcp/ # MCP services
โ โโโ verification/ # TrustGate tools
โ โโโ styleforge/ # Style tools
โ โโโ contextvault/ # Context tools
โ โโโ health/ # Health & metrics
โโโ frontend/ # React/TypeScript UI
โโโ tests/ # Comprehensive test suite
โโโ examples/ # Sample code
๐ง API Endpoints
Core Endpoints
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/health |
Server health check |
POST |
/api/verify |
Verify code |
POST |
/api/style |
Check style conventions |
POST |
/api/context/save |
Save context |
POST |
/api/context/restore |
Restore context |
GET |
/api/contexts |
List contexts |
Observability Endpoints
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/metrics |
Full metrics summary |
GET |
/api/metrics/trustgate |
TrustGate stats |
GET |
/api/metrics/styleforge |
StyleForge stats |
GET |
/api/metrics/tokens |
Token usage |
GET |
/api/tokens/efficiency |
Optimization stats |
GET |
/api/providers/status |
LLM provider status |
GET |
/api/providers/test |
Test LLM connectivity |
GET |
/api/integrations/status |
All integrations status |
๐ค Built With
| Sponsor | Integration |
|---|---|
| Daytona | Sandboxed code execution |
| LeanMCP | MCP observability platform |
| CometAPI | Unified AI gateway |
| Novita.ai | Cost-effective inference |
๐ License
MIT License โ see LICENSE for details.
๐ Support
- ๐ Documentation
- ๐ Issue Tracker
- ๐ฌ Discussions
CodeShield โ Because AI-generated code should be verified, not trusted.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file codeshield_ai-0.1.0.tar.gz.
File metadata
- Download URL: codeshield_ai-0.1.0.tar.gz
- Upload date:
- Size: 144.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0fafa3a2f925aa90a82b48140fc7921b77d456d746453ede5c17ea7dd2ecad82
|
|
| MD5 |
bc949dceb41469d6c7071e63db0580a0
|
|
| BLAKE2b-256 |
bda8aedd4811b067cc7877d320f8a5dba2b2dfd0ef25d35c1460f42a8dcf329c
|
File details
Details for the file codeshield_ai-0.1.0-py3-none-any.whl.
File metadata
- Download URL: codeshield_ai-0.1.0-py3-none-any.whl
- Upload date:
- Size: 47.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6cbbead6aa8509bed7524c6dc76948784ffac758edb301f119cb0eb0241b194d
|
|
| MD5 |
01423dcbcfeeecab599dcc181ad7cdde
|
|
| BLAKE2b-256 |
f2cfb1ed9010d424956c439a646bacd5bb823ad81adf4ce0a679656bee388852
|