MCP(一)——QuickStart
目录
- 1. MCP简介
- 2. MCP的优势
- 3. MCP核心
- 4. QuickStart For Server Developers(仅具参考)
- 4.1 MCP核心概念
- 4.2 构建MCP服务器的代码
- 4.2.1 设置MCP服务器实例
- 4.2.2 辅助函数
- 4.2.3 实现工具执行
- 4.2.4 在Cherry-Studio中添加MCP服务器
- 4.2.5 演示
- 4.2.5.1 测试工具get_alerts
- 4.2.5.2 测试工具get_forecast
- 4.2.6 评价DeepSeek MCP调用的能力
- 参考
1. MCP简介
MCP(大模型上下文协议)是一个开放协议,旨在标准化应用程序向LLMs提供上下文的方式。可以将MCP视为AI应用的USB-C接口。正如USB-C为设备连接各种外设和配件提供了标准化方案,MCP则为AI模型连接不同数据源和工具提供了标准化途径。
2. MCP的优势
MCP能帮助使用者在大语言模型之上构建智能体和复杂工作流。此外,大语言模型经常需要与数据和工具集成,而MCP提供了以下支持:
1. 大语言模型可直接接入且不断增长的预构建集成列表。
2. 灵活切换不同大语言模型供应商和服务商的能力(无须担忧切换了大语言模型就无法使用MCP、无须担忧切换了智能体框架就无法使用MCP)。
3. 在你的基础设施内保护数据安全的最佳实践。
3. MCP核心
MCP核心采用客户端-服务器架构,一个主机应用可连接多个服务器:
MCP Hosts(MCP主机):如Claude桌面程序、集成开发环境或希望通过MCP访问数据的AI工具。
MCP Clients(MCP客户端):与服务器保持一对一连接的协议客户端。
MCP Servers(MCP服务器):通过标准化模型上下文协议暴露特定功能的轻量级程序。
Local Data Sources(本地数据源):MCP服务器可安全访问的计算机文件、数据库及服务。
Remote Services(远程服务):MCP服务器可通过互联网连接的外部系统,例如通过API。
4. QuickStart For Server Developers(仅具参考)
modelcontextprotocol官网的QuickStart是构建一个查询美国天气的MCP天气服务器。该服务器会对外提供两个工具;get-alerts和get-forecast。官网选择了Claude桌面端作为演示该MCP的主机,但是Claude注册账户需要美国手机号,这里就使用cherry-studio作为主机,并且演示用的大语言模型选择为deepseek-reasoner。
4.1 MCP核心概念
MCP服务器主要能提供三类功能:
1. Resources(资源):可供客户端读取的类文件数据,如API响应或文件内容。
2. Tools(工具):可由大语言模型调用的函数。
3. Prompts(提示):预先编写的模板,帮助用户完成特定任务。
4.2 构建MCP服务器的代码
以下所有代码都添加到weather.py中。
4.2.1 设置MCP服务器实例
下面的代码通过FastMCP类来构建MCP服务器实例。FastMCP类利用Python类型提示和文档字符串自动生成工具定义,使得创建和维护MCP工具变得简单。
from typing import Any
import httpx
from mcp.server.fastmcp import FastMCP# Initialize FastMCP server
mcp = FastMCP("weather")# Constants
NWS_API_BASE = "https://api.weather.gov"
USER_AGENT = "weather-app/1.0"
4.2.2 辅助函数
添加用于查询和格式化来自美国气象局API数据的辅助函数:
async def make_nws_request(url: str) -> dict[str, Any] | None:"""Make a request to the NWS API with proper error handling."""headers = {"User-Agent": USER_AGENT,"Accept": "application/geo+json",}async with httpx.AsyncClient() as client:try:response = await client.get(url, headers=headers, timeout=30)response.raise_for_status()return response.json()except Exception:return Nonedef format_alert(feature: dict) -> str:props = feature["properties"]return f"""Event: {props.get('event', 'Unknown')}Area: {props.get('areaDesc', 'Unknown')}Severity: {props.get('severity', 'Unknown')}Description: {props.get('description', 'No description available')}Instructions: {props.get('instruction', 'No specific instructions')}"""
4.2.3 实现工具执行
工具执行主要是通过mcp.tool()装饰器来实现的:
@mcp.tool()
async def get_alerts(state: str) -> str:"""Get weather alerts for a US state.Args:state: Two-letter US state code (e.g. CA, NY)"""url = f"{NWS_API_BASE}/alerts/active/area/{state}"data = await make_nws_request(url)if not data or "features" not in data:return "Unable to fetch alerts or no alerts fuond."if not data["features"]:return "no active alerts for this state."alerts = [format_alert(feature) for feature in data["features"]]return "\n-----\n".join(alerts)@mcp.tool()
async def get_forecast(latitude: float, longitude: float) -> str:"""Get weather forecast for a location.Args:latitude: Latitude of the locationlongitude: Longitude of the location"""points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"points_data = await make_nws_request(points_url)if not points_data:return "Unable to fetch forecast data for this location."forecast_url = points_data["properties"]["forecast"]forecast_data = await make_nws_request(forecast_url)if not forecast_data:return "Unable to fetch detailed forecast."periods = forecast_data["properties"]["periods"]forecasts = []for period in periods[:5]:forecast = f"""{period["name"]}:Temperature: {period["temperature"]}°{period["temperatureUnit"]}Wind: {period["windSpeed"]} {period["windDirection"]}Forecast: {period["detailedForecast"]}"""forecasts.append(forecast)return "\n----\n".join(forecasts)
4.2.4 在Cherry-Studio中添加MCP服务器
Cherry-Studio下载:https://www.cherry-ai.com/download
在模型服务中配置API_KEY或本地模型名:
点击红圈所指的位置,进入后点击按钮安装uv和bun(需要挂梯子)。
将前面代码构建的weather MCP服务器导入到cherry-studio中,按照下图中的内容填写配置,其中参数的具体内容如下(每行只能有一个参数):
--directory
D:\\project\\Python\\learnMCP\\QuickStart (weather.py所在目录的绝对路径,括号里的内容不需要填入)
run
weather.py
点击保存并启用。
4.2.5 演示
4.2.5.1 测试工具get_alerts
从上图中,可以看出可能是由于函数文档字符串不够详细的缘故导致deepseek-reasoner错误调用了get_alerts工具,下面是大模型调用工具时填写的参数以及得到的响应:
这里错误调用的原因是state必须是两字母的城市缩写代码,比如New York必须填写为NY。下面我通过在提示词中输入了纽约的两位州代码是NY,使得大模型正确地调用了get_alerts工具,并得到了正确的响应。
4.2.5.2 测试工具get_forecast
4.2.6 评价DeepSeek MCP调用的能力
此外,我还使用了DeepSeek Chat来测试它MCP调用的能力,上面没有展示。
结论如下:DeepSeek Reasoner的MCP调用(工具调用)能力比DeepSeek-Chat好一点,但是两者在调用get_alerts工具时展现出的能力一样,都需要人为提示(部分原因还是MCP服务器工具函数的解释不够详细)。而在get_forecast工具的调用上,DeepSeek Reasoner能自己寻找到New York的经纬度从而正确完成工具的调用,与之相反,DeepSeek Chat则认为它需要一个工具来获取New York的经纬度从而无法完成工具的调用。
Claude官方是MCP的提出者,据说Claude对工具的调用是目前大语言模型里最好的,可是Claude账户的注册需要境外手机号,也就无法测试比较了。
参考
https://modelcontextprotocol.io/introduction
https://modelcontextprotocol.io/quickstart/server