MCP Server
Use when exposing Spring Boot 3 application capabilities through Model Context Protocol tools, resources, or prompts. Covers Spring AI 1.x tool callback registration, transports, schemas, errors, security, and standalone MCP Java SDK compatibility.
View SKILL.mdPrefer the Spring AI MCP server starters in a Spring Boot application. Let the Spring AI BOM manage its MCP SDK dependency; do not force the standalone SDK version into a starter-based application.
Dependencies
<!-- Pick exactly one transport starter. -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-server</artifactId>
</dependency>
<!-- Remote MVC: spring-ai-starter-mcp-server-webmvc -->
<!-- Remote reactive: spring-ai-starter-mcp-server-webflux -->
For a raw SDK application without Spring AI, use the current MCP Java SDK 2.x release and follow its migration guide. Do not assume raw SDK examples match the version managed by Spring AI 1.x.
<dependency>
<groupId>io.modelcontextprotocol.sdk</groupId>
<artifactId>mcp</artifactId>
<version>2.0.0</version>
</dependency>
Spring AI 1.x tool callback integration
Spring AI 1.0.x exposes @Tool methods only through an explicit MethodToolCallbackProvider —
a bare @Component with @Tool methods registers nothing. Spring AI 1.1.x additionally supports
native @McpTool/@McpToolParam with spring.ai.mcp.server.annotation-scanner.enabled=true,
imported from org.springaicommunity.mcp.annotation (Spring AI 2.0 moved them to
org.springframework.ai.mcp.annotation). Pick one registration path per tool.
@Configuration
class McpToolsConfiguration {
@Bean
ToolCallbackProvider orderTools(OrderMcpTools tools) {
return MethodToolCallbackProvider.builder()
.toolObjects(tools)
.build();
}
}
@Component
final class OrderMcpTools {
private final OrderService orderService;
OrderMcpTools(OrderService orderService) {
this.orderService = orderService;
}
@Tool(description = "Get an order by UUID with line items and status history")
OrderResponse getOrder(
@ToolParam(description = "Order UUID") String orderId) {
return OrderResponse.from(orderService.findById(UUID.fromString(orderId)));
}
}
- Return DTOs rather than serialized JPA entities.
- Register each tool object once; duplicate providers create duplicate capabilities.
- Keep tool names and descriptions stable because clients and models depend on them.
- Bound result size, execution time, and downstream calls.
- For raw SDK code, use builders such as
CallToolResult.builder(); old constructors were removed.
Transport configuration
spring:
main:
banner-mode: "off"
ai:
mcp:
server:
name: order-service-mcp
version: 1.0.0
type: SYNC
stdio: true
Use stdio when a local client launches the jar. Use the matching MVC or WebFlux starter and Streamable HTTP for a remote server when supported by the selected Spring AI 1.x release. Keep stdout clean in stdio mode because it carries JSON-RPC frames.
Security and verification
- Authenticate and authorize remote MCP endpoints and every underlying domain operation.
- Validate identifiers, enum values, pagination, and result limits.
- Do not expose secrets, stack traces, persistence entities, or unrestricted administrative tools.
- Test discovery, invalid arguments, authorization, timeouts, and shutdown with a real MCP client.
- Review the selected Spring AI 1.x release notes before copying 2.0 annotation examples.
Examples
- See
examples/OrderMcpTools.java,examples/good-order-tools.java, andexamples/bad-order-tools.java.
Official sources
- Spring AI MCP overview: https://docs.spring.io/spring-ai/reference/api/mcp/mcp-overview.html
- MCP Java SDK releases: https://github.com/modelcontextprotocol/java-sdk/releases
- MCP Java SDK 2.0 migration: https://github.com/modelcontextprotocol/java-sdk/blob/main/MIGRATION-2.0.md
Gotchas
- Agent overrides the MCP SDK under Spring AI 1.x - let the Spring AI BOM manage it.
- Agent copies Spring AI 2.0
org.springframework.ai.mcp.annotationimports into a 1.1 project - 1.1 usesorg.springaicommunity.mcp.annotation, and 1.0 has no MCP annotations at all. - Agent expects
@Toolmethods on a plain@Componentto appear as MCP tools in 1.x - register them through aToolCallbackProviderbean. - Agent passes
--spring.ai.mcp.server.transport=stdio- no such property; Boot ignores it silently. Usespring.ai.mcp.server.stdio=true. - Agent uses removed
new CallToolResult(...)constructors in raw SDK code - use builders. - Agent logs to stdout in stdio mode - route logs to stderr or a file and disable the banner.
- Agent registers the same tool object twice - keep one callback provider per capability.
- Agent exposes entities or unbounded collections - return bounded DTO contracts.
Examples & templates
bad-order-tools.javaexamples
@Tool(description = "Run anything")
String execute(String command) {
System.out.println("Executing " + command); // corrupts stdio and exposes an unsafe tool
return shell.run(command);
}good-order-tools.javaexamples
@Component
final class OrderMcpTools {
@Tool(description = "Get an order by UUID")
OrderResponse getOrder(@ToolParam(description = "Order UUID") String orderId) {
return OrderResponse.from(orderService.findById(UUID.fromString(orderId)));
}
}OrderMcpTools.javaexamples
package com.example.mcp;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.UUID;
/**
* MCP tools for Order Service.
* Spring AI 1.x does NOT auto-scan @Tool methods: register this bean through a
* ToolCallbackProvider, e.g. MethodToolCallbackProvider.builder().toolObjects(orderMcpTools).build().
*
* Usage in .mcp.json:
* {
* "mcpServers": {
* "order-service": {
* "command": "java",
* "args": ["-jar", "order-service.jar", "--spring.profiles.active=mcp"]
* }
* }
* }
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class OrderMcpTools {
private final OrderService orderService;
private final ObjectMapper objectMapper;
@Tool(description = "Get a single order by UUID. Returns full order details including line items, status, and timestamps.")
public String getOrder(
@ToolParam(description = "UUID of the order to retrieve") String orderId
) {
try {
Order order = orderService.findById(UUID.fromString(orderId));
return objectMapper.writeValueAsString(OrderResponse.from(order));
} catch (IllegalArgumentException e) {
return errorJson("INVALID_ID", "Not a valid UUID: " + orderId);
} catch (EntityNotFoundException e) {
return errorJson("NOT_FOUND", "Order not found: " + orderId);
} catch (Exception e) {
log.error("getOrder failed for id={}", orderId, e);
return errorJson("INTERNAL_ERROR", "Unexpected error");
}
}
@Tool(description = "List all orders for a customer email. Optionally filter by status: PENDING, CONFIRMED, SHIPPED, DELIVERED, CANCELLED.")
public String listOrders(
@ToolParam(description = "Customer email address") String email,
@ToolParam(description = "Optional status filter", required = false) String status
) {
try {
var orders = status != null
? orderService.findByEmailAndStatus(email, OrderStatus.valueOf(status.toUpperCase()))
: orderService.findByEmail(email);
return objectMapper.writeValueAsString(
orders.stream().map(OrderResponse::from).toList()
);
} catch (IllegalArgumentException e) {
return errorJson("INVALID_STATUS", "Unknown status: " + status +
". Valid values: PENDING, CONFIRMED, SHIPPED, DELIVERED, CANCELLED");
} catch (Exception e) {
log.error("listOrders failed for email={}", email, e);
return errorJson("INTERNAL_ERROR", "Unexpected error");
}
}
@Tool(description = "Get order statistics for a customer: total orders, total spend, orders by status.")
public String getOrderStats(
@ToolParam(description = "Customer email address") String email
) {
try {
OrderStats stats = orderService.getStatsByEmail(email);
return objectMapper.writeValueAsString(stats);
} catch (Exception e) {
log.error("getOrderStats failed for email={}", email, e);
return errorJson("INTERNAL_ERROR", "Unexpected error");
}
}
private String errorJson(String code, String message) {
return String.format("{\"error\":\"%s\",\"message\":\"%s\"}", code, message);
}
}mcp.jsontemplates
{
"mcpServers": {
"order-service": {
"command": "java",
"args": [
"-jar",
"/path/to/your/order-service.jar",
"--spring.profiles.active=mcp",
"--spring.ai.mcp.server.stdio=true",
"--spring.main.banner-mode=off"
],
"env": {
"SPRING_DATASOURCE_URL": "jdbc:postgresql://localhost:5432/orders",
"SPRING_DATASOURCE_USERNAME": "postgres",
"SPRING_DATASOURCE_PASSWORD": "your-password",
"ANTHROPIC_API_KEY": "sk-ant-..."
}
}
}
}Verification scope
- Compiled sources
- Boot 4 OrderMcpTools
- Runtime checks
- Compilation only; no protocol session tests
Coverage describes checked-in fixtures, not a guarantee for every snippet or project.
Coverage matrix & agent evidenceADD TO YOUR AGENTInstall Boot 3 skills
Install Boot 3 skills
claude plugin marketplace add rrezartprebreza/spring-boot-skills
claude plugin install spring-boot-3-skills@spring-boot-skillscodex plugin marketplace add rrezartprebreza/spring-boot-skills
codex plugin add spring-boot-3-skills@spring-boot-skills