A production-ready Model Context Protocol (MCP) server implementation with robust error handling, tool registry system, and comprehensive monitoring.
mcp-hello-world-server/
├── pom.xml
├── src/
│ └── main/
│ └── java/
│ └── com/
│ └── example/
│ └── mcp/
│ ├── McpServer.java
│ ├── exception/
│ │ ├── McpException.java
│ │ ├── ToolNotFoundException.java
│ │ ├── ToolExecutionException.java
│ │ ├── InvalidParametersException.java
│ │ └── ProtocolException.java
│ ├── handler/
│ │ └── ErrorHandler.java
│ ├── model/
│ │ └── McpModels.java
│ ├── registry/
│ │ └── ToolRegistry.java
│ └── tool/
│ ├── McpTool.java
│ └── builtin/
│ ├── HelloTool.java
│ ├── CurrentTimeTool.java
│ ├── EchoTool.java
│ ├── MathTool.java
│ └── RandomTool.java
└── README.md
- Java Development Kit (JDK) 17 or higher
- Apache Maven 3.6 or higher
-
Create and build the project:
mkdir mcp-hello-world-server cd mcp-hello-world-server # Copy all files to their respective locations mvn clean compile
-
Run the server:
mvn exec:java # Or with custom port mvn exec:java -Dexec.args="9000"
-
Test the server:
curl http://localhost:8080/health
- Tool Registry System: Thread-safe tool management with concurrent execution
- Exception Hierarchy: Comprehensive error handling with proper MCP error codes
- Request Validation: JSON-RPC protocol compliance and input sanitization
- Centralized Error Handling: Consistent error responses across all endpoints
- hello - Multi-language greetings (English, Spanish, French, German)
- current_time - Server time in multiple formats (ISO, readable, timestamp)
- echo - Message echoing with transformations (uppercase, lowercase, reverse)
- math - Calculator (add, subtract, multiply, divide, power, sqrt, abs)
- random - Random number generator (integers, decimals, booleans)
- Health Monitoring: Detailed status endpoint with uptime tracking
- Debug Mode: Enhanced error information for development
- Graceful Shutdown: Proper resource cleanup and connection handling
- Configurable Timeouts: Tool execution limits and thread pool management
- Comprehensive Logging: Structured logging with appropriate levels
curl http://localhost:8080/health
Returns server status, uptime, tool count, and initialization state.
curl http://localhost:8080/
Comprehensive server details including features and available tools.
export MCP_DEBUG=true
curl http://localhost:8080/tools
Lists all registered tools with their schemas (debug mode only).
export PORT=8080 # Server port
export MCP_DEBUG=true # Enable debug mode
export MCP_TOOL_TIMEOUT=30 # Tool execution timeout (seconds)
export MCP_TOOL_THREADS=10 # Tool execution thread pool size
java -jar server.jar \
-Dserver.port=9000 \
-Dmcp.debug=true \
-Dmcp.tool.timeout=60
# Test invalid method
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"invalid"}'
# Test missing parameters
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"echo"}}'
# Complex calculation
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": "math-power",
"method": "tools/call",
"params": {
"name": "math",
"arguments": {"operation": "power", "a": 2, "b": 10}
}
}'
# Generate multiple random numbers
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": "random-multi",
"method": "tools/call",
"params": {
"name": "random",
"arguments": {"type": "integer", "min": 1, "max": 100, "count": 5}
}
}'
- Implement McpTool interface:
public class CustomTool implements McpTool {
@Override
public String getName() { return "custom"; }
@Override
public String getDescription() { return "Custom tool"; }
@Override
public Map<String, Object> getInputSchema() {
return Map.of("type", "object", "properties", Map.of());
}
@Override
public McpModels.CallToolResponse.CallToolResult execute(Map<String, Object> args) {
return createTextResult("Custom result");
}
}
- Register the tool:
// In McpServer.registerBuiltinTools()
toolRegistry.registerTool(new CustomTool());
- Thread Safety: Concurrent tool registration and execution
- Validation: Input schema validation and parameter checking
- Timeout Management: Configurable execution timeouts
- Error Isolation: Tool failures don't affect other tools
- Lifecycle Management: Proper resource cleanup
- JSON Schema validation for all tool inputs
- String length limits and numeric range checking
- Required parameter validation
- Request size limits (10MB default)
- Sanitized error messages in production
- Detailed stack traces only in debug mode
- Proper HTTP status codes
- JSON-RPC compliant error responses
- Bounded thread pools for tool execution
- Configurable timeouts prevent resource exhaustion
- Graceful shutdown with connection draining
- Memory-efficient request processing
- Concurrent tool execution with thread pooling
- Non-blocking request processing
- Efficient JSON serialization
- Connection pooling and reuse
- Built-in health checks with detailed metrics
- Execution timing and error rate tracking
- Resource usage monitoring
- Uptime and availability metrics
This enhanced MCP server provides a solid foundation for building production-ready Model Context Protocol implementations with enterprise-grade reliability, monitoring, and extensibility.