当前位置: 首页 > news >正文

MCP终极指南 - 从原理到实战(基础篇)

MCP终极指南 - 从原理到实战(基础篇)内容总结

下面视频讲的很清楚,建议直接看视频。我这里只是做一个回顾

MCP终极指南 - 从原理到实战(基础篇)内容总结链接视频:

一、MCP简要介绍

  • 全称:Model Context Protocol(模型上下文协议)

  • 核心功能:让大模型更好地使用各类外部工具,例如:

    • 让模型使用浏览器查询信息
    • 让模型操作Unity编写游戏
    • 让模型查询实时路况等
      在这里插入图片描述
      重点理解:大模型只能对话,且不具备记忆能力

二、安装MCP Host(Cline)

  • MCP Host定义:支持MCP协议的软件
    1. 先安装vs code
    2. 在vs code中搜索并安装 cline 插件
    3. 安装完成后,点击插件图标即可使用

三、配置Cline用的API Key

  • 支持的模型
    • cloud3.7:对MCP支持最好,但价格较高
    • deep seek v30324:效果不错,价格较低
  • 以open router为例的配置步骤
    1. 登录open router网站,创建API key并妥善保存(创建后无法找回)
    2. 若使用付费模型,需在open router中充值
    3. 在cline中配置:选择API provider为open router,填写API key,选择模型(如deep seek v30324或者qwen都可以)
    4. 在act mode中也需配置相同信息
      在这里插入图片描述

四、第一个MCP问题

  • 示例问题:明天纽约的天气怎么样
  • 解决方案:cline建议创建一个天气相关的MCP server来解决该问题

五、概念解释:MCP Server和Tool

  • MCP Server
    • 本质:符合MCP协议的程序
    • 运行方式:可本地运行(通过node或Python启动),也可联网使用
    • 类比:类似手机应用,内置功能模块来解决特定问题
  • Tool
    • 本质:编程语言中的函数,是MCP Server内置的功能模块
    • 作用:执行特定任务,接收输入并返回输出
    • 示例:天气MCP server可能包含get forecast(传入经纬度返回未来几天天气)和get alert(传入地区返回气象预警)等Tool
      在这里插入图片描述
      在这里插入图片描述

六、配置MCP Server

对于配置MCP Server,本质就是运行MCP Server,并和host通过握手协议来完成以下工作

  • 提供工具预览
  • 请求工具调用
  • 返回工具调用结果

通信的格式可以是任何约定好的信息格式
在这里插入图片描述

  • 配置方式
    • 自动安装:让模型主导安装过程,或在MCP server市场直接点击安装。安装的过程就是让cline运行weather.py程序
    • 手动配置:在JSON格式文件中填入启动命令等信息,包括:
      • MCP server的名字
      • 是否禁用(disabled)
      • 超时时间(time out)
      • 启动程序及参数(command和args)
      • 沟通方式(transports type,如STDIO)
  • 生效方式:保存配置文件后,cline会自动识别并加载MCP server
{
{"mcpServers": {"weather": {"disabled": false,"timeout": 60,"type": "stdio","command": "uv","args": ["--directory","D:/work/test1_weather/weather","run","weather.py"]}}
}

启动MCP SERVER之后,host会和server进行协议交流(握手,相互交流下各自的信息),方式就是通过传递json,也可以是xml的任何约定好的格式

七、使用MCP Server

MCP server代码:这里我自己加了一个自动截图的功能测试

from typing import Any
import httpx
from mcp.server.fastmcp import FastMCP# Initialize FastMCP server
mcp = FastMCP("weather", log_level="ERROR")# 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 locationlongitude: Longitude of the location"""# First get the forecast grid endpointpoints_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 responseforecast_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 forecastperiods = forecast_data["properties"]["periods"]forecasts = []for period in periods[:5]:  # Only show next 5 periodsforecast = f"""
{period['name']}:
Temperature: {period['temperature']}°{period['temperatureUnit']}
Wind: {period['windSpeed']} {period['windDirection']}
Forecast: {period['detailedForecast']}
"""forecasts.append(forecast)return "\n---\n".join(forecasts)
import os
import time@mcp.tool()
def take_screenshots() -> str:"""每隔5秒截图一次,保存到当前目录的 pick 文件夹,累计10张后停止。"""try:import pyautoguiexcept ImportError:return "请先安装 pyautogui 库:pip install pyautogui"save_dir = os.path.join(os.getcwd(), "pick")os.makedirs(save_dir, exist_ok=True)for i in range(1, 11):img = pyautogui.screenshot()filename = os.path.join(save_dir, f"screenshot_{i:02d}.png")img.save(filename)time.sleep(5)return "截图已完成,已保存10张图片到 pick 文件夹。"if __name__ == "__main__":# Initialize and run the servermcp.run(transport='stdio')
  • 以查询纽约天气为例:
    1. 开启配置好的天气MCP server
    2. 再次询问纽约明天的天气,cline会发现该server及其中的get forecast Tool
    3. cline填入纽约经纬度,经用户确认后,调用Tool获取天气信息
    4. 模型对信息进行总结,给出纽约明天的天气情况及相关建议

八、MCP交互流程详解

  1. 配置并保存MCP server后,cline执行程序,与server交互获取Tool列表
  2. 用户提问后,cline将问题和Tool列表传给模型(这里是使用JSON的格式)
  3. 模型决定需要调用的Tool及参数,并告知cline
  4. cline调用对应MCP server的Tool,获取结果
  5. cline将结果返回给模型,模型对结果进行总结
  6. 模型将答案反馈给cline,cline再将答案返回给用户
    在这里插入图片描述

九、如何使用他人制作的MCP Server

  • 获取渠道:MCP市场(如MCP.so、mcp market.com、smedery.AI等)
  • 常见编写语言:Python、node,对应的启动程序一般是UVX或NPX

(一)uvx部分

  • UVX:u v to run命令的缩写,用于运行Python程序(UV是Python界的包管理软件)
  • 使用步骤
    1. 安装UV(可从UV的GITHUB仓库获取安装命令)
    2. 在MCP市场找到目标MCP server(如fetch,用于抓取网页内容),复制其UVX配置命令
    3. 在cline的配置文件中粘贴并格式化命令,点击安装
    4. 若首次执行因下载耗时导致超时,可先在终端执行命令完成下载,再在cline中点击retry connection重新加载

(二)npx部分

  • NPX:用于运行node程序,是node的一部分
  • 使用步骤
    1. 安装node js(从官方网站下载安装)
    2. 在MCP市场找到目标MCP server(如hot news,用于拉取新闻),复制其NPX配置命令
    3. 在cline的配置文件中粘贴命令,完成加载
    4. 若加载超时,可先在终端执行命令完成下载,再在cline中重新加载
    5. 使用时,新建对话提问,经用户确认后,模型调用Tool并总结结果返回

以上就是MCP调用的流程,下一篇会是对host和mcp server交流的细节。

http://www.dtcms.com/a/312015.html

相关文章:

  • 面试实战,问题二十二,Java JDK 17 有哪些新特性,怎么回答
  • windows内核研究(软件调试-异常的处理流程)
  • 幂等性介绍和下单接口幂等性保证实现方案
  • 雷卯针对香橙派Orange Pi RV2开发板防雷防静电方案
  • kotlin小记(1)
  • Waterfox水狐浏览器、火狐浏览器外观修改
  • Dice Combinations(Dynamic Programming)
  • 【Bug记录】关于copy的表不能copy主键和index的解决办法
  • python:以支持向量机(SVM)为例,通过调整正则化参数C和核函数类型来控制欠拟合和过拟合
  • SM2椭圆曲线密码算法原理与纯C语言实现详解
  • #Linux内存管理# 用一个案例详细介绍ARMv7-A架构 缺页中断处理的原理
  • ARMv8/v9架构FAR_EL3寄存器介绍
  • imx6ull-驱动开发篇6——Linux 设备树语法
  • P10816 [EC Final 2020] Namomo Subsequence|普及+
  • 堆----1.数组中的第K个最大元素
  • [buuctf-misc]喵喵喵
  • Linux学习--数据结构
  • 前端-移动Web-day3
  • 基于springboot的郑州旅游景点推荐系统
  • Kotlin单例模式懒汉模式:LazyThreadSafetyMode.SYNCHRONIZED(2)
  • 多线程(二) ~ 线程核心属性与状态
  • C#中对于List的多种排序方式
  • LeeCode 88. 合并两个有序数组
  • DeepSpeed - 超大LLM分布式训练框架 ZeRO技术
  • Python day32
  • 力扣 二叉树遍历 中序/前序/后序(递归和迭代版)
  • dbt中多源数据的处理
  • 混合嵌入与置信度增强:新一代RAG技术如何提升LLM性能
  • 1.6 vue 监听
  • JavaScript 原始值与引用值