Content
# Jinja2 MCP Server
> **🚀 Production-ready MCP Protocol Jinja2 Template Rendering Server**
> Provides powerful template processing capabilities for AI applications, supporting complex JSON parameters and secure sandbox execution.
[](https://python.org)
[](https://modelcontextprotocol.io)
[](LICENSE)
[](https://github.com/WW-AI-Lab/jinja2-mcp-server)
---
## 🎯 Core Features
### 🔧 Complete MCP Protocol Support
- **Dual Transport Protocols**: Supports both stdio and StreamableHttp transport simultaneously.
- **Standard Compliance**: Fully compliant with the official MCP protocol specification.
- **AI Integration**: Seamless integration with AI models like Claude and GPT.
- **Debugging Friendly**: Supports MCP Inspector for visual debugging.
### 🛡️ Security and Performance
- **Secure Sandbox**: Multi-layer security validation to prevent malicious template execution.
- **Asynchronous Processing**: High-performance asynchronous architecture based on FastMCP.
- **Smart Caching**: Template parsing cache to enhance rendering performance.
- **Resource Limits**: Security mechanisms such as execution timeout and loop limits.
### 🎨 Feature Completeness
- **Jinja2 3.1+**: Supports all features of the latest version.
- **Complex Data**: Full support for JSON data structures.
- **File Templates**: Supports template file systems and inheritance.
- **Debugging Tools**: Template validation, syntax checking, and performance analysis.
---
## 🚀 Quick Start
### 📋 Environment Requirements
- **Python**: 3.8+ (recommended 3.12+)
- **System**: macOS / Linux / Windows
- **Memory**: Minimum 512MB, recommended 1GB+
### ⚡ One-click Installation
```bash
# Clone the project
git clone https://github.com/WW-AI-Lab/jinja2-mcp-server.git
cd jinja2-mcp-server
# Install dependencies
pip install -r requirements.txt
# Start immediately (stdio mode, suitable for AI clients)
python run_server.py --transport stdio
# Or start HTTP mode (suitable for debugging and testing)
python run_server.py --transport streamable-http --port 8123
```
### 🎮 Quick Experience
```bash
# Use MCP Inspector for visual testing
# 1. Start the HTTP server
python run_server.py --transport streamable-http --port 8123
# 2. Open MCP Inspector: https://github.com/modelcontextprotocol/inspector
# 3. Connect to: http://localhost:8123
# 4. Test the render_template tool
```
---
## 🛠️ Core Tools
### 1️⃣ render_template - Template Rendering
```json
{
"template": "Hello {{ user.name }}! You have {{ messages | length }} messages.",
"variables": {
"user": {"name": "Alice"},
"messages": [{"id": 1}, {"id": 2}]
}
}
```
**Output**: `"Hello Alice! You have 2 messages."`
### 2️⃣ render_template_file - File Template
```json
{
"template_path": "examples/templates/email.html",
"variables": {
"user": {"name": "Bob", "email": "bob@example.com"},
"items": [{"name": "Product A", "price": 29.99}]
}
}
```
### 3️⃣ validate_template - Template Validation
```json
{
"template": "{% for item in items %}{{ item.name }}{% endfor %}"
}
```
**Output**: `{"valid": true, "variables_used": ["items"], "complexity": "low"}`
### 4️⃣ list_filters - Filter List
Get all available Jinja2 filters (54 built-in filters).
### 5️⃣ get_template_info - Template Analysis
Get detailed information and performance analysis of the template.
---
## 📁 Project Structure
```
jinja2-mcp-server/
├── 🏗️ src/jinja_mcp_server/ # Core code
│ ├── mcp_server.py # FastMCP server implementation
│ ├── server.py # Entry point
│ ├── jinja/environment.py # Jinja2 environment management
│ ├── config/settings.py # Configuration system
│ ├── tools/registry.py # MCP tool registration
│ └── utils/ # Utility library
├── 📄 examples/templates/ # Example templates
│ ├── basic.html # Basic HTML template
│ ├── email.html # Email template
│ └── config.yaml # Configuration template
├── 🧪 tests/ # Test cases
├── 📚 docs/ # Project documentation
└── 🚀 run_server.py # Startup script
```
---
## 🎨 Use Cases
### 🤖 AI Application Integration
```python
# Integration with Claude/GPT
# AI models can call template rendering functions via the MCP protocol
# Supports dynamic generation of emails, reports, configuration files, etc.
```
### 📧 Email Template System
```html
<!-- examples/templates/email.html -->
<html>
<body>
<h1>Hello {{ user.name }}!</h1>
<p>Your order summary:</p>
<ul>
{% for item in items %}
<li>{{ item.name }} - ${{ item.price }}</li>
{% endfor %}
</ul>
</body>
</html>
```
### ⚙️ Configuration File Generation
```yaml
# examples/templates/config.yaml
server:
name: {{ server.name }}
port: {{ server.port }}
environment: {{ env }}
features:
{% for feature in features %}
- {{ feature }}
{% endfor %}
```
### 📊 Report Generation
```html
<!-- Dynamic report template -->
<div class="report">
<h2>{{ report.title }}</h2>
<p>Generated on: {{ now() | strftime('%Y-%m-%d') }}</p>
{% if metrics %}
<table>
{% for metric in metrics %}
<tr>
<td>{{ metric.name }}</td>
<td>{{ metric.value | round(2) }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
</div>
```
---
## ⚙️ Advanced Configuration
### Environment Variable Configuration
```bash
# Copy configuration file
cp env.example .env
# Edit configuration
JINJA_AUTOESCAPE=true
JINJA_CACHE_SIZE=400
SECURITY_MAX_LOOP_ITERATIONS=10000
LOGGING_LEVEL=INFO
```
### JSON Configuration File
```json
{
"jinja": {
"template_dirs": ["templates", "examples/templates"],
"autoescape": true,
"cache_size": 400,
"strict_undefined": false
},
"security": {
"enable_sandbox": true,
"max_template_size": 1048576,
"execution_timeout": 30,
"max_loop_iterations": 10000
},
"logging": {
"level": "INFO",
"enable_structlog": true,
"format": "json"
},
"mcp": {
"server_name": "jinja2-mcp-server",
"version": "1.0.0"
}
}
```
---
## 🧪 Development and Testing
### Setting Up Development Environment
```bash
# Clone and enter the project
git clone https://github.com/WW-AI-Lab/jinja2-mcp-server.git
cd jinja2-mcp-server
# Create a virtual environment
python -m venv .venv
source .venv/bin/activate # Linux/macOS
# .venv\Scripts\activate # Windows
# Install development dependencies
pip install -r requirements.txt
# Run tests
python -m pytest tests/ -v
# Code formatting
black src/ tests/
isort src/ tests/
# Type checking
mypy src/
```
### Performance Testing
```bash
# Basic functionality tests
python test_server.py
# MCP protocol tests
python test_mcp_tools.py
# Template file tests
python test_template_files.py
# HTTP protocol tests
python test_mcp_http.py
```
---
## 📊 Performance Metrics
### 🚀 Benchmark Performance
- **Startup Time**: < 2 seconds
- **Memory Usage**: Initial ~50MB, runtime < 256MB
- **Response Latency**: Average < 10ms
- **Concurrent Processing**: > 200 requests/second
- **Template Rendering**: Simple templates < 1ms, complex templates < 50ms
### 📈 Scalability
- **Template Cache**: Supports caching of 400 templates
- **File Size**: Maximum single template size of 1MB
- **Concurrent Connections**: Theoretically unlimited (limited by system resources)
- **Transport Protocols**: Supports both stdio and StreamableHttp dual protocols
---
## 🔧 Technical Implementation
### Core Technology Stack
```python
# Based on modern Python ecosystem
FastMCP # MCP protocol framework
Jinja2 3.1+ # Template engine
Pydantic v2 # Data validation
structlog # Structured logging
asyncio # Asynchronous processing
MarkupSafe # Safe escaping
```
### Architectural Design
```
┌─────────────────────────────────────────┐
│ MCP Clients │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ AI Models │ │ MCP Inspector│ │
│ └─────────────┘ └─────────────┘ │
└─────────┬─────────────────┬─────────────┘
│ MCP Protocol │
│ │
┌─────────▼─────────────────▼─────────────┐
│ jinja2-mcp-server │
│ ┌─────────────────────────────────┐ │
│ │ FastMCP Core │ │
│ └─────────────────────────────────┘ │
│ ┌─────────────────────────────────┐ │
│ │ MCP Tools (5 tools) │ │
│ └─────────────────────────────────┘ │
│ ┌─────────────────────────────────┐ │
│ │ Jinja2 Service Layer │ │
│ └─────────────────────────────────┘ │
│ ┌─────────────────────────────────┐ │
│ │ Infrastructure │ │
│ └─────────────────────────────────┘ │
└─────────────────────────────────────────┘
```
### Security Mechanisms
```python
# Multi-layer security protection
1. AST syntax parsing validation
2. Sandbox environment execution
3. Resource usage limits
4. Execution timeout control
5. Loop iteration limits
6. Dangerous function filtering
```
---
## 🛠️ Future Directions
### Implemented Features ✅
- [x] Complete MCP protocol support
- [x] Full feature support for Jinja2 3.1+
- [x] Dual transport protocols (stdio/HTTP)
- [x] Secure sandbox execution
- [x] Asynchronous high-performance processing
- [x] Template file system support
- [x] Detailed error diagnostics
- [x] Structured logging
---
## 📚 Documentation Resources
### 📖 Core Documentation
- **[Development Plan](docs/开发规划.md)** - Detailed development history and technical decisions.
- **[Quick Start](#-quick-start)** - 5-minute getting started guide.
- **[API Reference](#️-core-tools)** - Complete tool API documentation.
- **[Configuration Guide](#️-advanced-configuration)** - Advanced configuration options.
### 🎯 Usage Examples
- **[Basic Template](examples/templates/basic.html)** - HTML template example.
- **[Email Template](examples/templates/email.html)** - Email template example.
- **[Configuration Template](examples/templates/config.yaml)** - YAML configuration example.
### 🔧 Development Guide
- **[Contribution Guide](#-development-and-testing)** - How to participate in project development.
- **[Testing Guide](#-development-and-testing)** - Writing test cases.
- **[Performance Optimization](docs/performance.md)** - Performance tuning suggestions.
---
## 🤝 Contribution Guidelines
### 🚀 Participate in Development
1. **Fork** this repository.
2. Create a feature branch: `git checkout -b feature/amazing-feature`.
3. Commit changes: `git commit -m 'Add amazing feature'`.
4. Push the branch: `git push origin feature/amazing-feature`.
5. Submit a **Pull Request**.
### 🐛 Issue Reporting
- [Issues](https://github.com/WW-AI-Lab/jinja2-mcp-server/issues) - Bug reports and feature requests.
- [Discussions](https://github.com/WW-AI-Lab/jinja2-mcp-server/discussions) - Community discussions.
### 📋 Development Standards
- **Code Style**: Follow PEP 8, use black for formatting.
- **Type Hinting**: Use mypy for type checking.
- **Test Coverage**: New features must include test cases.
- **Documentation Updates**: Important changes require documentation updates.
---
## 📄 Open Source License
**MIT License** — Feel free to use, modify, and contribute code!
If this project helps you, please give it a ⭐ **Star** for support!
---
## 🤖 About WW-AI-Lab
This is an open-source project by **WW-AI-Lab**, focusing on:
- 🔄 **Enterprise Automation Solutions** - Browser automation, AI workflows.
- 🤖 **Agentic Workflow** - End-to-end AI business processes.
- 🖼️ **Generative AI Applications** - Multimodal models, image processing.
- 📊 **Data Insight Tools** - AI-driven data analysis.
### 💡 Project Features
- **AI-assisted Development**: This project was entirely developed in collaboration with Cursor IDE + Claude.
- **Production Ready**: Although it's an open-source project, the code quality meets production standards.
- **Open Source Sharing**: Includes complete development process documentation and best practices.
- **Learning Friendly**: Detailed technical implementation descriptions for easy learning and improvement.
### 🚀 From Open Source to Enterprise
When open-source projects prove effective in practice, we upgrade them to enterprise-level solutions:
👉 **YFGaia** - Providing more rigorous testing, documentation, and long-term maintenance.
### 📞 Contact Us
| Channel | Address | Purpose |
|---------|---------|---------|
| 📧 **Email** | [toxingwang@gmail.com](mailto:toxingwang@gmail.com) | Collaboration / Business inquiries |
| 🐦 **X (Twitter)** | [@WW_AI_Lab](https://x.com/WW_AI_Lab) | Latest updates, technical sharing |
| 💬 **WeChat** | toxingwang | In-depth communication, please specify the source when adding |
---
**Disclaimer**: This project is open-sourced under the MIT license and is intended for learning and research purposes only. For commercial support, please contact us through the channels above.
**Built with ❤️ using Python, Jinja2, FastMCP, and Cursor IDE**
Connection Info
You Might Also Like
MarkItDown MCP
Converting files and office documents to Markdown.
Time
Obtaining current time information and converting time between different...
Filesystem
Model Context Protocol Servers
Sequential Thinking
Offers a structured approach to dynamic and reflective problem-solving,...
Git
Model Context Protocol Servers
Context 7
Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors