# MCP 客户端

`huggingface_hub` 库现在包含一个 [MCPClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/mcp#huggingface_hub.MCPClient)，旨在通过 [Model Context Protocol](https://modelcontextprotocol.io)（MCP）赋予大型语言模型（LLM）与外部工具交互的能力。该客户端扩展了 [AsyncInferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.AsyncInferenceClient)，以无缝集成工具的使用。

[MCPClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/mcp#huggingface_hub.MCPClient) 连接到暴露工具的 MCP 服务器（本地 `stdio` 脚本或远程 `http`/`sse` 服务）。它将这些工具提供给 LLM（通过 [AsyncInferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.AsyncInferenceClient)）。如果 LLM 决定使用某个工具，[MCPClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/mcp#huggingface_hub.MCPClient) 会管理向 MCP 服务器发出的执行请求，并将该工具的输出传回给 LLM，通常以实时流式方式返回结果。

我们还提供了一个更高级的 [Agent](/docs/huggingface_hub/v2.4.0/zh/package_reference/mcp#huggingface_hub.Agent) 类。这个“Tiny Agent”通过管理聊天循环和状态，简化了创建对话式 Agent 的过程，它充当 [MCPClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/mcp#huggingface_hub.MCPClient) 的封装器。

## MCP 客户端[[huggingface_hub.MCPClient]]

#### huggingface_hub.MCPClient[[huggingface_hub.MCPClient]]

```python
huggingface_hub.MCPClient(model: typing.Optional[str] = None, provider: typing.Union[typing.Literal['baseten', 'cerebras', 'cohere', 'deepinfra', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'novita', 'nscale', 'openai', 'ovhcloud', 'publicai', 'replicate', 'scaleway', 'together', 'wavespeed', 'zai-org'], typing.Literal['auto'], NoneType] = None, base_url: typing.Optional[str] = None, api_key: typing.Optional[str] = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_mcp/mcp_client.py#L55)

**参数：**

model (`str`, `optional`) : 用于运行推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID，例如 `meta-llama/Meta-Llama-3-8B-Instruct`，也可以是已部署的 Inference Endpoint 的 URL 或其他本地或远程端点。

provider (`str`, *可选*) : 用于推理的提供商名称。默认为 "auto"，即按用户在 https://hf.co/settings/inference-providers 中设置的顺序，选择该模型可用的第一个提供商。如果 model 是 URL 或传入了 `base_url`，则不使用 `provider`。

base_url (`str`, *可选*) : 用于运行推理的基础 URL。默认为 None。

api_key (`str`, `optional`) : 用于身份验证的令牌。如果未提供，将默认使用本地保存的 Hugging Face 令牌。您也可以使用自己的提供商 API 密钥直接与提供商的服务进行交互。

用于连接一个或多个 MCP 服务器并使用工具处理聊天补全的客户端。

> [!WARNING]
> 此类为实验性功能，未来可能会在没有提前通知的情况下进行破坏性更改。

#### add_mcp_server[[huggingface_hub.MCPClient.add_mcp_server]]

```python
add_mcp_server(type: typing.Literal['stdio', 'sse', 'http'], **params: typing.Any)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_mcp/mcp_client.py#L123)

**参数：**

type (`str`) : 要连接的服务器类型。可以是以下之一： - "stdio"：标准输入/输出服务器（本地） - "sse"：服务器发送事件（SSE）服务器 - "http"：可流式传输的 HTTP 服务器

- ****params** (`dict[str, Any]`) : 服务器参数，可以是以下之一： - 对于 stdio 服务器： - command (str)：用于运行 MCP 服务器的命令 - args (list[str], 可选)：命令的参数 - env (dict[str, str], 可选)：命令的环境变量 - cwd (Union[str, Path, None], 可选)：命令的工作目录 - allowed_tools (list[str], 可选)：允许从此服务器使用的工具名称列表 - 对于 SSE 服务器： - url (str)：SSE 服务器的 URL - headers (dict[str, Any], 可选)：SSE 连接的请求头 - timeout (float, 可选)：连接超时时间 - sse_read_timeout (float, 可选)：SSE 读取超时时间 - allowed_tools (list[str], 可选)：允许从此服务器使用的工具名称列表 - 对于 StreamableHTTP 服务器： - url (str)：StreamableHTTP 服务器的 URL - headers (dict[str, Any], 可选)：StreamableHTTP 连接的请求头 - timeout (timedelta, 可选)：连接超时时间 - sse_read_timeout (timedelta, 可选)：SSE 读取超时时间 - terminate_on_close (bool, 可选)：是否在关闭时终止连接 - allowed_tools (list[str], 可选)：允许从此服务器使用的工具名称列表

连接到 MCP 服务器

#### 清理[[huggingface_hub.MCPClient.cleanup]]

```python
cleanup()
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_mcp/mcp_client.py#L109)

清理资源

#### process_single_turn_with_tools[[huggingface_hub.MCPClient.process_single_turn_with_tools]]

```python
process_single_turn_with_tools(messages: list, exit_loop_tools: typing.Optional[list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool]] = None, exit_if_first_chunk_no_tool: bool = False)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_mcp/mcp_client.py#L252)

**参数：**

messages (`list[dict]`) : 表示对话历史的消息对象列表

exit_loop_tools (`list[ChatCompletionInputTool]`，*可选*)：当调用时会使生成器退出的工具列表

exit_if_first_chunk_no_tool (`bool`, *可选*) : 如果第一个块中不存在工具，则退出。默认为 False。

**返回值：**

[ChatCompletionStreamOutput](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_types#huggingface_hub.ChatCompletionStreamOutput) 数据块或 [ChatCompletionInputMessage](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_types#huggingface_hub.ChatCompletionInputMessage) 对象

使用 `self.model` 和可用工具处理查询，生成数据块和工具输出。

## Agent[[huggingface_hub.Agent]]

#### huggingface_hub.Agent[[huggingface_hub.Agent]]

```python
huggingface_hub.Agent(model: Optional[str] = None, servers: Iterable[ServerConfig], provider: Optional[PROVIDER_OR_POLICY_T] = None, base_url: Optional[str] = None, api_key: Optional[str] = None, prompt: Optional[str] = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_mcp/agent.py#L13)

**参数：**

model (`str`, *可选*) : 用于运行推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID，例如 `meta-llama/Meta-Llama-3-8B-Instruct`，也可以是已部署的 Inference Endpoint 的 URL 或其他本地或远程端点。

servers (`Iterable[dict]`) : 要连接的 MCP 服务器。每个服务器是一个字典，包含 `type` 键和 `config` 键。`type` 键可以是 `"stdio"` 或 `"sse"`，`config` 键是用于服务器的参数字典。

provider (`str`, *可选*) : 用于推理的提供商名称。默认为 "auto"，即按用户在 https://hf.co/settings/inference-providers 中设置的顺序，选择该模型可用的第一个提供商。如果 model 是 URL 或传入了 `base_url`，则不使用 `provider`。

base_url (`str`, *可选*) : 用于运行推理的基础 URL。默认为 None。

api_key (`str`, *可选*) : 用于身份验证的令牌。如果未提供，将默认使用本地保存的 Hugging Face 令牌。您也可以使用自己的提供商 API 密钥直接与提供商的服务进行交互。

prompt (`str`, *可选*) : 用于该智能体的系统提示词。默认为 `constants.py` 中的默认系统提示词。

一个简单智能体的实现，它直接构建在 [MCPClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/mcp#huggingface_hub.MCPClient) 之上，本质上是一个简单的 while 循环。

> [!WARNING]
> 此类为实验性功能，未来可能会在没有提前通知的情况下进行破坏性更改。

#### 运行[[huggingface_hub.Agent.run]]

```python
run(user_input: str, abort_event: Optional[asyncio.Event] = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_mcp/agent.py#L57)

**参数：**

user_input (`str`) : 用于运行智能体的用户输入。

abort_event (`asyncio.Event`, *可选*) : 一个可用于中止智能体的事件。如果该事件被设置，智能体将停止运行。

使用给定的用户输入运行智能体。

