MCP是一个常见的英文缩写,全称为Model Context Protocol(模型上下文协议),是业界领先的开放标准,旨在构建大模型与数据源之间的安全双向链接,解决了开发社区中工具实现风格不统一的问题。目前很多国内云服务器商也提供MCP Server 配置服务,如腾讯云代码助手Craft开发智能体支持用户进行本地 MCP Server 配置,有需要的朋友可以进入腾讯云官网进行了解。为了大家可以一次性弄清楚MCP是什么,本文就来具体分享一下MCP的定义、功能以及相关教程等内容,仅供参考。
点击进入:腾讯云官网
一、什么是MCP
MCP(Model Context Protocol,模型上下文协议)是由Anthropic公司于2024年11月推出的开放标准协议,它规范了应用程序向LLM提供上下文的方式。把MCP想象成人工智能应用的USB-C端口。就像USB-C提供了将设备连接到各种外设和配件的标准化方式一样,MCP也提供了将人工智能模型连接到不同数据源和工具的标准化方式。
MCP由三个关键组件构成:
- 元数据管理:动态追踪数据来源与状态,确保数据的可溯源性和可靠性。
- 关系映射:定义模型间的依赖与协作规则,使不同系统能够理解彼此的数据结构和操作逻辑。
- 动态适配:支持跨平台、跨场景的数据一致性,确保数据在不同环境中的表现形式保持一致。
MCP的工作原理:
- 通过调用聊天完成API,将函数和用户输入传递给MCP服务器;
- 使用模型的响应来调用API或函数;
- 再次调用聊天完成API,包括从函数获得的响应,以得到最终响应。
二、MCP是干嘛的
1、数据访问标准化
MCP提供了一个通用的开放协议,允许开发者通过统一的方式连接各种数据源,如Google Drive、Slack、GitHub等,无需为每种数据源单独开发复杂的接口代码。
2、双向安全连接
MCP支持在AI应用和数据源之间建立双向的、安全的通信通道,确保数据的隐私性和交互的完整性。
3、上下文感知能力
MCP允许AI助手从数据源中提取更全面的上下文信息,提供更加精准和相关的回答。
4、模块化与可扩展性
MCP的架构灵活,支持模块化开发,允许开发者扩展MCP,创建更多的数据源支持。
5、开源与社区支持
MCP是一个完全开源的标准,鼓励开发者社区贡献代码或创建新的连接器,形成健康的开发者生态。
6、多场景应用支持
MCP适用于多种场景,包括但不限于软件开发、数据分析、企业自动化等。
7、安全性
内置安全机制,保护数据和API密钥。
8、开发者支持
提供SDK和文档,支持开发者构建和测试MCP连接器。
9、预构建服务器
提供预构建的MCP服务器,快速集成流行企业系统。
10、上下文维护
在不同工具和数据集之间保持上下文,实现更智能的任务处理。
三、构建一个简单的MCP服务器
1、使用Claude for Desktop作为客户端,自己编写python文件作为服务端,在Claude Desktop里调用server.py。
要求:
- 已安装python 3.10
- 已安装Claude for Desktop
2、打开Powershell,输入如下命令:
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
打开系统高级环境变量,在Path将uv路径添加进去:
C:\Users\windows\.local\bin
3、在命令行输入uv--version,能返回版本信息就算安装成功了:
4、打开Powershell,cd到用户想要创建项目的目录位置,如:
接着依次输入以下命令:
# Create a new directory for our project
uv init weather
cd weather# Create virtual environment and activate it
uv venv
.venv\Scripts\activate# Install dependencies
uv add mcp[cli] httpx# Create our server file。new-item 是powershell 命令,用于创建文件
new-item weather.py
5、添加代码
将以下代码整个复制到weather.py:
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"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.0)
response.raise_for_status()
return response.json()
except Exception:
return Nonedef format_alert(feature: dict) -> str:
"""Format an alert feature into a readable string."""
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 provided')}
"""@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 found."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 location longitude: Longitude of the location """ # First get the forecast grid endpoint
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."# Get the forecast URL from the points response
forecast_url = points_data["properties"]["forecast"]
forecast_data = await make_nws_request(forecast_url)if not forecast_data:
return "Unable to fetch detailed forecast."# Format the periods into a readable forecast
periods = forecast_data["properties"]["periods"]
forecasts = []
for period in periods[:5]: # Only show next 5 periods
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)
if __name__ == "__main__":
# Initialize and run the server
mcp.run(transport='stdio')
如果代码里提示依赖错误,安装对应的包就好。
6、打开Claude for Desktop,点击左上角菜单——File——Settings——Developer
点击Edit Config,就会在C:UserswindowsAppDataRoamingClaude目录下自动创建claude_desktop_config.json文件。
打开claude_desktop_config.json,添加如下代码:
{
"mcpServers": {
"weather": {
"command": "uv",
"args": [
"--directory",
"T:\\PythonProject\\weather",
"run",
"weather.py"
]
}
}
}
其中路径为在上一步创建的weather目录,使用绝对路径。
保存文件。
7、打开任务管理器,将Claude结束任务,彻底关掉。
重新打开Claude for Desktop。
如图所示,MCP服务就配置成功了。