MCP Server 开发实战指南(Python版)

news/2025/3/19 19:54:47/文章来源:https://www.cnblogs.com/ryanzheng/p/18781666

原文链接:https://www.ryanzoe.top/ai/mcp-server-%e5%bc%80%e5%8f%91%e6%95%99%e7%a8%8b/

MCP 官方文档

https://modelcontextprotocol.io/introduction

各个 clients 对 MCP 的支持情况

https://modelcontextprotocol.io/clients

MCP Python SDK:MCP Client 和 Server 官方 SDK

https://github.com/modelcontextprotocol/python-sdk

 

MCP Server Demo

开发语言:Python 3.13.2

环境:MacOS

MCP 客户端:Cursor、Cline、Claude Desktop

一、环境配置

安装 uv 命令

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

初始化项目

# 给项目创建一个文件夹
uv init weather
cd weather# 创建一个虚拟环境并激活
uv venv
source .venv/bin/activate# 安装依赖
uv add "mcp[cli]" httpx# 创建 server 文件
touch weather.py

二、编写Server 代码

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 Nonedef 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 locationlongitude: Longitude of the location"""
    # First get the forecast grid endpointpoints_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 responseforecast_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 forecastperiods = forecast_data["properties"]["periods"]forecasts = []for period in periods[:5]:  # Only show next 5 periodsforecast = 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 servermcp.run(transport='stdio')

三、运行服务

MCP Inspector

mcp dev weather.py

当看到以下界面,说明服务运行成功。打开 http://localhost:5173/ 即可进行功能测试

 

 

Cursor

也可以通过一些支持 MCP Server 的客户端进行调试

设置 -> MCP → Add new MCP server

类型选择 command,名称可以自定义,执行的命令如下,需要指定路径

uv --directory /Users/ryanjhzheng/Documents/my_mcp/weather run weather.py

 

 

 

 

 

Cline

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

 

调试

https://modelcontextprotocol.io/docs/tools/debugging

 

调试工具

  • MCP Inspector https://modelcontextprotocol.io/docs/tools/inspector

  • Claude Desktop Developer Tools

  • Server Logging

 

MCP Python SDK

创建 Tools

  • 提供清晰、描述性的名称和说明

  • 使用详细的 JSON Schema 定义参数

  • 在工具描述中包含示例,告诉模型应如何使用它们

  • 实施适当的错误处理和验证

  • 对长时间操作使用进度报告

  • 保持工具操作集中且原子化

  • 记录预期返回结果

  • 实施适当的超时

  • 考虑对资源密集型操作进行速率限制

  • 用于调试和监控的日志工具使用情况

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/901675.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Amphion 推出合成音频鉴别系统 Auditi;Gemini 引入 NotebookLM 功能,生成文档、网页音频摘要丨日报

开发者朋友们大家好:这里是 「RTE 开发者日报」 ,每天和大家一起看新闻、聊八卦。我们的社区编辑团队会整理分享 RTE(Real-Time Engagement) 领域内「有话题的 技术 」、「有亮点的 产品 」、「有思考的 文章 」、「有态度的 观点 」、「有看点的 活动 」,但内容仅代表编辑…

洛谷题单指南-图论之树-P3398 仓鼠找 sugar

原题链接:https://www.luogu.com.cn/problem/P3398 题意解读:一颗n个节点的树,m个判断,判断树上两条路径是否相交,相交输出Y,否则输出N 解题思路:此题需要画一棵多叉树来辅助判断多次观察相交的路径,可以得出一个关键性质: 两条路径相交,必然有一条路径的LCA在另一条…

lg 主页

\(\Large\text{My Blog}\)中学:济南天山高级实验中学 关于我的学校究极久远预告:寒假游记滚滚长江东逝水,浪花淘尽英雄 是非成败转头空 青山依旧在,几度夕阳红 白发渔樵江渚上,观看秋月春风 一壶浊酒喜相逢 古今多少事,都付笑谈中街喧闹,人过往 且记曾相识,莫为少年留 …

day:25 selenium之介绍和环境配置

一、selenium介绍 selenium是一个第三方库,python有很多库; 1、什么是ui自动化? 通过模拟手工操作用户ui页面的方式,用代码去实现自动化操作和验证的行为。 2、ui自动化的优点? (1)解决重复性的功能测试和验证 (2)减少测试人员在回归测试时用例漏测和验证点的漏测 (3…

[算法学习记录] [更新中]最短路

顾名思义,最短路算法,就是求一个图中所有的点距某一个点的最短距离,常见的有Dijkstra算法、Bellman-Ford算法、Johnson算法与Floyd算法。 Dijkstra Dijistra算法实际上是一种由贪心与动态规划结合的算法,我们每次都贪心地选择到某个点的最近距离,又动态地更新着距离数组d的…

day6-static静态变量

静态变量/静态方法 被static修饰 工具类静态方法不能调用非静态。 非静态可以访问所有。 继承一个子类只能继承一个父类,可以多层继承,最大的父类为Objectcoding 练习:更好的方法:双指针不浪费空间

SpringBoot引入JWT实现用户校验

一JWT JWT(JSON Web Token)是一种开放标准(RFC 7519),用于在网络应用环境间安全地传输信息。这些信息以JSON对象的形式存储在令牌中,并且可以被签名和加密。JWT通常用于身份验证和信息交换主要用途 身份验证:当用户登录成功后,服务器会生成一个JWT并返回给客户端。之后…

mcp-playwright测评

mcp-playwright介绍 mcp-playwright是一个使用 Playwright 提供浏览器自动化能力的模型上下文协议服务器。该服务器使 LLMs 能够与网页交互、截屏,并在真实的浏览器环境中执行 JavaScript。 GitHub地址:https://github.com/executeautomation/mcp-playwright。安装 npm insta…

传媒行业项目管理全解析:日事清在流程、文件、数据与风控中的一体化应用

一、关于森可文化 森可文化传媒有限公司(Senke Vision)占据了超过2800平方米的宽敞办公及拍摄场地,与众多内衣及服饰行业的上市巨头建立了不可动摇的深度合作关系。 Senke Vision汇聚了国内外顶尖的策划、设计、摄影摄像、服装搭配、化妆及品牌视觉顾问,形成了一支独一无二…

在 .NET 项目中使用 husky 完成 pre-commit 操作

将 husky 引入 .NET 项目Husky 是一个用于 Git 仓库的工具,主要用于管理 Git 钩子(hooks)。它可以帮助开发者在特定的 Git 操作(如提交、推送等)之前或之后执行自定义的脚本或命令,从而提高代码质量和团队协作效率。 主要用在前端项目中,可以通过 Husky.Net,将 Husky 的…

贸易企业数字化转型案例:基于日事清的目标管理、任务协作与流程可视化绩效优化实践

这家贸易公司如何提升内部协同效率?一、基本情况 所属行业:传统贸易行业 业务类型:国内贸易、货物及技术进出口 行业地位:拥有自己的研发人员,具备一站式解决方案能力。 合作概要:为解决组织提效,目标体系、协同体系、绩效体系的管理问题,客户与日事清达成合作,并将日…

使用nvm管理node.js版本

1.情景展示如上图所示,项目某个模块支持的node.js最高版本是17,我用的是20,所以只能降级。 2.具体分析 我现在把node.js降到16,那后续如果再需要20呢?能不能实现版本的随时切换? 3.安装nvm 我们可以使用nvm来管理node.js的版本。 下载nvm windows下载地址:https://githu…