客户端开发
在本教程中,你将学习如何构建一个连接到 MCP 服务器的 LLM 驱动的聊天机器人客户端。建议先完成服务器快速入门教程,了解构建第一个服务器的基础知识。
系统要求
开始之前,请确保你的系统满足以下要求:
- Mac 或 Windows 电脑
- 已安装最新版本的 Python
- 已安装最新版本的
uv
配置环境
首先,使用 uv
创建一个新的 Python 项目:
# 创建项目目录
uv init mcp-client
cd mcp-client
# 创建虚拟环境
uv venv
# 激活虚拟环境
# Windows系统:
.venv\Scripts\activate
# Unix或MacOS系统:
source .venv/bin/activate
# 安装必需的包
uv add mcp anthropic python-dotenv
# 删除模板文件
rm hello.py
# 创建主文件
touch client.py
设置 API 密钥
你需要从 Anthropic 控制台 获取一个 Anthropic API 密钥。
创建 .env
文件来存储密钥:
# 创建 .env 文件
touch .env
将密钥添加到 .env
文件中:
ANTHROPIC_API_KEY=<你的密钥>
将 .env
添加到 .gitignore
:
echo ".env" >> .gitignore
创建客户端
基本客户端结构
首先,设置导入语句并创建基本的客户端类。
import asyncio
from typing import Optional
from contextlib import AsyncExitStack
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from anthropic import Anthropic
from dotenv import load_dotenv
load_dotenv() # 从 .env 加载环境变量
class MCPClient:
def __init__(self):
# 初始化会话和客户端对象
self.session: Optional[ClientSession] = None
self.exit_stack = AsyncExitStack()
self.anthropic = Anthropic()
服务器连接管理
接下来,实现连接到 MCP 服务器的方法:
async def connect_to_server(self, server_script_path: str):
"""连接到 MCP 服务器
参数:
server_script_path: 服务器脚本路径 (.py 或 .js)
"""
is_python = server_script_path.endswith('.py')
is_js = server_script_path.endswith('.js')
if not (is_python or is_js):
raise ValueError("服务器脚本必须是 .py 或 .js 文件")
command = "python" if is_python else "node"
server_params = StdioServerParameters(
command=command,
args=[server_script_path],
env=None
)
stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
self.stdio, self.write = stdio_transport
self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))
await self.session.initialize()
# 列出可用工具
response = await self.session.list_tools()
tools = response.tools
print("\n已连接到服务器,可用工具:", [tool.name for tool in tools])
查询处理逻辑
现在添加处理查询和工具调用的核心功能:
async def process_query(self, query: str) -> str:
"""使用 Claude 和可用工具处理查询"""
messages = [
{
"role": "user",
"content": query
}
]
response = await self.session.list_tools()
available_tools = [{
"name": tool.name,
"description": tool.description,
"input_schema": tool.inputSchema
} for tool in response.tools]
# 初始 Claude API 调用
response = self.anthropic.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1000,
messages=messages,
tools=available_tools
)
# 处理响应和工具调用
tool_results = []
final_text = []
assistant_message_content = []
for content in response.content:
if content.type == 'text':
final_text.append(content.text)
assistant_message_content.append(content)
elif content.type == 'tool_use':
tool_name = content.name
tool_args = content.input
# 执行工具调用
result = await self.session.call_tool(tool_name, tool_args)
tool_results.append({"call": tool_name, "result": result})
final_text.append(f"[调用工具 {tool_name},参数 {tool_args}]")
assistant_message_content.append(content)
messages.append({
"role": "assistant",
"content": assistant_message_content
})
messages.append({
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": content.id,
"content": result.content
}
]
})
# 获取 Claude 的下一个响应
response = self.anthropic.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1000,
messages=messages,
tools=available_tools
)
final_text.append(response.content[0].text)
return "\n".join(final_text)
交互式聊天界面
现在添加聊天循环和清理功能:
async def chat_loop(self):
"""运行交互式聊天循环"""
print("\nMCP 客户端已启动!")
print("输入你的查询或 'quit' 退出。")
while True:
try:
query = input("\n查询: ").strip()
if query.lower() == 'quit':
break
response = await self.process_query(query)
print("\n" + response)
except Exception as e:
print(f"\n错误: {str(e)}")
async def cleanup(self):
"""清理资源"""
await self.exit_stack.aclose()
主入口点
最后,添加主执行逻辑:
async def main():
if len(sys.argv) < 2:
print("用法: python client.py <服务器脚本路径>")
sys.exit(1)
client = MCPClient()
try:
await client.connect_to_server(sys.argv[1])
await client.chat_loop()
finally:
await client.cleanup()
if __name__ == "__main__":
import sys
asyncio.run(main())
关键组件解释
1. 客户端初始化
MCPClient
类初始化会话管理和 API 客户端- 使用
AsyncExitStack
进行资源管理 - 配置 Anthropic 客户端以进行 Claude 交互
2. 服务器连接
- 支持 Python 和 Node.js 服务器
- 验证服务器脚本类型
- 设置通信通道
- 初始化会话并列出可用工具
3. 查询处理
- 维护对话上下文
- 处理 Claude 的响应和工具调用
- 管理 Claude 和工具之间的消息流
- 将结果组合成连贯的响应
4. 交互界面
- 提供简单的命令行界面
- 处理用户输入并显示响应
- 包含基本错误处理
- 允许正常退出
5. 资源管理
- 资源的正确清理
- 连接问题的错误处理
故障排除
服务器路径问题
- 检查服务器脚本路径是否正确
- 如果相对路径不起作用,请使用绝对路径
- 对于 Windows 用户,确保使用正斜杠(/) 或转义的反斜杠(\)
- 确认服务器文件具有正确的扩展名 (.py 用于 Python 或 .js 用于 Node.js)
正确路径使用示例:
# 相对路径
uv run client.py ./server/weather.py
# 绝对路径
uv run client.py /Users/username/projects/mcp-server/weather.py
# Windows 路径(两种格式都可以)
uv run client.py C:/projects/mcp-server/weather.py
uv run client.py C:\\projects\\mcp-server\\weather.py
响应时间
- 第一个响应可能需要长达 30 秒
- 这是正常现象,发生在以下情况下:
- 服务器初始化
- Claude 处理查询
- 工具执行
- 后续响应通常更快
- 在初始等待期间不要中断进程
ℹ️
这是基于 Spring AI MCP 自动配置和启动器的快速入门演示。
要了解如何手动创建同步和异步 MCP 客户端,请查阅 Java SDK 客户端 文档
系统要求
开始之前,请确保你的系统满足以下要求:
- Java 17 或更高版本
- Maven 3.6 或更高版本
- 支持 Spring Boot 的 IDE
创建项目
使用 Maven 创建一个新的 Spring Boot 项目:
mvn archetype:generate \
-DgroupId=com.example \
-DartifactId=ai-mcp-brave-chatbot \
-DarchetypeArtifactId=maven-archetype-quickstart \
-DinteractiveMode=false
更新你的 pom.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>ai-mcp-brave-chatbot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
<properties>
<java.version>17</java.version>
<spring-ai.version>0.8.0</spring-ai.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-anthropic-spring-boot-starter</artifactId>
<version>${spring-ai.version}</version>
</dependency>
<dependency>
<groupId>org.modelcontext</groupId>
<artifactId>mcp-spring-boot-starter</artifactId>
<version>0.4.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
应用配置
在 application.yml
中添加以下配置:
spring:
ai:
anthropic:
api-key: ${ANTHROPIC_API_KEY}
mcp:
servers:
filesystem:
command: npx
args:
- "-y"
- "@modelcontextprotocol/server-filesystem"
- "C:\\Users\\username\\Desktop"
- "C:\\Users\\username\\Downloads"
创建应用
创建主应用类:
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BraveChatApplication {
public static void main(String[] args) {
SpringApplication.run(BraveChatApplication.class, args);
}
}
运行应用
# 构建并运行
./mvnw clean install
java -jar ./target/ai-mcp-brave-chatbot-0.0.1-SNAPSHOT.jar
# 另一种方式
./mvnw spring-boot:run
⚠️
在运行应用之前,请记得设置你的
ANTHROPIC_API_KEY
环境变量!工作原理
该应用通过多个组件将 Spring AI 与 MCP 服务器集成:
MCP 客户端配置
pom.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.yml
):
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}
- MCP 服务器配置(
mcp-servers-config.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 工具集成:
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 提供工具功能
- 使用 InMemoryChatMemory 维护对话记忆
- 作为交互式命令行应用运行
高级配置
MCP 客户端支持其他配置选项:
- 通过
McpSyncClientCustomizer
或McpAsyncClientCustomizer
自定义客户端 - 支持多种传输类型:
STDIO
和SSE
(服务器发送事件) - 与 Spring AI 的工具执行框架集成
- 自动客户端初始化和生命周期管理
对于基于 WebFlux 的应用,可以使用 WebFlux 启动器:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mcp-client-webflux-spring-boot-starter</artifactId>
</dependency>
这提供了类似的功能,但使用基于 WebFlux 的 SSE 传输实现,推荐用于生产部署。