Hub Python Library documentation

MCP 客户端

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v2.4.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

MCP 客户端

huggingface_hub 库现在包含一个 MCPClient,旨在通过 Model Context Protocol(MCP)赋予大型语言模型(LLM)与外部工具交互的能力。该客户端扩展了 AsyncInferenceClient,以无缝集成工具的使用。

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

我们还提供了一个更高级的 Agent 类。这个“Tiny Agent”通过管理聊天循环和状态,简化了创建对话式 Agent 的过程,它充当 MCPClient 的封装器。

MCP 客户端

类 huggingface_hub.MCPClient

< >

( model: typing.Optional[str] = Noneprovider: 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] = Nonebase_url: typing.Optional[str] = Noneapi_key: typing.Optional[str] = None )

参数

  • 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) — 用于身份验证的 Token。如果未提供,将默认使用本地保存的 Hugging Face token。您也可以使用自己的提供商 API key 直接与提供商的服务进行交互。

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

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

add_mcp_server

< >

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

参数

  • 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], optional): 命令的工作目录
      • 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 服务器

清理

< >

( )

清理资源

process_single_turn_with_tools

< >

( messages: listexit_loop_tools: typing.Optional[list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool]] = Noneexit_if_first_chunk_no_tool: bool = False )

参数

  • messages (list[dict]) — 表示对话历史的 message 对象列表
  • exit_loop_tools (list[ChatCompletionInputTool],可选) — 调用后应使生成器退出的工具列表
  • exit_if_first_chunk_no_tool (bool, 可选) — 如果第一个块中不存在工具,则退出。默认为 False。

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

Agent

类 huggingface_hub.Agent

< >

( model: Optional[str] = Noneservers: Iterable[ServerConfig]provider: Optional[PROVIDER_OR_POLICY_T] = Nonebase_url: Optional[str] = Noneapi_key: Optional[str] = Noneprompt: Optional[str] = None )

参数

  • 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 之上,本质上是一个简单的 while 循环。

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

运行

< >

( user_input: strabort_event: Optional[asyncio.Event] = None )

参数

  • user_input (str) — 用于运行智能体的用户输入。
  • abort_event (asyncio.Event, 可选) — 可用于中止智能体的事件。如果该事件被设置,智能体将停止运行。

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

Update on GitHub