MCP 課程文件

Gradio 作為 MCP 客戶端

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

Gradio 作為 MCP 客戶端

在上一節中,我們探討了如何使用 Gradio 建立 MCP 伺服器並使用 MCP 客戶端連線到它。在本節中,我們將探討如何使用 Gradio 作為 MCP 客戶端連線到 MCP 伺服器。

Gradio 最適合建立 UI 客戶端和 MCP 伺服器,但它也可以用作 MCP 客戶端並將其暴露為 UI。

我們將連線到一個類似於我們在上一節中建立的 MCP 伺服器,但它具有額外的功能,並使用它來回答問題。

Gradio 中的 MCP 客戶端

連線到示例 MCP 伺服器

讓我們連線到 Hugging Face 上已執行的示例 MCP 伺服器。我們將使用這個作為示例。它是一個包含 MCP 工具集合的 Space。

from smolagents.mcp_client import MCPClient

with MCPClient(
    {"url": "https://abidlabs-mcp-tool-http.hf.space/gradio_api/mcp/sse"}
) as tools:
    # Tools from the remote server are available
    print("\n".join(f"{t.name}: {t.description}" for t in tools))
輸出

prime_factors: Compute the prime factorization of a positive integer.
generate_cheetah_image: Generate a cheetah image.
image_orientation: Returns whether image is portrait or landscape.
sepia: Apply a sepia filter to the input image.

從 Gradio 連線到 MCP 伺服器

很好,您已經連線到示例 MCP 伺服器。現在,您需要在示例應用程式中使用它。

首先,我們需要安裝 smolagents、Gradio 和 mcp-client 庫(如果尚未安裝)

pip install "smolagents[mcp]" "gradio[mcp]" mcp fastmcp

現在,我們可以匯入必要的庫並建立一個簡單的 Gradio 介面,該介面使用 MCP 客戶端連線到 MCP 伺服器。

import gradio as gr
import os

from mcp import StdioServerParameters
from smolagents import InferenceClientModel, CodeAgent, ToolCollection, MCPClient

接下來,我們將連線到 MCP 伺服器並獲取可用於回答問題的工具。

mcp_client = MCPClient(
    {"url": "https://abidlabs-mcp-tool-http.hf.space/gradio_api/mcp/sse"} # This is the MCP Client we created in the previous section
)
tools = mcp_client.get_tools()

現在我們有了工具,我們可以建立一個簡單的智慧體,它使用這些工具來回答問題。我們暫時只使用一個簡單的 InferenceClientModelsmolagents 中的預設模型。

將您的 api_key 傳遞給 InferenceClientModel 非常重要。您可以從您的 huggingface 帳戶訪問該令牌。請在此處檢視。並使用環境變數 HF_TOKEN 設定訪問令牌。

model = InferenceClientModel(token=os.getenv("HF_TOKEN"))
agent = CodeAgent(tools=[*tools], model=model)

現在,我們可以建立一個簡單的 Gradio 介面,該介面使用該智慧體來回答問題。

demo = gr.ChatInterface(
    fn=lambda message, history: str(agent.run(message)),
    type="messages",
    examples=["Prime factorization of 68"],
    title="Agent with MCP Tools",
    description="This is a simple agent that uses MCP tools to answer questions."
)

demo.launch()

就這樣!我們建立了一個簡單的 Gradio 介面,該介面使用 MCP 客戶端連線到 MCP 伺服器並回答問題。

完整示例

這是在 Gradio 中使用 MCP 客戶端的完整示例

import gradio as gr
import os

from smolagents import InferenceClientModel, CodeAgent, MCPClient


try:
    mcp_client = MCPClient(
        {"url": "https://abidlabs-mcp-tool-http.hf.space/gradio_api/mcp/sse"}
    )
    tools = mcp_client.get_tools()

    model = InferenceClientModel(token=os.getenv("HUGGINGFACE_API_TOKEN"))
    agent = CodeAgent(tools=[*tools], model=model, additional_authorized_imports=["json", "ast", "urllib", "base64"])

    demo = gr.ChatInterface(
        fn=lambda message, history: str(agent.run(message)),
        type="messages",
        examples=["Analyze the sentiment of the following text 'This is awesome'"],
        title="Agent with MCP Tools",
        description="This is a simple agent that uses MCP tools to answer questions.",
    )

    demo.launch()
finally:
    mcp_client.disconnect()

您會注意到我們正在 finally 塊中關閉 MCP 客戶端。這很重要,因為 MCP 客戶端是一個長期存在的物件,當程式退出時需要關閉它。

部署到 Hugging Face Spaces

要讓您的伺服器可供他人使用,您可以將其部署到 Hugging Face Spaces,就像我們在上一節中做的那樣。要將您的 Gradio MCP 客戶端部署到 Hugging Face Spaces,請執行以下操作:

  1. 在 Hugging Face 上建立一個新 Space

    • 前往 huggingface.co/spaces
    • 點選“Create new Space”(建立新 Space)
    • 選擇“Gradio”作為 SDK
    • 命名您的 Space(例如,“mcp-client”)
  2. 更新程式碼中的 MCP 伺服器 URL

mcp_client = MCPClient(
    {"url": "https://abidlabs-mcp-tool-http.hf.space/gradio_api/mcp/sse"}
)
  1. 建立 requirements.txt 檔案
gradio[mcp]
smolagents[mcp]
  1. 將您的程式碼推送到 Space
git init
git add app.py requirements.txt
git commit -m "Initial commit"
git remote add origin https://huggingface.co/spaces/YOUR_USERNAME/mcp-client
git push -u origin main

注意:新增遠端源時,請參閱password-git-deprecation以瞭解如何使用 AccessToken 進行新增。

結論

在本節中,我們探討了如何使用 Gradio 作為 MCP 客戶端連線到 MCP 伺服器。我們還了解了如何將 MCP 客戶端部署到 Hugging Face Spaces。

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.