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
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user