feat: 集成 MCP 工具支持
- 添加 spring-ai-starter-mcp-client 依赖 - 创建 Node.js MCP 服务器(risk-cost-server) - 在 Application.java 中配置 MCP 工具回调 - 添加 get_customer_risk_cost 工具(返回 1.2%-2.5% 的风险成本率) - 支持通过 FunctionToolCallback 调用 MCP 工具 - 更新系统提示,指导 AI 使用 MCP 工具 - 降级 Spring AI 到 1.1.2 版本 技术实现: - 使用 FunctionToolCallback 包装 MCP 工具 - 通过 Stdio 方式与 MCP 服务器通信 - JSON-RPC 协议调用工具 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c6f3eef29b
commit
581f731de3
10 files changed
+1045
-98
No files matched your search
+13
-53
@@ -1,63 +1,23 @@
|
||||
# Maven
|
||||
target/
|
||||
pom.xml.tag
|
||||
pom.xml.releaseBackup
|
||||
pom.xml.versionsBackup
|
||||
pom.xml.next
|
||||
release.properties
|
||||
dependency-reduced-pom.xml
|
||||
buildNumber.properties
|
||||
.mvn/timing.properties
|
||||
.mvn/wrapper/maven-wrapper.jar
|
||||
# Node modules
|
||||
node_modules/
|
||||
mcp-servers/*/node_modules/
|
||||
|
||||
# Logs
|
||||
logs/
|
||||
*.log
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
*.iml
|
||||
*.iws
|
||||
*.ipr
|
||||
.vscode/
|
||||
.classpath
|
||||
.project
|
||||
.settings/
|
||||
bin/
|
||||
*.iml
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
logs/
|
||||
|
||||
# Environment variables
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# Spring Boot
|
||||
application-*.properties
|
||||
application-*.yml
|
||||
!application.properties
|
||||
!application.yml
|
||||
|
||||
# Build
|
||||
build/
|
||||
out/
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
*.egg-info/
|
||||
dist/
|
||||
build/
|
||||
|
||||
# Temporary files
|
||||
# Temp files
|
||||
nul
|
||||
*.tmp
|
||||
*.bak
|
||||
*.cache
|
||||
|
||||
# Playwright
|
||||
.playwright-mcp/
|
||||
@@ -0,0 +1,293 @@
|
||||
# MCP 集成完成 - 启动和测试指南
|
||||
|
||||
## 修复的问题
|
||||
|
||||
### 错误原因
|
||||
Spring AI 1.1.2 不支持直接将 `Function` 对象传递给 `.defaultTools()`,需要使用 `FunctionCallback` 包装。
|
||||
|
||||
### 解决方案
|
||||
使用 `FunctionCallbackWrapper.builder()` 将 `GetCustomerRiskCostTool` 包装为 `FunctionCallback`:
|
||||
|
||||
```java
|
||||
@Bean
|
||||
FunctionCallback getCustomerRiskCostToolCallback(MCPClient riskCostMCPClient) {
|
||||
GetCustomerRiskCostTool tool = new GetCustomerRiskCostTool(riskCostMCPClient);
|
||||
|
||||
return FunctionCallbackWrapper.builder(tool)
|
||||
.withName("get_customer_risk_cost")
|
||||
.withDescription("获取客户的风险成本率(%)...")
|
||||
.build();
|
||||
}
|
||||
```
|
||||
|
||||
然后使用 `.defaultToolCallbacks()` 注册:
|
||||
```java
|
||||
.defaultToolCallbacks(getCustomerRiskCostToolCallback)
|
||||
```
|
||||
|
||||
## 启动应用
|
||||
|
||||
### 方法 1: 使用 Maven
|
||||
```bash
|
||||
cd D:\project\spring-ai-skill
|
||||
mvn spring-boot:run
|
||||
```
|
||||
|
||||
### 方法 2: 使用 IDE
|
||||
在 IDE 中直接运行 `Application.java` 的 `main` 方法
|
||||
|
||||
### 方法 3: 使用 Gradle(如果配置了)
|
||||
```bash
|
||||
cd D:\project\spring-ai-skill
|
||||
gradle bootRun
|
||||
```
|
||||
|
||||
## 启动验证
|
||||
|
||||
### 1. 检查控制台日志
|
||||
|
||||
应该看到以下日志:
|
||||
|
||||
```
|
||||
MCP 服务器已启动: node D:/project/spring-ai-skill/mcp-servers/risk-cost-server/index.js
|
||||
客户风险成本 MCP 服务器已启动
|
||||
```
|
||||
|
||||
如果看到这些日志,说明 MCP 服务器已成功启动。
|
||||
|
||||
### 2. 检查应用端口
|
||||
|
||||
应该看到:
|
||||
```
|
||||
Tomcat started on port 8080 (http) with context path '/'
|
||||
```
|
||||
|
||||
## 测试步骤
|
||||
|
||||
### 1. 访问 Web 界面
|
||||
打开浏览器:http://localhost:8080/index.html
|
||||
|
||||
### 2. 测试用例
|
||||
|
||||
#### 测试 1: 单独测试 MCP 工具
|
||||
**输入**:
|
||||
```
|
||||
查询"某某科技有限公司"的风险成本率
|
||||
```
|
||||
|
||||
**预期结果**:
|
||||
- 前端显示工具调用:`get_customer_risk_cost`
|
||||
- 工具参数:`{"company_name": "某某科技有限公司"}`
|
||||
- 工具结果:包含风险成本率(1.2% ~ 2.5%)
|
||||
- AI 回复:解释该企业的风险成本率
|
||||
|
||||
**控制台日志**:
|
||||
```
|
||||
MCP 请求: {"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_customer_risk_cost","arguments":{"company_name":"某某科技有限公司"}}}
|
||||
MCP 响应: {"result":{"content":[{"type":"text","text":"..."}]},"jsonrpc":"2.0","id":1}
|
||||
```
|
||||
|
||||
#### 测试 2: Skill + MCP 组合(重点测试!)
|
||||
**输入**:
|
||||
```
|
||||
帮我计算"某某科技有限公司"的定价,需要考虑风险成本
|
||||
```
|
||||
|
||||
**预期结果**:
|
||||
- 前端显示两个工具调用:
|
||||
1. `get_customer_risk_cost` - 获取风险成本率
|
||||
2. `SkillsTool` (客户定价) - 计算定价
|
||||
- AI 回复:综合两个工具的结果,给出最终定价
|
||||
|
||||
**这个测试验证了 Skill 和 MCP 工具的组合使用!**
|
||||
|
||||
#### 测试 3: 多次调用 MCP 工具
|
||||
**输入**:
|
||||
```
|
||||
对比"企业A"、"企业B"和"企业C"的风险成本率
|
||||
```
|
||||
|
||||
**预期结果**:
|
||||
- 前端显示三次工具调用
|
||||
- AI 回复:对比三个企业的风险成本率
|
||||
|
||||
#### 测试 4: 结合文件操作
|
||||
**输入**:
|
||||
```
|
||||
查询"测试企业"的风险成本,并将结果保存到 risk_cost.txt 文件
|
||||
```
|
||||
|
||||
**预期结果**:
|
||||
- 调用 `get_customer_risk_cost` 工具
|
||||
- 调用 `FileSystemTools` 写入文件
|
||||
- 文件创建成功
|
||||
|
||||
## 验证要点
|
||||
|
||||
### 1. MCP 服务器状态
|
||||
- ✅ 控制台显示 "MCP 服务器已启动"
|
||||
- ✅ 控制台显示 "客户风险成本 MCP 服务器已启动"
|
||||
|
||||
### 2. 工具调用日志
|
||||
- ✅ 控制台显示 MCP 请求和响应
|
||||
- ✅ MyLoggingAdvisor 输出工具调用信息
|
||||
- ✅ ToolCallCaptureAdvisor 捕获工具调用
|
||||
|
||||
### 3. 前端显示
|
||||
- ✅ 工具调用在 AI 回复之前显示
|
||||
- ✅ 工具名称、参数、结果清晰可见
|
||||
- ✅ 支持 Markdown 渲染和代码高亮
|
||||
|
||||
### 4. LLM 日志
|
||||
- ✅ `logs/llm/llm-YYYY-MM-DD.log` 包含完整的请求响应
|
||||
- ✅ 包含工具调用信息
|
||||
- ✅ 包含 token 使用统计
|
||||
|
||||
## 常见问题排查
|
||||
|
||||
### Q1: 应用启动失败
|
||||
**症状**:`BeanInstantiationException` 或其他启动错误
|
||||
|
||||
**排查步骤**:
|
||||
1. 检查 Java 版本:`java -version`(需要 Java 17+)
|
||||
2. 检查依赖是否下载完成
|
||||
3. 查看完整的错误堆栈
|
||||
4. 检查 application.properties 配置是否正确
|
||||
|
||||
### Q2: MCP 服务器无法启动
|
||||
**症状**:控制台显示 "MCP 服务器无响应" 或 IOException
|
||||
|
||||
**排查步骤**:
|
||||
1. 检查 Node.js 是否安装:`node --version`
|
||||
2. 检查 MCP 服务器路径是否正确:
|
||||
```
|
||||
D:/project/spring-ai-skill/mcp-servers/risk-cost-server/index.js
|
||||
```
|
||||
3. 手动测试 MCP 服务器:
|
||||
```bash
|
||||
cd mcp-servers/risk-cost-server
|
||||
echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_customer_risk_cost","arguments":{"company_name":"测试"}}}' | node index.js
|
||||
```
|
||||
|
||||
### Q3: 工具未被调用
|
||||
**症状**:AI 直接回复,没有调用 MCP 工具
|
||||
|
||||
**可能原因**:
|
||||
1. 系统提示不够明确
|
||||
2. 用户输入不够明确
|
||||
3. 工具描述不够清晰
|
||||
|
||||
**解决方法**:
|
||||
1. 使用更明确的提示词,例如:"使用 MCP 工具查询..."
|
||||
2. 检查工具是否正确注册:查看 MyLoggingAdvisor 的 "Available Tools" 日志
|
||||
3. 检查 FunctionCallback 的描述是否清晰
|
||||
|
||||
### Q4: 工具调用失败
|
||||
**症状**:前端显示工具调用,但返回错误
|
||||
|
||||
**排查步骤**:
|
||||
1. 查看控制台的 MCP 请求和响应
|
||||
2. 检查参数格式是否正确
|
||||
3. 检查 MCP 服务器是否正常运行
|
||||
4. 查看 LLM 日志文件
|
||||
|
||||
## 技术架构总览
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ 用户浏览器 │
|
||||
│ http://localhost:8080 │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
↓
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ ChatController (REST) │
|
||||
│ POST /api/chat/chat │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
↓
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ ChatService │
|
||||
│ 管理对话、调用 ChatClient │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
↓
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ ChatClient (Spring AI) │
|
||||
│ │
|
||||
│ Advisors: │
|
||||
│ - ToolCallAdvisor (执行工具) │
|
||||
│ - MyLoggingAdvisor (日志记录) │
|
||||
│ - ToolCallCaptureAdvisor (捕获工具调用) │
|
||||
│ - MessageChatMemoryAdvisor (对话记忆) │
|
||||
│ - LLMLoggingAdvisor (LLM 日志) │
|
||||
│ │
|
||||
│ Tools: │
|
||||
│ - SkillsTool (业务技能) │
|
||||
│ - ShellTools (Shell 命令) │
|
||||
│ - FileSystemTools (文件操作) │
|
||||
│ - get_customer_risk_cost (MCP 工具) ← 新增! │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
↓
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ GetCustomerRiskCostTool (Function) │
|
||||
│ 包装为 FunctionCallback │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
↓
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ MCPClient (JSON-RPC) │
|
||||
│ 管理与 MCP 服务器的通信 │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
↓
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Node.js MCP Server (stdio) │
|
||||
│ mcp-servers/risk-cost-server/index.js │
|
||||
│ │
|
||||
│ Tool: get_customer_risk_cost │
|
||||
│ - 输入: company_name │
|
||||
│ - 输出: risk_cost_rate (1.2% ~ 2.5%) │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## 成功标志
|
||||
|
||||
当你看到以下所有现象时,说明 MCP 集成完全成功:
|
||||
|
||||
1. ✅ 应用正常启动,无错误日志
|
||||
2. ✅ MCP 服务器成功启动
|
||||
3. ✅ Web 界面能正常访问
|
||||
4. ✅ 能够调用 MCP 工具获取风险成本
|
||||
5. ✅ 能够组合使用 Skill 和 MCP 工具
|
||||
6. ✅ 前端正确显示工具调用过程
|
||||
7. ✅ LLM 日志正确记录所有交互
|
||||
|
||||
## 下一步
|
||||
|
||||
MCP 集成已完成!现在你可以:
|
||||
|
||||
1. **扩展更多 MCP 工具**:
|
||||
- 创建新的 MCP 服务器
|
||||
- 在 Application.java 中注册新的 FunctionCallback
|
||||
- 更新系统提示
|
||||
|
||||
2. **优化工具描述**:
|
||||
- 改进 FunctionCallback 的描述
|
||||
- 让 AI 更准确地理解何时使用工具
|
||||
|
||||
3. **添加错误处理**:
|
||||
- 改进 MCPClient 的错误处理
|
||||
- 添加超时机制
|
||||
- 添加重试逻辑
|
||||
|
||||
4. **性能优化**:
|
||||
- 使用连接池管理 MCP 客户端
|
||||
- 缓存 MCP 工具结果
|
||||
- 异步调用 MCP 工具
|
||||
|
||||
## 相关文件
|
||||
|
||||
- `src/main/java/org/springaicommunity/skills/Application.java` - MCP 工具注册
|
||||
- `src/main/java/org/springaicommunity/skills/mcp/MCPClient.java` - MCP 客户端
|
||||
- `src/main/java/org/springaicommunity/skills/mcp/GetCustomerRiskCostTool.java` - MCP 工具实现
|
||||
- `mcp-servers/risk-cost-server/index.js` - Node.js MCP 服务器
|
||||
- `src/main/resources/application.properties` - MCP 配置
|
||||
- `MCP_TEST.md` - 详细测试文档
|
||||
|
||||
现在可以启动应用并开始测试了!🚀
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
# MCP 工具集成测试指南
|
||||
|
||||
## 已完成的工作
|
||||
|
||||
1. ✅ 创建了 Node.js MCP 服务器 (`mcp-servers/risk-cost-server/`)
|
||||
- 提供 `get_customer_risk_cost` 工具
|
||||
- 返回随机风险成本率(1.2% ~ 2.5%)
|
||||
|
||||
2. ✅ 创建了 MCPClient.java
|
||||
- 用于与 MCP 服务器通信
|
||||
- 支持 JSON-RPC 协议
|
||||
|
||||
3. ✅ 创建了 MCPTool.java
|
||||
- 将 MCP 工具封装为 Spring AI 可用的 Function
|
||||
- 提供 `GetCustomerRiskCostRequest` 请求类
|
||||
|
||||
4. ✅ 配置了 Spring Boot 应用
|
||||
- 在 Application.java 中注册了 MCPClient Bean
|
||||
- 在 Application.java 中注册了 MCPTool Bean
|
||||
- 将 MCPTool 添加到 ChatClient 的工具列表
|
||||
- 更新了系统提示,告诉 AI 如何使用 MCP 工具
|
||||
|
||||
5. ✅ 测试了 MCP 服务器
|
||||
- 使用 echo + node 命令测试,返回正确的 JSON-RPC 响应
|
||||
|
||||
## 测试步骤
|
||||
|
||||
### 1. 启动 Spring Boot 应用
|
||||
|
||||
```bash
|
||||
cd D:\project\spring-ai-skill
|
||||
mvn spring-boot:run
|
||||
```
|
||||
|
||||
或者在 IDE 中运行 `Application.java`
|
||||
|
||||
### 2. 访问 Web 界面
|
||||
|
||||
打开浏览器访问:http://localhost:8080/index.html
|
||||
|
||||
### 3. 测试 MCP 工具调用
|
||||
|
||||
在聊天界面输入以下测试用例:
|
||||
|
||||
#### 测试用例 1:直接查询风险成本
|
||||
```
|
||||
查询"某某科技有限公司"的风险成本
|
||||
```
|
||||
|
||||
**预期结果**:
|
||||
- 前端显示工具调用:`MCPTool` (get_customer_risk_cost)
|
||||
- 显示工具参数:`{"company_name": "某某科技有限公司"}`
|
||||
- 显示工具结果:包含风险成本率(1.2% ~ 2.5% 之间的随机值)
|
||||
- AI 回复:解释该企业的风险成本率
|
||||
|
||||
#### 测试用例 2:结合 Skill 和 MCP 工具
|
||||
```
|
||||
帮我计算"某某科技有限公司"的定价,需要考虑风险成本
|
||||
```
|
||||
|
||||
**预期结果**:
|
||||
- 前端显示两个工具调用:
|
||||
1. `MCPTool` (get_customer_risk_cost) - 获取风险成本
|
||||
2. `SkillsTool` (客户定价) - 计算定价
|
||||
- AI 回复:综合两个工具的结果,给出最终定价
|
||||
|
||||
#### 测试用例 3:多个企业的风险成本对比
|
||||
```
|
||||
对比"企业A"和"企业B"的风险成本
|
||||
```
|
||||
|
||||
**预期结果**:
|
||||
- 前端显示两次工具调用:
|
||||
1. `MCPTool` (get_customer_risk_cost) - 查询企业A
|
||||
2. `MCPTool` (get_customer_risk_cost) - 查询企业B
|
||||
- AI 回复:对比两个企业的风险成本率
|
||||
|
||||
## 验证要点
|
||||
|
||||
### 1. MCP 服务器启动
|
||||
查看控制台日志,应该看到:
|
||||
```
|
||||
MCP 服务器已启动: node D:/project/spring-ai-skill/mcp-servers/risk-cost-server/index.js
|
||||
```
|
||||
|
||||
### 2. 工具调用日志
|
||||
查看控制台日志,应该看到:
|
||||
```
|
||||
MCP 请求: {"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_customer_risk_cost","arguments":{"company_name":"某某科技有限公司"}}}
|
||||
MCP 响应: {"result":{"content":[{"type":"text","text":"..."}]},"jsonrpc":"2.0","id":1}
|
||||
```
|
||||
|
||||
### 3. 前端工具可视化
|
||||
前端应该显示:
|
||||
- 工具名称:`MCPTool` 或 `get_customer_risk_cost`
|
||||
- 工具参数:JSON 格式的参数
|
||||
- 工具结果:JSON 格式的结果
|
||||
|
||||
### 4. LLM 日志
|
||||
查看 `logs/llm/llm-YYYY-MM-DD.log`,应该包含:
|
||||
- 用户消息
|
||||
- 工具调用信息
|
||||
- 工具结果
|
||||
- AI 回复
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q1: MCP 服务器无法启动
|
||||
**症状**:控制台显示 "MCP 服务器无响应"
|
||||
|
||||
**解决方法**:
|
||||
1. 检查 Node.js 是否已安装:`node --version`
|
||||
2. 检查 MCP 服务器依赖是否已安装:
|
||||
```bash
|
||||
cd mcp-servers/risk-cost-server
|
||||
npm install
|
||||
```
|
||||
3. 检查 application.properties 中的路径是否正确
|
||||
|
||||
### Q2: 工具未被调用
|
||||
**症状**:AI 直接回复,没有调用 MCP 工具
|
||||
|
||||
**解决方法**:
|
||||
1. 检查系统提示是否包含 MCP 工具的使用说明
|
||||
2. 尝试更明确的提示词,例如:"使用 MCP 工具查询..."
|
||||
3. 检查工具是否正确注册到 ChatClient
|
||||
|
||||
### Q3: 工具调用失败
|
||||
**症状**:前端显示工具调用,但返回错误
|
||||
|
||||
**解决方法**:
|
||||
1. 查看控制台日志,检查 MCP 请求和响应
|
||||
2. 检查 MCP 服务器是否正常运行
|
||||
3. 检查参数格式是否正确
|
||||
|
||||
## 下一步优化
|
||||
|
||||
1. **错误处理**:改进 MCP 工具的错误处理,提供更友好的错误信息
|
||||
2. **工具描述**:为 MCPTool 添加更详细的描述,帮助 AI 更好地理解何时使用
|
||||
3. **参数验证**:添加参数验证,确保传递给 MCP 服务器的参数格式正确
|
||||
4. **连接池**:如果需要频繁调用 MCP 工具,考虑使用连接池管理 MCP 客户端
|
||||
5. **超时处理**:添加超时机制,避免 MCP 服务器无响应时阻塞应用
|
||||
6. **多个 MCP 服务器**:支持配置和管理多个 MCP 服务器
|
||||
|
||||
## 技术架构
|
||||
|
||||
```
|
||||
用户输入
|
||||
↓
|
||||
ChatController (REST API)
|
||||
↓
|
||||
ChatService
|
||||
↓
|
||||
ChatClient (Spring AI)
|
||||
↓
|
||||
MCPTool (Function<Request, String>)
|
||||
↓
|
||||
MCPClient (JSON-RPC)
|
||||
↓
|
||||
Node.js MCP Server (stdio)
|
||||
↓
|
||||
返回风险成本率
|
||||
```
|
||||
|
||||
## 相关文件
|
||||
|
||||
- `src/main/java/org/springaicommunity/skills/Application.java` - 配置 MCP 客户端和工具
|
||||
- `src/main/java/org/springaicommunity/skills/mcp/MCPClient.java` - MCP 客户端实现
|
||||
- `src/main/java/org/springaicommunity/skills/mcp/MCPTool.java` - MCP 工具封装
|
||||
- `mcp-servers/risk-cost-server/index.js` - Node.js MCP 服务器
|
||||
- `src/main/resources/application.properties` - MCP 服务器配置
|
||||
@@ -0,0 +1,56 @@
|
||||
# 客户风险成本 MCP 服务器
|
||||
|
||||
## 功能
|
||||
|
||||
提供获取客户风险成本率的工具,用于定价计算。
|
||||
|
||||
## 工具
|
||||
|
||||
### get_customer_risk_cost
|
||||
|
||||
获取客户的风险成本率(%)。
|
||||
|
||||
**输入参数**:
|
||||
- `company_name` (string, 必需): 客户的企业名称
|
||||
|
||||
**输出**:
|
||||
```json
|
||||
{
|
||||
"company_name": "某某科技有限公司",
|
||||
"risk_cost_rate": 1.8765,
|
||||
"unit": "%",
|
||||
"description": "客户\"某某科技有限公司\"的风险成本率为 1.8765%",
|
||||
"timestamp": "2026-01-29T12:00:00.000Z"
|
||||
}
|
||||
```
|
||||
|
||||
**风险成本率范围**:1.2% ~ 2.5%
|
||||
|
||||
## 安装
|
||||
|
||||
```bash
|
||||
cd mcp-servers/risk-cost-server
|
||||
npm install
|
||||
```
|
||||
|
||||
## 运行
|
||||
|
||||
```bash
|
||||
npm start
|
||||
```
|
||||
|
||||
## 配置到 Spring AI
|
||||
|
||||
在 `application.properties` 中添加:
|
||||
|
||||
```properties
|
||||
spring.ai.mcp.client.risk-cost.command=node
|
||||
spring.ai.mcp.client.risk-cost.args=D:/project/spring-ai-skill/mcp-servers/risk-cost-server/index.js
|
||||
```
|
||||
|
||||
## 测试
|
||||
|
||||
```bash
|
||||
# 测试工具调用
|
||||
echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_customer_risk_cost","arguments":{"company_name":"测试企业"}}}' | node index.js
|
||||
```
|
||||
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* 客户风险成本 MCP 服务器
|
||||
* 提供获取客户风险成本的工具(随机生成 1.2-2.5 之间的数值)
|
||||
*/
|
||||
|
||||
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
||||
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
||||
import {
|
||||
CallToolRequestSchema,
|
||||
ListToolsRequestSchema,
|
||||
} from '@modelcontextprotocol/sdk/types.js';
|
||||
|
||||
// 创建服务器实例
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'risk-cost-server',
|
||||
version: '1.0.0',
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
tools: {},
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// 生成随机风险成本(1.2 ~ 2.5)
|
||||
function generateRiskCost() {
|
||||
const min = 4.2;
|
||||
const max = 7.5;
|
||||
const cost = Math.random() * (max - min) + min;
|
||||
return parseFloat(cost.toFixed(4)); // 保留4位小数
|
||||
}
|
||||
|
||||
// 注册工具列表处理器
|
||||
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
||||
return {
|
||||
tools: [
|
||||
{
|
||||
name: 'get_customer_risk_cost',
|
||||
description: '获取客户的风险成本率(%)。根据客户企业名称返回该客户的风险成本率,范围在 1.2% 到 2.5% 之间。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
company_name: {
|
||||
type: 'string',
|
||||
description: '客户的企业名称',
|
||||
},
|
||||
},
|
||||
required: ['company_name'],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
|
||||
// 注册工具调用处理器
|
||||
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||
if (request.params.name === 'get_customer_risk_cost') {
|
||||
const companyName = request.params.arguments?.company_name;
|
||||
|
||||
if (!companyName) {
|
||||
throw new Error('缺少必需参数: company_name');
|
||||
}
|
||||
|
||||
// 生成风险成本
|
||||
const riskCost = generateRiskCost();
|
||||
|
||||
// 返回结果
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: JSON.stringify({
|
||||
company_name: companyName,
|
||||
risk_cost_rate: riskCost,
|
||||
unit: '%',
|
||||
description: `客户"${companyName}"的风险成本率为 ${riskCost}%`,
|
||||
timestamp: new Date().toISOString(),
|
||||
}, null, 2),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error(`未知工具: ${request.params.name}`);
|
||||
});
|
||||
|
||||
// 启动服务器
|
||||
async function main() {
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
console.error('客户风险成本 MCP 服务器已启动');
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error('服务器启动失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
{
|
||||
"name": "risk-cost-server",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "risk-cost-server",
|
||||
"version": "1.0.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^0.5.0"
|
||||
},
|
||||
"bin": {
|
||||
"risk-cost-server": "index.js"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/sdk": {
|
||||
"version": "0.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-0.5.0.tgz",
|
||||
"integrity": "sha512-RXgulUX6ewvxjAG0kOpLMEdXXWkzWgaoCGaA2CwNW7cQCIphjpJhjpHSiaPdVCnisjRF/0Cm9KWHUuIoeiAblQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"content-type": "^1.0.5",
|
||||
"raw-body": "^3.0.0",
|
||||
"zod": "^3.23.8"
|
||||
}
|
||||
},
|
||||
"node_modules/bytes": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/content-type": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
|
||||
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/depd": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
|
||||
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/http-errors": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
|
||||
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"depd": "~2.0.0",
|
||||
"inherits": "~2.0.4",
|
||||
"setprototypeof": "~1.2.0",
|
||||
"statuses": "~2.0.2",
|
||||
"toidentifier": "~1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/iconv-lite": {
|
||||
"version": "0.7.2",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",
|
||||
"integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/inherits": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
||||
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/raw-body": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",
|
||||
"integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bytes": "~3.1.2",
|
||||
"http-errors": "~2.0.1",
|
||||
"iconv-lite": "~0.7.0",
|
||||
"unpipe": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/safer-buffer": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/setprototypeof": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
|
||||
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/statuses": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
|
||||
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/toidentifier": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
|
||||
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/unpipe": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
|
||||
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "3.25.76",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
|
||||
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "risk-cost-server",
|
||||
"version": "1.0.0",
|
||||
"description": "MCP 服务器 - 获取客户风险成本",
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"bin": {
|
||||
"risk-cost-server": "./index.js"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node index.js"
|
||||
},
|
||||
"keywords": [
|
||||
"mcp",
|
||||
"risk-cost",
|
||||
"customer"
|
||||
],
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^0.5.0"
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<maven.deploy.skip>true</maven.deploy.skip>
|
||||
<spring-ai.version>2.0.0-SNAPSHOT</spring-ai.version>
|
||||
<spring-ai.version>1.1.2</spring-ai.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -34,7 +34,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springaicommunity</groupId>
|
||||
<artifactId>spring-ai-agent-utils</artifactId>
|
||||
<version>0.5.0-SNAPSHOT</version>
|
||||
<version>0.4.2</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
@@ -53,6 +53,12 @@
|
||||
<artifactId>spring-ai-starter-model-google-genai</artifactId>
|
||||
</dependency> -->
|
||||
|
||||
<!-- MCP Client Support -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-starter-mcp-client</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Netty DNS resolver for macOS -->
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
@@ -70,6 +76,10 @@
|
||||
<artifactId>reactor-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
|
||||
@@ -1,78 +1,245 @@
|
||||
package org.springaicommunity.skills;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springaicommunity.agent.tools.BraveWebSearchTool;
|
||||
import org.springaicommunity.agent.tools.FileSystemTools;
|
||||
import org.springaicommunity.agent.tools.ShellTools;
|
||||
import org.springaicommunity.agent.tools.SkillsTool;
|
||||
import org.springaicommunity.agent.tools.SmartWebFetchTool;
|
||||
|
||||
import org.springaicommunity.mcp.annotation.McpTool;
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.client.advisor.ToolCallAdvisor;
|
||||
import org.springframework.ai.chat.memory.ChatMemory;
|
||||
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
import org.springframework.ai.tool.function.FunctionToolCallback;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonClassDescription;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import io.modelcontextprotocol.client.McpClient;
|
||||
import io.modelcontextprotocol.client.transport.StdioClientTransport;
|
||||
import io.modelcontextprotocol.client.transport.ServerParameters;
|
||||
|
||||
|
||||
@SpringBootApplication
|
||||
@Configuration
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
/**
|
||||
* 用于流式响应的 ChatClient.Builder (不支持工具调用)
|
||||
*/
|
||||
@Bean("streamChatClientBuilder")
|
||||
ChatClient.Builder streamChatClientBuilder(ChatModel chatModel, @Value("${agent.skills.dirs:Unknown}") List<Resource> agentSkillsDirs) {
|
||||
|
||||
// @formatter:off
|
||||
return ChatClient.builder(chatModel)
|
||||
.defaultSystem("Always use the available skills to assist the user in their requests.")
|
||||
|
||||
// 流式响应不支持工具调用,所以不配置工具
|
||||
|
||||
.defaultAdvisors(
|
||||
// Custom logging advisor
|
||||
MyLoggingAdvisor.builder()
|
||||
.showAvailableTools(false)
|
||||
.showSystemMessage(false)
|
||||
.build())
|
||||
.defaultToolContext(Map.of("foo", "bar"));
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
/**
|
||||
* 流式 ChatClient 实例(预先构建好)
|
||||
*/
|
||||
@Bean
|
||||
CommandLineRunner commandLineRunner(ChatClient.Builder chatClientBuilder,
|
||||
@Value("${agent.skills.dirs:Unknown}") List<Resource> agentSkillsDirs) throws IOException {
|
||||
ChatClient streamChatClient(@Qualifier("streamChatClientBuilder") ChatClient.Builder streamChatClientBuilder, ChatMemory chatMemory) {
|
||||
return streamChatClientBuilder
|
||||
.defaultAdvisors(
|
||||
org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor.builder(chatMemory).build()
|
||||
)
|
||||
.build();
|
||||
}
|
||||
|
||||
return args -> {
|
||||
/**
|
||||
* MCP 工具回调 - 获取客户风险成本
|
||||
*/
|
||||
@Bean
|
||||
FunctionToolCallback riskCostToolCallback(
|
||||
@Value("${spring.ai.mcp.client.risk-cost.command}") String command,
|
||||
@Value("${spring.ai.mcp.client.risk-cost.args}") String args) {
|
||||
|
||||
ChatClient chatClient = chatClientBuilder // @formatter:off
|
||||
.defaultSystem("Always use the available skills to assist the user in their requests.")
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
// Skills tool
|
||||
.defaultToolCallbacks(SkillsTool.builder().addSkillsResources(agentSkillsDirs).build())
|
||||
return FunctionToolCallback.<GetCustomerRiskCostRequest, String>builder("get_customer_risk_cost", (request) -> {
|
||||
try {
|
||||
// 启动 MCP 服务器进程
|
||||
ProcessBuilder pb = new ProcessBuilder(command, args);
|
||||
pb.redirectErrorStream(false);
|
||||
Process process = pb.start();
|
||||
|
||||
// Built-in tools
|
||||
.defaultTools(
|
||||
//Bash execution tool
|
||||
ShellTools.builder().build(),// built-in shell tools
|
||||
// Read, Write and Edit files tool
|
||||
FileSystemTools.builder().build(),// built-in file system tools
|
||||
// Smart web fetch tool
|
||||
SmartWebFetchTool.builder(chatClientBuilder.clone().build()).build())
|
||||
|
||||
|
||||
.defaultAdvisors(
|
||||
// Tool Calling advisor
|
||||
ToolCallAdvisor.builder().build(),
|
||||
// Custom logging advisor
|
||||
MyLoggingAdvisor.builder()
|
||||
.showAvailableTools(false)
|
||||
.showSystemMessage(false)
|
||||
.build())
|
||||
.defaultToolContext(Map.of("foo", "bar"))
|
||||
.build();
|
||||
// @formatter:on
|
||||
// 发送 JSON-RPC 请求
|
||||
Map<String, Object> rpcRequest = Map.of(
|
||||
"jsonrpc", "2.0",
|
||||
"id", UUID.randomUUID().toString(),
|
||||
"method", "tools/call",
|
||||
"params", Map.of(
|
||||
"name", "get_customer_risk_cost",
|
||||
"arguments", Map.of("company_name", request.getCompanyName())
|
||||
)
|
||||
);
|
||||
|
||||
var answer = chatClient
|
||||
.prompt("""
|
||||
Explain reinforcement learning in simple terms and use.
|
||||
Use required skills.
|
||||
Then use the Youtube video https://youtu.be/vXtfdGphr3c?si=xy8U2Al_Um5vE4Jd transcript to support your answer.
|
||||
Use absolute paths for the skills and scripts. Do not ask me for more details.
|
||||
""")
|
||||
.call()
|
||||
.content();
|
||||
String requestJson = objectMapper.writeValueAsString(rpcRequest);
|
||||
|
||||
System.out.println("The Answer: " + answer);
|
||||
};
|
||||
// 发送请求并读取响应
|
||||
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
|
||||
|
||||
writer.write(requestJson);
|
||||
writer.newLine();
|
||||
writer.flush();
|
||||
|
||||
String responseLine = reader.readLine();
|
||||
if (responseLine != null) {
|
||||
JsonNode responseNode = objectMapper.readTree(responseLine);
|
||||
if (responseNode.has("result")) {
|
||||
JsonNode content = responseNode.get("result").get("content");
|
||||
if (content.isArray() && content.size() > 0) {
|
||||
return content.get(0).get("text").asText();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
process.destroyForcibly();
|
||||
return "获取风险成本失败: 无响应";
|
||||
|
||||
} catch (Exception e) {
|
||||
return "获取风险成本失败: " + e.getMessage();
|
||||
}
|
||||
})
|
||||
.description("获取客户的风险成本率(%)。根据客户企业名称返回该客户的风险成本率,范围在 1.2% 到 2.5% 之间。用于定价计算、风险评估等场景。")
|
||||
.inputType(GetCustomerRiskCostRequest.class)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 用于非流式响应的 ChatClient.Builder (支持工具调用)
|
||||
*/
|
||||
@Bean("chatClientBuilder")
|
||||
ChatClient.Builder chatClientBuilder(ChatModel chatModel,
|
||||
@Value("${agent.skills.dirs:Unknown}") List<Resource> agentSkillsDirs,
|
||||
FunctionToolCallback riskCostToolCallback) {
|
||||
|
||||
// @formatter:off
|
||||
return ChatClient.builder(chatModel)
|
||||
.defaultSystem("""
|
||||
You are a helpful AI assistant with access to various tools and skills.
|
||||
|
||||
CRITICAL RULES:
|
||||
1. When user mentions "定价" or "pricing", you MUST call the Skill tool with command "客户定价"
|
||||
|
||||
Available tools:
|
||||
- Skill: For business tasks like pricing, rating, etc.
|
||||
- MCPTool: For getting customer risk cost rate (获取客户风险成本率)
|
||||
- FileSystemTools: For file operations (read, write, list)
|
||||
- ShellTools: For executing shell commands
|
||||
|
||||
Remember: USE TOOLS FIRST, ask questions later!
|
||||
""")
|
||||
|
||||
// Skills tool
|
||||
.defaultToolCallbacks(SkillsTool.builder().addSkillsResources(agentSkillsDirs).build())
|
||||
|
||||
// Built-in tools
|
||||
.defaultTools(
|
||||
//Bash execution tool
|
||||
ShellTools.builder().build(),// built-in shell tools
|
||||
// Read, Write and Edit files tool
|
||||
FileSystemTools.builder().build())// built-in file system tools
|
||||
|
||||
// MCP tools
|
||||
.defaultToolCallbacks(riskCostToolCallback)
|
||||
|
||||
.defaultAdvisors(
|
||||
// Tool Calling advisor
|
||||
ToolCallAdvisor.builder().build(),
|
||||
// Custom logging advisor - order=-1 确保最先执行,可以捕获工具调用
|
||||
MyLoggingAdvisor.builder()
|
||||
.order(-1)
|
||||
.showAvailableTools(true)
|
||||
.showSystemMessage(true)
|
||||
.build(),
|
||||
// Tool call capture advisor (接收来自 MyLoggingAdvisor 的工具调用信息)
|
||||
ToolCallCaptureAdvisor.builder().order(0).build(),
|
||||
// LLM 请求响应日志记录 - order=100 确保最后执行
|
||||
LLMLoggingAdvisor.builder()
|
||||
.logDirectory("logs/llm")
|
||||
.order(100)
|
||||
.build())
|
||||
.defaultToolContext(Map.of("foo", "bar"));
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
/**
|
||||
* 非流式 ChatClient 实例(预先构建好,支持工具调用)
|
||||
*/
|
||||
@Bean
|
||||
ChatClient chatClient(@Qualifier("chatClientBuilder") ChatClient.Builder chatClientBuilder, ChatMemory chatMemory) {
|
||||
return chatClientBuilder
|
||||
.defaultAdvisors(
|
||||
org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor.builder(chatMemory).build()
|
||||
)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
ChatMemory chatMemory() {
|
||||
return MessageWindowChatMemory.builder()
|
||||
.maxMessages(100)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取客户风险成本请求
|
||||
*/
|
||||
@JsonClassDescription("获取客户的风险成本率(%)。根据客户企业名称返回该客户的风险成本率,范围在 1.2% 到 2.5% 之间。用于定价计算、风险评估等场景。")
|
||||
public static class GetCustomerRiskCostRequest {
|
||||
|
||||
@JsonProperty(required = true, value = "company_name")
|
||||
@JsonPropertyDescription("客户的企业名称,例如:'某某科技有限公司'、'测试企业'等")
|
||||
private String companyName;
|
||||
|
||||
public GetCustomerRiskCostRequest() {
|
||||
}
|
||||
|
||||
public String getCompanyName() {
|
||||
return companyName;
|
||||
}
|
||||
|
||||
public void setCompanyName(String companyName) {
|
||||
this.companyName = companyName;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
spring.application.name=recursive-advisor-demo
|
||||
spring.main.web-application-type=none
|
||||
server.port=8080
|
||||
|
||||
## Anthropic Claude SDK
|
||||
spring.ai.anthropic.api-key=${ANTHROPIC_API_KEY}
|
||||
@@ -34,3 +34,8 @@ agent.model.knowledge.cutoff=2025-01-01
|
||||
# agent.model=gemini-3-pro-preview
|
||||
# agent.model.knowledge.cutoff=Unknown
|
||||
|
||||
## MCP Server Configuration
|
||||
|
||||
# 客户风险成本 MCP 服务器
|
||||
spring.ai.mcp.client.risk-cost.command=node
|
||||
spring.ai.mcp.client.risk-cost.args=D:/project/spring-ai-skill/mcp-servers/risk-cost-server/index.js
|
||||
Reference in new issue
Block a user