弹簧靴MCP伴侣
一个生产就绪的注释驱动框架,用于将模型上下文协议(MCP)集成到Spring Boot应用程序中。将Spring组件作为远程可调用工具、资源和提示公开,无需配置。
    [![Tests]()](./TEST_REPORT.md) 
______________________________________________________________________
📌 目录
______________________________________________________________________
为什么选择Spring Boot MCP伴侣?
模型上下文协议(MCP)使AI系统能够通过标准化的接口与您的服务进行交互。但是,将MCP集成到Spring Boot应用程序中需要样板代码、模式生成、类型映射和安全考虑。
弹簧靴MCP Companion消除了这种摩擦 与:
- ✅ 单线激活 -添加
@EnableMcpCompanion到你的主课堂 - ✅ 零样板 -无XML、无手动路由、无架构文件
- ✅ 类型安全 -从Java类型自动生成JSON模式
- ✅ 验证就绪 -内置Jakarta Bean验证支持
- ✅ 生产级 -包括安全性、错误处理、可观察性和最佳实践
- ✅ 非侵入性 -与现有的Spring Boot代码一起工作,无需修改
现实世界的好处
| 场景 | 没有MCP伴侣 | 有MCP伴侣 |
|---|---|---|
| 将控制器方法作为MCP工具公开 | 编写JSON-RPC处理程序、模式生成、类型映射(1-2小时) | 添加 @McpTool 注释(2分钟) |
| 添加输入验证 | 手动验证MCP处理程序中的参数(30+分钟) | 利用现有的Jakarta验证器(0分钟) |
| 支持新的Java类型 | 更新JSON模式映射、类型转换器(变量) | 自动生成JSON模式(0分钟) |
| 部署到生产环境 | 配置安全性、监控、速率限制(2-4小时) | 内置安全性和可观察性(0分钟) |
______________________________________________________________________
快速入门(5分钟)
1.添加依赖关系
Maven:
com.raynermendez
spring-boot-mcp-companion-core
1.0.0
Gradle:
implementation 'com.raynermendez:spring-boot-mcp-companion-core:1.0.0'2.在您的应用程序中启用MCP
@SpringBootApplication
@EnableMcpCompanion // ← That's it!
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}3.注释你的方法
@RestController
@RequestMapping("/api/orders")
public class OrderController {
@Autowired
private OrderRepository orderRepository;
// Expose as MCP tool (remote-callable function)
@GetMapping("/{orderId}")
@McpTool(description = "Get order by ID with full details")
public Order getOrder(
@PathVariable
@McpInput(description = "The order ID")
String orderId
) {
return orderRepository.findById(orderId).orElseThrow();
}
// Expose as MCP resource (URI-accessible data)
@McpResource(
uri = "order://{id}",
description = "Order details resource"
)
public Order getOrderResource(@McpInput String id) {
return getOrder(id);
}
// Expose as MCP prompt (template generator)
@McpPrompt(name = "order_summary", description = "Generate order summary")
public String generateSummary(@McpInput String orderId) {
Order order = getOrder(orderId);
return String.format(
"Order #%s: %d items, Total: $%.2f",
order.getId(),
order.getItems().size(),
order.getTotal()
);
}
}4.启动您的应用程序
mvn spring-boot:run5.测试您的MCP服务器
# List available tools
curl -X POST http://localhost:8090/mcp/tools/list \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}'
# Call a tool
curl -X POST http://localhost:8090/mcp/tools/call \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "get_order",
"arguments": {"orderId": "12345"}
}
}'就是这样! 您的应用程序现在公开了MCP端点。
______________________________________________________________________
安装和设置
系统要求
| 组件 | 要求 | 注释 |
|---|---|---|
| Java | 建议使用17+ | LTS版本(17、21、23) |
| Spring Boot | 4.0.5+ | 任何Spring Boot 4.x.x版本 |
| Maven | 3.9.0+ | 或Gradle 8.0+ |
| 内存 | 最小256 MB | 建议用于生产 |
| 端口 | 8080+8090 | 可通过配置 application.yml |
构建系统集成
Maven(推荐)
com.raynermendez
spring-boot-mcp-companion-core
1.0.0
Gradle
dependencies {
implementation 'com.raynermendez:spring-boot-mcp-companion-core:1.0.0'
}配置
通过配置 application.yml 在您的资源目录中:
# Main Spring Boot Application
server:
port: 8080 # Main application server
mcp:
server:
enabled: true # Enable/disable MCP endpoints
name: "My Service" # Server name advertised to MCP clients
version: "1.0.0" # Server version
base-path: /mcp # Endpoint prefix (serves on same port as server.port)验证依赖关系(可选但推荐)
要获得输入验证支持,请添加:
org.springframework.boot
spring-boot-starter-validation
______________________________________________________________________
核心概念
1.MCP工具
工具是可远程调用的业务逻辑函数。将它们视为RPC端点。
@McpTool(description = "Create a new user account")
public User createUser(
@McpInput @Email String email,
@McpInput @Size(min = 8) String password,
@McpInput String fullName
) {
// Implementation
}何时使用: API端点、数据突变、计算、集成。
2.MCP资源
资源是可通过URI模式访问的数据。将它们视为内容存储库。
@McpResource(
uri = "user://{userId}/profile",
description = "User profile data",
mimeType = "application/json"
)
public UserProfile getUserProfile(@McpInput String userId) {
// Implementation
}何时使用: 只读数据访问、文档、配置、报告。
3.MCP提示
提示是生成文本的模板生成器(通常用于LLM)。
@McpPrompt(name = "summarize", description = "Generate a concise summary")
public String generateSummary(
@McpInput String content,
@McpInput Integer maxLength
) {
// Implementation
}何时使用: 模板生成、提示工程、报告生成。
4.MCP输入
这 @McpInput 注释将元数据添加到参数中:
@McpInput(
description = "User's email address",
required = true,
sensitive = false // Set true for passwords, API keys, etc.
)
String email特征:
- 自动生成JSON模式
- Jakarta Bean验证集成(
@Email,@Size等等) - 敏感数据的输入净化
- 清晰的参数文档
______________________________________________________________________
项目架构
高级设计
┌─────────────────────────────────────────────────────────────┐
│ Unified Spring Boot Application │
│ (Single Server) │
│ (Port 8080) │
│ │
│ ┌──────────────────┐ ┌─────────────────────────┐ │
│ │ REST API │ │ MCP Endpoints │ │
│ │ /api/v1/... │ │ /mcp/... │ │
│ │ │ │ │ │
│ │ - User routes │ │ - tools/list │ │
│ │ - Auth endpoints │ │ - tools/call │ │
│ │ - CRUD ops │ │ - resources/list │ │
│ └──────────────────┘ │ - resources/read │ │
│ │ - prompts/list │ │
│ └─────────────────────────┘ │
| ┌────────────────────────────────────────────────────┐ │
│ │ Spring Beans, Controllers, Services, Repositories │ │
│ │ (Decorated with @McpTool/@McpResource/@McpPrompt) │ │
│ └────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────┐ │
│ │ Spring Boot MCP Companion Framework │ │
│ │ │ │
│ │ • Metadata Extraction │ │
│ │ • Type Mapping & JSON Schema Generation │ │
│ │ • Input Validation │ │
│ │ • JSON-RPC 2.0 Handler │ │
│ │ • Security, Rate Limiting, Observability │ │
│ └────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────┐ │
│ │ Shared Resources: Thread Pool, Connection Pool │ │
│ │ Database Access, Metrics, Logging │ │
│ └────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘项目结构
spring-boot-mcp-companion/
│
├── src/main/java/com/raynermendez/spring_boot_mcp_companion/
│ ├── config/ # Auto-configuration, properties
│ ├── annotations/ # @EnableMcpCompanion, @McpTool, etc.
│ ├── dispatch/ # Tool/resource/prompt routing
│ ├── mapper/ # Type mapping, JSON schema generation
│ ├── validation/ # Input validation engine
│ ├── security/ # Security filters, sanitization
│ ├── transport/ # JSON-RPC 2.0 protocol handling
│ └── exception/ # Error handling & responses
│
├── src/test/java/ # 225+ integration & unit tests
├── docs/ # Complete documentation
│ ├── getting-started/ # Quick start guides
│ ├── core/ # API reference, examples
│ └── production/ # Best practices, security, advanced topics
├── pom.xml # Maven configuration
└── README.md # This file关键组件
| 组件 | 责任 | Java包 |
|---|---|---|
| 自动配置 | 启动Bootstrap MCP框架 | config |
| 注解处理 | 检测并编目@McpTool/@McpResource/@McpPrompt方法 | config |
| 类型映射器 | 转换Java类型↔ JSON模式,处理自定义对象 | mapper |
| 验证引擎 | MCP边界的Jakarta Bean验证实施 | validation |
| 调度员 | 将JSON-RPC调用路由到适当的方法 | dispatch |
| 运输搬运员 | JSON-RPC 2.0协议合规性,流式响应 | transport |
| 安全层 | 输入净化、速率限制、敏感数据屏蔽 | security |
| 错误处理器 | 结构化异常响应、错误清理 | exception |
______________________________________________________________________
主要特点
✅ 零配置激活
@SpringBootApplication
@EnableMcpCompanion // That's literally all you need!
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}✅ 约定胜于配置
该框架从代码中派生行为:
- 命名:
getUserById()→get_user_by_id在MCP中 - 描述:阅读自
@McpTool/@McpResource注释或Javadoc - 类型:从Java类型签名推断JSON模式
- 验证:利用现有的雅加达验证器
✅ 类型安全,自动生成JSON模式
所有Java类型都会自动映射到JSON模式:
@McpTool
public OrderResponse createOrder(
@McpInput String orderId, // → string
@McpInput BigDecimal price, // → number
@McpInput LocalDateTime createdAt, // → string (ISO 8601 format)
@McpInput List items, // → array of items
@McpInput OrderStatus status, // → enum with values
@McpInput Optional notes // → nullable string
) { ... }特征:
- 原始和复杂类型
- 收藏(列表、集合、地图)
- 具有值约束的枚举
- 嵌套对象
- 可选/可空处理
- 自定义POJO(通过Jackson自动转换)
✅ 输入验证
MCP边界处的自动Jakarta Bean验证:
@McpTool
public User createUser(
@McpInput @NotBlank String name,
@McpInput @Email String email,
@McpInput @Size(min = 8, max = 128) String password,
@McpInput @Min(18) @Max(120) Integer age,
@McpInput @Pattern(regexp = "\\d{10}") String phone
) { ... }支持的约束:
@NotNull,@NotBlank,@NotEmpty@Email,@Pattern(regexp = "...")@Min(n),@Max(n),@Size(min=x, max=y)@Positive,@Negative,@Digits- 任何自定义Jakarta验证器
✅ 可观察和可监测
内置千分尺指标和弹簧启动执行器集成:
# Expose metrics via /actuator/metrics
management:
endpoints:
web:
exposure:
include: health,metrics,prometheus
metrics:
tags:
app: spring-boot-mcp-companion可用指标:
- MCP工具调用计数和持续时间
- 请求/响应大小
- 按类型划分的错误率
- 类型映射性能
- 验证失败
✅ 安全与威胁防护
内置生产级安全:
- 输入消毒:防止注射攻击
- 敏感参数屏蔽:不记录密码/令牌
- 速率限制:防止滥用
- 斯洛洛里斯保护:缓解资源耗尽攻击
- 请求边界验证:防止格式错误的请求
- 错误清理:不要在错误消息中泄露内部详细信息
- Spring安全集成:OAuth2、JWT、多因素身份验证支持
看 文档/生产/安全.md 详细的安全指南。
✅ 非侵入性集成
与现有的Spring Boot代码一起工作:
- 无需修改当前REST API
- 与Spring Security、Spring Data、Spring Cloud共存
- 重用现有的bean、存储库、服务
- 独立于您的主要API端口(8080与8090)
- 可选--通过配置启用/禁用
______________________________________________________________________
常见用例
1.AI助手集成
将您的业务逻辑暴露给AI系统(Claude、ChatGPT等):
@RestController
@RequestMapping("/api/documents")
public class DocumentController {
@McpTool(description = "Search documents by keyword")
public List searchDocuments(
@McpInput @Size(min = 1, max = 256) String keyword,
@McpInput @Min(1) @Max(100) Integer limit
) {
return documentRepository.search(keyword, limit);
}
@McpResource(uri = "doc://{id}", description = "Document content")
public Document getDocument(@McpInput String id) {
return documentRepository.findById(id).orElseThrow();
}
@McpPrompt(name = "extract_summary", description = "Generate document summary")
public String extractSummary(@McpInput String documentId) {
Document doc = getDocument(documentId);
return "Title: " + doc.getTitle() + "\nContent: " + doc.getContent();
}
}2.工作流自动化
公开业务流程以供外部编排:
@Service
public class OrderProcessingService {
@McpTool(description = "Process customer order")
public OrderConfirmation processOrder(
@McpInput @Email String customerEmail,
@McpInput List items
) {
// Validate, payment, inventory, shipping
return new OrderConfirmation(...);
}
@McpTool(description = "Update order status")
public void updateOrderStatus(
@McpInput String orderId,
@McpInput OrderStatus newStatus
) {
// Update database
}
}3.数据集成API
提供对内部系统的结构化访问:
@Repository
public class ReportRepository {
@McpResource(
uri = "report://{reportId}",
description = "Retrieve business report"
)
public Report getReport(@McpInput String reportId) {
return findById(reportId);
}
@McpTool(description = "Generate custom report")
public Report generateReport(
@McpInput @DateFormat LocalDate startDate,
@McpInput @DateFormat LocalDate endDate,
@McpInput ReportType type
) {
return computeReport(startDate, endDate, type);
}
}4.知识库和文档
公开可搜索的文档和知识:
@Service
public class KnowledgeBaseService {
@McpResource(uri = "kb://{articleId}")
public KBArticle getArticle(@McpInput String articleId) {
return articles.findById(articleId).orElseThrow();
}
@McpTool(description = "Search knowledge base")
public List search(@McpInput String query) {
return articles.search(query);
}
@McpPrompt(name = "contextual_info", description = "Get relevant documentation")
public String getContextualInfo(@McpInput String topic) {
return articles.searchByTopic(topic).stream()
.map(KBArticle::getContent)
.collect(Collectors.joining("\n\n"));
}
}______________________________________________________________________
文档中心
此README提供了一个概述。有关详细信息,请参阅:
🚀 入门指南
📚 核心文档
🏭 生产与运营
🤝 贡献与社区
📋 技术参考
______________________________________________________________________
要求和兼容性
Java版本
| 版本 | 状态 | 注释 |
|---|---|---|
| Java 17✅ 支持 | 最低要求 | |
| Java 21✅ 支持 | LTS版本 | |
| Java 23✅ 支持 | 最新稳定 | |
| Java 11、16❌ 不支持 | 使用Spring Boot MCP Companion 0.x |
Spring Boot版本
| 版本 | 状态 | 注释 |
|---|---|---|
| 弹簧靴4.0.5+ | ✅ 支持 | 推荐 |
| 弹簧靴3.x | ⚠️ 传统 | 使用v0.x分支 |
操作系统
| 操作系统 | 状态 | 注释 |
|---|---|---|
| Linux | ✅ 完全支持 | 生产标准 |
| macOS | ✅ 完全支持 | 英特尔和苹果硅 |
| Windows | ✅ 完全支持 | Windows 10+ |
| Docker | ✅ 推荐 | 请参阅 最佳实践.md |
外部依赖项
该框架具有最小的依赖关系:
spring-boot-starter
spring-boot-starter-web
spring-boot-starter-validation
spring-boot-starter-actuator
jackson-databind (included in spring-boot-starter-web)
______________________________________________________________________
安全与性能
安全态势
✅ 生产级安全功能:
- MCP边界的输入验证和净化
- 敏感参数屏蔽(密码、API密钥)
- 速率限制和DoS保护
- Spring安全集成(OAuth2、JWT、SAML)
- 错误消息清理
- 请求/响应加密支持
❌ 我们不做的事:
- 修改您的身份验证/授权逻辑
- 处理凭证管理
- 加密静态数据
- 验证外部API调用(您的责任)
看 安全.md 获取全面的安全指南。
性能特征
| 操作 | 延迟 | 注意事项 |
|---|---|---|
| 工具调用 | 1-5ms | 直接方法调用+JSON序列化 |
| 类型映射 | 0.5-2ms | 利用Spring的类型转换 |
| 验证 | 0.5-3ms | 雅加达Bean验证开销 |
| 架构生成 | 10-50ms | 仅在启动时生成,之后缓存 |
| 端到端延迟 | 5-15ms | 典型的网络往返时间 |
测试方法: JMH基准测试、1M+呼叫、p99延迟跟踪
内存使用
| 组件 | 内存 | 注释 |
|---|---|---|
| MCP配套框架 | ~5-8 MB | 开销最小 |
| 元数据缓存 | ~2-3 MB | 每100个工具/资源 |
| 类型映射器 | ~1-2MB | 在所有调用中共享 |
| 总开销 | ~8-13MB | 对于典型应用程序可以忽略不计 |
______________________________________________________________________
贡献与支持
🤝 贡献
我们欢迎捐款!感兴趣的领域:
- 🐛 错误报告 -复制步骤中的文件问题
- ✨ 特性 -建议使用用例进行增强
- 📚 文档 -改进指南和示例
- 🔧 代码 -按照我们的指导方针提交PR
看 贡献.md 了解详细信息。
🆘 获取帮助
📊 项目状态
- 版本: 1.0.0(最新)
- 测试覆盖范围: 97.4%(225/231次测试通过)
- 生产就绪: ✅ 是
- 维护: ✅ 活跃的
📅 发布周期
- 最新版本: 更新日志
- 发布时间表: 季度主要版本,每月错误修复
- 长期支持: 每个主要版本2年
______________________________________________________________________
许可证
Apache许可证2.0-请参阅 许可证 全文。
要点:
- ✅ 商业用途
- ✅ 修改和分发
- ❌ 承担责任(无保修)
- ✅ 专用
- ⚠️ 包括许可和版权声明
______________________________________________________________________
按角色快速导航
👨💻 Java开发人员
入门和构建功能:
🏗️ 软件架构师
了解系统设计和集成:
🤝 贡献者
设置开发环境:
🏢 DevOps与运营
部署和监控:
______________________________________________________________________
常用命令
# Build the project
mvn clean package
# Run tests
mvn test
# Run with debugging
mvn spring-boot:run -Dspring-boot.run.arguments="--debug"
# Test MCP connectivity
curl -X POST http://localhost:8090/mcp/tools/list \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}'
# Generate Javadoc
mvn javadoc:javadoc
# Deploy to Maven Central
mvn clean deploy -P ossrh-release______________________________________________________________________
路线图
当前版本(v1.0.0)
- ✅ 核心MCP工具、资源、提示
- ✅ 类型安全模式生成
- ✅ 输入验证
- ✅ 安全和限速
- ✅ 可观察性和指标
- ✅ 生产就绪
计划中(v1.1.0+)
- 📋 异步/流媒体工具
- 📋 WebSocket传输
- 📋 GraphQL端点暴露
- 📋 多租户支持
- 📋 自定义中间件/拦截器
- 📋 gRPC端点暴露
______________________________________________________________________
致谢
内置于❤️ 使用:
- Spring Boot -应用框架
- 模型上下文协议 -协议规范
- 雅加达Bean验证 -输入验证
______________________________________________________________________
联系与社交
- github: RaynerMDZ/弹簧靴mcp伴侣
- 作者 雷蒙·门德斯
- 电子邮件: raynermendezg@gmail.com
______________________________________________________________________
快乐建筑! 🚀 准备好开始了吗? → 快速入门指南
