客户端开发(Java)
提示
这是一个基于Spring AI MCP自动配置和启动器的快速入门演示。要了解如何手动创建同步和异步MCP客户端,请参考Java SDK客户端文档。
本示例演示如何构建一个交互式聊天机器人,该机器人将Spring AI的model context protocol(MCP)与Brave Search MCP服务器相结合。该应用程序创建了一个由Anthropic的Claude AI模型驱动的对话界面,可以通过Brave Search执行互联网搜索,实现与实时网络数据的自然语言交互。您可以在这里找到本教程的完整代码。
系统要求
在开始之前,请确保您的系统满足以下要求:
- Java 17或更高版本
- Maven 3.6+
- npx包管理器
- Anthropic API密钥(Claude)
- Brave Search API密钥
- 安装npx(Node Package eXecute):首先,确保安装npm,然后运行:
bash
npm install -g npx
- 克隆仓库:
bash
git clone https://github.com/spring-projects/spring-ai-examples.git
cd model-context-protocol/brave-chatbot
- 设置你的 API keys:
bash
export ANTHROPIC_API_KEY='your-anthropic-api-key-here'
export BRAVE_API_KEY='your-brave-api-key-here'
- 构建应用:
bash
./mvnw clean install
- 使用Maven运行应用:
bash
./mvnw spring-boot:run
注意
确保你的 ANTHROPIC_API_KEY 安全!
它怎样工作
该应用程序通过几个组件将Spring AI与Brave Search MCP服务器集成:
MCP客户端配置
pom.xml中的必需依赖项:
- pom.xml中的必需依赖项:
xml
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mcp-client-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-anthropic-spring-boot-starter</artifactId>
</dependency>
- Application properties (application.yml):
yaml
spring:
ai:
mcp:
client:
enabled: true
name: brave-search-client
version: 1.0.0
type: SYNC
request-timeout: 20s
stdio:
root-change-notification: true
servers-configuration: classpath:/mcp-servers-config.json
anthropic:
api-key: ${ANTHROPIC_API_KEY}
这将激活spring-ai-mcp-client-spring-boot-starter,根据提供的服务器配置创建一个或多个McpClients。
- MCP服务器配置(mcp-servers-config.json):
json
{
"mcpServers": {
"brave-search": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-brave-search"
],
"env": {
"BRAVE_API_KEY": "<PUT YOUR BRAVE API KEY>"
}
}
}
}
聊天实现
聊天机器人使用Spring AI的ChatClient与MCP工具集成实现:
java
var chatClient = chatClientBuilder
.defaultSystem("You are useful assistant, expert in AI and Java.")
.defaultTools((Object[]) mcpToolAdapter.toolCallbacks())
.defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory()))
.build();
主要特点:
- 使用Claude AI模型进行自然语言理解
- 通过MCP集成Brave Search实现实时网络搜索功能
- 使用InMemoryChatMemory维护对话记忆
- 作为交互式命令行应用程序运行
构建和运行
bash
./mvnw clean install
java -jar ./target/ai-mcp-brave-chatbot-0.0.1-SNAPSHOT.jar
或者
bash
./mvnw spring-boot:run
应用程序将启动一个交互式聊天会话,您可以在其中提问。当聊天机器人需要从互联网查找信息来回答您的问题时,它会使用Brave Search。
聊天机器人可以:
- 使用其内置知识回答问题
- 在需要时使用Brave Search执行网络搜索
- 记住对话中之前消息的上下文
- 结合多个来源的信息提供全面的答案
高级配置
MCP客户端支持其他配置选项:
- 通过McpSyncClientCustomizer或McpAsyncClientCustomizer进行客户端定制
- 支持多个客户端和多种传输类型:STDIO和SSE(服务器发送事件)
- 与Spring AI的工具执行框架集成
- 自动客户端初始化和生命周期管理
对于基于WebFlux的应用程序,您可以使用WebFlux启动器:
xml
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mcp-client-webflux-spring-boot-starter</artifactId>
</dependency>
这提供了类似的功能,但使用基于WebFlux的SSE传输实现,推荐用于生产部署。
Next Steps