MCP 使用笔记

9 阅读4分钟

MCP 基础

笔记内容整理自 https://www.bilibili.com/video/BV1uronYREWR

mcp执行时序图

image.png

简介

MCP (Model Context Protocol) 是 Anthropic 公司 2024年11月25日 发布的一个协议

现已成为一个开源标准

MCP就是一个让大模型更好使用各类工具的一个协议

使用 MCP 需要 MCP host (支持MCP协议的软件) ,常用的MCP host :

  • Cursor
  • Claude Desktop
  • Cherry Studio
  • Cline (VSCode 的一个插件)
    • npm install -g cline

以Cline为例子演示使用方法

安装 image.png

使用 配置API keys

image.png

手动配置mcp server image.png

image.png x

image.png

自动安装mcp server

image.png

mkdir -p ~/Documents/Cline/MCP
cd ~/Documents/Cline/MCP && git clone https://github.com/zcaceres/fetch-mcp.git
cd ~/Documents/Cline/MCP/fetch-mcp && npm install
cd ~/Documents/Cline/MCP/fetch-mcp && npm run build
open ~/Library/Application\ Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json

配置文件修改的内容

{
  "mcpServers": {}
}
=======
{
  "mcpServers": {
    "github.com/zcaceres/fetch-mcp": {
      "command": "node",
      "args": [
        "~/Documents/Cline/MCP/fetch-mcp/dist/index.js"
      ],
      "env": {}
    }
  }
}
++++++ REPLACE

MCP 市场

image.png

uvx & npx

  • uvx = uv tool run
  • npx

好用的MCP Server

MCP 进阶

笔记内容整理自 https://www.bilibili.com/video/BV1Y854zmEg9

编写 MCP Server 使用 python

按照官方案例编写

# Create a new directory for our project
uv init weather
cd weather

# Create virtual environment and activate it
uv venv
source .venv/bin/activate

# Install dependencies
uv add "mcp[cli]" httpx

# Create our server file
touch weather.py
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 None

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

{
  "mcpServers": {
    "weather": {
      "command": "uv",
      "args": [
        "--directory",
        "~/workspace/PycharmProjects/weather",
        "run",
        "weather.py"
      ]
    }
  }
}

获取交互信息

image.png

注册到mcp host

    "weather": {
      "command": "python",
      "args": [
        "/Users/morningcat/workspace/PycharmProjects/weather/mcp_logger.py",
        "uv",
        "--directory",
        "/Users/morningcat/workspace/PycharmProjects/weather",
        "run",
        "weather.py"
      ]
    }

得到结果

输入: {"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"Cline","version":"3.63.0"}},"jsonrpc":"2.0","id":0}
输出: {"jsonrpc":"2.0","id":0,"result":{"protocolVersion":"2025-11-25","capabilities":{"experimental":{},"prompts":{"listChanged":false},"resources":{"subscribe":false,"listChanged":false},"tools":{"listChanged":false}},"serverInfo":{"name":"weather","version":"1.26.0"}}}
输入: {"method":"notifications/initialized","jsonrpc":"2.0"}
输入: {"method":"tools/list","jsonrpc":"2.0","id":1}
输出: {"jsonrpc":"2.0","id":1,"result":{"tools":[{"name":"get_forecast","description":"Get weather forecast for a location.\n\n    Args:\n        latitude: Latitude of the location\n        longitude: Longitude of the location\n    ","inputSchema":{"properties":{"latitude":{"title":"Latitude","type":"number"},"longitude":{"title":"Longitude","type":"number"}},"required":["latitude","longitude"],"title":"get_forecastArguments","type":"object"},"outputSchema":{"properties":{"result":{"title":"Result","type":"string"}},"required":["result"],"title":"get_forecastOutput","type":"object"}}]}}
输入: {"method":"resources/list","jsonrpc":"2.0","id":2}
输出: {"jsonrpc":"2.0","id":2,"result":{"resources":[]}}
输入: {"method":"resources/templates/list","jsonrpc":"2.0","id":3}
输出: {"jsonrpc":"2.0","id":3,"result":{"resourceTemplates":[]}}
输入: {"method":"prompts/list","jsonrpc":"2.0","id":4}
输出: {"jsonrpc":"2.0","id":4,"result":{"prompts":[]}}

输入: {"method":"tools/call","params":{"name":"get_forecast","arguments":{"latitude":40.7128,"longitude":-74.006}},"jsonrpc":"2.0","id":4}
输出: {"jsonrpc":"2.0","id":4,"result":{"content":[{"type":"text","text":"\nToday:\nTemperature: 64°F\nWind: 2 to 18 mph S\nForecast: Mostly sunny. High near 64, with temperatures falling to around 62 in the afternoon. South wind 2 to 18 mph, with gusts as high as 30 mph.\n\n---\n\nTonight:\nTemperature: 57°F\nWind: 12 to 17 mph S\nForecast: Mostly cloudy. Low around 57, with temperatures rising to around 59 overnight. South wind 12 to 17 mph, with gusts as high as 29 mph.\n\n---\n\nSaturday:\nTemperature: 78°F\nWind: 12 to 21 mph SW\nForecast: Partly sunny, with a high near 78. Southwest wind 12 to 21 mph, with gusts as high as 32 mph.\n\n---\n\nSaturday Night:\nTemperature: 57°F\nWind: 15 to 18 mph W\nForecast: A chance of rain showers between 8pm and 2am. Mostly cloudy. Low around 57, with temperatures rising to around 61 overnight. West wind 15 to 18 mph. Chance of precipitation is 30%.\n\n---\n\nSunday:\nTemperature: 62°F\nWind: 14 to 17 mph NW\nForecast: Partly sunny, with a high near 62. Northwest wind 14 to 17 mph.\n"}],"isError":false}}

手动启动weather.py测试交互数据如下

image.png

MCP 番外

image.png