atul-gupta47/spring-ai-mcp-server-demo
If you are the rightful owner of spring-ai-mcp-server-demo 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 project demonstrates the integration of Spring AI with Model Context Protocol (MCP) to create a natural language interface for REST API operations in an E-commerce Order Management System.
Spring AI MCP Server Demo - E-commerce Order Management
Overview
This project demonstrates how to integrate Spring AI with Model Context Protocol (MCP) to create a natural language interface for REST API operations. The demo showcases an E-commerce Order Management System where developers can use natural language prompts to create customers, products, and orders instead of manually crafting complex API requests.
Problem Statement
In enterprise development, testing features often requires setting up complex data through multiple API calls in a specific sequence. This process is:
- Time-consuming for developers
- Error-prone when dealing with complex request payloads
- Requires deep understanding of API contracts and business logic
- Difficult to maintain and document
Solution: MCP Server Integration
The MCP server allows developers to use natural language to:
- Create customers with complete address information
- Add products with pricing and inventory details
- Place orders with multiple products
- Query existing data
Architecture
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ MCP Client │ │ MCP Server │ │ Spring Boot │
│ (Claude/Other) │◄──►│ (This Demo) │◄──►│ REST APIs │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐
│ PostgreSQL │
│ Database │
└─────────────────┘
Technology Stack
- Spring Boot 3.2.0 - Main application framework
- Spring AI 1.0.0-M4 - AI integration and MCP server
- PostgreSQL 15 - Database
- Gradle - Build tool
- Docker - Containerization
- OpenAI GPT-3.5-turbo - Language model
API Endpoints
Customer Management
POST /api/customers- Create a new customerGET /api/customers/{id}- Get customer by IDGET /api/customers/email/{email}- Get customer by emailGET /api/customers- Get all customers
Product Management
POST /api/products- Create a new productGET /api/products/{id}- Get product by IDGET /api/products/category/{category}- Get products by categoryGET /api/products/search?name={name}- Search products by nameGET /api/products/sku/{sku}- Get product by SKUGET /api/products- Get all products
Order Management
POST /api/orders- Create a new orderGET /api/orders/{id}- Get order by IDGET /api/orders/customer/{customerId}- Get orders by customerPUT /api/orders/{id}/status?status={status}- Update order statusGET /api/orders- Get all orders
MCP Tools Available
The MCP server exposes the following tools for natural language interaction:
- create_customer - Create customers with address information
- create_product - Add products with pricing and inventory
- create_order - Place orders with multiple products
- get_customer - Retrieve customer information
- get_product - Find products by various criteria
- get_order - Get order details and history
Quick Start
Prerequisites
- Java 17 or higher
- Docker and Docker Compose
- OpenAI API key (for MCP client integration)
1. Clone and Setup
git clone <repository-url>
cd spring-ai-mcp-server-demo
2. Environment Configuration
Create a .env file in the project root:
OPENAI_API_KEY=your-openai-api-key-here
3. Run with Docker Compose
# Start the application and database
docker-compose up --build
# The application will be available at http://localhost:8080
# PostgreSQL will be available at localhost:5432
4. Alternative: Local Development
# Start PostgreSQL (if not using Docker)
docker run --name ecommerce-postgres -e POSTGRES_DB=ecommerce_demo -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 -d postgres:15
# Run the application
./gradlew bootRun
Usage Examples
Traditional API Approach
Creating a complete order scenario requires multiple API calls:
# 1. Create customer
curl -X POST http://localhost:8080/api/customers \
-H "Content-Type: application/json" \
-d '{
"firstName": "John",
"lastName": "Doe",
"email": "john.doe@example.com",
"phone": "+1-555-0123",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zipCode": "10001",
"country": "USA"
}
}'
# 2. Create products
curl -X POST http://localhost:8080/api/products \
-H "Content-Type: application/json" \
-d '{
"name": "MacBook Pro",
"description": "Apple MacBook Pro 16-inch",
"price": 2499.99,
"category": "Electronics",
"sku": "MBP-16-001",
"stockQuantity": 10
}'
# 3. Create order
curl -X POST http://localhost:8080/api/orders \
-H "Content-Type: application/json" \
-d '{
"customerId": 1,
"orderItems": [
{
"productId": 1,
"quantity": 1
}
]
}'
MCP Natural Language Approach
With MCP integration, the same scenario becomes:
"Create a customer named John Doe with email john.doe@example.com, phone +1-555-0123, and address at 123 Main St, New York, NY 10001, USA. Then add a MacBook Pro product priced at $2499.99 with SKU MBP-16-001 and 10 units in stock. Finally, create an order for John Doe with 1 MacBook Pro."
MCP Client Setup
Option 1: Claude Desktop Integration
- Install Claude Desktop application
- Add the following to your Claude Desktop configuration:
{
"mcpServers": {
"ecommerce-demo": {
"command": "java",
"args": ["-jar", "/path/to/ecommerce-mcp-demo.jar"],
"env": {
"OPENAI_API_KEY": "your-api-key"
}
}
}
}
Option 2: Local MCP Client
- Install MCP client tools:
npm install -g @modelcontextprotocol/cli
- Connect to the MCP server:
mcp connect http://localhost:8080/mcp
Testing the MCP Integration
Sample Natural Language Commands
-
Customer Creation:
- "Create a customer named Alice Smith with email alice@example.com and address in San Francisco, CA"
-
Product Management:
- "Add a wireless mouse product for $29.99 with 50 units in stock"
- "Find all products in the Electronics category"
-
Order Processing:
- "Create an order for Alice Smith with 2 wireless mice"
- "Show me all orders for customer with email alice@example.com"
-
Complex Scenarios:
- "Set up a complete e-commerce scenario: Create customer Bob Johnson in Seattle, add a gaming laptop for $1999, and place an order for 1 laptop"
Development
Project Structure
src/
├── main/
│ ├── java/com/example/ecommerce/
│ │ ├── controller/ # REST controllers
│ │ ├── dto/ # Data transfer objects
│ │ ├── entity/ # JPA entities
│ │ ├── mcp/ # MCP server implementation
│ │ ├── repository/ # Data repositories
│ │ ├── service/ # Business logic
│ │ └── config/ # Configuration classes
│ └── resources/
│ └── application.yml # Application configuration
├── test/ # Test files
└── build.gradle # Build configuration
Adding New MCP Tools
- Create a new method in
EcommerceMcpServer.java - Annotate with
@McpTool - Define parameters with
@McpTool.Parameter - Implement the business logic
- Return a Map with success status and data
Example:
@McpTool(
name = "new_tool",
description = "Description of what this tool does"
)
public Map<String, Object> newTool(
@McpTool.Parameter(description = "Parameter description") String param) {
// Implementation
return Map.of("success", true, "data", result);
}
Monitoring and Logging
The application includes comprehensive logging for:
- MCP tool invocations
- API request/response cycles
- Database operations
- Error handling
Logs are available in the console output and can be configured in application.yml.
Security Considerations
- API keys should be stored securely (environment variables)
- Input validation is implemented for all endpoints
- Database connections use connection pooling
- CORS can be configured for web client access
Performance
- Connection pooling for database operations
- Lazy loading for entity relationships
- Efficient query patterns with JPA
- Docker containerization for consistent performance
Troubleshooting
Common Issues
-
Database Connection Failed:
- Ensure PostgreSQL is running
- Check connection parameters in
application.yml - Verify database exists
-
MCP Client Connection Issues:
- Check if the application is running on port 8080
- Verify MCP server configuration
- Check OpenAI API key validity
-
Build Failures:
- Ensure Java 17+ is installed
- Check Gradle wrapper permissions
- Verify all dependencies are available
Logs and Debugging
Enable debug logging by adding to application.yml:
logging:
level:
com.example.ecommerce: DEBUG
org.springframework.ai: DEBUG
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Submit a pull request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
For questions and support:
- Create an issue in the repository
- Check the troubleshooting section
- Review the Spring AI documentation
Future Enhancements
- Add more complex business logic scenarios
- Implement authentication and authorization
- Add comprehensive test coverage
- Create web-based MCP client interface
- Add support for batch operations
- Implement caching for better performance
- Add metrics and monitoring
- Create API documentation with Swagger/OpenAPI