Skip to content

Only add a Controller Class to make your Spring project be a MCP server【添加一个Controller让你的Spring秒变MCP】

License

Notifications You must be signed in to change notification settings

sawyer-shi/spring-boot-mcp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Spring Boot MCP Integration Guide / Spring Boot MCP集成指南

License: MIT Author GitHub

Author / 作者: sawyer-shi
License / 许可证: MIT
Project Type / 项目类型: Open Source / 开源项目
GitHub Repository / 项目地址: https://github.com/sawyer-shi/spring-boot-mcp


🌐 Language / 语言选择

Choose your preferred language / 选择您的首选语言:

🇨🇳 中文版 🇺🇸 English Version
完整的中文集成指南 Complete English Integration Guide

中文版 / Chinese Version

🔝 Back to Language Selection / 返回语言选择

🚀 快速集成MCP到您的Spring Boot项目

本指南将帮助您在现有的Spring Boot项目中快速集成MCP (Model Context Protocol) 功能,让您的应用能够与AI平台(如Claude Desktop、CherryStudio等)无缝对接。


第一部分:复制MCP控制器文件

步骤1:复制控制器文件

从当前项目的目录 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/

步骤2:修改包名和导入

打开复制的 MCPController.java 文件,修改以下内容:

  1. 修改包声明
// 原来的包声明
package com.example.controller;

// 改为您的包名
package com.yourpackage.controller;
  1. 修改业务服务导入
// 原来的导入
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.*;
  1. 根据项目安全需求调整认证注解

⚠️ 重要:根据您项目的安全配置决定是否保留 @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中的业务工具方法替换为您自己的Service层方法

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();
    }
}

替换步骤:

1. 注入您的业务服务

@Autowired
private YourBusinessService1 yourBusinessService1;

@Autowired  
private YourBusinessService2 yourBusinessService2;

@Autowired
private YourReportService yourReportService;

2. 替换工具方法实现

将每个 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();
    }
}

3. 更新工具列表定义

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())
    );
}

第三部分:启动项目并配置MCP服务

步骤1:启动您的Spring Boot项目

# 使用Maven启动
mvn spring-boot:run

# 或使用Gradle启动
./gradlew bootRun

步骤2:验证MCP服务

访问以下端点验证MCP服务正常运行:

⚠️ 重要提示:大部分Spring Boot项目都配置了安全认证,访问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,请根据您的项目配置调整

步骤3:配置到AI平台

配置Claude Desktop

~/.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

  1. 打开CherryStudio设置
  2. 添加MCP服务器
  3. 输入服务器地址:http://localhost:8080/mcp
  4. 配置授权信息(Bearer Token或其他认证方式)
  5. 测试连接

步骤4:测试MCP功能

在AI平台中测试您的MCP工具:

用户:请查询我的业务数据
AI:我来帮您查询业务数据... [调用您的MCP工具]

用户:创建一个新的业务项目
AI:我来为您创建新项目... [调用您的创建工具]

🔧 高级配置

安全配置

如果您需要在生产环境中使用,建议:

  1. 启用HTTPS
  2. 配置认证机制
  3. 设置访问控制
  4. 添加请求限制

性能优化

  1. 配置连接池
  2. 启用缓存
  3. 设置超时时间
  4. 监控资源使用

English Version

🔝 Back to Language Selection / 返回语言选择

🚀 Quick MCP Integration for Your Spring Boot Project

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.


Part 1: Copy MCP Controller File

Step 1: Copy Controller File

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/

Step 2: Modify Package and Imports

Open the copied MCPController.java file and modify the following:

  1. Update package declaration:
// Original package declaration
package com.example.controller;

// Change to your package name
package com.yourpackage.controller;
  1. 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.*;
  1. Adjust authentication annotations based on your project's security requirements:

⚠️ Important: Decide whether to keep the @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.)
  • 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(...)

Part 2: Replace Business Tool Methods

Core Task: Replace MCPController business tool methods with your own Service layer methods

In the MCPController.java file, find the executeToolCall method (around line 339), which is the entry point for all business tools.

Original Business Tool Example:

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();
    }
}

Replacement Steps:

1. Inject Your Business Services

@Autowired
private YourBusinessService1 yourBusinessService1;

@Autowired  
private YourBusinessService2 yourBusinessService2;

@Autowired
private YourReportService yourReportService;

2. Replace Tool Method Implementations

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();
    }
}

3. Update Tool List Definitions

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())
    );
}

Part 3: Start Project and Configure MCP Service

Step 1: Start Your Spring Boot Project

# Start with Maven
mvn spring-boot:run

# Or start with Gradle
./gradlew bootRun

Step 2: Verify MCP Service

Access the following endpoints to verify MCP service is running properly:

⚠️ Important Notice: Most Spring Boot projects have security authentication configured. You MUST provide valid authorization information when accessing MCP endpoints!

# 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

Step 3: Configure AI Platforms

Configure Claude Desktop

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

Configure CherryStudio

  1. Open CherryStudio settings
  2. Add MCP server
  3. Enter server address: http://localhost:8080/mcp
  4. Configure authentication information (Bearer Token or other authentication methods)
  5. Test connection

Step 4: Test MCP Functionality

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]

🔧 Advanced Configuration

Security Configuration

For production use, consider:

  1. Enable HTTPS
  2. Configure authentication mechanisms
  3. Set up access controls
  4. Add request limiting

Performance Optimization

  1. Configure connection pools
  2. Enable caching
  3. Set timeout values
  4. Monitor resource usage

📚 Additional Resources

🤝 Support

If you encounter any issues during integration, please:

  1. Check the console logs for error messages
  2. Verify all dependencies are properly configured
  3. Test endpoints manually using curl or Postman
  4. Ensure your business services are working correctly

Happy coding! 🎉 / 祝您编码愉快!🎉


🔗 Quick Navigation / 快速导航

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

📄 License / 许可证

This project is licensed under the MIT License - see the details below.

本项目采用MIT许可证 - 详见下方说明。

MIT License

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.

👨‍💻 Author / 作者

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

About

Only add a Controller Class to make your Spring project be a MCP server【添加一个Controller让你的Spring秒变MCP】

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages