2026/5/13 23:42:29
网站建设
项目流程
做商城类网站备案时需提供什么证件,wordpress 口碑营销主题,ios网站开发工具有哪些,关键词seo教程核心目标
本指南专为Java工程师设计#xff0c;通过使用Python构建MCP#xff08;Model Context Protocol#xff09;服务器这一实际项目#xff0c;系统讲解Python语法要点。我们将采用结果导向模式#xff1a;先展示完整代码#xff0c;再逐行解析Python语…核心目标本指南专为Java工程师设计通过使用Python构建MCPModel Context Protocol服务器这一实际项目系统讲解Python语法要点。我们将采用结果导向模式先展示完整代码再逐行解析Python语法特性并与Java进行对比帮助您快速建立Python语法体系认知。代码实现1. 创建项目作为Java工程师我们熟悉Maven的项目管理和依赖控制。在Python世界中我们需要适应类似的工具。# 安装uvPython包管理工具类似Maven/Gradlecurl-LsSf https://astral.sh/uv/install.sh|sh# PowerShell 安装irm https://astral.sh/uv/install.ps1|iex# pip 安装适合已装 Python 的环境pip install uv# 以上3种任选其一 # 创建项目目录uv init weather-service cd weather-service# 创建虚拟环境类似Maven的依赖隔离uv venv# Windows下使用: .venv\Scripts\activatesource.venv/bin/activate# 安装依赖类似在pom.xml中添加依赖uv add mcp[cli]httpx# PowerShell Create our server filenew-item weather.py项目结构weather-service/├── pyproject.toml# 项目配置文件类似pom.xml├──.gitignore ├── README.md ├── uv.lock └── weather.py# 我们的主程序文件1. 导入必要的包和设置服务器fromtypingimportAnyimporthttpxfrommcp.server.fastmcpimportFastMCP# 初始化MCP服务器mcpFastMCP(weather)# 常量定义NWS_API_BASEhttps://api.weather.govUSER_AGENTweather-app/1.0Java工程师注释from typing import AnyPython 3.5的类型提示系统等效于Java的泛型声明。在Java中我们使用Object来表示任何类型而Python的Any是类似的概念但用于类型提示系统不是强制类型检查import httpx模块导入语法类似Java的import语句httpx 是 Python的HTTP客户端库类似于Java的OkHttpfrom mcp.server.fastmcp import FastMCP模块导入语法从包中导入具体类mcp FastMCP(weather)类实例化语法与Java的Fast mcp new FastMCP(weather)关键字功能相同mcp变量声明无需类型注解但可选类型提示如mcp: FastMCP ...增强可读性。NWS_API_BASE和USER_AGENT常量定义类似于 Java 中的 public static final2. 创建辅助函数asyncdefmake_nws_request(url:str)-dict[str,Any]|None: 使用适当的错误处理向NWS API发送请求。 headers{User-Agent:USER_AGENT,Accept:application/geojson}asyncwithhttpx.AsyncClient()asclient:try:responseawaitclient.get(url,headersheaders,timeout30.0)response.raise_for_status()returnresponse.json()exceptException:returnNonedefformat_alert(feature:dict)-str: 将警报特征格式化为可读字符串。 propsfeature[properties]returnf 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)}Java工程师注释async def make_nws_request(...)Python的异步函数类似Java中的CompletableFuture或async/await用于非阻塞I/O操作async with httpx.AsyncClient() as client使用异步HTTP客户端类似于Java中使用AsyncHttpClient或WebClient进行异步请求response.raise_for_status()如果HTTP状态码不是2xx会抛出异常类似Java中使用ResponseEntity检查状态码props.get(event, Unknown)安全获取字典值类似Java中使用Map.getOrDefault避免NullPointerExceptionf...Python的f-string类似Java的字符串模板但更简洁await等待异步结果类似Java的future.get()但更简洁async with异步上下文管理器自动处理资源释放类似Java的try-with-resources返回类型标注dict[str, Any] | None表示返回字典或None类似Java的MapString, Object3. 实现工具执行mcp.tool()asyncdefget_alerts(state:str)-str: 获取美国各州的天气警报。 Args: state: 美国州代码例如CA, NY urlf{NWS_API_BASE}/alerts/active/area/{state}dataawaitmake_nws_request(url)ifnotdataorfeaturesnotindata:returnUnable to fetch alerts or no alerts found.ifnotdata[features]:returnNo active alerts for this state.alerts[format_alert(feature)forfeatureindata[features]]return\n---\n.join(alerts)mcp.tool()asyncdefget_forecast(latitude:float,longitude:float)-str: 获取某地点的天气预报。 Args: latitude: 位置纬度 longitude: 位置经度 # 首先获取预报网格端点points_urlf{NWS_API_BASE}/points/{latitude},{longitude}points_dataawaitmake_nws_request(points_url)ifnotpoints_data:returnUnable to fetch forecast data for this location.# 从点响应中获取预报URLforecast_urlpoints_data[properties][forecast]forecast_dataawaitmake_nws_request(forecast_url)ifnotforecast_data:returnUnable to fetch detailed forecast.# 将时段格式化为可读的预报periodsforecast_data[properties][periods]forecasts[]forperiodinperiods[:5]:# 仅显示前5个时段forecastf{period[name]}: Temperature:{period[temperature]}°{period[temperatureUnit]}Wind:{period[windSpeed]}{period[windDirection]}Forecast:{period[detailedForecast]}forecasts.append(forecast)return\n---\n.join(forecasts)Java工程师注释mcp.tool()装饰器用于标记这是一个MCP工具类似Java中使用Bean或Controller标记Spring组件async def get_alerts(...)异步函数处理HTTP请求避免阻塞主线程类似Java中使用CompletableFuture或Asyncdata await make_nws_request(url)等待异步请求完成类似Java中使用CompletableFuture.get()if not data or features not in data检查数据是否存在类似Java中检查null和Map.containsKey()[format_alert(feature) for feature in data[features]]列表推导式类似Java的Stream API的map操作periods[:5]切片操作获取前5个元素类似Java的List.subList(0, 5)\n---\n.join(alerts)将列表元素用分隔符连接成字符串类似Java的String.join4. 运行服务器if__name____main__:# 初始化并运行服务器mcp.run(transportstdio)Java工程师注释if __name__ __main__Python的入口点类似Java的public static void main(String[] args)mcp.run(transportstdio)启动服务器使用标准输入/输出传输类似Java中启动Tomcat或Jetty服务器完整代码fromtypingimportAnyimporthttpxfrommcp.server.fastmcpimportFastMCP# Initialize FastMCP servermcpFastMCP(weather)# ConstantsNWS_API_BASEhttps://api.weather.govUSER_AGENTweather-app/1.0asyncdefmake_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/geojson}asyncwithhttpx.AsyncClient()asclient:try:responseawaitclient.get(url,headersheaders,timeout30.0)response.raise_for_status()returnresponse.json()exceptException:returnNonedefformat_alert(feature:dict)-str:Format an alert feature into a readable string.propsfeature[properties]returnf 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()asyncdefget_alerts(state:str)-str:Get weather alerts for a US state. Args: state: Two-letter US state code (e.g. CA, NY) urlf{NWS_API_BASE}/alerts/active/area/{state}dataawaitmake_nws_request(url)ifnotdataorfeaturesnotindata:returnUnable to fetch alerts or no alerts found.ifnotdata[features]:returnNo active alerts for this state.alerts[format_alert(feature)forfeatureindata[features]]return\n---\n.join(alerts)mcp.tool()asyncdefget_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 endpointpoints_urlf{NWS_API_BASE}/points/{latitude},{longitude}points_dataawaitmake_nws_request(points_url)ifnotpoints_data:returnUnable to fetch forecast data for this location.# Get the forecast URL from the points responseforecast_urlpoints_data[properties][forecast]forecast_dataawaitmake_nws_request(forecast_url)ifnotforecast_data:returnUnable to fetch detailed forecast.# Format the periods into a readable forecastperiodsforecast_data[properties][periods]forecasts[]forperiodinperiods[:5]:# Only show next 5 periodsforecastf{period[name]}: Temperature:{period[temperature]}°{period[temperatureUnit]}Wind:{period[windSpeed]}{period[windDirection]}Forecast:{period[detailedForecast]}forecasts.append(forecast)return\n---\n.join(forecasts)defmain():# Initialize and run the servermcp.run(transportstdio)if__name____main__:main()与 Trae 集成测试配置Trae找到设置Settings里的 MCP选择手动添加Add Manually添加以下配置{mcpServers:{weather:{command:uv,args:[--directory,/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather,run,weather.py]}}}添加完成可以看到 MCP 下的工具列表对话可以看到使用了我们开发的 MCP 工具MCP 工作原理当您提出问题时客户端将您的问题发送给 TraeTrae 分析可用的工具并决定使用哪个工具客户端通过MCP服务器执行选定的工具结果发送回TraeTrae生成自然语言响应响应显示给您练习以下是我通过上述内容自己练习的代码创建项目D:\cyao\codesuv init time-tools Initialized projecttime-toolsatD:\cyao\codes\time-toolsD:\cyao\codescd time-tools D:\cyao\codes\time-toolsuv venv Using CPython3.11.12 Creating virtual environment at: .venv Activate with: .venv\Scripts\activate D:\cyao\codes\time-toolsuvaddmcp[cli]Resolved38packagesin1.64s Prepared2packagesin552ms创建主程序文件time_tools.pytypenultime_tools.py项目结构time-tools/├── pyproject.toml# 项目配置文件类似pom.xml├──.gitignore ├── README.md ├── uv.lock └── time_tools.py# 我们的主程序文件{mcpServers:{time_tools:{command:uv,args:[--directory,/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather,run,time_tools.py]}}}总结通过本教程您已经学会了如何使用Python构建MCP服务器如何与Claude for Desktop集成如何调试MCP服务器这些技能类似于Java中使用Spring Boot构建REST API并进行集成但使用了更标准化的MCP协议专门针对AI模型交互设计。对Java工程师的提示MCP本质上是一种标准化的API协议类似于我们使用OpenAPI定义REST API。通过MCP我们可以让AI模型像调用Java服务一样安全、结构化地调用我们的Python服务。这为AI应用开发提供了更便捷的集成方式。Java工程师视角如果您已经熟悉Java的Spring Boot或JAX-RS那么MCP的开发体验会非常相似只是使用了Python语言和特定的MCP框架。MCP的核心思想是让AI模型能够像调用Java微服务一样调用我们的服务但使用了更简单的协议和更少的样板代码。Referencehttps://modelcontextprotocol.io/docs/develop/build-server