spring-ai-mcp-server-patterns
Provides Spring Boot MCP server patterns that create Model Context Protocol servers with Spring AI by defining tool handlers, exposing resources, configuring prompt templates, and setting up transports for AI function calling and tool calling. Use when building MCP servers to extend AI capabilities with Spring's official AI framework, implementing AI tools, custom function calling, or MCP client integration.
What this skill does
# Spring AI MCP Server Implementation Patterns
Implements MCP servers with Spring AI for AI function calling, tool handlers, and MCP transport configuration.
## Overview
Production-ready MCP server patterns: `@Tool` functions, `@PromptTemplate` resources, and stdio/HTTP/SSE transports with Spring AI security.
## When to Use
MCP servers, Spring AI function calling, AI tools, tool calling, custom tool handlers, Spring Boot MCP, resource endpoints, or MCP transport configuration.
## Quick Reference
### Core Annotations
| 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 Types
| Transport | Use Case | Config |
|-----------|----------|--------|
| `stdio` | Local process / Claude Desktop | Default |
| `http` | Remote HTTP clients | `port`, `path` |
| `sse` | Real-time streaming clients | `port`, `path` |
### Key Dependencies
```xml
<!-- 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
// Gradle
implementation 'org.springframework.ai:spring-ai-mcp-server:1.0.0'
implementation 'org.springframework.ai:spring-ai-starter-model-openai:1.0.0'
```
## Instructions
### 1. Project Setup
Add Spring AI MCP dependencies (see Quick Reference above), configure the AI model in `application.properties`, and enable MCP with `@EnableMcpServer`:
```java
@SpringBootApplication
@EnableMcpServer
public class MyMcpApplication {
public static void main(String[] args) {
SpringApplication.run(MyMcpApplication.class, args);
}
}
```
```properties
spring.ai.openai.api-key=${OPENAI_API_KEY}
spring.ai.mcp.enabled=true
spring.ai.mcp.transport.type=stdio
```
### 2. Define Tools
Annotate methods with `@Tool` inside `@Component` beans. Use `@ToolParam` to document parameters:
```java
@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](references/implementation-patterns.md) for database tools, API integration tools, and the `FunctionCallback` low-level pattern.
### 3. Create Prompt Templates
```java
@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](references/implementation-patterns.md) for additional prompt template patterns.
### 4. Configure Transport
```yaml
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
```
### 5. Add Security
```java
@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](references/implementation-patterns.md) for full security patterns.
### 6. Testing
```java
@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](references/testing-guide.md) for integration tests, Testcontainers, security tests, and slice tests.
## Best Practices
### Tool Design
- Keep tools focused — one operation per tool
- Use clear, action-oriented names (`getWeather`, `executeQuery`)
- Always annotate parameters with `@ToolParam` and descriptive text
- Return structured records/DTOs, not raw strings or maps
- Design tools to be idempotent when possible
### Security
- Validate and sanitize all inputs — AI-generated parameters are untrusted
- Use parameterized queries for SQL; validate and normalize paths for file tools
- Apply `@PreAuthorize` for role-based access on sensitive tools
- Audit log all data-modifying tool executions
- Never expose credentials or sensitive data in tool descriptions or error messages
### Performance
- Use `@Cacheable` for expensive operations with appropriate TTL
- Set timeouts for all external calls
- Use `@Async` for long-running operations
- Monitor with Micrometer metrics
### Error Handling
- Return structured error responses with user-friendly messages
- Log context (user, tool name, parameters) for debugging
- Implement retry logic for transient failures
- Implement `@ControllerAdvice` for consistent error responses
## Examples
### Example 1: Minimal Weather MCP Server
```java
@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) {}
```
### Example 2: Secure Database Tool
```java
@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(roRelated in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.