YashUkhare/mcp-server-template
If you are the rightful owner of mcp-server-template and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.
This document provides a comprehensive overview of a production-ready Model Context Protocol (MCP) server implemented using Java 21 and Spring Boot 3.2, designed with enterprise-grade features.
MCP Server Template - Java Spring Boot
Production-ready Model Context Protocol (MCP) server implementation using Java 21 and Spring Boot 3.2 with enterprise-grade features.
⚠️ IMPORTANT: No Login Required!
This application does NOT have a username/password login page. It uses API key authentication via HTTP headers.
- 🔓 For Development: Set
MCP_SECURITY_ENABLED=falsein.env(no API key needed) - 🔐 For Production: Set
MCP_SECURITY_ENABLED=trueand configureMCP_API_KEY - 📖 See: for 5-minute setup guide
🚀 Features
Core MCP Features
- MCP Protocol Compliance: Full implementation of MCP protocol with JSON-RPC 2.0
- Tools: Extensible tool system with sample implementations (echo, calculate)
- Resources: Resource management system with URI-based access
- Prompts: Dynamic prompt generation with parameter support
🏆 Enterprise Features (Competition Ready!)
1. Database Persistence (PostgreSQL)
- Request/Response audit logging
- Tool execution history
- API key management with expiration
- Webhook configuration storage
2. Redis Caching
- High-performance caching layer
- Configurable TTL per cache type
- Reduced database load
3. Advanced Analytics & Metrics
- Real-time metrics with Prometheus integration
- Request analytics: success rates, execution times, error distribution
- Performance trends: daily/weekly/monthly reports
- Top clients & methods tracking
- Tool execution statistics
4. Webhook System
- Event-driven architecture
- Multiple event types (tool.executed, resource.accessed, etc.)
- Automatic retry with exponential backoff
- HMAC signature verification
- Success/failure tracking
5. API Key Management
- Secure key generation with SHA-256 hashing
- Per-key rate limiting
- Key expiration support
- Usage tracking and analytics
- Admin dashboard for key management
6. Resilience & Fault Tolerance
- Circuit Breaker: Prevents cascade failures
- Retry Logic: Automatic retry with backoff
- Bulkhead: Resource isolation
- Rate Limiting: Per-client request throttling
7. Comprehensive Audit System
- Full request/response logging
- Performance monitoring
- Error tracking
- Client activity tracking
8. OpenAPI/Swagger Documentation
- Interactive API documentation at
/swagger-ui.html - Auto-generated from code
- Try-it-out functionality
9. Admin Dashboard API
- Analytics summary endpoints
- Real-time metrics
- API key CRUD operations
- Webhook management
- System health monitoring
Prerequisites
- Java 21 or higher
- Maven 3.9+
- Docker (recommended for SQL Server and Redis)
📖 Documentation
- - 5-minute setup guide (START HERE!)
- - Common issues and solutions
- - Dependency versions and compatibility
- - Database setup for all platforms
- - System architecture and design
- - Business value and ROI
Quick Start
Option 1: Docker Compose (Recommended)
- Clone and configure:
git clone <your-repo-url>
cd mcp-server
cp .env.example .env
# Edit .env and set your MCP_API_KEY (any secure string)
- Start all services (MS SQL Server, Redis, MCP Server):
docker-compose up -d
- Access the server:
- API: http://localhost:8080
- Swagger UI: http://localhost:8080/swagger-ui.html
- Health Check: http://localhost:8080/health
Note: There's no login page. The application uses API key authentication via headers (see Authentication section below).
Option 2: Local Development
Option 2: Local Development
- Start MS SQL Server and Redis:
docker-compose up sqlserver redis -d
- Configure environment:
cp .env.example .env
# Edit .env with your settings
- Build and run:
mvn clean install
mvn spring-boot:run
📊 Admin Dashboard API
Create API Key
curl -X POST http://localhost:8080/api/admin/api-keys \
-H "Content-Type: application/json" \
-H "X-API-Key: your-admin-key" \
-d '{
"clientName": "MyApp",
"description": "API key for MyApp",
"rateLimitPerMinute": 100,
"expiresInDays": 365
}'
Get Analytics Summary
curl "http://localhost:8080/api/admin/analytics/summary?startTime=2024-01-01T00:00:00&endTime=2024-12-31T23:59:59" \
-H "X-API-Key: your-admin-key"
Real-time Metrics
curl http://localhost:8080/api/admin/analytics/realtime \
-H "X-API-Key: your-admin-key"
Create Webhook
curl -X POST http://localhost:8080/api/admin/webhooks \
-H "Content-Type: application/json" \
-H "X-API-Key: your-admin-key" \
-d '{
"name": "Tool Execution Webhook",
"url": "https://your-app.com/webhook",
"eventType": "tool.executed",
"secret": "your-webhook-secret"
}'
API Endpoints
MCP Protocol Endpoint
POST /mcp
Send MCP requests following the JSON-RPC 2.0 format.
Initialize
{
"jsonrpc": "2.0",
"id": "1",
"method": "initialize",
"params": {}
}
List Tools
{
"jsonrpc": "2.0",
"id": "2",
"method": "tools/list",
"params": {}
}
Call Tool
{
"jsonrpc": "2.0",
"id": "3",
"method": "tools/call",
"params": {
"name": "echo",
"arguments": {
"message": "Hello, MCP!"
}
}
}
List Resources
{
"jsonrpc": "2.0",
"id": "4",
"method": "resources/list",
"params": {}
}
Read Resource
{
"jsonrpc": "2.0",
"id": "5",
"method": "resources/read",
"params": {
"uri": "config://server"
}
}
List Prompts
{
"jsonrpc": "2.0",
"id": "6",
"method": "prompts/list",
"params": {}
}
Get Prompt
{
"jsonrpc": "2.0",
"id": "7",
"method": "prompts/get",
"params": {
"name": "greeting",
"arguments": {
"name": "John"
}
}
}
Other Endpoints
- GET
/health- Health check endpoint - GET
/mcp/info- Server information - GET
/actuator/health- Detailed health information - GET
/actuator/metrics- Application metrics - GET
/actuator/prometheus- Prometheus metrics - GET
/swagger-ui.html- Interactive API documentation - GET
/api-docs- OpenAPI specification
Admin Endpoints (Require Admin API Key)
- POST
/api/admin/api-keys- Create new API key - GET
/api/admin/api-keys- List all API keys - DELETE
/api/admin/api-keys/{id}- Revoke API key - PUT
/api/admin/api-keys/{id}/rate-limit- Update rate limit - GET
/api/admin/analytics/summary- Get analytics summary - GET
/api/admin/analytics/realtime- Get real-time metrics - GET
/api/admin/analytics/trend- Get performance trends - POST
/api/admin/webhooks- Create webhook - GET
/api/admin/webhooks- List webhooks - DELETE
/api/admin/webhooks/{id}- Delete webhook - POST
/api/admin/webhooks/{id}/test- Test webhook
🎯 Use Cases for Business
Add the API key to your request headers:
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-H "X-API-Key: your-secret-api-key-here" \
-d '{"jsonrpc":"2.0","id":"1","method":"initialize","params":{}}'
Configuration
All configuration options can be set via environment variables or application.properties:
| Variable | Description | Default |
|---|---|---|
SERVER_PORT | Server port | 8080 |
MCP_SERVER_NAME | Server name | MCP Server Template |
MCP_SERVER_VERSION | Server version | 1.0.0 |
MCP_SECURITY_ENABLED | Enable security | true |
MCP_API_KEY | API key for authentication | (empty) |
MCP_RATE_LIMIT_PER_MINUTE | Rate limit per client | 60 |
LOG_LEVEL | Root log level | INFO |
LOG_LEVEL_APP | Application log level | DEBUG |
DATABASE_URL | MS SQL Server connection URL | jdbc:sqlserver://localhost:1433;databaseName=mcpserver;encrypt=true;trustServerCertificate=true |
DATABASE_USERNAME | Database username | sa |
DATABASE_PASSWORD | Database password | YourStrong@Passw0rd |
REDIS_HOST | Redis host | localhost |
REDIS_PORT | Redis port | 6379 |
REDIS_PASSWORD | Redis password | (empty) |
🏆 Competition Advantages
Why This Template Wins:
-
Production-Ready from Day One
- Enterprise-grade architecture
- Battle-tested patterns (Circuit Breaker, Retry, Bulkhead)
- Comprehensive error handling
-
Observable & Maintainable
- Full request/response audit trail
- Real-time metrics and analytics
- Performance trend analysis
- Swagger documentation
-
Scalable Architecture
- Redis caching for high performance
- Connection pooling (HikariCP)
- Async processing for webhooks
- Rate limiting per client
-
Business-Focused Features
- Multi-tenant support via API keys
- Usage tracking and analytics
- Webhook integration for events
- Admin dashboard for management
-
Developer Experience
- One-command setup with Docker Compose
- Interactive API documentation
- Comprehensive examples
- Clean, maintainable code
-
Security First
- Secure API key generation (SHA-256)
- HMAC webhook signatures
- Rate limiting
- Input validation
📦 What's Included
This is not just a basic template - it's a complete, production-ready solution:
| Component | Included | Business Value |
|---|---|---|
| ✅ MCP Protocol | Full JSON-RPC 2.0 | Standard compliance |
| ✅ Database Layer | PostgreSQL + JPA | Data persistence |
| ✅ Caching | Redis | 10x faster responses |
| ✅ API Management | Key generation & validation | Multi-tenant support |
| ✅ Rate Limiting | Per-key limits | Fair use & monetization |
| ✅ Analytics | Real-time + historical | Business insights |
| ✅ Webhooks | Event-driven | Easy integrations |
| ✅ Audit Logging | Complete trail | Compliance ready |
| ✅ Monitoring | Prometheus + Grafana | Operational visibility |
| ✅ Resilience | Circuit breaker, retry | High availability |
| ✅ Documentation | Swagger UI | Developer experience |
| ✅ Docker | Multi-service compose | One-command deploy |
| ✅ Kubernetes | Production manifests | Enterprise scalability |
| ✅ Admin API | Full management | Self-service portal |
Development Time Saved: 12+ weeks • Cost Savings: $44,000+ • Time to Market: 2-3 months faster
See for detailed ROI analysis.
Production Considerations
mcp-server/
├── src/main/java/com/example/mcpserver/
│ ├── McpServerApplication.java # Main application
│ ├── config/
│ │ ├── McpServerConfig.java # MCP configuration
│ │ ├── DatabaseConfig.java # Database & JPA config
│ │ ├── CacheConfig.java # Redis caching config
│ │ ├── ResilienceConfig.java # Circuit breaker config
│ │ └── OpenApiConfig.java # Swagger configuration
│ ├── controller/
│ │ ├── McpController.java # MCP protocol endpoints
│ │ ├── HealthController.java # Health checks
│ │ └── AdminController.java # Admin dashboard API
│ ├── service/
│ │ ├── McpService.java # Core MCP logic
│ │ ├── ToolService.java # Tool management
│ │ ├── ResourceService.java # Resource management
│ │ ├── PromptService.java # Prompt management
│ │ ├── AnalyticsService.java # Analytics & metrics
│ │ ├── ApiKeyService.java # API key management
│ │ ├── WebhookService.java # Webhook delivery
│ │ └── WebhookManagementService.java # Webhook CRUD
│ ├── entity/
│ │ ├── McpRequestLog.java # Request audit log
│ │ ├── ToolExecution.java # Tool execution log
│ │ ├── ApiKey.java # API key entity
│ │ └── Webhook.java # Webhook entity
│ ├── repository/
│ │ ├── McpRequestLogRepository.java
│ │ ├── ToolExecutionRepository.java
│ │ ├── ApiKeyRepository.java
│ │ └── WebhookRepository.java
│ ├── model/ # MCP protocol models
│ ├── filter/
│ │ └── SecurityFilter.java # Auth & rate limiting
│ ├── interceptor/
│ │ └── AuditInterceptor.java # Request/response audit
│ └── exception/
│ └── GlobalExceptionHandler.java # Error handling
├── src/main/resources/
│ └── application.properties
├── pom.xml
├── Dockerfile
├── docker-compose.yml
├── .env.example
├── .gitignore
└── README.md
Extending the Server
Adding a New Tool
- Add tool definition in
ToolService.listTools():
Tool.builder()
.name("myTool")
.description("My custom tool")
.inputSchema(InputSchema.builder()
.type("object")
.properties(Map.of(
"param1", PropertySchema.builder()
.type("string")
.description("Parameter description")
.build()
))
.required(List.of("param1"))
.build())
.build()
- Implement tool logic in
ToolService.callTool():
case "myTool" -> handleMyTool(arguments);
Adding a New Resource
Update ResourceService.listResources() and readResource() methods.
Adding a New Prompt
Update PromptService.listPrompts() and getPrompt() methods.
Monitoring
Prometheus Metrics
Metrics are available at /actuator/prometheus when enabled.
Health Checks
- Basic health:
/health - Detailed health:
/actuator/health
Production Considerations
- Set a strong API key in production
- Enable HTTPS using Spring Boot SSL configuration
- Configure proper logging levels (INFO or WARN for production)
- Set up monitoring using Prometheus and Grafana
- Use environment-specific profiles (dev, staging, prod)
- Configure resource limits in Docker/Kubernetes
- Set up proper backup and disaster recovery
- Enable request/response logging for audit trails
Testing
Run tests:
mvn test
Run with coverage:
mvn test jacoco:report
License
MIT License - feel free to use this template for your projects.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Support
For issues and questions, please open an issue on GitHub.