import gradio as gr
defcheck_weather(city):"""
Simple weather checker function (mock data for demonstration).
Args:
city (str): The city name to check weather for
Returns:
str: Weather information for the city
"""# Mock weather data for demonstration
weather_data ={"london":"Cloudy, 15°C","paris":"Sunny, 22°C","tokyo":"Rainy, 18°C","new york":"Partly cloudy, 20°C","sydney":"Sunny, 25°C",}
city_lower = city.lower().strip()if city_lower in weather_data:returnf"Weather in {city.title()}: {weather_data[city_lower]}"else:returnf"Weather data not available for {city}. Try: London, Paris, Tokyo, New York, or Sydney"
demo = gr.Interface(
fn=check_weather,
inputs=[gr.Textbox("London", label="Enter city name")],
outputs=[gr.Textbox(label="Weather Info")],
title="Simple Weather Checker",
description="Enter a city name to check the weather (demo with mock data).",)if __name__ =="__main__":
demo.launch(mcp_server=True)技术支持
3. 在 Gradio 中启用 MCP 有两种方式:
使用 mcp_server 参数:demo.launch(mcp_server=True)
设置环境变量: export GRADIO_MCP_SERVER=True
4. 将 Python 文件保存为 test.py 并运行。
$ python test.py
* Running on local URL: http://127.0.0.1:7860* To create a public link,set `share=True` in `launch()`.
🔨 MCP server (using SSE) running at: http://127.0.0.1:7860/gradio_api/mcp/sse技术支持
该 MCP 服务器包含两个工具,均使用 Tavily API 访问网页的最新信息。第一个工具接收城市名并生成详细天气报告;第二个工具接收城市名并列出当地前五条新闻头条。我们为每个工具创建了图形界面,并通过标签页界面将二者组合。
app.py:
import gradio as gr
from tavily import TavilyClient
defget_city_weather_info(city_name):"""
Search for current weather information about a city using Tavily search API
Args:
city_name (str): Name of the city
api_key (str): Your Tavily API key
Returns:
dict: Search results containing weather information
"""# Initialize Tavily client
client = TavilyClient()# Search for current weather information
search_query =f"current weather in {city_name} temperature humidity conditions"try:# Perform the search
response = client.search(
query=search_query, search_depth="basic", max_results=5)# Extract relevant information from search results
weather_info ={"city": city_name,"search_query": search_query,"results":[]}# Process each search resultfor result in response.get("results",[]):
weather_info["results"].append({"title": result.get("title",""),"content": result.get("content",""),"url": result.get("url",""),})# Add the answer if availableif"answer"in response:
weather_info["summary"]= response["answer"]return weather_info
except Exception as e:return{"city": city_name,"error":f"Failed to fetch weather information: {str(e)}",}defget_city_news(city_name):"""
Fetches the top 5 news articles for a given city using the Tavily API.
Args:
city_name (str): Name of the city
Returns:
dict: News results containing the top 5 articles or an error message
"""# Initialize Tavily client
client = TavilyClient()# Search query for news about the city
search_query =f"Top 5 latest news articles about {city_name}, including major events, politics, economy, and local updates."try:# Perform the search
response = client.search(
query=search_query,
search_depth="advanced",
max_results=5,)# Extract relevant information from search results
news_info ={"city": city_name,"search_query": search_query,"articles":[]}# Process each search resultfor result in response.get("results",[]):
news_info["articles"].append({"title": result.get("title",""),"content": result.get("content",""),"url": result.get("url",""),})# Add the answer if availableif"answer"in response:
news_info["summary"]= response["answer"]return news_info
except Exception as e:return{"city": city_name,"error":f"Failed to fetch news: {str(e)}"}# Create Gradio interfaces
weather_demo = gr.Interface(
fn=get_city_weather_info,
inputs=gr.Textbox(label="Enter City Name", placeholder="e.g., New York"),
outputs=gr.JSON(label="Weather Information"),
description="Get current weather details for a city.",)
news_demo = gr.Interface(
fn=get_city_news,
inputs=gr.Textbox(label="Enter City Name", placeholder="e.g., London"),
outputs=gr.JSON(label="News Articles"),
description="Get the latest news articles for a city.",)# Create tabbed interface
demo = gr.TabbedInterface([weather_demo, news_demo],["Weather","News"], title="City Information Hub")if __name__ =="__main__":# Launch without MCP server to avoid initialization issues
demo.launch(share=False, mcp_server=True, debug=True)技术支持
* Running on local URL: http://127.0.0.1:7860
* To create a public link, set`share=True`in`launch()`.
🔨 MCP server (using SSE) running at: http://127.0.0.1:7860/gradio_api/mcp/sse技术支持
Model Context Protocol(MCP,模型上下文协议) 是一种开放标准,用于将 AI 模型连接到外部工具、API 和数据源。它为大语言模型(LLM)与外部系统交互提供了标准化方式。
随着世界迈向 Agentic 工作流(AI 系统以自主体形式行动),学习 MCP 变得愈发重要。Gradio 生态为构建 MCP 服务器提供了最简单高效的方式,使开发者以最小成本创建强大的 AI 工具。
在本教程中,您将:
如果您想亲手实践 使用 LangChain 设计 Agentic 系统,推荐查看我们的课程。
Gradio MCP 快速上手
最新版 Gradio(5.32.0)已原生支持 MCP,使构建和运行 MCP 服务器变得极其简单。您只需通过一行代码参数或环境变量启用 MCP 支持即可。
Gradio MCP 服务器使用 Server-Sent Events(SSE)协议,从服务器向客户端进行实时单向通信——非常适合流式返回 LLM 的响应。
1. 安装带 MCP 支持的 Gradio 最新版本。
2. 构建一个 Gradio 应用:输入城市名并返回天气数据(此处为模拟数据)。如果您已熟悉 Gradio,这是个很好的起点。
3. 在 Gradio 中启用 MCP 有两种方式:
mcp_server参数:demo.launch(mcp_server=True)export GRADIO_MCP_SERVER=True4. 将 Python 文件保存为
test.py并运行。您将在终端输出中看到两个 URL:
5. 在浏览器中打开应用 URL(http://127.0.0.1:7860)。输入城市名(如 Tokyo)并查看天气。
6. 在应用底部点击“Use via API or MCP”按钮。应用会显示关于其 API 和 MCP 服务器的更多信息。
7. 若要在 Cursor AI 中测试 MCP 服务器,打开 Cursor 设置,进入“MCP”选项卡,点击“+ Add new global MCP server”按钮。
8. 将以下 JSON 配置添加到 MCP 设置文件:
9. 保存文件。此时您会看到一个名为
gradio的活动 MCP 服务器,其中包含工具check_weather。为测试该 MCP 服务器,我们将在 Cursor 的 agent 模式中新建会话(CTRL + T),询问东京的天气。Cursor 会请求运行 MCP 工具的权限,请批准。
随后,MCP 服务器将获取天气数据并返回结果:
使用 Gradio 构建多工具 MCP 服务器
让我们创建一个实用且可用于生产的项目。在本项目中,我们将使用 Gradio 构建一个多工具 MCP 服务器。
服务器将包含两个工具:
该服务器通过提供天气更新与相关新闻,帮助用户规划行程。
我们将搭建 MCP 服务器、在本地测试、部署到 Hugging Face Spaces,并用 Cursor AI 和 Claude Desktop 测试已部署的服务器。
1. 环境准备
前往 https://huggingface.co/new-space 创建新 Space,填写应用名称与简短描述,并选择 Gradio 模板。
来源: new-space
创建完成后,您将跳转到新的 Space。按页面说明完成设置。
将代码库克隆到本地项目目录
本项目将使用 Tavily API 实现网页搜索功能,请在 Tavily AI 创建账户并生成 API 密钥。
来源: Tavily AI
然后,将该 API 密钥保存为本地系统的环境变量
随后安装 Tavily 的 Python SDK
2. 创建 MCP 服务器
该 MCP 服务器包含两个工具,均使用 Tavily API 访问网页的最新信息。第一个工具接收城市名并生成详细天气报告;第二个工具接收城市名并列出当地前五条新闻头条。我们为每个工具创建了图形界面,并通过标签页界面将二者组合。
app.py:
3. 本地测试 MCP 服务器
在部署之前,务必先进行本地测试。在终端运行以下命令启动服务器:
输出:
打开浏览器访问 http://127.0.0.1:7860,在输入框中输入城市名。服务器将以 JSON 格式返回详细天气信息。
应用应能正常工作,并为输入的城市提供准确的天气和新闻数据。
4. 将 MCP 服务器部署到 Hugging Face Spaces
按照以下步骤进行部署:
1. 创建
requirements.txt文件并添加以下依赖:2. 提交更改并推送到 Hugging Face Space。
推送后,Hugging Face Space 将开始构建。
来源:Live City Mcp
约一分钟后,MCP 服务器将上线,可通过 Live City Mcp 访问。
来源:Live City Mcp
3. 在作为 MCP 服务器使用前,我们需要设置包含 Tavily 访问令牌的环境变量。前往 Space 设置页面,下滑点击“New Secret”按钮,然后添加 Tavily 的 API 名称与密钥。
来源:live-city-mcp/settings
5. 使用 Cursor AI 测试已部署的 MCP 服务器
我们的 MCP 已部署并正常运行。接下来设置 MCP 客户端。首先配置 Cursor AI。进入 Cursor 设置,点击 MCP 选项卡,然后点击“+Add new global MCP server”按钮。输入以下代码:
您会看到
weather-newsMCP 正常运行,并包含两个工具。我们来询问伊斯兰堡的天气。可以看到,响应快速且准确。
我们可通过在线搜索并在 AccuWeather 上核对天气来验证正确性。
来源:AccuWeather
接着,测试第二个工具,询问伊斯兰堡周边的新闻。
结果返回了关于巴基斯坦的四条新闻头条。如果 Tavily API 无法找到伊斯兰堡的最新消息,它会回退到国家层面的新闻。
6. 使用 Claude Desktop 测试已部署的 MCP 服务器
前往设置,点击“Developer”,再点击“Edit Config”按钮,完成 Claude Desktop 的设置。这将打开需要编辑的
claude_desktop_config.json文件所在文件夹。Claude Desktop 目前不支持基于 SSE 的 MCP 服务器。在这种情况下,您可以使用名为
mcp-remote的工具。要运行
mcp-remote,需先安装 Node.js,可前往e Download Node.js® 页面。 然后将以下代码添加到claude_desktop_config.json文件中:以下为添加 MCP 服务器配置的示例。
完成后,请退出 Claude Desktop 并重新启动。您将看到名为 “Live City MCP” 的新 MCP 服务器,包含两个可用工具。
我即将前往爱尔兰旅行,于是询问了都柏林的天气,并获得了非常不错的结果。
访问 MCP 服务器的最佳方式是通过 Claude Desktop。它具备交互性,并为工具使用和信息展示提供了更佳的能力。
结语
如果您已经熟悉为机器学习项目构建 Gradio 应用,那么将现有应用转换为 MCP 服务器再容易不过。只需添加一个参数(
mcp_server=True),您的 Gradio 应用即可同时充当 MCP 服务器,顺畅集成 Cursor AI 与 Claude Desktop 等工具。这为您的 AI 应用连接外部系统与工作流打开了新的可能性。本教程以轻松的方式介绍了 Gradio MCP 的基础,带您构建并测试 MCP 服务器,并通过 Tavily API 实现实时天气与城市新闻的实用项目。最后,我们将项目部署到 Hugging Face Spaces,并用多个兼容 MCP 的客户端完成测试。
若您希望进一步学习 Agentic AI 及本教程涉及的其他概念,推荐以下资源: