Author / 作者: sawyer-shi
License / 许可证: MIT
Project Type / 项目类型: Open Source / 开源项目
GitHub Repository / 项目地址: https://github.com/sawyer-shi/spring-boot-mcp
Choose your preferred language / 选择您的首选语言:
🇨🇳 中文版 | 🇺🇸 English Version |
---|---|
完整的中文集成指南 | Complete English Integration Guide |
🔝 Back to Language Selection / 返回语言选择
本指南将帮助您在现有的Spring Boot项目中快速集成MCP (Model Context Protocol) 功能,让您的应用能够与AI平台(如Claude Desktop、CherryStudio等)无缝对接。
从当前项目的目录 src/main/java/com/example/controller/
中复制 MCPController.java
文件到您的Spring Boot项目中。
# 复制文件到您的项目
cp src/main/java/com/example/controller/MCPController.java /path/to/your/project/src/main/java/com/yourpackage/controller/
打开复制的 MCPController.java
文件,修改以下内容:
- 修改包声明:
// 原来的包声明
package com.example.controller;
// 改为您的包名
package com.yourpackage.controller;
- 修改业务服务导入:
// 原来的导入
import com.example.service.ProductService;
import com.example.service.CustomerService;
import com.example.service.OrderService;
import com.example.service.TransactionReportService;
import com.example.entity.*;
// 改为您的业务服务
import com.yourpackage.service.YourBusinessService1;
import com.yourpackage.service.YourBusinessService2;
import com.yourpackage.entity.*;
- 根据项目安全需求调整认证注解:
@RequireAuth
注解
在 MCPController.java
文件中,您会看到以下注解:
@RequireAuth("MCP Protocol Access")
@PostMapping(value = "", produces = "application/json", consumes = "application/json")
public ResponseEntity<?> handleMcpRequest(...)
选择适合您项目的配置:
-
如果您的项目有自定义的安全认证系统:
- 保留
@RequireAuth("MCP Protocol Access")
注解 - 确保您的安全框架能识别这个注解
- 或者替换为您项目中使用的认证注解(如
@PreAuthorize
,@Secured
等)
- 保留
-
如果您的项目使用Spring Security但不需要特殊MCP认证:
// 移除 @RequireAuth 注解,使用Spring Security默认配置 @PostMapping(value = "", produces = "application/json", consumes = "application/json") public ResponseEntity<?> handleMcpRequest(...)
-
如果您的项目不需要认证(开发/测试环境):
// 完全移除认证注解 @PostMapping(value = "", produces = "application/json", consumes = "application/json") public ResponseEntity<?> handleMcpRequest(...)
-
如果您想使用标准Spring Security注解:
@PreAuthorize("hasRole('MCP_USER')") // 或 @Secured("ROLE_MCP_ACCESS") @PostMapping(value = "", produces = "application/json", consumes = "application/json") public ResponseEntity<?> handleMcpRequest(...)
在 MCPController.java
文件中,找到 executeToolCall
方法(约第339行),这是所有业务工具的入口点。
private String executeToolCall(String toolName, Map<String, Object> arguments, String clientType) {
try {
return switch (toolName) {
// 产品工具 - 替换为您的业务逻辑
case "query_products" -> executeProductQuery(arguments, clientType);
case "create_product" -> executeProductCreate(arguments, clientType);
case "update_product" -> executeProductUpdate(arguments, clientType);
// 客户工具 - 替换为您的业务逻辑
case "query_customers" -> executeCustomerQuery(arguments, clientType);
case "create_customer" -> executeCustomerCreate(arguments, clientType);
case "update_customer" -> executeCustomerUpdate(arguments, clientType);
// 订单工具 - 替换为您的业务逻辑
case "query_orders" -> executeOrderQuery(arguments, clientType);
case "create_order" -> executeOrderCreate(arguments, clientType);
case "update_order" -> executeOrderUpdate(arguments, clientType);
// 报告工具 - 替换为您的业务逻辑
case "generate_report" -> executeReportGeneration(arguments, clientType);
default -> "ERROR: Unknown tool: " + toolName;
};
} catch (Exception e) {
return "Error executing tool '" + toolName + "': " + e.getMessage();
}
}
@Autowired
private YourBusinessService1 yourBusinessService1;
@Autowired
private YourBusinessService2 yourBusinessService2;
@Autowired
private YourReportService yourReportService;
将每个 executeXxxXxx
方法替换为调用您的Service层方法:
// 示例:将产品查询替换为您的业务逻辑
private String executeProductQuery(Map<String, Object> arguments, String clientType) {
// 调用您的Service方法
var results = yourBusinessService1.queryYourData(arguments);
// 格式化返回结果
StringBuilder result = new StringBuilder();
result.append("Query Results (").append(results.size()).append(" items)\n\n");
for (var item : results) {
result.append("- **").append(item.getName()).append("**\n");
result.append(" - Details: ").append(item.getDetails()).append("\n\n");
}
return result.toString();
}
// 示例:将创建功能替换为您的业务逻辑
private String executeProductCreate(Map<String, Object> arguments, String clientType) {
try {
// 调用您的Service创建方法
var createdItem = yourBusinessService1.createItem(arguments);
return String.format("Item Created Successfully\n\n**%s** (ID: %d)\n- Status: %s",
createdItem.getName(),
createdItem.getId(),
createdItem.getStatus());
} catch (Exception e) {
return "Error creating item: " + e.getMessage();
}
}
在 createToolsList()
方法中(约第741行),更新工具定义以反映您的业务功能:
private List<Map<String, Object>> createToolsList() {
return Arrays.asList(
// 您的业务工具1
createTool("query_your_data", "Query Your Data",
"Search and filter your business data",
createYourDataQuerySchema()),
createTool("create_your_item", "Create Your Item",
"Create a new item in your system",
createYourItemCreateSchema()),
// 您的业务工具2
createTool("generate_your_report", "Generate Your Report",
"Generate your business reports",
createYourReportSchema())
);
}
# 使用Maven启动
mvn spring-boot:run
# 或使用Gradle启动
./gradlew bootRun
访问以下端点验证MCP服务正常运行:
# 健康检查(通常不需要认证)
curl http://localhost:8080/mcp/health
# 服务器发现(可能需要认证)
curl http://localhost:8080/mcp \
-H "Authorization: Bearer YOUR_TOKEN_HERE"
# 工具列表(需要认证 - 请替换为您的实际授权信息)
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"jsonrpc":"2.0","method":"tools/list","id":1}'
授权配置说明:
YOUR_TOKEN_HERE
需要替换为您项目中的实际JWT Token、API Key或其他认证令牌- 如果使用Basic Auth,请使用:
-H "Authorization: Basic base64(username:password)"
- 如果使用自定义Header,请根据您的项目配置调整
在 ~/.claude_desktop_config.json
中添加(包含授权信息):
{
"mcpServers": {
"your-spring-boot-app": {
"command": "curl",
"args": [
"-X", "POST",
"http://localhost:8080/mcp",
"-H", "Content-Type: application/json",
"-H", "Authorization: Bearer YOUR_TOKEN_HERE",
"-d", "@-"
]
}
}
}
注意:请将 YOUR_TOKEN_HERE
替换为您的实际授权令牌
- 打开CherryStudio设置
- 添加MCP服务器
- 输入服务器地址:
http://localhost:8080/mcp
- 配置授权信息(Bearer Token或其他认证方式)
- 测试连接
在AI平台中测试您的MCP工具:
用户:请查询我的业务数据
AI:我来帮您查询业务数据... [调用您的MCP工具]
用户:创建一个新的业务项目
AI:我来为您创建新项目... [调用您的创建工具]
如果您需要在生产环境中使用,建议:
- 启用HTTPS
- 配置认证机制
- 设置访问控制
- 添加请求限制
- 配置连接池
- 启用缓存
- 设置超时时间
- 监控资源使用
🔝 Back to Language Selection / 返回语言选择
This guide helps you quickly integrate MCP (Model Context Protocol) functionality into your existing Spring Boot project, enabling seamless integration with AI platforms like Claude Desktop, CherryStudio, and more.
Copy the MCPController.java
file from the current project directory src/main/java/com/example/controller/
to your Spring Boot project.
# Copy file to your project
cp src/main/java/com/example/controller/MCPController.java /path/to/your/project/src/main/java/com/yourpackage/controller/
Open the copied MCPController.java
file and modify the following:
- Update package declaration:
// Original package declaration
package com.example.controller;
// Change to your package name
package com.yourpackage.controller;
- Update business service imports:
// Original imports
import com.example.service.ProductService;
import com.example.service.CustomerService;
import com.example.service.OrderService;
import com.example.service.TransactionReportService;
import com.example.entity.*;
// Change to your business services
import com.yourpackage.service.YourBusinessService1;
import com.yourpackage.service.YourBusinessService2;
import com.yourpackage.entity.*;
- Adjust authentication annotations based on your project's security requirements:
@RequireAuth
annotation based on your project's security configuration
In the MCPController.java
file, you'll see the following annotation:
@RequireAuth("MCP Protocol Access")
@PostMapping(value = "", produces = "application/json", consumes = "application/json")
public ResponseEntity<?> handleMcpRequest(...)
Choose the configuration that fits your project:
-
If your project has a custom security authentication system:
- Keep the
@RequireAuth("MCP Protocol Access")
annotation - Ensure your security framework can recognize this annotation
- Or replace it with authentication annotations used in your project (like
@PreAuthorize
,@Secured
, etc.)
- Keep the
-
If your project uses Spring Security but doesn't need special MCP authentication:
// Remove @RequireAuth annotation, use Spring Security default configuration @PostMapping(value = "", produces = "application/json", consumes = "application/json") public ResponseEntity<?> handleMcpRequest(...)
-
If your project doesn't need authentication (development/testing environment):
// Completely remove authentication annotation @PostMapping(value = "", produces = "application/json", consumes = "application/json") public ResponseEntity<?> handleMcpRequest(...)
-
If you want to use standard Spring Security annotations:
@PreAuthorize("hasRole('MCP_USER')") // or @Secured("ROLE_MCP_ACCESS") @PostMapping(value = "", produces = "application/json", consumes = "application/json") public ResponseEntity<?> handleMcpRequest(...)
In the MCPController.java
file, find the executeToolCall
method (around line 339), which is the entry point for all business tools.
private String executeToolCall(String toolName, Map<String, Object> arguments, String clientType) {
try {
return switch (toolName) {
// Product tools - Replace with your business logic
case "query_products" -> executeProductQuery(arguments, clientType);
case "create_product" -> executeProductCreate(arguments, clientType);
case "update_product" -> executeProductUpdate(arguments, clientType);
// Customer tools - Replace with your business logic
case "query_customers" -> executeCustomerQuery(arguments, clientType);
case "create_customer" -> executeCustomerCreate(arguments, clientType);
case "update_customer" -> executeCustomerUpdate(arguments, clientType);
// Order tools - Replace with your business logic
case "query_orders" -> executeOrderQuery(arguments, clientType);
case "create_order" -> executeOrderCreate(arguments, clientType);
case "update_order" -> executeOrderUpdate(arguments, clientType);
// Report tools - Replace with your business logic
case "generate_report" -> executeReportGeneration(arguments, clientType);
default -> "ERROR: Unknown tool: " + toolName;
};
} catch (Exception e) {
return "Error executing tool '" + toolName + "': " + e.getMessage();
}
}
@Autowired
private YourBusinessService1 yourBusinessService1;
@Autowired
private YourBusinessService2 yourBusinessService2;
@Autowired
private YourReportService yourReportService;
Replace each executeXxxXxx
method to call your Service layer methods:
// Example: Replace product query with your business logic
private String executeProductQuery(Map<String, Object> arguments, String clientType) {
// Call your Service method
var results = yourBusinessService1.queryYourData(arguments);
// Format return results
StringBuilder result = new StringBuilder();
result.append("Query Results (").append(results.size()).append(" items)\n\n");
for (var item : results) {
result.append("- **").append(item.getName()).append("**\n");
result.append(" - Details: ").append(item.getDetails()).append("\n\n");
}
return result.toString();
}
// Example: Replace create functionality with your business logic
private String executeProductCreate(Map<String, Object> arguments, String clientType) {
try {
// Call your Service create method
var createdItem = yourBusinessService1.createItem(arguments);
return String.format("Item Created Successfully\n\n**%s** (ID: %d)\n- Status: %s",
createdItem.getName(),
createdItem.getId(),
createdItem.getStatus());
} catch (Exception e) {
return "Error creating item: " + e.getMessage();
}
}
In the createToolsList()
method (around line 741), update tool definitions to reflect your business functionality:
private List<Map<String, Object>> createToolsList() {
return Arrays.asList(
// Your business tool 1
createTool("query_your_data", "Query Your Data",
"Search and filter your business data",
createYourDataQuerySchema()),
createTool("create_your_item", "Create Your Item",
"Create a new item in your system",
createYourItemCreateSchema()),
// Your business tool 2
createTool("generate_your_report", "Generate Your Report",
"Generate your business reports",
createYourReportSchema())
);
}
# Start with Maven
mvn spring-boot:run
# Or start with Gradle
./gradlew bootRun
Access the following endpoints to verify MCP service is running properly:
# Health check (usually doesn't require authentication)
curl http://localhost:8080/mcp/health
# Server discovery (may require authentication)
curl http://localhost:8080/mcp \
-H "Authorization: Bearer YOUR_TOKEN_HERE"
# Tool list (requires authentication - replace with your actual authorization info)
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{"jsonrpc":"2.0","method":"tools/list","id":1}'
Authorization Configuration:
YOUR_TOKEN_HERE
needs to be replaced with your actual JWT Token, API Key, or other authentication tokens- If using Basic Auth, use:
-H "Authorization: Basic base64(username:password)"
- If using custom headers, adjust according to your project configuration
Add to ~/.claude_desktop_config.json
(including authorization information):
{
"mcpServers": {
"your-spring-boot-app": {
"command": "curl",
"args": [
"-X", "POST",
"http://localhost:8080/mcp",
"-H", "Content-Type: application/json",
"-H", "Authorization: Bearer YOUR_TOKEN_HERE",
"-d", "@-"
]
}
}
}
Note: Please replace YOUR_TOKEN_HERE
with your actual authorization token
- Open CherryStudio settings
- Add MCP server
- Enter server address:
http://localhost:8080/mcp
- Configure authentication information (Bearer Token or other authentication methods)
- Test connection
Test your MCP tools in AI platforms:
User: Please query my business data
AI: I'll help you query business data... [Calls your MCP tool]
User: Create a new business project
AI: I'll create a new project for you... [Calls your create tool]
For production use, consider:
- Enable HTTPS
- Configure authentication mechanisms
- Set up access controls
- Add request limiting
- Configure connection pools
- Enable caching
- Set timeout values
- Monitor resource usage
- 🔗 This Project Repository - 本项目源码和文档
- MCP Protocol Documentation
- Spring Boot Documentation
- Claude Desktop MCP Guide
If you encounter any issues during integration, please:
- Check the console logs for error messages
- Verify all dependencies are properly configured
- Test endpoints manually using curl or Postman
- Ensure your business services are working correctly
Happy coding! 🎉 / 祝您编码愉快!🎉
Section / 章节 | 中文版 | English Version |
---|---|---|
Language Selection / 语言选择 | 🌐 语言选择 | 🌐 Language Selection |
Getting Started / 快速开始 | 🚀 快速集成 | 🚀 Quick Integration |
Copy Files / 复制文件 | 📁 第一部分 | 📁 Part 1 |
Business Logic / 业务逻辑 | 🔧 第二部分 | 🔧 Part 2 |
Deployment / 部署配置 | 🚀 第三部分 | 🚀 Part 3 |
Advanced Config / 高级配置 | ⚙️ 高级配置 | ⚙️ Advanced Config |
Resources / 资源链接 | 📚 相关资源 | 📚 Additional Resources |
This project is licensed under the MIT License - see the details below.
本项目采用MIT许可证 - 详见下方说明。
MIT License
Copyright (c) 2024 sawyer-shi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
sawyer-shi
- 🌟 This project is open source and free to use
- 🔗 GitHub Repository: https://github.com/sawyer-shi/spring-boot-mcp
- 🤝 Contributions and feedback are welcome
- 📧 Feel free to report issues or suggest improvements
- ⭐ If this project helps you, please give it a star!
sawyer-shi
- 🌟 本项目开源免费使用
- 🔗 项目地址: https://github.com/sawyer-shi/spring-boot-mcp
- 🤝 欢迎贡献代码和反馈建议
- 📧 欢迎报告问题或提出改进建议
- ⭐ 如果这个项目对您有帮助,请给个星标!