找回密码
 立即注册
首页 业界区 业界 MCP快速入门—快速构建自己的服务器

MCP快速入门—快速构建自己的服务器

忿媚饱 2025-7-15 11:14:13
引言

随着大语言模型(LLM)技术的快速发展,如何扩展其能力边界成为开发者关注的重点。MCP(Model Capability Protocol)作为一种协议标准,允许开发者构建自定义服务器来增强LLM的功能。
正文内容

1. MCP核心概念与技术背景

MCP服务器主要提供三种能力类型:

  • 资源(Resources):客户端可读取的类似文件的数据(如API响应或文件内容)
  • 工具(Tools):经用户批准后LLM可调用的函数
  • 提示(Prompts):帮助用户完成特定任务的预编写模板
本教程将重点介绍工具类型的实现,通过构建两个实用工具(get-alerts和get-forecast)来扩展Claude的功能,使其能够获取天气预报和恶劣天气警报。
2. 环境准备与项目初始化

2.1 系统要求


  • Python 3.10或更高版本
  • Python MCP SDK 1.2.0或更高版本
2.2 安装uv并创建项目
  1. # 安装uv包管理器
  2. curl -LsSf https://astral.sh/uv/install.sh | sh
  3. # 创建项目目录
  4. uv init weather
  5. cd weather
  6. # 创建并激活虚拟环境
  7. uv venv
  8. source .venv/bin/activate
  9. # 安装依赖
  10. uv add "mcp[cli]" httpx
  11. # 创建服务器文件
  12. touch weather.py
复制代码
3. 构建天气服务器

3.1 初始化FastMCP实例
  1. from typing import Any
  2. import httpx
  3. from mcp.server.fastmcp import FastMCP
  4. # 初始化FastMCP服务器
  5. mcp = FastMCP("weather")
  6. # 常量定义
  7. NWS_API_BASE = "https://api.weather.gov"
  8. USER_AGENT = "weather-app/1.0"
  9. ```
  10. FastMCP类利用Python类型提示和文档字符串自动生成工具定义,简化了MCP工具的创建和维护过程。
复制代码
3.2 实现辅助函数
  1. async def make_nws_request(url: str) -> dict[str, Any] | None:
  2.     """向NWS API发起请求并处理错误"""
  3.     headers = {
  4.         "User-Agent": USER_AGENT,
  5.         "Accept": "application/geo+json"
  6.     }
  7.     async with httpx.AsyncClient() as client:
  8.         try:
  9.             response = await client.get(url, headers=headers, timeout=30.0)
  10.             response.raise_for_status()
  11.             return response.json()
  12.         except Exception:
  13.             return None
  14. def format_alert(feature: dict) -> str:
  15.     """格式化警报特征为可读字符串"""
  16.     props = feature["properties"]
  17.     return f"""
  18. Event: {props.get('event', 'Unknown')}
  19. Area: {props.get('areaDesc', 'Unknown')}
  20. Severity: {props.get('severity', 'Unknown')}
  21. Description: {props.get('description', 'No description available')}
  22. Instructions: {props.get('instruction', 'No specific instructions provided')}
  23. """
复制代码
3.3 实现工具功能
  1. @mcp.tool()
  2. async def get_alerts(state: str) -> str:
  3.     """获取美国各州的天气警报
  4.    
  5.     Args:
  6.         state: 两字母州代码(如CA, NY)
  7.     """
  8.     url = f"{NWS_API_BASE}/alerts/active/area/{state}"
  9.     data = await make_nws_request(url)
  10.     if not data or "features" not in data:
  11.         return "无法获取警报或未发现警报"
  12.     if not data["features"]:
  13.         return "该州无活跃警报"
  14.     alerts = [format_alert(feature) for feature in data["features"]]
  15.     return "\n---\n".join(alerts)
  16. @mcp.tool()
  17. async def get_forecast(latitude: float, longitude: float) -> str:
  18.     """获取某地天气预报
  19.    
  20.     Args:
  21.         latitude: 纬度
  22.         longitude: 经度
  23.     """
  24.     # 首先获取预测网格端点
  25.     points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
  26.     points_data = await make_nws_request(points_url)
  27.     if not points_data:
  28.         return "无法获取该位置的预测数据"
  29.     # 从points响应中获取预测URL
  30.     forecast_url = points_data["properties"]["forecast"]
  31.     forecast_data = await make_nws_request(forecast_url)
  32.     if not forecast_data:
  33.         return "无法获取详细预测"
  34.     # 将时间段格式化为可读预测
  35.     periods = forecast_data["properties"]["periods"]
  36.     forecasts = []
  37.     for period in periods[:5]:  # 仅显示接下来5个时段
  38.         forecast = f"""
  39. {period['name']}:
  40. 温度: {period['temperature']}°{period['temperatureUnit']}
  41. 风速: {period['windSpeed']} {period['windDirection']}
  42. 预测: {period['detailedForecast']}
  43. """
  44.         forecasts.append(forecast)
  45.     return "\n---\n".join(forecasts)
复制代码
3.4 运行服务器
  1. if __name__ == "__main__":
  2.     # 初始化并运行服务器
  3.     mcp.run(transport='stdio')
复制代码
4. 连接Claude for Desktop进行测试

4.1 配置客户端
  1. {
  2.   "mcpServers": {
  3.     "weather": {
  4.       "command": "uv",
  5.       "args": [
  6.         "--directory",
  7.         "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
  8.         "run",
  9.         "weather.py"
  10.       ]
  11.     }
  12.   }
  13. }
复制代码
4.2 测试命令


  • "萨克拉门托的天气怎么样?"
  • "德克萨斯州有哪些活跃的天气警报?"
1.png

5. 技术实现原理

当用户提问时,系统会经历以下流程:

  • 客户端将问题发送给Claude
  • Claude分析可用工具并决定使用哪些
  • 客户端通过MCP服务器执行选定工具
  • 结果返回给Claude
  • Claude生成自然语言响应
  • 向用户显示响应
结论

本文详细介绍了如何使用Python和MCP SDK快速构建一个功能完整的天气服务器。通过实现get-alerts和get-forecast两个工具,我们成功扩展了Claude的能力,使其能够查询实时天气信息。这种模式可以推广到其他领域,为LLM添加各种实用功能。MCP协议的灵活性和Python SDK的易用性使得开发者可以快速构建和集成自定义功能,极大地丰富了LLM的应用场景。
MCP 核心架构解析

来源:豆瓜网用户自行投稿发布,如果侵权,请联系站长删除

相关推荐

您需要登录后才可以回帖 登录 | 立即注册