金融钱包MCP服务器
项目条款:https://gokhana.medium.com/from-rest-api-to-mcp-server-convert-your-spring-apis-into-ai-tools-with-spring-ai-07b8f36b0212
该项目是一个简单的钱包管理后端,它公开了REST API,并与Spring AI的MCP(模型上下文协议)服务器集成,用于AI驱动的工具访问。
______________________________________________________________________
Spring AI集成
- 集成Spring AI MCP服务器启动器
- 带注释的服务方法
@Tool用于AI工具曝光 - 添加了MCP服务器操作的配置
______________________________________________________________________
关键依赖关系
17
1.0.0
org.springframework.ai
spring-ai-starter-mcp-server
______________________________________________________________________
特性
- 钱包管理(创建、读取、更新、删除)
- 将收入和支出添加到钱包中
- 自动余额更新
- 输入验证和错误处理
- H2内存数据库,便于测试
______________________________________________________________________
技术栈
- Java 17
- 弹簧靴3.2.3
- Spring数据JPA
- H2数据库(内存中)
- 梅文
- 龙目
- Spring AI MCP服务器
______________________________________________________________________
数据模型
| 字段 | 类型 | 描述 |
|---|---|---|
| id | 长 | 钱包id |
| name | 字符串 | 钱包名称 |
| balance | BigDecimal | 当前余额 |
______________________________________________________________________
API终点
GET /api/wallets-获取所有钱包GET /api/wallets/{id}-通过ID获取钱包POST /api/wallets-创建新钱包PUT /api/wallets/{id}-更新钱包DELETE /api/wallets/{id}-删除钱包POST /api/wallets/{id}/expense?amount={amount}-添加费用POST /api/wallets/{id}/income?amount={amount}-增加收入
______________________________________________________________________
工具注释
该应用程序使用Spring AI Tool注释将服务方法作为MCP工具公开。
例子:
@Tool(name = "create-wallet", description = "Creates a new wallet with the given details")
public Wallet createWallet(Wallet wallet) { ... }外露工具:
- 创建钱包
- 获取所有钱包
- 通过id获取钱包
- 更新钱包
- 删除钱包
- 增加费用
- 增加收入
______________________________________________________________________
MCP服务器配置
将以下内容添加到您的 src/main/resources/application.properties:
spring.main.web-application-type=none
spring.ai.mcp.server.name=wallet-mcp
spring.ai.mcp.server.version=0.0.1
server.port=8091在配置中注册工具回调:
@Bean
public List walletTools(WalletService walletService) {
return List.of(ToolCallbacks.from(walletService));
}______________________________________________________________________
H2控制台
- 网址:http://localhost:8091/h2-控制台
- JDBC网址:
jdbc:h2:mem:walletdb - 用户名:
sa - 密码:(空)
______________________________________________________________________
错误处理
- 404找不到钱包
- 400因不平衡或非法论点
- 集中在
GlobalExceptionHandler
______________________________________________________________________
运行应用程序
- 克隆存储库
- 建立
mvn clean package - 启动MCP服务器:
java -jar target/finance-wallet-0.0.1-SNAPSHOT.jar或使用 .cursor/mcp.json:
{
"mcpServers": {
"finance-wallet-mcp": {
"command": "java",
"args": [
"-jar",
"/Users/gokhanayrancioglu/finance-wallet/target/finance-wallet-0.0.1-SNAPSHOT.jar"
]
}
}
}