【LLM模型】如何构建自己的MCP Server?

什么是 MCP?

Model Context Protocol (MCP) 是一种协议,它允许大型语言模型(LLMs)访问自定义的工具和服务。Trae 中的智能体作为 MCP 客户端可以选择向 MCP Server 发起请求,以使用它们提供的工具。你可以自行添加 MCP Server,并添加到自定义的智能体中来使用。

MCP 是一个开放协议,它规范了应用程序向 LLM 提供上下文的方式。MCP 就像 AI 应用程序的 USB-C 端口一样。正如 USB-C 提供了一种标准化的方式将您的设备连接到各种外围设备和配件一样,MCP 也提供了一种标准化的方式将 AI 模型连接到不同的数据源和工具。

为什么选择 MCP?

MCP 可帮助您在 LLM 之上构建代理和复杂的工作流。LLM 通常需要与数据和工具集成,而 MCP 可提供以下功能:

  • 越来越多的预建集成可供您的 LLM 直接插入
  • 在 LLM 提供商和供应商之间切换的灵活性
  • 保护基础架构内数据的最佳实践

总体架构

MCP 的核心遵循客户端-服务器架构,其中主机应用程序可以连接到多个服务器:

在这里插入图片描述

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

For Server Developers

开始构建您自己的服务器,以便在 Claude for Desktop 和其他客户端中使用。

在本教程中,我们将构建一个简单的 MCP 天气服务器,并将其连接到主机 Claude for Desktop。我们将从基本设置开始,然后逐步介绍更复杂的用例。

我们将要构建什么

目前,许多 LLM 课程无法获取天气预报和恶劣天气警报。让我们使用 MCP 来解决这个问题!

我们将构建一个服务器,其中包含两个工具:get-alerts和get-forecast。然后,我们将服务器连接到 MCP 主机(在本例中为 Claude for Desktop):
在这里插入图片描述
在这里插入图片描述

服务器可以连接到任何客户端。为了简单起见,我们选择了 Claude for Desktop

为什么选择 Claude for Desktop 而不是 Claude.ai?
由于服务器在本地运行,MCP 目前仅支持桌面主机。远程主机正在积极开发中。

MCP核心概念

MCP 服务器可以提供三种主要类型的功能:

  1. 资源:客户端可以读取的类似文件的数据(例如 API 响应或文件内容)
  2. 工具:可由 LLM 调用的函数(经用户批准)
  3. 提示:预先编写的模板,帮助用户完成特定任务

让我们开始构建我们的天气服务器吧!你可以在这里找到我们将要构建的完整代码。

预备知识

本快速入门假设您熟悉以下内容:

  • Python
  • LLMs like Claude

系统要求

  • 安装了 Python 3.10 或更高版本。
  • 您必须使用 Python MCP SDK 1.2.0 或更高版本。

设置环境

首先,让我们安装uv并设置我们的 Python 项目和环境:

MacOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh

之后请确保重新启动终端以确保uv命令被接收。

现在,让我们创建并设置我们的项目:

# 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

现在让我们开始构建您的服务器。

构建你的服务器

导入包并设置实例

将这些添加到您的顶部weather.py:

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"

FastMCP 类使用 Python 类型提示和文档字符串自动生成工具定义,从而轻松创建和维护 MCP 工具。

辅助函数

接下来,让我们添加辅助函数来查询和格式化来自国家气象局 API 的数据:

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)

运行服务器

最后,让我们初始化并运行服务器:

if __name__ == "__main__":
    # Initialize and run the server
    mcp.run(transport='stdio')

您的服务器已完成!运行uv run weather.py确认一切正常

现在让我们从现有的 MCP 主机 Claude for Desktop 测试您的服务器。

使用 Claude for Desktop 测试您的服务器

Claude 桌面版目前尚未在 Linux 上推出。Linux 用户可以继续学习构建客户端教程,构建一个连接到我们刚刚搭建的服务器的 MCP 客户端。
首先,请确保您已安装 Claude 桌面版。您可以点击此处安装最新版本。如果您已安装 Claude 桌面版,请确保将其更新至最新版本。

我们需要为您想要使用的 MCP 服务器配置 Claude for Desktop。为此,请在~/Library/Application Support/Claude/claude_desktop_config.json文本编辑器中打开您的 Claude for Desktop App 配置。如果该文件不存在,请务必创建。

例如,如果您安装了VS Code:
MacOS/Linux

code ~/Library/Application\ Support/Claude/claude_desktop_config.json

Windows

code $env:AppData\Claude\claude_desktop_config.json

然后,您需要在密钥中添加服务器mcpServers。只有至少一台服务器正确配置后,MCP UI 元素才会显示在 Claude for Desktop 中。

在这种情况下,我们将像这样添加单个天气服务器:
MacOS/Linux

{
    "mcpServers": {
        "weather": {
            "command": "uv",
            "args": [
                "--directory",
                "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
                "run",
                "weather.py"
            ]
        }
    }
}

Windows

{
    "mcpServers": {
        "weather": {
            "command": "uv",
            "args": [
                "--directory",
                "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather",
                "run",
                "weather.py"
            ]
        }
    }
}

这告诉 Claude for Desktop:

  1. 有一个名为“天气”的 MCP 服务器
  2. 通过运行来启动它uv --directory
    /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather.py

保存文件,然后重新启动Claude for Desktop。

使用命令进行测试

让我们确保 Claude for Desktop 能够获取我们在weather服务器中公开的两个工具。您可以通过查找锤子图标来执行此操作:
在这里插入图片描述
单击锤子图标后,您应该会看到列出两个工具:
在这里插入图片描述

如果您的服务器未被 Claude for Desktop 接收,请继续执行故障排除部分以获取调试提示。

如果出现了锤子图标,您现在可以通过在 Claude for Desktop 中运行以下命令来测试您的服务器:

  • 萨克拉门托的天气怎么样?
  • 德克萨斯州有哪些有效天气警报?

在这里插入图片描述
在这里插入图片描述

幕后发生了什么

当你问一个问题时:

  1. 客户将您的问题发送给 Claude
  2. Claude 分析可用的工具并决定使用哪一个
  3. 客户端通过 MCP 服务器执行所选工具
  4. 结果发回给克劳德
  5. 克劳德制定了自然语言回应
  6. 答案已显示给您!

故障排除

Claude 中未显示服务器

  1. 检查claude_desktop_config.json文件语法
  2. 确保项目路径是绝对路径而不是相对路径
  3. 完全重启 Claude for Desktop 工具调用静默失败

如果Claude 尝试使用这些工具但失败了:

  1. 检查 Claude 的日志是否存在错误
  2. 验证您的服务器构建和运行是否没有错误
  3. 尝试重启 Claude for Desktop
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值