使用说明
Spring AI-MCP初学者WebFlux客户端
本项目演示了如何在Spring Boot应用程序中使用Spring AI MCP(模型上下文协议)客户端引导启动器和WebFlux。它展示了如何连接到MCP服务器并将其与Spring AI的工具执行框架集成。
跟随 MCP客户端启动启动器 参考文件。
概述
该项目使用Spring Boot和Spring AI创建了一个命令行应用程序,演示了MCP服务器与WebFlux的集成。应用程序:
- 使用STDIO和/或SSE(基于WebFlux)传输连接到MCP服务器
- 与Spring AI的聊天功能集成
- 演示通过MCP服务器执行工具
- 通过以下方式回答用户定义的问题
-Dai.user.input命令行属性,映射到Spring@Value代码中的注释
例如,使用以下命令运行应用程序 -Dai.user.input="Does Spring AI support MCP?" 将通过Spring的属性注入将此问题注入到应用程序中,应用程序将使用它使用WebFlux的响应式编程模型查询MCP服务器。
先决条件
- Java 17或更高版本
- Maven 3.6+
- Anthropic API密钥(Claude)(在https://docs.anthropic.com/en/docs/initial-setup)
- 勇敢搜索API密钥(在https://brave.com/search/api/)
依赖项
该项目使用以下主要依赖项:
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mcp-client-webflux-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-anthropic-spring-boot-starter</artifactId>
</dependency>
</dependencies>
配置
应用程序属性
检查 MCP客户端配置属性 文档。
应用程序可以通过以下方式配置 application.properties 或 application.yml:
共同属性
# Application Configuration
spring.application.name=mcp
spring.main.web-application-type=none
# AI Provider Configuration
spring.ai.anthropic.api-key=${ANTHROPIC_API_KEY}
STDIO传输属性
跟随 STDIO配置属性 文档。
为连接到的每个STDIO服务器配置单独的命名配置:
spring.ai.mcp.client.stdio.connections.brave-search.command=npx
spring.ai.mcp.client.stdio.connections.brave-search.args=-y,@modelcontextprotocol/server-brave-search
在这里, brave-search 是您的连接名称。
或者,您可以使用Claude Desktop格式的外部JSON文件配置STDIO连接:
spring.ai.mcp.client.stdio.servers-configuration=classpath:/mcp-servers-config.json
示例 mcp-servers-config.json:
{
"mcpServers": {
"brave-search": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-brave-search"
],
"env": {
}
}
}
}
苏格兰和南方能源公司运输物业
您还可以使用WebFlux连接到服务器发送事件(SSE)服务器。 跟随 SSE配置属性 文档。
SSE传输的属性前缀为 spring.ai.mcp.client.sse:
spring.ai.mcp.client.sse.connections.server1.url=http://localhost:8080
spring.ai.mcp.client.sse.connections.server2.url=http://localhost:8081
运作原理
该应用程序演示了使用MCP工具与AI模型进行简单的命令行交互:
- 应用程序启动并配置多个MCP客户端(每个客户端对应一个提供的STDIO或SSE连接配置)
- 它使用配置的MCP工具构建ChatClient
- 发送预定义的问题(设置vi
ai.user.input属性)到AI模型 - 显示AI的响应
- 自动关闭应用程序
运行应用程序
-
设置所需的环境变量:
export ANTHROPIC_API_KEY=your-api-key export BRAVE_API_KEY='your-brave-api-key-here' -
构建应用程序:
./mvnw clean install -
运行应用程序:
java -Dai.user.input='Does Spring AI support MCP?' -jar target/mcp-starter-webflux-client-0.0.1-SNAPSHOT.jar
该应用程序将执行问题“Spring AI是否支持MCP?”,使用提供的brave(或其他工具)进行回答,并显示AI助手的响应。
