> ## Documentation Index
> Fetch the complete documentation index at: https://mcp.vyagent.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 面向客户端开发者

> 学习如何构建一个可以与所有MCP服务器集成的客户端。

在本教程中，你将学习如何构建一个连接到MCP服务器的LLM驱动的聊天机器人客户端。建议你先完成[服务器快速入门](/quickstart/server)教程，它会指导你完成构建第一个服务器的基础知识。

<Tabs>
  <Tab title="Python">
    [你可以在这里找到本教程的完整代码。](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client)

    ## 系统要求

    在开始之前，请确保你的系统满足以下要求：

    * Mac或Windows电脑
    * 已安装最新版本的Python
    * 已安装最新版本的`uv`

    ## 配置环境

    首先，使用`uv`创建一个新的Python项目：

    ```bash
    # 创建项目目录
    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控制台](https://console.anthropic.com/settings/keys)获取一个Anthropic API密钥。

    创建一个`.env`文件来存储密钥：

    ```bash
    # 创建.env文件
    touch .env
    ```

    将你的密钥添加到`.env`文件中：

    ```bash
    ANTHROPIC_API_KEY=<你的密钥>
    ```

    将`.env`添加到`.gitignore`中：

    ```bash
    echo ".env" >> .gitignore
    ```

    <Warning>
      确保妥善保管你的`ANTHROPIC_API_KEY`！
    </Warning>

    ## 创建客户端

    ### 基本客户端结构

    首先，让我们设置导入并创建基本的客户端类：

    ```python
    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服务器的方法：

    ```python
    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])
    ```

    ### 查询处理逻辑

    现在让我们添加处理查询和工具调用的核心功能：

    ```python
    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)
    ```

    ### 交互式聊天界面

    现在我们将添加聊天循环和清理功能：

    ```python
    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()
    ```

    ### 主入口点

    最后，我们将添加主执行逻辑：

    ```python
    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())
    ```

    你可以在[这里](https://gist.github.com/zckly/f3f28ea731e096e53b39b47bf0a2d4b1)找到完整的`client.py`文件。

    ## 关键组件说明

    ### 1. 客户端初始化

    * `MCPClient`类初始化会话管理和API客户端
    * 使用`AsyncExitStack`进行适当的资源管理
    * 配置Anthropic客户端以与Claude交互

    ### 2. 服务器连接

    * 支持Python和Node.js服务器
    * 验证服务器脚本类型
    * 设置适当的通信通道
    * 初始化会话并列出可用工具

    ### 3. 查询处理

    * 维护对话上下文
    * 处理Claude的响应和工具调用
    * 管理Claude和工具之间的消息流
    * 将结果组合成连贯的响应

    ### 4. 交互式界面

    * 提供简单的命令行界面
    * 处理用户输入并显示响应
    * 包含基本错误处理
    * 允许优雅退出

    ### 5. 资源管理

    * 适当清理资源
    * 连接问题的错误处理
    * 优雅的关闭程序

    ## 常见定制点

    1. **工具处理**
       * 修改`process_query()`以处理特定工具类型
       * 添加工具调用的自定义错误处理
       * 实现工具特定的响应格式化

    2. **响应处理**
       * 自定义工具结果的格式化方式
       * 添加响应过滤或转换
       * 实现自定义日志记录

    3. **用户界面**
       * 添加GUI或Web界面
       * 实现丰富的控制台输出
       * 添加命令历史或自动完成功能

    ## 运行客户端

    要使用任何MCP服务器运行你的客户端：

    ```bash
    uv run client.py path/to/server.py # python服务器
    uv run client.py path/to/build/index.js # node服务器
    ```

    <Note>
      如果你正在继续服务器快速入门中的天气教程，你的命令可能看起来像这样：`python client.py .../weather/src/weather/server.py`
    </Note>

    客户端将：

    1. 连接到指定的服务器
    2. 列出可用工具
    3. 启动交互式聊天会话，你可以：
       * 输入查询
       * 查看工具执行情况
       * 获取Claude的响应

    以下是连接到服务器快速入门中的天气服务器时的示例界面：

    <Frame>
      <img src="https://mintlify.s3.us-west-1.amazonaws.com/merge-303ecc93/images/client-claude-cli-python.png" />
    </Frame>

    ## 工作原理

    当你提交查询时：

    1. 客户端从服务器获取可用工具列表
    2. 你的查询连同工具描述一起发送给Claude
    3. Claude决定使用哪些工具（如果需要）
    4. 客户端通过服务器执行请求的工具调用
    5. 结果发送回Claude
    6. Claude提供自然语言响应
    7. 响应显示给你

    ## 最佳实践

    1. **错误处理**
       * 始终使用try-catch块包装工具调用
       * 提供有意义的错误消息
       * 优雅地处理连接问题

    2. **资源管理**
       * 使用`AsyncExitStack`进行适当的清理
       * 完成后关闭连接
       * 处理服务器断开连接

    3. **安全性**
       * 在`.env`中安全存储API密钥
       * 验证服务器响应
       * 谨慎处理工具权限

    ## 故障排除

    ### 服务器路径问题

    * 仔细检查服务器脚本路径是否正确
    * 如果相对路径不起作用，请使用绝对路径
    * 对于Windows用户，确保使用正斜杠(/)或转义的反斜杠(\\)在路径中
    * 验证服务器文件具有正确的扩展名（.py表示Python或.js表示Node.js）

    正确路径使用示例：

    ```bash
    # 相对路径
    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处理查询时
      * 工具执行时
    * 后续响应通常会更快
    * 在初始等待期间不要中断进程

    ### 常见错误消息

    如果你看到：

    * `FileNotFoundError`：检查你的服务器路径
    * `Connection refused`：确保服务器正在运行且路径正确
    * `Tool execution failed`：验证工具所需的环境变量是否已设置
    * `Timeout error`：考虑在客户端配置中增加超时时间
  </Tab>

  <Tab title="Java">
    <Note>
      这是一个基于Spring AI MCP自动配置和启动器的快速入门演示。
      要了解如何手动创建同步和异步MCP客户端，请参考[Java SDK客户端](/sdk/java/mcp-client)文档
    </Note>

    本示例演示如何构建一个结合Spring AI的模型上下文协议（MCP）和[Brave Search MCP服务器](https://github.com/modelcontextprotocol/servers/tree/main/src/brave-search)的交互式聊天机器人。该应用程序创建了一个由Anthropic的Claude AI模型驱动的对话界面，可以通过Brave Search执行互联网搜索，实现与实时网络数据的自然语言交互。
    [你可以在这里找到本教程的完整代码。](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/web-search/brave-chatbot)

    ## 系统要求

    在开始之前，请确保你的系统满足以下要求：

    * Java 17或更高版本
    * Maven 3.6+
    * npx包管理器
    * Anthropic API密钥（Claude）
    * Brave Search API密钥

    ## 配置环境

    1. 安装npx（Node Package eXecute）：
       首先，确保安装[npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)
       然后运行：
       ```bash
       npm install -g npx
       ```

    2. 克隆仓库：
       ```bash
       git clone https://github.com/spring-projects/spring-ai-examples.git
       cd model-context-protocol/brave-chatbot
       ```

    3. 设置API密钥：
       ```bash
       export ANTHROPIC_API_KEY='你的anthropic-api-密钥'
       export BRAVE_API_KEY='你的brave-api-密钥'
       ```

    4. 构建应用程序：
       ```bash
       ./mvnw clean install
       ```

    5. 使用Maven运行应用程序：
       ```bash
       ./mvnw spring-boot:run
       ```

    <Warning>
      请确保安全保管你的`ANTHROPIC_API_KEY`和`BRAVE_API_KEY`密钥！
    </Warning>

    ## 工作原理

    该应用程序通过以下几个组件将Spring AI与Brave Search MCP服务器集成：

    ### MCP客户端配置

    1. 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>
    ```

    2. 应用程序属性配置（application.yml）：

    ```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}
    ```

    这将激活`spring-ai-mcp-client-spring-boot-starter`，根据提供的服务器配置创建一个或多个`McpClient`实例。

    3. 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传输实现，推荐用于生产部署。
  </Tab>
</Tabs>

## 后续步骤

<CardGroup cols={2}>
  <Card title="示例服务器" icon="grid" href="/examples">
    查看我们的官方MCP服务器和实现示例库
  </Card>

  <Card title="客户端" icon="cubes" href="/clients">
    浏览支持MCP集成的客户端列表
  </Card>

  <Card title="使用LLMs构建MCP" icon="comments" href="/building-mcp-with-llms">
    了解如何使用Claude等LLMs加速MCP开发
  </Card>

  <Card title="核心架构" icon="sitemap" href="/docs/concepts/architecture">
    理解MCP如何连接客户端、服务器和LLMs
  </Card>
</CardGroup>
