Ecommerce MCP Server
A production-ready Model Context Protocol (MCP) Server built with Spring Boot 4, exposing ecommerce tools — product search, cart management, order lifecycle, inventory tracking, and coupon validation — to any AI client (Claude Desktop, GitHub Copilot, Cursor, Anthropic API).
Table of Contents
- Project Introduction
- Tech Stack
- Project Structure
- Local Setup
- MCP Introduction & Core Components
- How It Works Internally
- Available Tools (15 Total)
- Endpoints Reference
- Testing with curl
- Testing with Postman
- Integrating with AI Clients
- Seed Data Reference
- Troubleshooting
1. Project Introduction
This project demonstrates how to turn a Spring Boot ecommerce backend into an MCP Server — a standardized interface that allows AI models to call backend tools directly using natural language.
Instead of building a traditional REST API that humans call, an MCP server exposes structured tools that AI agents discover and invoke autonomously. You can ask Claude:
"Search for slim fit jeans under ₹1500, add one to Arjun's cart, validate coupon FLAT20, then place the order"
…and Claude will chain searchProducts → addToCart → validateCoupon → placeOrder automatically, returning a natural language summary.
What this server covers
2. Tech Stack
3. Project Structure
ecommerce-mcp/
├── build.gradle
├── settings.gradle
└── src/
├── main/
│ ├── java/com/ecommerce/mcp/
│ │ ├── EcommerceMcpApplication.java # Entry point
│ │ ├── config/
│ │ │ ├── McpToolConfig.java # Registers all tools with Spring AI
│ │ │ └── DiagnosticController.java # GET /health
│ │ ├── model/
│ │ │ ├── Product.java # JPA entity + Category enum
│ │ │ ├── Customer.java
│ │ │ ├── Order.java # Status enum: PENDING→DELIVERED
│ │ │ ├── OrderItem.java
│ │ │ ├── CartItem.java
│ │ │ └── Coupon.java
│ │ ├── dto/
│ │ │ └── Dtos.java # All DTOs (ProductDto, OrderDto, ...)
│ │ ├── repository/
│ │ │ ├── ProductRepository.java # Custom JPQL search query
│ │ │ ├── OrderRepository.java
│ │ │ ├── CustomerRepository.java
│ │ │ ├── CartItemRepository.java
│ │ │ └── CouponRepository.java
│ │ ├── service/
│ │ │ ├── ProductService.java
│ │ │ ├── OrderService.java # Transactional order + coupon + stock
│ │ │ ├── CartService.java
│ │ │ ├── CouponService.java
│ │ │ └── CustomerService.java
│ │ ├── tool/ # ← MCP Tools (exposed to AI)
│ │ │ ├── ProductTool.java
│ │ │ ├── OrderTool.java
│ │ │ ├── CartTool.java
│ │ │ ├── InventoryTool.java
│ │ │ ├── CouponTool.java
│ │ │ └── CustomerTool.java
│ │ └── exception/
│ │ └── Exceptions.java
│ └── resources/
│ ├── application.yml # H2 + JPA + MCP config
│ └── data.sql # Seed: 3 customers, 10 products, 3 coupons
└── test/
└── java/com/ecommerce/mcp/
└── EcommerceMcpApplicationTests.java # 22 integration tests
4. Local Setup
Prerequisites
- Java 21+
- Node.js 18+ (only needed for MCP Inspector or mcp-remote)
- Git
Clone and Run
# Clone
git clone https://github.com/your-org/ecommerce-mcp.git
cd ecommerce-mcp
# Build
./gradlew build
# Run
./gradlew bootRun
The server starts on http://localhost:8080.
Verify startup
curl http://localhost:8080/health
Expected response:
{
"status": "UP",
"sse-endpoint": "GET http://localhost:8080/sse",
"message-endpoint": "POST http://localhost:8080/mcp/messages"
}
H2 Console (inspect database)
Open http://localhost:8080/h2-console in a browser:
Run Tests
./gradlew test
22 integration tests covering all 6 feature domains. All run against the H2 in-memory database with seed data.
5. MCP Introduction & Core Components
What is MCP?
Model Context Protocol (MCP) is an open standard by Anthropic that defines how AI models communicate with external tools and data sources. It gives AI agents a structured way to discover and invoke backend capabilities — similar to how a browser uses HTTP to talk to web servers, MCP defines how an AI client talks to a tool server.
AI Client (Claude) ──MCP Protocol──▶ MCP Server (Your Spring Boot App)
│
┌─────▼──────┐
│ Tools │ searchProducts()
│ │ placeOrder()
│ │ addToCart()
└─────┬──────┘
│
┌─────▼──────┐
│ Services │
│ + JPA │
│ + H2 DB │
└────────────┘
Core MCP Concepts
Key Spring AI Annotations
// Marks a method as an MCP-callable tool
@Tool(description = "Human-readable description the AI uses to decide when to call this")
public ProductDto getProduct(
@ToolParam(description = "Product ID e.g. 'prod-001'") String productId
) { ... }
The description fields are critical — the AI reads them to understand when and how to call each tool. Write them like documentation for a developer, not for a user.
Registration
All tool classes are registered in McpToolConfig:
@Bean
public ToolCallbackProvider ecommerceTools(
ProductTool productTool, OrderTool orderTool,
CartTool cartTool, InventoryTool inventoryTool,
CouponTool couponTool, CustomerTool customerTool) {
return MethodToolCallbackProvider.builder()
.toolObjects(productTool, orderTool, cartTool,
inventoryTool, couponTool, customerTool)
.build();
}
Spring AI's McpWebMvcServerAutoConfiguration picks up this bean and registers all @Tool-annotated methods as callable MCP tools.
6. How It Works Internally
Request Flow
Claude Desktop
│
│ 1. GET /sse (opens SSE stream, receives sessionId)
│◀─────────────────────────────────────────────────────
│
│ 2. POST /mcp/messages?sessionId=xxx
│ {"method": "initialize", ...}
│─────────────────────────────────────────────────────▶
│◀── response arrives on SSE stream ───────────────────
│
│ 3. POST /mcp/messages?sessionId=xxx
│ {"method": "tools/list"}
│─────────────────────────────────────────────────────▶
│◀── [{name:"searchProducts",...}, {name:"placeOrder",...}]
│
│ 4. POST /mcp/messages?sessionId=xxx
│ {"method": "tools/call", "params": {"name": "placeOrder", "arguments": {...}}}
│─────────────────────────────────────────────────────▶
│
│ Spring AI MCP Layer
│ │ dispatches to OrderTool.placeOrder()
│ │ │ calls OrderService.placeOrder()
│ │ │ │ validates stock
│ │ │ │ applies coupon
│ │ │ │ saves Order to H2
│ │ │ │ decrements Product.stockQuantity
│ │ │◀──────┘
│ │◀──────┘
│◀─────────────┘ result arrives on SSE stream
Transaction Flow for placeOrder
placeOrder()
├── Validate customer exists (CustomerRepository)
├── For each item:
│ ├── Fetch Product (ProductRepository)
│ └── Check stockQuantity >= requested
├── Calculate total amount
├── If couponCode provided:
│ ├── CouponService.getValidCoupon()
│ │ ├── Check active flag
│ │ ├── Check expiresAt
│ │ ├── Check usedCount < maxUses
│ │ └── Check total >= minOrderAmount
│ └── Calculate discount
├── Save Order + OrderItems (OrderRepository)
├── Decrement stock for each item (ProductRepository)
└── Increment coupon.usedCount (CouponRepository)
[All in one @Transactional — rolled back if any step fails]
SSE Transport Protocol (MCP spec 2024-11-05)
The spring-ai-starter-mcp-server-webmvc dependency activates SSE transport with two endpoints:
GET /sse— long-lived Server-Sent Events stream. Client connects once and keeps listening. The server pushes all JSON-RPC responses here.POST /mcp/messages?sessionId={id}— client sends all JSON-RPC requests here. ThesessionIdcomes from the initial SSE connection event.
7. Available Tools (15 Total)
ProductTool
OrderTool
CartTool
InventoryTool
CouponTool
CustomerTool
8. Endpoints Reference
JSON-RPC Methods
9. Testing with curl
Complete Test Script
Save as test-mcp.sh and run: bash test-mcp.sh
#!/bin/bash
set -e
MCP_BASE="http://localhost:8080"
MSG="$MCP_BASE/mcp/messages"
echo "════════════════════════════════════════"
echo " Ecommerce MCP Server — curl Test Suite"
echo "════════════════════════════════════════"
# ── Step 1: Open SSE stream in background, capture sessionId ────────────────
echo -e "\n[1] Connecting SSE stream..."
SSE_RESPONSE=$(curl -s --max-time 3 "$MCP_BASE/sse" || true)
SESSION_ID=$(echo "$SSE_RESPONSE" | grep -o 'sessionId=[^"&]*' | head -1 | cut -d= -f2)
if [ -z "$SESSION_ID" ]; then
echo "ERROR: Could not get sessionId from /sse"
echo "Make sure the server is running: ./gradlew bootRun"
exit 1
fi
echo "Session ID: $SESSION_ID"
call() {
local LABEL=$1
local BODY=$2
echo -e "\n────────────────────────────────────────"
echo " $LABEL"
echo "────────────────────────────────────────"
curl -s -X POST "$MSG?sessionId=$SESSION_ID" \
-H "Content-Type: application/json" \
-d "$BODY" | python3 -m json.tool 2>/dev/null || echo "(no response body)"
}
# ── Step 2: Initialize ───────────────────────────────────────────────────────
call "Initialize" '{
"jsonrpc":"2.0","method":"initialize",
"params":{
"protocolVersion":"2024-11-05",
"capabilities":{},
"clientInfo":{"name":"curl-test","version":"1.0"}
},"id":1
}'
# ── Step 3: Confirm initialized ──────────────────────────────────────────────
curl -s -X POST "$MSG?sessionId=$SESSION_ID" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"notifications/initialized"}' > /dev/null
# ── Step 4: List tools ───────────────────────────────────────────────────────
call "List All Tools" '{"jsonrpc":"2.0","method":"tools/list","id":2}'
# ── Step 5: Product Search ───────────────────────────────────────────────────
call "Search: white t-shirts under ₹500, size M" '{
"jsonrpc":"2.0","method":"tools/call",
"params":{
"name":"searchProducts",
"arguments":{"keyword":"white","category":"T_SHIRTS","maxPrice":500.0,"size":"M"}
},"id":3
}'
# ── Step 6: Get Product ──────────────────────────────────────────────────────
call "Get Product: prod-001" '{
"jsonrpc":"2.0","method":"tools/call",
"params":{"name":"getProduct","arguments":{"productId":"prod-001"}},"id":4
}'
# ── Step 7: Featured Products ────────────────────────────────────────────────
call "Featured Products" '{
"jsonrpc":"2.0","method":"tools/call",
"params":{"name":"getFeaturedProducts","arguments":{}},"id":5
}'
# ── Step 8: Check Stock ──────────────────────────────────────────────────────
call "Check Stock: prod-010 (Hoodie, L)" '{
"jsonrpc":"2.0","method":"tools/call",
"params":{"name":"checkStock","arguments":{"productId":"prod-010","size":"L"}},"id":6
}'
# ── Step 9: Low Stock Alerts ─────────────────────────────────────────────────
call "Low Stock Alerts (threshold=10)" '{
"jsonrpc":"2.0","method":"tools/call",
"params":{"name":"getLowStockAlerts","arguments":{"threshold":10}},"id":7
}'
# ── Step 10: Validate Coupon ─────────────────────────────────────────────────
call "Validate Coupon: FLAT20 for ₹1500 order" '{
"jsonrpc":"2.0","method":"tools/call",
"params":{"name":"validateCoupon","arguments":{"code":"FLAT20","orderTotal":1500.0}},"id":8
}'
# ── Step 11: Customer Profile ────────────────────────────────────────────────
call "Get Customer: cust-001" '{
"jsonrpc":"2.0","method":"tools/call",
"params":{"name":"getCustomerProfile","arguments":{"customerId":"cust-001"}},"id":9
}'
# ── Step 12: Add to Cart ─────────────────────────────────────────────────────
call "Add to Cart: 2x Navy Polo (M) for cust-001" '{
"jsonrpc":"2.0","method":"tools/call",
"params":{"name":"addToCart","arguments":{"customerId":"cust-001","productId":"prod-003","quantity":2,"size":"M"}},"id":10
}'
# ── Step 13: View Cart ───────────────────────────────────────────────────────
call "View Cart: cust-001" '{
"jsonrpc":"2.0","method":"tools/call",
"params":{"name":"viewCart","arguments":{"customerId":"cust-001"}},"id":11
}'
# ── Step 14: Place Order ─────────────────────────────────────────────────────
call "Place Order: Formal Shirt + Jeans with FLAT20" '{
"jsonrpc":"2.0","method":"tools/call",
"params":{
"name":"placeOrder",
"arguments":{
"customerId":"cust-001",
"items":[
{"productId":"prod-008","quantity":1,"size":"M"},
{"productId":"prod-005","quantity":1,"size":"32"}
],
"shippingAddress":"Hyderabad, Telangana",
"couponCode":"FLAT20"
}
},"id":12
}'
echo -e "\n════════════════════════════════════════"
echo " All tests complete!"
echo "════════════════════════════════════════"
Individual curl Commands
Open SSE connection (Terminal 1 — keep running)
curl -N http://localhost:8080/sse
# Returns: data: {"endpoint":"/mcp/messages?sessionId=abc-123..."}
# Copy the sessionId value
Set session variable (Terminal 2)
SESSION="abc-123..." # paste your sessionId here
MSG="http://localhost:8080/mcp/messages?sessionId=$SESSION"
Initialize
curl -s -X POST "$MSG" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc":"2.0",
"method":"initialize",
"params":{
"protocolVersion":"2024-11-05",
"capabilities":{},
"clientInfo":{"name":"test","version":"1.0"}
},
"id":1
}'
Confirm initialized
curl -s -X POST "$MSG" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"notifications/initialized"}'
List tools
curl -s -X POST "$MSG" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"tools/list","id":2}' | python3 -m json.tool
Search products
curl -s -X POST "$MSG" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc":"2.0","method":"tools/call",
"params":{
"name":"searchProducts",
"arguments":{"keyword":"jeans","maxPrice":1500.0,"size":"32"}
},"id":3
}' | python3 -m json.tool
Place order with coupon
curl -s -X POST "$MSG" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc":"2.0","method":"tools/call",
"params":{
"name":"placeOrder",
"arguments":{
"customerId":"cust-001",
"items":[
{"productId":"prod-008","quantity":1,"size":"M"},
{"productId":"prod-005","quantity":1,"size":"32"}
],
"shippingAddress":"Hyderabad, Telangana",
"couponCode":"FLAT20"
}
},"id":4
}' | python3 -m json.tool
Track order
curl -s -X POST "$MSG" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc":"2.0","method":"tools/call",
"params":{"name":"trackOrder","arguments":{"orderId":"ORDER_ID_HERE"}},"id":5
}' | python3 -m json.tool
Cancel order
curl -s -X POST "$MSG" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc":"2.0","method":"tools/call",
"params":{
"name":"cancelOrder",
"arguments":{"orderId":"ORDER_ID_HERE","reason":"Changed my mind"}
},"id":6
}' | python3 -m json.tool
Note: Responses appear on the SSE stream (Terminal 1), not in the POST response body.
10. Testing with Postman
Setup
- Create a new Postman Collection named Ecommerce MCP
- Add a Collection Variable:
sessionId= (leave blank for now) - Create the requests below in order
Request 1 — Open SSE Stream
GET http://localhost:8080/sse
In the response body, look for:
data: {"endpoint":"/mcp/messages?sessionId=abc-123-xyz"}
Copy the sessionId value and set it as the sessionId collection variable.
Request 2 — Initialize
POST http://localhost:8080/mcp/messages?sessionId={{sessionId}}
Content-Type: application/json
Body:
{
"jsonrpc": "2.0",
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": { "name": "postman", "version": "1.0" }
},
"id": 1
}
Request 3 — Confirm Initialized
POST http://localhost:8080/mcp/messages?sessionId={{sessionId}}
Content-Type: application/json
Body:
{ "jsonrpc": "2.0", "method": "notifications/initialized" }
Request 4 — List Tools
POST http://localhost:8080/mcp/messages?sessionId={{sessionId}}
Content-Type: application/json
Body:
{ "jsonrpc": "2.0", "method": "tools/list", "id": 2 }
Request 5 — Search Products
POST http://localhost:8080/mcp/messages?sessionId={{sessionId}}
Content-Type: application/json
Body:
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "searchProducts",
"arguments": {
"keyword": "polo",
"category": "SHIRTS",
"maxPrice": 1000.0,
"size": "M"
}
},
"id": 3
}
Request 6 — Add to Cart
Body:
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "addToCart",
"arguments": {
"customerId": "cust-002",
"productId": "prod-003",
"quantity": 1,
"size": "M"
}
},
"id": 4
}
Request 7 — Place Order
Body:
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "placeOrder",
"arguments": {
"customerId": "cust-002",
"items": [
{ "productId": "prod-003", "quantity": 1, "size": "M" },
{ "productId": "prod-001", "quantity": 2, "size": "M" }
],
"shippingAddress": "Bangalore, Karnataka",
"couponCode": "WELCOME10"
}
},
"id": 5
}
MCP Inspector (Recommended GUI Alternative)
MCP Inspector is a purpose-built browser tool that handles SSE session management automatically, giving you a clean form-based interface for each tool.
npx @modelcontextprotocol/inspector
# Opens at http://localhost:6274
Set Transport → SSE, URL → http://localhost:8080/sse, click Connect. Then browse and invoke tools from the visual UI without managing sessions manually.
11. Integrating with AI Clients
Client 1 — Claude Desktop
Claude Desktop connects to local SSE servers via the mcp-remote Node.js proxy.
Prerequisites: Node.js 18+
npm install -g mcp-remote
Config file location:
Add this config:
{
"mcpServers": {
"ecommerce-mcp": {
"command": "npx",
"args": [
"mcp-remote",
"http://127.0.0.1:8080/sse"
]
}
}
}
Steps:
- Start your Spring Boot server:
./gradlew bootRun - Edit the config file above
- Fully quit Claude Desktop (not just close window)
- Reopen Claude Desktop
- Look for the 🔨 hammer icon in the chat input — click to confirm tools are listed
Example conversations:
You: Show me all featured products
You: Search for blue jeans in size 32 under ₹1500
You: Add the Navy Polo shirt in size M to Arjun's cart (cust-001)
You: Check the stock level for prod-010
You: Place an order for cust-001 for a Formal White Shirt size M
and Slim Fit Jeans size 32, ship to Hyderabad, apply FLAT20 coupon
You: What's the status of order <orderId>?
You: Show me Arjun's last 5 orders
Client 2 — VS Code + GitHub Copilot
Requires VS Code 1.102+ and a GitHub Copilot subscription. MCP tools only work in Agent mode.
Option A — Workspace config (committed to repo, shared with team)
Create .vscode/mcp.json in your project root:
{
"servers": {
"ecommerce-mcp": {
"type": "sse",
"url": "http://localhost:8080/sse"
}
}
}
A Start button appears at the top of the file. Click it to activate the server connection.
Option B — User config (personal, available in all workspaces)
- Open Command Palette:
Ctrl+Shift+P - Run: MCP: Open User Configuration
- Add:
{
"servers": {
"ecommerce-mcp": {
"type": "sse",
"url": "http://localhost:8080/sse"
}
}
}
Using in Copilot Chat:
- Open Copilot Chat:
Ctrl+Alt+I - Select Agent from the popup menu
- Click the tools icon (top left of chat box) to see registered tools
- Use
#toolNameto reference tools explicitly, or just ask naturally
#searchProducts find all shirts under ₹1000 in size M
Place an order for customer cust-002 for 2 white t-shirts size L shipped to Bangalore
Client 3 — Cursor
Cursor uses the same format as Claude Desktop but in its own config file.
Config file: ~/.cursor/mcp.json
{
"mcpServers": {
"ecommerce-mcp": {
"command": "npx",
"args": [
"mcp-remote",
"http://127.0.0.1:8080/sse"
]
}
}
}
Verify: Cursor Settings → MCP — server should show as Connected.
Use in Composer (Ctrl+I) or Agent mode.
Client 4 — Anthropic API (direct integration)
Useful for building your own AI-powered frontend. The Anthropic API calls your MCP server from the cloud, so you need a public URL.
Expose localhost with ngrok (for testing):
ngrok http 8080
# Note the https URL e.g. https://abc123.ngrok.io
Python example:
import anthropic
client = anthropic.Anthropic(api_key="YOUR_ANTHROPIC_API_KEY")
response = client.beta.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{
"role": "user",
"content": "Search for jeans under ₹1500 in size 32 and add the cheapest one to cust-001's cart"
}],
mcp_servers=[{
"type": "url",
"url": "https://abc123.ngrok.io/sse", # your ngrok URL
"name": "ecommerce-mcp"
}],
betas=["mcp-client-2025-11-20"]
)
for block in response.content:
if block.type == "text":
print(block.text)
Node.js example:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
const response = await client.beta.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [{
role: "user",
content: "Show me all featured products and place an order for the cheapest t-shirt for cust-002"
}],
mcp_servers: [{
type: "url",
url: "https://abc123.ngrok.io/sse",
name: "ecommerce-mcp"
}],
betas: ["mcp-client-2025-11-20"]
});
console.log(response.content);
Client Comparison
12. Seed Data Reference
Customers
Products
⚠️ = LOW_STOCK (≤5 units)
Coupons
Order Status Lifecycle
PENDING → PROCESSING → SHIPPED → DELIVERED
↓
CANCELLED (only from PENDING or PROCESSING)
13. Troubleshooting
/sse or /mcp/messages returns 404
Cause: MCP servlet not registered — missing config keys.
Fix: Ensure application.yml has all three keys:
spring:
ai:
mcp:
server:
type: SYNC
sse-message-endpoint: /mcp/messages
Table "CUSTOMERS" not found on startup
Cause: data.sql runs before Hibernate creates tables.
Fix: Ensure application.yml has:
spring:
jpa:
defer-datasource-initialization: true
mcp-remote fails on Windows
Cause: Known bug where spaces in args aren't escaped.
Fix: Install globally first, then use the full path:
npm install -g mcp-remote
{
"mcpServers": {
"ecommerce-mcp": {
"command": "mcp-remote",
"args": ["http://127.0.0.1:8080/sse"]
}
}
}
Hammer icon missing in Claude Desktop
- Confirm server is running:
curl http://localhost:8080/health - Confirm config file path is correct for your OS
- Fully quit Claude Desktop (check system tray) and reopen
- Check Claude Desktop logs:
%APPDATA%\Claude\logs\(Windows) or~/Library/Logs/Claude/(macOS)
Responses not appearing in curl
Responses come back on the SSE stream (Terminal 1), not in the POST response body. Watch Terminal 1 after every POST /mcp/messages call.
License
MIT License — free to use, modify, and distribute.