mit einem Klick
spring-boot-ai-mcp-server-patterns
Use when building Model Context Protocol servers in Spring Boot with Spring AI, exposing tools or resources, configuring transports, or integrating AI tool-calling workflows.
Menü
Use when building Model Context Protocol servers in Spring Boot with Spring AI, exposing tools or resources, configuring transports, or integrating AI tool-calling workflows.
Use when configuring Spring Boot Actuator for production-grade monitoring, health probes, secured management endpoints, readiness/liveness checks, and Micrometer metrics in Spring Boot 4 applications.
Use when adding caching to Spring Boot 4 services, configuring cache providers and TTL policies, invalidating stale data, or diagnosing cache hit and miss behavior.
Use when integrating Neo4j into a Spring Boot 4 backend with graph models, Cypher queries, reactive repositories, relationship mapping, or graph-focused testing patterns.
Use when implementing event-driven or message-based integration in Spring Boot 4, publishing domain events, coordinating Kafka or broker messaging, or applying outbox and idempotency patterns for reliable delivery.
Use when documenting reactive Spring Boot 4 HTTP APIs with SpringDoc OpenAPI, configuring Swagger UI, annotating endpoints, documenting security schemes, or defining request and response schemas.
Use when implementing reactive fault-tolerance patterns in Spring Boot 4 with native Spring Framework 7 resilience features or Resilience4j, including retries, concurrency limiting, circuit breakers, rate limiting, timeouts, and fallbacks for downstream calls.
| name | spring-boot-ai-mcp-server-patterns |
| description | Use when building Model Context Protocol servers in Spring Boot with Spring AI, exposing tools or resources, configuring transports, or integrating AI tool-calling workflows. |
| allowed-tools | Read, Write, Edit, Bash, Glob, Grep |
Implements MCP servers with Spring AI for AI function calling, tool handlers, and MCP transport configuration.
Production-ready MCP server patterns: @Tool functions, @PromptTemplate resources, and
stdio/HTTP/SSE transports with Spring AI security.
MCP servers, Spring AI function calling, AI tools, tool calling, custom tool handlers, Spring Boot MCP, resource endpoints, or MCP transport configuration.
| Annotation | Target | Purpose |
|---|---|---|
@EnableMcpServer | Class | Enable MCP server auto-configuration |
@Tool(description) | Method | Declare AI-callable tool |
@ToolParam(value) | Parameter | Document tool parameter for AI |
@PromptTemplate(name) | Method | Declare reusable prompt template |
@PromptParam(value) | Parameter | Document prompt parameter |
| Transport | Use Case | Config |
|---|---|---|
stdio | Local process / Claude Desktop | Default |
http | Remote HTTP clients | port, path |
sse | Real-time streaming clients | port, path |
<!-- Maven -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mcp-server</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
<version>1.0.0</version>
</dependency>
// Gradle
implementation 'org.springframework.ai:spring-ai-mcp-server:1.0.0'
implementation 'org.springframework.ai:spring-ai-starter-model-openai:1.0.0'
Add Spring AI MCP dependencies (see Quick Reference above), configure the AI model in
application.properties, and enable MCP with @EnableMcpServer:
@SpringBootApplication
@EnableMcpServer
public class MyMcpApplication {
public static void main(String[] args) {
SpringApplication.run(MyMcpApplication.class, args);
}
}
spring.ai.openai.api-key=${OPENAI_API_KEY}
spring.ai.mcp.enabled=true
spring.ai.mcp.transport.type=stdio
Annotate methods with @Tool inside @Component beans. Use @ToolParam to document parameters:
@Component
public class WeatherTools {
@Tool(description = "Get current weather for a city")
public WeatherData getWeather(@ToolParam("City name") String city) {
return weatherService.getCurrentWeather(city);
}
@Tool(description = "Get 5-day forecast for a city")
public ForecastData getForecast(
@ToolParam("City name") String city,
@ToolParam(value = "Unit: celsius or fahrenheit", required = false) String unit) {
return weatherService.getForecast(city, unit != null ? unit : "celsius");
}
}
See references/implementation-patterns.md for database
tools, API integration tools, and the FunctionCallback low-level pattern.
@Component
public class CodeReviewPrompts {
@PromptTemplate(
name = "java-code-review",
description = "Review Java code for best practices and issues"
)
public Prompt createCodeReviewPrompt(
@PromptParam("code") String code,
@PromptParam(value = "focusAreas", required = false) List<String> focusAreas) {
String focus = focusAreas != null ? String.join(", ", focusAreas) : "general best practices";
return Prompt.builder()
.system("You are an expert Java code reviewer with 20 years of experience.")
.user("Review the following Java code for " + focus + ":\n```java\n" + code + "\n```")
.build();
}
}
See references/implementation-patterns.md for additional prompt template patterns.
spring:
ai:
mcp:
enabled: true
transport:
type: stdio # stdio | http | sse
http:
port: 8080
path: /mcp
server:
name: my-mcp-server
version: 1.0.0
@Configuration
public class McpSecurityConfig {
@Bean
public ToolFilter toolFilter(SecurityService securityService) {
return (tool, context) -> {
User user = securityService.getCurrentUser();
if (tool.name().startsWith("admin_")) {
return user.hasRole("ADMIN");
}
return securityService.isToolAllowed(user, tool.name());
};
}
}
Use @PreAuthorize("hasRole('ADMIN')") on tool methods for method-level security.
See references/implementation-patterns.md for full security
patterns.
@SpringBootTest
class WeatherToolsTest {
@Autowired
private WeatherTools weatherTools;
@MockBean
private WeatherService weatherService;
@Test
void testGetWeather_Success() {
when(weatherService.getCurrentWeather("London"))
.thenReturn(new WeatherData("London", "Cloudy", 15.0));
WeatherData result = weatherTools.getWeather("London");
assertThat(result.city()).isEqualTo("London");
verify(weatherService).getCurrentWeather("London");
}
}
See references/testing-guide.md for integration tests, Testcontainers, security tests, and slice tests.
getWeather, executeQuery)@ToolParam and descriptive text@PreAuthorize for role-based access on sensitive tools@Cacheable for expensive operations with appropriate TTL@Async for long-running operations@ControllerAdvice for consistent error responses@SpringBootApplication
@EnableMcpServer
public class WeatherMcpApplication {
public static void main(String[] args) {
SpringApplication.run(WeatherMcpApplication.class, args);
}
}
@Component
public class WeatherTools {
@Tool(description = "Get current weather for a city")
public WeatherData getWeather(@ToolParam("City name") String city) {
return new WeatherData(city, "Sunny", 22.5);
}
}
record WeatherData(String city, String condition, double temperatureCelsius) {}
@Component
@PreAuthorize("hasRole('USER')")
public class DatabaseTools {
private final JdbcTemplate jdbcTemplate;
@Tool(description = "Execute a read-only SQL query and return results")
public QueryResult executeQuery(
@ToolParam("SQL SELECT query") String sql,
@ToolParam(value = "Parameters as JSON map", required = false) String paramsJson) {
if (!sql.trim().toUpperCase().startsWith("SELECT")) {
throw new IllegalArgumentException("Only SELECT queries are allowed");
}
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
return new QueryResult(rows, rows.size());
}
}
See references/examples.md for complete examples including file system tools, REST API integration, and prompt template servers.
stdio for local processes, http/sse for remote clientsConsult these files for detailed patterns and examples: