【总结】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)以及模型之间的交互的过程

相关推荐
Alice-YUE12 小时前
A2A 协议详解:Agent 间通信标准、四大核心机制与 MCP 互补
大模型·多智能体·ai agent·mcp·a2a协议
光依旧17 小时前
MCP实战手记(九):生产化MCP Server的6层安全防护
java·人工智能·spring boot·安全·网络安全·ai agent·mcp
cczixun2 天前
智能体怎么接进业务系统?2026 MCP 工具调用实战:从对话到数据库
落地·智能体·mcp
EatFan2 天前
GitHub Trending 三连观察:AI 编码智能体进入“周边生态”竞争阶段
人工智能·驱动开发·github·mcp·superpowers·github trending·spec kit
Java的搬运工3 天前
2026 AI Agent 实战:五层架构、MCP 工具调用与十条避坑清单 合集 - AI行业观察
人工智能·架构·智能体·大模型应用·langgraph·aiagent·mcp
EatFan3 天前
AI Agent 上生产前先加三道闸门:审批、限权、可回放的工程实践
人工智能·python·算法·多智能体·ai agent·mcp·harness
無a伟3 天前
彻底搞懂ToolCalling、MCP,Skills的核心区别,能力上的层层封装
大数据·agent·mcp·toolcalling·skills
cpolar技术支持4 天前
服务器上的 Nginx 只想改配置却不敢动?把 Nginx-UI 跑起来,用 MCP 让 AI 助手帮你安全改配置,再用 cpolar 把面板短时开给自己
nginx·ai·cpolar·mcp·nginx-ui
code_Bo4 天前
多 Agent 协作最大的坑不是模型,是失忆
ai编程·cursor·mcp