主要观点:MCP 服务器可扩展大型语言模型功能,需自行编写 MCP 客户端,本文介绍使用 Spring AI 编写 MCP 客户端的步骤及相关内容。
关键信息:
- 提供了 MCP 服务器的四个工具:get_artists、search_artist、get_songs、search_song。
- 构建 MCP 服务器需先克隆仓库并执行
mvn clean verify命令,jar 文件在server/target目录。 - 创建 MCP 客户端时,在 Spring Initializr 中添加
Spring Web、Model Context Protocol Client、OpenAI依赖,还需添加io.projectreactor.netty:reactor-netty-http依赖,注入ChatClient和ToolCallbackProvider,在application.properties中配置客户端名称、MCP 服务器等信息。 - 可使用
curl测试chat端点,如http://localhost:8080/chat?message=give%20me%20a%20list%20of%20gunter's%20favorite%20artists。 - 能控制工具执行,如使用
controlled tool execution,在McpClientWithHitlController中可设置internalToolExecutionEnabled为 false 来阻止工具自动调用,可根据chatResponse是否包含工具调用来决定是否执行工具调用。
重要细节: - 构建 MCP 服务器的仓库地址为
https://github.com/mydeveloperplanet/mymcpserverplanet,客户端代码在client目录。 - 控制工具执行的代码示例中,通过循环判断
chatResponse是否有工具调用,若有则执行工具调用并更新prompt继续调用模型。 - 不同请求如获取艺术家列表和讲笑话,在控制工具执行时的控制台消息和 LLM 响应不同。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用。你还可以使用@来通知其他用户。