К основному содержанию
скилл CX Codex

spring-ai-mcp-server-patterns — скилл для Claude Code: MCP-серверы

Скилл с шаблонами MCP-серверов на Spring Boot и Spring AI: инструменты через @Tool, промпт-шаблоны, транспорты stdio, HTTP и SSE.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add giuseppe-trisciuoglio/developer-kit --skill spring-ai-mcp-server-patterns -a claude-code
Открыть на GitHub

Что делает spring-ai-mcp-server-patterns

Скилл подсказывает агенту, как собрать MCP-сервер на Spring Boot с официальным Spring AI. Внутри — набор паттернов: объявление инструментов аннотацией @Tool, документирование параметров через @ToolParam, промпт-шаблоны @PromptTemplate с @PromptParam, конфигурация транспорта и фильтрация инструментов по ролям пользователя.

Перед началом понадобится ключ модели: в application.properties прописывается spring.ai.openai.api-key=${OPENAI_API_KEY}, а сам сервер включается аннотацией @EnableMcpServer на главном классе. Зависимости — spring-ai-mcp-server и spring-ai-starter-model-openai версии 1.0.0, для Maven или Gradle. Транспорт выбирается в конфиге: stdio для локального процесса, http или sse с указанием port и path.

Отдельный раздел про безопасность. Параметры, которые генерирует модель, скилл советует считать недоверенными: проверять входные данные, использовать параметризованные SQL-запросы, ставить @PreAuthorize на чувствительные методы. Если этого не сделать, инструмент с доступом к базе или файлам станет дырой — вот на чём чаще всего ломаются самодельные MCP-серверы. Есть и раздел про тесты: @SpringBootTest, мок сервиса, проверка вызова.

Какие задачи решает

  • объявить инструмент, который модель вызовет по описанию
  • поднять MCP-сервер на Spring Boot без ручной сборки протокола
  • переключить транспорт с stdio на HTTP или SSE
  • закрыть админские инструменты проверкой роли
  • написать тест на обработчик инструмента с моком сервиса

Примеры запросов агенту

  • Создай MCP-сервер на Spring Boot: инструмент для получения погоды по городу и промпт-шаблон для ревью Java-кода
  • Переведи MCP-сервер со stdio на HTTP-транспорт на порту 8080, путь /mcp
  • Добавь фильтр инструментов: методы с префиксом admin_ доступны только роли ADMIN

Как установить spring-ai-mcp-server-patterns

1Через Skills CLI (Vercel)

npx skills add giuseppe-trisciuoglio/developer-kit --skill spring-ai-mcp-server-patterns -a claude-code

2Вручную: положить файлы

~/.claude/skills/spring-ai-mcp-server-patterns/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/spring-ai-mcp-server-patterns/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о spring-ai-mcp-server-patterns

Как установить spring-ai-mcp-server-patterns в Claude?

Выполните npx skills add giuseppe-trisciuoglio/developer-kit --skill spring-ai-mcp-server-patterns -a claude-code. Скилл окажется в ~/.claude/skills/spring-ai-mcp-server-patterns/SKILL.md.

Что делает spring-ai-mcp-server-patterns?

Даёт агенту готовые паттерны MCP-серверов на Spring AI: инструменты с @Tool, промпт-шаблоны, транспорты и фильтрацию доступа. Плюс разделы про безопасность и тестирование.

Что нужно, чтобы скилл сработал?

Проект на Spring Boot с зависимостями spring-ai-mcp-server и spring-ai-starter-model-openai версии 1.0.0. Для модели в конфиге задаётся ключ, например spring.ai.openai.api-key=${OPENAI_API_KEY}.

Исходный текст

SKILL.md · MIT
---
name: spring-ai-mcp-server-patterns
description: 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.
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
---

# 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(rows, rows.size());
    }
}
```

See [references/examples.md](references/examples.md) for complete examples including file system tools, REST API integration, and prompt template servers.

## Constraints and Warnings

### Security
- **Never expose** sensitive data in tool descriptions, parameters, or error messages
- **Input validation is mandatory** — always validate before executing
- **External content is untrusted** — tools fetching URLs may receive prompt injection payloads; validate all fetched content
- **SQL injection**: use parameterized queries exclusively
- **Path traversal**: normalize and validate all file paths against a base path

### Operational
- Responses should be concise — large responses can exceed AI context window limits
- All tools must implement timeouts; default should be configurable
- Rate limit expensive operations
- Tools may be called concurrently — ensure thread safety

### Spring AI Specific
- Spring AI is actively developed — pin specific versions in production
- Error messages thrown by tools are exposed to AI models; sanitize them
- Choose transport type carefully: `stdio` for local processes, `http`/`sse` for remote clients

## References

Consult these files for detailed patterns and examples:

- **[references/implementation-patterns.md](references/implementation-patterns.md)** - Tool creation, prompt templates, FunctionCallback, Spring Boot auto-configuration, application properties
- **[references/advanced-patterns.md](references/advanced-patterns.md)** - Dynamic tool registration, multi-model support, caching, error handling
- **[references/testing-guide.md](references/testing-guide.md)** - Unit tests, integration tests, Testcontainers, security tests, slice tests
- **[references/examples.md](references/examples.md)** - Complete server examples: weather, database, file system, REST API, prompt templates
- **[references/api-reference.md](references/api-reference.md)** - Full API: annotations, interfaces, configuration classes, transport implementations, event system
- **[references/migration-guide.md](references/migration-guide.md)** - Migrating from LangChain4j MCP to Spring AI MCP

© giuseppe-trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit

Похожие скиллы

Всё по теме «ИИ и ML» →
spring-boot-patterns decebals Скилл задаёт структуру Spring Boot-проекта и шаблоны для контроллеров, сервисов и репозиториев. Пригодится, когда агент пишет новый код или разбирает чужой. CX Codex +1 322установок java-spring-boot pluginagentmarketplace Скилл помогает создавать бэкенд на Spring Boot 3: настраивать REST API, аутентификацию через Spring Security, доступ к базам через Spring Data и мониторинг Actuator. CX Codex +1 11 800установок create-spring-boot-java-project официальный github Создаёт каркас Spring Boot на Java с Maven, базами данных и Docker Compose. Подходит для старта API, которому нужны PostgreSQL, Redis и MongoDB. 9 516установок spring-boot-engineer https://github.com/Jeffallan Разворачивает архитектуру Spring Boot 3.x, контроллеры, репозитории Spring Data JPA и правила Spring Security 6. Пригодится при сборке REST API, реактивных сервисов и микросервисов на Java. CX Codex +1 8 400установок spring-boot Mindrally Скилл задаёт агенту стиль кода на Spring Boot: REST-контроллеры, тесты, безопасность, сборка и деплой. Пригодится, когда проект на Java и хочется единообразия. CX Codex +1 832установок spring-framework Mindrally Скилл задаёт агенту правила разработки на Spring Framework и Spring Boot: структура слоёв, внедрение зависимостей, тесты, REST. CX Codex +1 731установок

Из того же набора93

spring-boot-dependency-injection Скилл внедряет паттерны внедрения зависимостей через конструктор в Spring Boot. Он помогает избавиться от field injection и настроить выбор бинов через @Primary и @Qualifier. CX Codex +1 3 800установок nextjs-code-review Проверяет код Next.js перед слиянием изменений: компоненты, серверные действия, кэш и маршруты. Пригодится после новой функции или миграции. CX Codex +1 3 800установок unit-test-wiremock-rest-api Скилл задаёт шаблоны юнит-тестов внешних REST API на WireMock: заглушки ответов, проверка запросов, имитация сбоев без реальной сети. CX Codex +1 3 800установок spring-boot-actuator Скилл помогает настроить Spring Boot Actuator: добавить пробы жизнеспособности для оркестраторов, защитить служебные эндпоинты и экспортировать метрики Micrometer в Prometheus. CX Codex +1 3 800установок nestjs-code-review Скилл для ревью NestJS-приложений: проверяет контроллеры, сервисы, модули, DI, гарды и работу с базой. Пригодится перед мержем пул-реквеста. CX Codex +1 3 800установок spring-boot-resilience4j Скилл добавляет паттерны отказоустойчивости Resilience4j в Spring Boot 3.x. Он помогает настроить размыкатели цепи и повторные вызовы при сбоях внешних сервисов. CX Codex +1 3 800установок unit-test-service-layer Скилл задаёт агенту шаблон юнит-тестов сервисного слоя на Mockito: моки репозиториев, проверка вызовов, сценарии с исключениями. CX Codex +1 3 800установок nestjs-best-practices Скилл задаёт агенту правила NestJS: модули, области видимости провайдеров, фильтры исключений, DTO-валидация и Drizzle ORM. CX Codex +1 3 800установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой