MCP 課程文件
構建 Gradio MCP 伺服器
加入 Hugging Face 社群
並獲得增強的文件體驗
開始使用
構建 Gradio MCP 伺服器
在本節中,我們將使用 Gradio 建立我們的情感分析 MCP 伺服器。該伺服器將公開一個情感分析工具,人類使用者可以透過 Web 介面使用它,AI 模型可以透過 MCP 協議使用它。
Gradio MCP 整合簡介
Gradio 提供了一種直接建立 MCP 伺服器的方法,它會自動將您的 Python 函式轉換為 MCP 工具。當您在 launch()
中設定 mcp_server=True
時,Gradio 會
- 自動將您的函式轉換為 MCP 工具
- 將輸入元件對映到工具引數模式
- 根據輸出元件確定響應格式
- 設定基於 HTTP+SSE 的 JSON-RPC 用於客戶端-伺服器通訊
- 建立 Web 介面和 MCP 伺服器端點
專案設定
首先,我們為專案建立一個新目錄並設定所需的依賴項
mkdir mcp-sentiment
cd mcp-sentiment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install "gradio[mcp]" textblob
建立伺服器
Hugging Face Spaces 需要一個 app.py 檔案來構建空間。因此,Python 檔案的名稱必須是 app.py
建立一個名為 app.py
的新檔案,其中包含以下程式碼
import json
import gradio as gr
from textblob import TextBlob
def sentiment_analysis(text: str) -> str:
"""
Analyze the sentiment of the given text.
Args:
text (str): The text to analyze
Returns:
str: A JSON string containing polarity, subjectivity, and assessment
"""
blob = TextBlob(text)
sentiment = blob.sentiment
result = {
"polarity": round(sentiment.polarity, 2), # -1 (negative) to 1 (positive)
"subjectivity": round(sentiment.subjectivity, 2), # 0 (objective) to 1 (subjective)
"assessment": "positive" if sentiment.polarity > 0 else "negative" if sentiment.polarity < 0 else "neutral"
}
return json.dumps(result)
# Create the Gradio interface
demo = gr.Interface(
fn=sentiment_analysis,
inputs=gr.Textbox(placeholder="Enter text to analyze..."),
outputs=gr.Textbox(), # Changed from gr.JSON() to gr.Textbox()
title="Text Sentiment Analysis",
description="Analyze the sentiment of text using TextBlob"
)
# Launch the interface and MCP server
if __name__ == "__main__":
demo.launch(mcp_server=True)
理解程式碼
讓我們分解關鍵元件
函式定義:
sentiment_analysis
函式接受文字輸入並返回一個字典- 它使用 TextBlob 來分析情感
- 文件字串至關重要,因為它有助於 Gradio 生成 MCP 工具模式
- 型別提示 (
str
和dict
) 有助於定義輸入/輸出模式
Gradio 介面:
gr.Interface
建立 Web UI 和 MCP 伺服器- 該函式自動作為 MCP 工具公開
- 輸入和輸出元件定義了工具的模式
- JSON 輸出元件確保正確序列化
MCP 伺服器:
- 設定
mcp_server=True
啟用 MCP 伺服器 - 伺服器將在
https://:7860/gradio_api/mcp/sse
可用 - 您也可以使用環境變數啟用它
export GRADIO_MCP_SERVER=True
- 設定
執行伺服器
透過執行以下命令啟動伺服器
python app.py
您應該會看到輸出,表明 Web 介面和 MCP 伺服器正在執行。Web 介面將在 https://:7860
可用,MCP 伺服器將在 https://:7860/gradio_api/mcp/sse
可用。
測試伺服器
您可以透過兩種方式測試伺服器
Web 介面:
- 在瀏覽器中開啟
https://:7860
- 輸入一些文字並點選“提交”
- 您應該會看到情感分析結果
- 在瀏覽器中開啟
MCP 模式:
- 訪問
https://:7860/gradio_api/mcp/schema
- 這顯示了客戶端將使用的 MCP 工具模式
- 您也可以在 Gradio 應用程式底部的“檢視 API”連結中找到它
- 訪問
故障排除提示
型別提示和文件字串:
- 始終為您的函式引數和返回值提供型別提示
- 包含一個帶有“Args:”塊的文件字串,用於每個引數
- 這有助於 Gradio 生成準確的 MCP 工具模式
字串輸入:
- 如有疑問,請將輸入引數接受為
str
- 在函式內部將其轉換為所需型別
- 這提供了與 MCP 客戶端更好的相容性
- 如有疑問,請將輸入引數接受為
SSE 支援:
- 某些 MCP 客戶端不支援基於 SSE 的 MCP 伺服器
- 在這些情況下,請使用
mcp-remote
{ "mcpServers": { "gradio": { "command": "npx", "args": [ "mcp-remote", "https://:7860/gradio_api/mcp/sse" ] } } }
連線問題:
- 如果遇到連線問題,請嘗試重啟客戶端和伺服器
- 檢查伺服器是否正在執行且可訪問
- 驗證 MCP 模式是否在預期 URL 可用
部署到 Hugging Face Spaces
要使您的伺服器可供他人使用,您可以將其部署到 Hugging Face Spaces
在 Hugging Face 上建立一個新空間
- 訪問 huggingface.co/spaces
- 點選“建立新空間”
- 選擇“Gradio”作為 SDK
- 命名您的空間(例如,“mcp-sentiment”)
建立
requirements.txt
檔案
gradio[mcp] textblob
- 將您的程式碼推送到空間
git init
git add app.py requirements.txt
git commit -m "Initial commit"
git remote add origin https://huggingface.co/spaces/YOUR_USERNAME/mcp-sentiment
git push -u origin main
您的 MCP 伺服器現在可在以下地址訪問
https://YOUR_USERNAME-mcp-sentiment.hf.space/gradio_api/mcp/sse
後續步驟
既然我們的 MCP 伺服器已在執行,我們將建立客戶端與其互動。在接下來的章節中,我們將
- 建立一個受 Tiny Agents 啟發的基於 HuggingFace.js 的客戶端
- 實現一個基於 SmolAgents 的 Python 客戶端
- 使用我們部署的伺服器測試兩個客戶端
讓我們開始構建我們的第一個客戶端!
< > 在 GitHub 上更新