Can You Build an MCP Server with Spring Boot? Complete Java Guide to Standardized AI APIs
This article explains why the Model Context Protocol (MCP) is becoming the universal AI interface standard, compares three implementation approaches, and provides a step‑by‑step tutorial for Java developers to create a production‑ready MCP server with Spring Boot, including tool definition, registration, controller, LLM integration, and best‑practice optimizations.
Why MCP is becoming a key part of AI architecture
A typical scenario: an internal AI assistant can query calendars and Slack, and a product manager asks whether the AI can directly query transaction records. The choice of integration method determines portability and future‑proofing.
Three implementation options
REST tool : expose a custom REST endpoint and define a tool that calls it.
Pros : fast implementation (can be ready within two days).
Cons : tightly bound to a specific AI client; low portability.
Platform plugin : develop a plugin for a particular AI platform (e.g., ChatGPT Plugin).
Pros : good integration experience.
Cons : strong platform lock‑in; switching platforms requires rewriting.
MCP protocol (recommended) : expose services via the Model Context Protocol so any MCP‑compatible client can invoke them.
Pros : standardized interface, reusable across multiple AI clients, and aligned with the evolving AI ecosystem.
The essence of MCP
MCP is not merely an API; it is a protocol that lets an LLM understand a system’s capabilities. It consists of three parts:
Tools – definition of the capability.
Resources – access to underlying data.
Prompts – templates for interaction.
Building an MCP server with Spring Boot (Java practical)
Project structure
/home/project/mcp-server/
├── src/main/java/com/icoderoad/mcp/
│ ├── controller/
│ ├── service/
│ ├── tool/
│ └── config/
├── src/main/resources/
│ └── application.yml
└── pom.xmlMaven dependencies
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- Lombok (optional) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>Defining an MCP tool interface
package com.icoderoad.mcp.tool;
import java.util.Map;
/** MCP tool definition interface */
public interface McpTool {
/** Tool name */
String name();
/** Tool description */
String description();
/** Execution logic */
Object execute(Map<String, Object> input);
}Implementing a transaction‑lookup tool
package com.icoderoad.mcp.tool;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/** Simulated transaction lookup tool */
@Component
public class TransactionLookupTool implements McpTool {
@Override
public String name() { return "transaction_lookup"; }
@Override
public String description() { return "根据用户ID查询交易记录"; }
@Override
public Object execute(Map<String, Object> input) {
String userId = (String) input.get("userId");
Map<String, Object> result = new HashMap<>();
result.put("userId", userId);
result.put("amount", 1280.55);
result.put("status", "SUCCESS");
return result;
}
}Tool registry service
package com.icoderoad.mcp.service;
import com.icoderoad.mcp.tool.McpTool;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Tool registration and management */
@Service
public class ToolRegistry {
private final Map<String, McpTool> toolMap = new HashMap<>();
public ToolRegistry(List<McpTool> tools) {
for (McpTool tool : tools) {
toolMap.put(tool.name(), tool);
}
}
public McpTool getTool(String name) { return toolMap.get(name); }
}MCP request entry controller
package com.icoderoad.mcp.controller;
import com.icoderoad.mcp.service.ToolRegistry;
import com.icoderoad.mcp.tool.McpTool;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/** MCP request entry */
@RestController
@RequestMapping("/mcp")
public class McpController {
private final ToolRegistry toolRegistry;
public McpController(ToolRegistry toolRegistry) { this.toolRegistry = toolRegistry; }
@PostMapping("/invoke")
public Object invoke(@RequestBody Map<String, Object> request) {
String toolName = (String) request.get("tool");
Map<String, Object> input = (Map<String, Object>) request.get("input");
McpTool tool = toolRegistry.getTool(toolName);
if (tool == null) {
throw new RuntimeException("Tool not found: " + toolName);
}
return tool.execute(input);
}
}Full‑chain MCP call flow
Integrating LLMs: making the AI actually use the service
The LLM must receive a JSON tool description. Example:
{
"name": "transaction_lookup",
"description": "查询用户交易记录",
"input_schema": {
"type": "object",
"properties": {"userId": {"type": "string"}},
"required": ["userId"]
}
}Production‑level optimizations
Automatic tool discovery via Spring component scanning.
Security configuration (token‑based) in application.yml:
mcp:
security:
enabled: true
token: your-secret-tokenGlobal exception handling with @RestControllerAdvice:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public Map<String, Object> handle(Exception e) {
return Map.of("error", e.getMessage());
}
}Rate limiting and monitoring suggestions: gateway throttling, Prometheus + Grafana, audit logging.
Architectural comparison (REST tool vs Plugin vs MCP)
REST tool
Development cost: low
Scalability: poor
Binding degree: high (tied to a specific client)
Plugin
Development cost: medium
Scalability: average
Binding degree: very high (platform specific)
MCP
Development cost: medium
Scalability: very high
Binding degree: very low (standardized across clients)
Conclusion
When AI evolves from a conversational tool to a system entry point, interface design becomes an ecosystem concern. REST solves “can use”, Plugin solves “easy to use”, while MCP ensures that a service can be invoked by any future AI system, making Java‑based services future‑proof in an AI‑driven landscape.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
LuTiao Programming
LuTiao Programming is a friendly community offering free programming lessons. We inspire learners to explore new ideas and technologies and quickly acquire job-ready skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
