ModelContext Protocol(MCP)简介
Cloud Native
SpringAI MCP 简介
Cloud Native
Spring AI 应用程序:使用 Spring AI 框架构建想要通过 MCP 访问数据的生成式 AI 应用程序
Spring MCP 客户端:MCP 协议的 Spring AI 实现,与服务器保持 1:1 连接
MCP 服务器:轻量级程序,每个程序都通过标准化的模型上下文协议公开特定的功能
本地数据源:MCP 服务器可以安全访问的计算机文件、数据库和服务
远程服务:MCP 服务器可以通过互联网(例如,通过 API)连接到的外部系统
通过一个示例快速体验 SpringAI MCP
Cloud Native
示例完整源码ingFang SC", Cambria, Cochin, Georgia, Times, "Times New Roman", serif;">[ingFang SC", Cambria, Cochin, Georgia, Times, "Times New Roman", serif;">3]:https://github.com/springaialibaba/spring-ai-alibaba-examples/spring-ai-alibaba-mcp-example
1. MCP Client,与 MCP 集成的关键,提供了与本地文件系统进行交互的能力。
2. Function Callbacks,Spring AI MCP 的 function calling 声明方式。
//List<McpFunctionCallback>functionCallbacks;varchatClient=chatClientBuilder.defaultFunctions(functionCallbacks).build();
和开发之前的 Spring AI 应用一样,我们先定义一个 ChatClient Bean,用于与大模型交互的代理。需要注意的是,我们为 ChatClient 注入的 functions 是通过 MCP 组件(McpFunctionCallback)创建的。
发现 MCP server 中可用的工具 tool(Spring AI 中叫做 function)列表。
依次将每个 tool 转换成 Spring AI function callback。
@BeanpublicList<McpFunctionCallback>functionCallbacks(McpSyncClientmcpClient){returnmcpClient.listTools(null).tools().stream().map(tool->newMcpFunctionCallback(mcpClient,tool)).toList();}可以看出,ChatClient 与模型交互的过程是没有变化的,模型在需要的时候告知 ChatClient 去做函数调用,只不过 Spring AI 通过 McpFunctionCallback 将实际的函数调用过程委托给了 MCP,通过标准的 MCP 协议与本地文件系统交互:
在与大模交互的过程中,ChatClient 处理相关的 function calls 请求
ChatClient 调用 MCP 工具(通过 McpClient)
@Bean(destroyMethod = "close")public McpSyncClient mcpClient() {var stdioParams = ServerParameters.builder("npx").args("-y", "@modelcontextprotocol/server-filesystem", "path)).build(); // 1var mcpClient = McpClient.sync(new StdioServerTransport(stdioParams),Duration.ofSeconds(10), new ObjectMapper()); //2var init = mcpClient.initialize(); // 3System.out.println("MCP Initialized: " + init);return mcpClient;}
在以上代码中:
1. 配置 MCP server 启动命令与参数。
2. 初始化 McpClient:关联 MCP server、指定超时时间等。
3. Spring AI 会使用 npx -y @modelcontextprotocol/server-filesystem "/path/to/file"在本地机器创建一个独立的子进程(代表本地 Mcp server),Spring AI 与 McpClient 通信,McpClient 进而通过与 Mcp server 的连接操作本地文件。
npminstall-gnpx
2. 下载示例源码
gitclonehttps://github.com/springaialibaba/spring-ai-alibaba-examples.gitcdspring-ai-alibaba-examples/spring-ai-alibaba-mcp-example/filesystem
3. 设置环境变量
#通义大模型DashscopeAPI-KEYexportAI_DASHSCOPE_API_KEY=${your-api-key-here}4. 构建示例
./mvnwcleaninstall
./mvnwspring-boot:run
总结
Cloud Native
在客户端,让 Spring AI 开发的智能体可以快速接入 MCP 生态中的各种 server 服务。
| 欢迎光临 链载Ai (https://www.lianzai.com/) | Powered by Discuz! X3.5 |