5分钟了解MCP如何使用(Model Context Protocol)

5分钟了解MCP如何使用(Model Context Protocol)

MCP是什么

MCP is an open protocol that standardizes how applications provide context to LLMs. Think of MCP like a USB-C port for AI applications. Just as USB-C provides a standardized way to connect your devices to various peripherals and accessories, MCP provides a standardized way to connect AI models to different data sources and tools. from offical site

MCP 是一种开放协议,由Anthropic在24年11月提出. 它标准化了应用程序向大型语言模型提供上下文的方式。将 MCP 想象成 AI 应用程序的 USB-C 端口。就像 USB-C 为您的设备提供了一种标准化的方式来连接各种外围设备和配件一样,MCP 为 AI 模型提供了一种标准化的方式来连接不同的数据源和工具。

MCP实际上就是为LLM的function call 套用了一层接口(协议), 使得用户可以在与模型的交互中按照这套协议调用自己的本地工具(服务).这里要强调本地, 是因为实际上MCP机制全部都是在本地发生的.这样的设计可以有效地保护用户的隐私, 用户在调用function时, 不需要把apikey提供给LLM供应商.

MCP架构

在大模型应用里,建立多个MCP Client. 每个实例负责访问对应的MCP Server.MCP Server负责真实的function call功能交互, 如(访问数据库, API等)

  • MCP 主机:像 Claude Desktop、IDE 或 AI 工具这样的程序,它们希望通过 MCP 访问数据
  • MCP 客户端:与服务器保持 1:1 连接的协议客户端
  • MCP 服务器:轻量级程序,每个程序通过标准化的模型上下文协议暴露特定的功能
  • 本地数据源:MCP 服务器可以安全访问的计算机文件、数据库和服务
  • 远程服务:通过互联网(例如,通过 API)可用的外部系统,MCP 服务器可以连接到

MCP交互过程

用MCP的机制查询天气

现在我们搭建一个请求天气预报的MCP Server的例子, 看看具体流程是什么样子. 详细的内容参考官网例子.

1. 安装环境

我这里使用的是python sdk, 需要安装uv来启动server

2. 开发weather服务

    1. 绑定服务名
python 复制代码
from typing import Any
import httpx
from mcp.server.fastmcp import FastMCP

# Initialize FastMCP server
mcp = FastMCP("weather")
    1. 实际api请求与输出格式化
python 复制代码
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 None

def 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')}
"""
    1. 接口开发
python 复制代码
@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)
    1. main
ini 复制代码
if __name__ == "__main__":
    # Initialize and run the server
    mcp.run(transport='stdio')

到这里MCP Server就开发好了.

3. 修改配置

这里以Claude Desktop为例. 实际上用MCP的app有很多(如, ClaudeDesktop, Cursor, ...)

  1. 打开Claude设置Settings
  2. 选择Developer的设置
  3. 这是一个json文件, 加入MCP Server的启动配置

4. 重启Claude Desktop

重启Claude Desktop, 然后就可以小锤子选项了.

5. MCP 工具调用

e2de0b04b82e2d3dc33a5fb259e0d9e4.png

对比其他机制

这里对比一下模型版Chatglm的工具调用.

MCP Chatglm
初始化 app init MCP client tool register注册
调用方式 MCP client-server调用 toolCall调用
架构 Client-server 有状态, 可以保持连接 Function call 无状态, 单次调用

总结

总体来说, 就是MCP进行一层tool function call的完整封装. 相对于其他智能对话产品, MCP提供了用户一种自定义function call的解决方案. 由于是在本地调用api, 保障了用户的隐私(apikey). 但MCP主要还是面向于开发者用户. 需要用户自行搭建MCP Server服务以及后续链路. 对于一般用户的成本还是略高.

引用

  1. modelcontextprotocol.io/
  2. github.com/modelcontex...
  3. onevcat.com/2025/02/mcp...
  4. github.com/THUDM/ChatG...
  5. open.bigmodel.cn/dev/howuse/...

本文使用 markdown.com.cn 排版

相关推荐
摆烂工程师14 分钟前
Claude Code 为什么突然火了?聊一下Claude Code 跟 Cursor 之间的区别
程序员·claude·cursor
AI大模型7 小时前
COZE实战部署(一)—— 扣子任务空间调配和实现
agent·coze·mcp
堆栈future12 小时前
揭秘 Google A2A 协议:赋能智能体协作的未来
llm·agent·mcp
悟乙己2 天前
通过Claude 生成图片的prompt集锦(一)
prompt·claude·李继刚
win4r2 天前
🚀 SuperClaude让Claude Code编程能力暴增300%!小白秒变顶尖程序员!19个专业命令+9大预定义角色,零编程经验也能开发复杂项目,完全碾
aigc·ai编程·claude
小雷FansUnion2 天前
深入理解MCP架构:智能服务编排、上下文管理与动态路由实战
人工智能·架构·大模型·mcp
CoderLiu3 天前
用这个MCP,只给大模型一个figma链接就能直接导出图片,还能自动压缩上传?
前端·llm·mcp
吴佳浩3 天前
Python入门指南-AI番外-MCP完整教程:从零开始学会Model Context Protocol
人工智能·python·mcp
摆烂工程师3 天前
Claude Code 落地实践的工作简易流程
人工智能·claude·敏捷开发
聚客AI3 天前
🚀拒绝试错成本!企业接入MCP协议的避坑清单
人工智能·掘金·日新计划·mcp