【总结】MCP:模型上下文协议

目录

[1 前言](#1 前言)

[2 MCP server 和我们常听到的服务器 server有什么区别?](#2 MCP server 和我们常听到的服务器 server有什么区别?)

[3 使用cline演示查询天气的MCP server](#3 使用cline演示查询天气的MCP server)

[4 Cline中配置weather 服务,并聊天验证](#4 Cline中配置weather 服务,并聊天验证)

[5 总结](#5 总结)


1 前言

在学习MCP具体知识之前,我们需要了解下什么是 MCP server 以及 MCP host

角色 简单理解 核心职责 典型例子
MCP Host AI应用的"躯干" 用户直接交互的AI应用,是整个系统的控制中心,负责协调和管理所有连接。 Claude桌面版、VS Code中Cline、Cursor等IDE或聊天工具。
MCP Server 外接的"技能卡" 提供特定功能的轻量级程序,如访问本地文件、查询数据库或调用第三方API。 文件系统服务器、GitHub服务器、Slack服务器、Browserbase服务器。

本文的介绍选择的MCP host是vscode中的插件 Cline

插件安装完成之后,打开配置图标,会让配置模型,我配置的是deepseek,


2 MCP server 和我们常听到的服务器 server有什么区别?

**服务器 server:**比如我们大考google的网站,我们访问的是google的服务器。

**MCP server:**可以是使用node.js以及python写的程序文件,只不过这个程序的执行遵循MCP协议的。

MCP server,其实不是我我们所理解的server, 我们可以将其看成我们手机里的应用,每个应用可以完成不同的功能

进一步看来,MCP server 其实就是一个工具tool的集合


3 使用cline演示查询天气的MCP server

python 复制代码
在此之前需要使用uv创建个项目:uv init weather

创建虚拟环境:uv venv

激活虚拟环境:.venv/script/activate

装包:uv add "mcp[cli]" httpx

使用vscode打开创建的项目

编写【weather.py

python 复制代码
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 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")}
"""

@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)

def main():
    # Initialize and run the server
    mcp.run(transport="stdio")


if __name__ == "__main__":
    main()

运行该脚本文件:上述脚本文件就是我们所写的MCP server

python 复制代码
uv run weather.py

4 Cline中配置weather 服务,并聊天验证

打开配置,打开cline_mcp_settings.json文件,输入以下内容:

javascript 复制代码
{
  "mcpServers": {
    "weather": {
      "disabled": false,
      "timeout": 60,
      "type": "stdio",
      "command": "uv",
      "args": [
        "--directory",
        "D:/MCP_projects/weather",
        "run",
        "weather.py"
      ]
    }
  }
}

【验证】


5 总结

这边给出一张我特别喜欢的图,给出MCP server, MCP host(本文选的是Cline)以及模型之间的交互的过程

相关推荐
行走的陀螺仪4 小时前
一次 opencode + OpenPencil MCP 协同解析 .fig 文件的踩坑实录
node.js·figma·mcp·opencode
AI笔记Pro5 小时前
mcp协议是什么?用装一次 MCP 的时间彻底搞懂它
mcp
抢囡囡糖未遂6 小时前
从 LINQPad 到 MCP:打造 CRM 智能助手的实战记录
ai·大模型·skill·mcp·linqpad·microsoft dynamics crm·mscrm·dynamic 365
武子康9 小时前
MCP 2026-07-28 无状态核心之后:身份、任务、幂等与审计状态到底放在哪里?
人工智能·llm·mcp
Python私教9 小时前
我只写了一个 add 工具,终于把 MCP 的 Host、Client、Server 跑明白了
python·ai编程·mcp
奋飛10 小时前
AI 应用工程:Tool、MCP、Skill 与 Workflow 如何接入 Agent?——搭建一个可运行的需求影响面分析 Agent
agent·workflow·skill·tool·mcp
VIP_CQCRE2 天前
最近发现一个小工具:把 Ace Data Cloud 接入 AI 助手
ai·开发工具·mcp
labixiong3 天前
MCP 7/28 最大改版实测:扒开真实 HTTP 请求,无状态化到底改了什么
agent·mcp
shepherd1113 天前
别再把 MCP 当成大模型的“手脚”:LLM 并不会直接调用 MCP
后端·ai编程·mcp
码哥字节3 天前
0元搭了240篇文章的AI知识库,比付费版查得更准
开源·ai编程·mcp