Hub Python 库文档

MCP 客户端

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

MCP 客户端

huggingface_hub 库现在包含一个MCPClient,旨在通过模型上下文协议(MCP)使大型语言模型(LLMs)能够与外部工具进行交互。此客户端扩展了AsyncInferenceClient以无缝集成工具使用。

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

我们还提供了一个更高级别的Agent类。这个“微型代理”通过管理聊天循环和状态来简化对话代理的创建,充当MCPClient的包装器。

MCP 客户端

class huggingface_hub.MCPClient

< >

( model: typing.Optional[str] = None provider: typing.Union[typing.Literal['black-forest-labs', 'cerebras', 'cohere', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'hyperbolic', 'nebius', 'novita', 'nscale', 'openai', 'replicate', 'sambanova', 'together'], typing.Literal['auto'], NoneType] = None base_url: typing.Optional[str] = None api_key: typing.Optional[str] = None )

参数

  • model (str, 可选) — 用于运行推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,例如 meta-llama/Meta-Llama-3-8B-Instruct,或者是已部署的推理端点或其他本地或远程端点的 URL。
  • provider (str, 可选) — 用于推理的提供商名称。默认为“auto”,即模型可用提供商中的第一个,按用户在https://huggingface.co/settings/inference-providers中的顺序排序。如果模型是 URL 或传递了 base_url,则不使用 provider
  • base_url (str, 可选) — 用于运行推理的基础 URL。默认为 None。
  • api_key (str, 可选) — 用于身份验证的令牌。如果未提供,将默认为本地 Hugging Face 保存的令牌。您也可以使用您自己的提供商 API 密钥直接与提供商的服务交互。

用于连接到一个或多个 MCP 服务器并处理带工具的聊天完成的客户端。

此类别为实验性质,未来可能会在不另行通知的情况下进行重大更改。

add_mcp_server

< >

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

参数

  • type (str) — 要连接的服务器类型。可以是以下之一:
    • “stdio”:标准输入/输出服务器(本地)
    • “sse”:服务器发送事件 (SSE) 服务器
    • “http”:StreamableHTTP 服务器
  • **params (Dict[str, Any]) — 服务器参数,可以是:
    • 对于 stdio 服务器:
      • command (str):运行 MCP 服务器的命令
      • args (List[str], 可选):命令的参数
      • env (Dict[str, str], 可选):命令的环境变量
      • cwd (Union[str, Path, None], 可选):命令的工作目录
    • 对于 SSE 服务器:
      • url (str):SSE 服务器的 URL
      • headers (Dict[str, Any], 可选):SSE 连接的请求头
      • timeout (float, 可选):连接超时时间
      • sse_read_timeout (float, 可选):SSE 读取超时时间
    • 对于 StreamableHTTP 服务器:
      • url (str):StreamableHTTP 服务器的 URL
      • headers (Dict[str, Any], 可选):StreamableHTTP 连接的请求头
      • timeout (timedelta, 可选):连接超时时间
      • sse_read_timeout (timedelta, 可选):SSE 读取超时时间
      • terminate_on_close (bool, 可选):是否在关闭时终止

连接到 MCP 服务器

清理

< >

( )

清理资源

process_single_turn_with_tools

< >

( messages: typing.List[typing.Union[typing.Dict, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputMessage]] exit_loop_tools: typing.Optional[typing.List[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool]] = None exit_if_first_chunk_no_tool: bool = False )

参数

  • messages (List[Dict]) — 表示对话历史的消息对象列表
  • exit_loop_tools (List[ChatCompletionInputTool], 可选) — 当调用时应退出生成器的工具列表
  • exit_if_first_chunk_no_tool (bool, 可选) — 如果第一个块中没有工具,则退出。默认为 False。

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

代理

class 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 )

参数

  • model (str, 可选) — 用于运行推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,例如 meta-llama/Meta-Llama-3-8B-Instruct,或者是已部署的推理端点或其他本地或远程端点的 URL。
  • servers (Iterable[Dict]) — 要连接的 MCP 服务器。每个服务器都是一个字典,包含一个 type 键和一个 config 键。type 键可以是 "stdio""sse"config 键是服务器参数的字典。
  • provider (str, 可选) — 用于推理的提供商名称。默认为“auto”,即模型可用提供商中的第一个,按用户在https://huggingface.co/settings/inference-providers中的顺序排序。如果模型是 URL 或传递了 base_url,则不使用 provider
  • base_url (str, 可选) — 用于运行推理的基础 URL。默认为 None。
  • api_key (str, 可选) — 用于身份验证的令牌。如果未提供,将默认为本地 Hugging Face 保存的令牌。您也可以使用您自己的提供商 API 密钥直接与提供商的服务交互。
  • prompt (str, 可选) — 用于代理的系统提示。默认为 constants.py 中的默认系统提示。

一个简单代理的实现,它是一个构建在MCPClient之上的简单 while 循环。

此类别为实验性质,未来可能会在不另行通知的情况下进行重大更改。

运行

< >

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

参数

  • user_input (str) — 用户输入以运行代理。
  • abort_event (asyncio.Event, 可选) — 一个可用于中止代理的事件。如果事件被设置,代理将停止运行。

使用给定的用户输入运行代理。

< > 在 GitHub 上更新