In this example, we will build a MCP Server/Client as a proxy to existing Java Spring REST API.
Assume an existing Spring Boot REST API app with a ProductController exposing /products endpoints.
We'll add MCP support using Spring AI.
- Add Dependencies (pom.xml):
<dependencies>
<!-- Existing Spring Boot deps -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
</dependency>
</dependencies>- Configure Properties (application.properties):
spring.ai.mcp.server.enabled=true
spring.ai.mcp.server.name=product-mcp-server
spring.ai.mcp.server.transport=http # Expose over HTTP- Annotate Existing Service:
Assume existing ProductService with methods calling repo or external API.
// Filename: ProductService.java
import org.springframework.ai.mcp.Tool;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductService {
// Existing logic, e.g., repo or REST calls
@Tool(name = "get_products", description = "Retrieve all products from the existing REST API")
public List<Product> getProducts() {
// Existing code: e.g., call repo.findAll() or RestTemplate.getForList("/products")
return List.of(new Product("1", "Laptop", 999.99));
}
@Tool(name = "get_product_by_id", description = "Get a product by ID from the existing REST API")
public Product getProductById(String id) {
// Existing code: e.g., repo.findById(id) or RestTemplate.getForObject("/products/" + id)
return new Product(id, "Product " + id, 100.0);
}
}
// Filename: Product.java
public record Product(String id, String name, double price) {}- Register Tools in Main App:
// Filename: ExistingRestApp.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.ai.mcp.ToolCallbacks;
import java.util.List;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class ExistingRestApp {
public static void main(String[] args) {
SpringApplication.run(ExistingRestApp.class, args);
}
@Bean
public List<ToolCallbacks> productTools(ProductService productService) {
return List.of(ToolCallbacks.from(productService));
}
}- Run: Start the app. The MCP server exposes tools at the configured endpoint (e.g., HTTP).
- AI clients can now use get_products etc., leveraging the existing REST logic.