Token导航 LogoToken导航TokenDH.com
开发external-servicegithub未标认证来源可访问许可证需确认审计提醒

spring-ai-mcp-server-patternsspring AI MCP server 模式

Agent Skill

用于辅助 Java 项目开发、面向对象设计、Spring 生态、Maven 或 Gradle 依赖和后端工程实践。它适合让 Agent 分析类结构、设计接口、整理服务分层、生成测试或检查常见代码坏味道。使用时需要结合项目已有架构、包结构和依赖版本,不应只按通用教程改代码;涉及数据库、事务、并发或框架配置时,应先确认运行环境和回归测试范围。

总安装

17,107

周安装

720

GitHub Stars

229

下载量

5,990
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:spring-ai-mcp-server-patterns(spring AI MCP server 模式)
来源仓库:https://github.com/giuseppe-trisciuoglio/developer-kit
仓库路径:skills/spring-ai-mcp-server-patterns
安装命令:
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-ai-mcp-server-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-ai-mcp-server-patterns

简介

使用声明性工具、提示模板和本机 Spring 集成模式通过 Spring AI 构建 MCP 服务器。

  • 通过 @Tool 将 Spring 组件公开为 AI 可调用工具
  • 注解,通过@ToolParam提供参数文档
  • 用于 AI 模型理解
  • 支持三种传输模式(stdio、HTTP、SSE),并内置 Spring Security 集成,以实现基于角色的访问控制和审核日志记录
  • 包括使用@PromptTemplate的可重用提示模板
  • 、动态工具注册、多模型支持以及生产部署的缓存策略
  • 使用 MockMvc、Testcontainers 和 Spring Boot 测试片提供全面的测试模式,包括单元、集成和安全测试示例

SKILL.md

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

AnnotationTargetPurpose
@EnableMcpServerClassEnable MCP server auto-configuration
@Tool(description)MethodDeclare AI-callable tool
@ToolParam(value)ParameterDocument tool parameter for AI
@PromptTemplate(name)MethodDeclare reusable prompt template
@PromptParam(value)ParameterDocument prompt parameter

Transport Types

TransportUse CaseConfig
stdioLocal process / Claude DesktopDefault
httpRemote HTTP clientsport, path
sseReal-time streaming clientsport, path

Key Dependencies

<!-- 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'

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:

@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

2. Define Tools

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.

3. Create Prompt Templates

@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.

4. Configure Transport

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

@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.

6. Testing

@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.

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

@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

@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.

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:

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

38.12%
按下载量换算2,283

Claude

29.06%
按下载量换算1,741

Cursor

16.75%
按下载量换算1,003

Gemini CLI

8.34%
按下载量换算500

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

external-service

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills