unnode001/mcp-spring-template
If you are the rightful owner of mcp-spring-template and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
This project is a Spring AI framework-based MCP (Model Context Protocol) server providing various utility services.
MCP Spring Template - 基础服务实例
这个项目基于Spring AI框架,提供了多个实用的MCP (Model Context Protocol) Server实例。
🚀 包含的服务
1. WeatherService (天气服务)
getWeather(location)- 获取指定地点的天气信息
2. FileOperationService (文件操作服务)
readFile(filePath)- 读取文件内容writeFile(filePath, content)- 写入内容到文件listDirectory(directoryPath)- 列出目录内容fileExists(path)- 检查文件/目录是否存在createDirectory(directoryPath)- 创建目录deleteFile(filePath)- 删除文件getFileInfo(filePath)- 获取文件详细信息
3. MathCalculationService (数学计算服务)
calculate(expression)- 基础四则运算sqrt(number)- 计算平方根power(base, exponent)- 幂运算factorial(n)- 计算阶乘sin(degrees)- 正弦值(角度输入)cos(degrees)- 余弦值(角度输入)tan(degrees)- 正切值(角度输入)average(numbers)- 计算平均值percentage(part, total)- 计算百分比currencyConvert(amount, rate, fromCurrency, toCurrency)- 货币转换compoundInterest(principal, rate, time, compoundFrequency)- 复利计算
4. TimeService (时间处理服务)
getCurrentTime()- 获取当前时间getCurrentTimeInTimezone(timezone)- 获取指定时区时间daysBetween(startDate, endDate)- 计算日期间隔addDays(date, days)- 日期加减getDayOfWeek(date)- 获取星期几formatTimestamp(timestamp)- 格式化时间戳dateToTimestamp(dateTime)- 日期转时间戳calculateAge(birthDate)- 计算年龄getDaysInMonth(year, month)- 获取月份天数convertTimezone(dateTime, fromTimezone, toTimezone)- 时区转换getWorkdays(startDate, endDate)- 计算工作日
5. DataValidationService (数据验证服务)
validateEmail(email)- 验证邮箱格式validatePhoneNumber(phone)- 验证中国手机号validateIdCard(idCard)- 验证中国身份证号validateUrl(url)- 验证URL格式validatePassword(password)- 验证密码强度validateIPv4(ip)- 验证IPv4地址validateChineseName(name)- 验证中文姓名validateBankCard(cardNumber)- 验证银行卡号(Luhn算法)
6. TextProcessingService (文本处理服务)
analyzeText(text)- 统计文本字符数、词数、行数convertCase(text, caseType)- 转换文本大小写removeDuplicateLines(text)- 移除重复行countWordFrequency(text)- 统计词频findAndReplace(text, searchText, replaceText, caseSensitive)- 查找替换extractNumbers(text)- 提取数字extractEmails(text)- 提取邮箱地址generateSummary(text, maxSentences)- 生成文本摘要calculateSimilarity(text1, text2)- 计算文本相似度
🛠 如何运行
-
确保你有Java 21或更高版本
-
运行项目:
mvn spring-boot:run -
服务将在默认端口启动,所有的@Tool标注的方法都会自动注册为MCP工具
🔗 MCP客户端连接指南
什么是MCP (Model Context Protocol)
MCP是一个开放标准,允许AI模型安全地连接到本地和远程资源。通过MCP,AI助手可以访问文件系统、数据库、API等资源,大大扩展其能力。
支持的MCP客户端
本项目作为MCP服务器,可以被以下客户端连接使用:
- Claude Desktop - Anthropic官方桌面应用
- Cline (VS Code扩展) - VS Code中的AI编程助手
- 其他支持MCP协议的AI客户端
在Claude Desktop中配置
-
安装Claude Desktop应用
- 从 Claude Desktop官网 下载并安装
-
配置MCP服务器
编辑Claude Desktop的配置文件:
- Windows:
%APPDATA%\Claude\claude_desktop_config.json - macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Linux:
~/.config/Claude/claude_desktop_config.json
- Windows:
-
添加配置
在配置文件中添加以下内容:
{ "mcpServers": { "spring-mcp-tools": { "command": "curl", "args": [ "-X", "POST", "http://localhost:8080/mcp/session", "-H", "Content-Type: application/json" ], "env": {} } } }
在VS Code中使用Cline扩展
-
安装Cline扩展
在VS Code扩展市场搜索并安装 "Cline" -
配置MCP服务器
在VS Code设置中找到Cline配置,添加MCP服务器:
{ "cline.mcpServers": [ { "name": "spring-mcp-tools", "url": "http://localhost:8080/mcp", "description": "Spring AI MCP工具集合" } ] }
自定义MCP客户端连接
如果你使用其他支持MCP的客户端,可以通过以下方式连接:
HTTP端点: http://localhost:8080/mcp
协议: MCP over HTTP
工具发现: 自动发现所有@Tool注解的方法
连接验证
启动服务后,你可以通过以下方式验证MCP连接:
-
检查服务状态
curl http://localhost:8080/actuator/health -
列出可用工具
curl http://localhost:8080/mcp/tools -
测试工具调用
curl -X POST http://localhost:8080/mcp/call \ -H "Content-Type: application/json" \ -d '{ "tool": "getCurrentTime", "arguments": {} }'
配置说明
端口配置
默认端口为8080,可通过以下方式修改:
在 application.properties 中添加:
server.port=9090
安全配置
在生产环境中,建议配置安全认证:
# 启用基础认证
spring.security.user.name=admin
spring.security.user.password=your-password
CORS配置
如果需要跨域访问,在配置类中添加:
@CrossOrigin(origins = "*")
@RestController
public class McpController {
// MCP endpoints
}
📝 使用示例
这些服务可以通过Spring AI框架与各种AI模型集成使用。每个服务的方法都使用了@Tool注解,使其可以被AI模型调用。
MCP客户端使用示例
连接成功后,你可以在支持MCP的AI客户端中直接使用这些工具。以下是一些使用示例:
1. 文件操作示例
用户: "帮我读取 /path/to/document.txt 文件的内容"
AI: 使用 readFile 工具读取文件内容并返回结果
用户: "在 /tmp 目录下创建一个名为 'test' 的目录"
AI: 使用 createDirectory 工具创建目录
用户: "列出当前目录的所有文件"
AI: 使用 listDirectory 工具列出文件清单
2. 数学计算示例
用户: "计算 (123 + 456) * 789 的结果"
AI: 使用 calculate 工具进行计算
用户: "计算复利:本金10000元,年利率5%,存期3年,每年复利一次"
AI: 使用 compoundInterest 工具计算复利结果
用户: "求这组数字的平均值:23, 45, 67, 89, 12"
AI: 使用 average 工具计算平均值
3. 时间处理示例
用户: "现在几点了?"
AI: 使用 getCurrentTime 工具获取当前时间
用户: "计算从2023-01-01到2023-12-31有多少天"
AI: 使用 daysBetween 工具计算日期差
用户: "帮我计算1990年5月15日出生的人现在多大了"
AI: 使用 calculateAge 工具计算年龄
4. 数据验证示例
用户: "验证这个邮箱地址是否正确:user@example.com"
AI: 使用 validateEmail 工具验证邮箱格式
用户: "检查这个密码的强度:MyPassword123!"
AI: 使用 validatePassword 工具分析密码强度
用户: "验证这个身份证号是否有效:110101199001011234"
AI: 使用 validateIdCard 工具验证身份证号
5. 文本处理示例
用户: "分析这段文本的字数、词数等统计信息:[文本内容]"
AI: 使用 analyzeText 工具进行文本分析
用户: "把这段文本转换为标题格式:hello world example"
AI: 使用 convertCase 工具转换大小写
用户: "帮我生成这篇文章的摘要,不超过3句话"
AI: 使用 generateSummary 工具生成摘要
示例场景
- 文件管理助手: 使用FileOperationService帮助用户管理文件
- 数学计算器: 使用MathCalculationService进行各种数学运算
- 时间管理工具: 使用TimeService处理日期时间相关任务
- 数据验证助手: 使用DataValidationService验证各种数据格式
- 文本处理工具: 使用TextProcessingService分析和处理文本
🔧 自定义扩展
你可以通过以下方式扩展功能:
- 在现有服务中添加新的
@Tool方法 - 创建新的Service类并在
ApplicationContext中注册 - 修改现有方法的实现以满足特定需求
📋 依赖项
- Spring Boot 3.2.6
- Spring AI MCP Server WebMVC 1.0.0
- Java 21
⚠️ 注意事项
- 文件操作服务在实际使用时要注意文件权限和安全性
- 某些数学计算可能在极大数值时产生精度问题
- 时间服务使用系统默认时区,可根据需要调整
- 数据验证基于常见的格式规则,可能需要根据具体业务调整
- 文本处理服务提供基础功能,复杂的NLP任务可能需要额外的库
🔧 故障排除
常见问题及解决方案
1. MCP连接失败
问题: AI客户端无法连接到MCP服务器 解决方案:
- 确保Spring Boot应用正在运行
- 检查端口是否被占用 (
netstat -an | findstr 8080) - 验证防火墙设置是否允许8080端口
- 确认配置文件中的URL和端口正确
2. 工具调用失败
问题: MCP工具调用返回错误 解决方案:
- 检查传入参数是否符合工具要求
- 查看Spring Boot控制台的错误日志
- 验证文件路径权限(文件操作相关工具)
- 确认网络连接(如果涉及外部资源)
3. 编译或启动失败
问题: 项目无法编译或启动 解决方案:
- 确保Java版本为21或更高
- 检查Maven依赖是否正确下载
- 清理并重新编译:
mvn clean compile - 检查日志中的具体错误信息
4. 性能问题
问题: 工具调用响应慢 解决方案:
- 增加JVM堆内存:
-Xmx2g - 检查文件I/O操作是否涉及大文件
- 优化数据库查询(如果有)
- 考虑添加缓存机制
调试技巧
启用详细日志
在 application.properties 中添加:
logging.level.com.unnode.SpringAiDemo=DEBUG
logging.level.org.springframework.ai=DEBUG
监控端点
访问以下端点获取运行状态信息:
- 健康检查:
http://localhost:8080/actuator/health - 应用信息:
http://localhost:8080/actuator/info - 环境信息:
http://localhost:8080/actuator/env
工具测试
可以通过以下方式直接测试工具功能:
# 测试时间工具
curl -X POST http://localhost:8080/mcp/call \
-H "Content-Type: application/json" \
-d '{"tool": "getCurrentTime", "arguments": {}}'
# 测试计算工具
curl -X POST http://localhost:8080/mcp/call \
-H "Content-Type: application/json" \
-d '{"tool": "calculate", "arguments": {"expression": "10+20"}}'
🤝 贡献
欢迎提交Issue和Pull Request来改进这个项目!