JSON2TOON MCP Server
Advanced Token-Optimized Object Notation MCP server that compresses JSON with up to 85% token reduction using AI-powered pattern detection, providing lossless compression and decompression through 12 MCP tools.
README
JSON2TOON v2.0 🚀
Advanced Token-Optimized Object Notation - The most powerful JSON compression system for AI context management.
JSON2TOON is a next-generation MCP server that revolutionizes JSON compression with AI-powered pattern detection, achieving 75-85% token reduction while maintaining perfect data integrity.
✨ Key Features
🎯 4 Compression Levels
- MINIMAL (30-40% savings): Lightning-fast key abbreviations
- STANDARD (40-60% savings): Balanced performance + compression
- AGGRESSIVE (60-75% savings): Advanced pattern optimization
- EXTREME (75-85% savings): Maximum compression with zlib
🤖 AI-Powered Pattern Detection
- 17+ Pattern Types: API responses, databases, time series, graphs, trees, and more
- Smart Strategy Selection: Automatic optimization based on data structure
- Confidence Scoring: Each pattern comes with accuracy metrics
- Compression Potential: Estimates savings before conversion
🔧 12 Advanced MCP Tools
convert_to_toon- Multi-level JSON compressionconvert_to_json- Lossless decompressionanalyze_patterns- Deep pattern analysis with AIget_optimal_strategy- AI-recommended compression plancalculate_metrics- Detailed compression statisticsbatch_convert- High-performance batch processingsmart_optimize- Auto-detect and apply best compressioncompare_levels- Side-by-side level comparisonvalidate_toon- Format validation + round-trip testingsuggest_abbreviations- Custom abbreviation generationestimate_savings- Pre-conversion savings estimationget_server_stats- Real-time performance metrics
💡 Advanced Capabilities
- 150+ Key Abbreviations (vs 68 in TOON v1.0)
- String Dictionary: De-duplication for repeated values
- Partial Schema Compression: Works with inconsistent data
- Value Pattern Compression: Optimizes timestamps, UUIDs, URLs, emails
- Reference System: Eliminates duplicate structures
- zlib Integration: Optional extreme compression
📊 Performance Benchmarks
| Data Type | Compression | Speed | Round-Trip |
|---|---|---|---|
| API Responses | 50-65% | 0.3ms/KB | ✅ Perfect |
| Database Results | 60-70% | 0.3ms/KB | ✅ Perfect |
| Time Series | 65-75% | 0.5ms/KB | ✅ Perfect |
| User Profiles | 45-55% | 0.3ms/KB | ✅ Perfect |
| Config Files | 40-55% | 0.1ms/KB | ✅ Perfect |
🚀 Quick Start
Installation
# Clone repository
git clone https://github.com/muhammedehab35/JSON2TOON-MCP.git
cd json2toon
# Install with pip
pip install -e .
# Or use Docker
docker-compose up -d
MCP Configuration
Add to your Claude Desktop config (~/.config/Claude/claude_desktop_config.json):
{
"mcpServers": {
"json2toon": {
"command": "python",
"args": ["-m", "src.mcp_server"],
"cwd": "/path/to/json2toon"
}
}
}
Docker Configuration:
{
"mcpServers": {
"json2toon": {
"command": "docker",
"args": ["run", "-i", "json2toon:2.0.0"]
}
}
}
💻 Usage Examples
Basic Conversion
from src.advanced_converter import convert_json_to_toon, convert_toon_to_json, CompressionLevel
# Simple conversion with STANDARD level
data = {
"id": 12345,
"name": "John Doe",
"email": "john@example.com",
"created_at": "2025-01-01T00:00:00Z"
}
# Convert to TOON
toon = convert_json_to_toon(data, level=CompressionLevel.STANDARD)
print(f"Compressed: {toon}")
# Convert back to JSON
original = convert_toon_to_json(toon)
print(f"Restored: {original}")
Advanced Pattern Analysis
from src.pattern_analyzer import AdvancedPatternAnalyzer
analyzer = AdvancedPatternAnalyzer()
# Analyze your data
patterns = analyzer.analyze(large_json_data)
# Get compression strategy
strategy = analyzer.get_compression_strategy(large_json_data)
print(f"Detected {len(patterns)} patterns")
print(f"Expected savings: {strategy.expected_savings * 100:.1f}%")
print(f"Recommended level: {strategy.recommended_level}")
print(f"Reasoning: {strategy.reasoning}")
Smart Optimization
from src.optimizer import SmartOptimizer
optimizer = SmartOptimizer()
# Automatic optimization with profile
result = optimizer.optimize(data, profile="balanced")
# Profiles: "speed", "balanced", "size"
print(f"Used profile: {result['profile_used']}")
print(f"Selected level: {result['level_selected']}")
print(f"Savings: {result['metrics']['savings_percent']:.1f}%")
Batch Processing
from src.advanced_converter import AdvancedTOONConverter, CompressionLevel
converter = AdvancedTOONConverter(level=CompressionLevel.AGGRESSIVE)
# Process multiple items
items = [
{"id": i, "data": f"Item {i}"}
for i in range(1000)
]
for item in items:
toon = converter.json_to_toon(item)
# Process compressed data
🔬 MCP Tools Examples
In Claude Code
1. Convert with Custom Level
Use the convert_to_toon tool with:
- json_data: <your JSON>
- level: 3 (AGGRESSIVE)
2. Analyze Patterns
Use the analyze_patterns tool to detect:
- Pattern types
- Compression potential
- Optimization recommendations
3. Compare All Levels
Use the compare_levels tool to see:
- Side-by-side comparison
- Savings per level
- Best recommendation
4. Smart Auto-Optimize
Use the smart_optimize tool with:
- json_data: <your JSON>
- profile: "size" (for maximum compression)
📖 Format Specification
TOON v2.0 Structure
{
"_toon": "2.0", // Version identifier
"_lvl": 2, // Compression level used
"d": {...}, // Compressed data
"_refs": {...}, // Optional: structure references
"_dict": {...} // Optional: string dictionary
}
Key Abbreviations (Sample)
| Original | TOON | Original | TOON | Original | TOON |
|---|---|---|---|---|---|
| id | i | eml | status | s | |
| name | n | phone | ph | created_at | ca |
| type | t | address | addr | updated_at | ua |
| value | v | username | unm | timestamp | ts |
150+ abbreviations covering common API, database, and application fields.
Value Optimizations
null→~true→T,false→F- Timestamps:
$ts:2025-01-01T00:00:00Z - UUIDs:
$uid:550e8400-e29b-41d4-a716-446655440000 - String refs:
@s0,@s1(from dictionary)
Schema Compression
Before:
[
{"id": 1, "name": "Alice", "email": "alice@test.com"},
{"id": 2, "name": "Bob", "email": "bob@test.com"},
{"id": 3, "name": "Carol", "email": "carol@test.com"}
]
After (TOON):
{
"_sch": ["i", "n", "eml"],
"_dat": [
[1, "Alice", "alice@test.com"],
[2, "Bob", "bob@test.com"],
[3, "Carol", "carol@test.com"]
]
}
Savings: ~55-60% for arrays with consistent schemas
🧪 Testing
# Run all tests
pytest tests/ -v
# With coverage
pytest tests/ --cov=src --cov-report=html
# Specific test file
pytest tests/test_converter.py -v
# Run tests in Docker
docker-compose run json2toon-server pytest tests/ -v
Test Coverage
- ✅ Converter: 100+ test cases covering all compression levels
- ✅ Pattern Analyzer: 30+ tests for all 17 pattern types
- ✅ Round-trip: Perfect data integrity verification
- ✅ Edge cases: Unicode, large numbers, special characters
- ✅ Performance: Benchmarks for all levels
🐳 Docker Deployment
Build Image
docker build -t json2toon:2.0.0 .
Run with Docker Compose
# Production mode
docker-compose up -d json2toon-server
# Development mode
docker-compose --profile dev up json2toon-dev
Docker Features
- ✅ Python 3.11 optimized image
- ✅ Non-root user for security
- ✅ Health checks
- ✅ Resource limits (2 CPU, 1GB RAM)
- ✅ Logging configuration
- ✅ Development mode with live reload
📐 Architecture
┌─────────────────────────────────────────┐
│ JSON2TOON MCP Server │
│ (v2.0) │
└─────────────┬───────────────────────────┘
│
┌─────────┼─────────┐
│ │ │
▼ ▼ ▼
┌─────────┐ ┌──────────┐ ┌──────────┐
│Advanced │ │Pattern │ │Smart │
│Converter│ │Analyzer │ │Optimizer │
└─────────┘ └──────────┘ └──────────┘
│ │ │
└─────────┴──────────────┘
│
┌─────────┼─────────┐
▼ ▼ ▼
┌──────┐ ┌──────┐ ┌──────┐
│Schema│ │String│ │Value │
│Comp │ │ Dict │ │ Comp │
└──────┘ └──────┘ └──────┘
🎯 Pattern Types Detected
- API Response - REST, GraphQL, JSON-RPC
- Database Record - CRUD, audit logs, versioned
- User Data - Profiles, auth, preferences
- Pagination - Page-based, offset-based
- Nested Address - Street, city, state, country
- Nested Coordinates - Lat/lng/alt
- Nested Dimensions - Width/height/depth
- Nested Metadata - Created/updated by, tags
- Homogeneous Array - Same-type elements
- Consistent Schema Array - Similar object structures
- Repeated Structure - Duplicate patterns
- Time Series - Temporal data sequences
- Graph Node - Network/graph structures
- Tree Structure - Hierarchical data
- Enum Values - Limited value sets
- Sparse Array - Many null/empty values
- Deep Nesting - Complex nested levels
🔧 Development
Setup Development Environment
# Install dev dependencies
pip install -e ".[dev]"
# Format code
black src/ tests/
# Lint
ruff src/ tests/
# Type check
mypy src/
Code Quality Tools
- black: Code formatting (line length: 100)
- ruff: Fast Python linter
- mypy: Static type checking (strict mode)
- pytest: Testing framework with async support
📊 Comparison with TOON v1.0
| Feature | TOON v1.0 | JSON2TOON v2.0 |
|---|---|---|
| Compression Levels | 2 | 4 |
| Key Abbreviations | 68 | 150+ |
| Pattern Types | 8 | 17+ |
| MCP Tools | 6 | 12 |
| Max Savings | 60% | 85% |
| String Dictionary | ❌ | ✅ |
| Value Compression | ❌ | ✅ |
| Partial Schema | ❌ | ✅ |
| zlib Support | ❌ | ✅ |
| AI Analysis | Basic | Advanced |
| Custom Abbreviations | ❌ | ✅ |
| Savings Estimation | ❌ | ✅ |
🤝 Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Run tests (
pytest tests/ -v) - Format code (
black src/ tests/) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
🌟 Use Cases
1. Large API Responses
Save 50-65% tokens when storing API responses in Claude conversations.
2. Database Query Results
Compress database results by 60-70% for efficient context usage.
3. Time Series Data
Achieve 65-75% compression on temporal datasets.
4. Configuration Files
Store configs in compact format with 40-55% savings.
5. Codebase Analysis
Fit more file contents in token limits when analyzing code.
6. Log Processing
Compress structured logs by 50-60% for pattern analysis.
🚦 Quick Tips
When to Use Each Level
- MINIMAL: Quick conversions, need high speed
- STANDARD: General purpose (best balance)
- AGGRESSIVE: Large datasets, high savings needed
- EXTREME: Maximum compression, archival use
Optimization Profiles
- speed: Prefer MINIMAL/STANDARD levels
- balanced: Auto-select based on data (recommended)
- size: Prefer AGGRESSIVE/EXTREME levels
Best Practices
- ✅ Analyze patterns first with
analyze_patterns - ✅ Use
smart_optimizefor automatic best results - ✅ Validate with
validate_toonafter conversion - ✅ Use
estimate_savingsbefore large batch jobs - ✅ Monitor with
get_server_statsfor metrics
pip install -e .
python -m src.mcp_server
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。
mcp-server-qdrant
这个仓库展示了如何为向量搜索引擎 Qdrant 创建一个 MCP (Managed Control Plane) 服务器的示例。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。