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 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 for Desktop 尚未在 Linux 上可用。Linux 用户可以继续阅读构建客户端教程,以构建连接到我们刚刚构建的服务器的 MCP 客户端。
首先,确保你已经安装了 Claude for Desktop。你可以在这里安装最新版本。 如果你已经安装了 Claude for Desktop,请确保它已更新到最新版本。我们需要为你想使用的任何 MCP 服务器配置 Claude for Desktop。为此,请在文本编辑器中打开你的 Claude for Desktop 应用配置,路径为 ~/Library/Application Support/Claude/claude_desktop_config.json。如果文件不存在,请确保创建它。例如,如果你安装了 VS Code:
// 注册天气工具server.tool( "get-alerts", "Get weather alerts for a state", { state: z.string().length(2).describe("Two-letter state code (e.g. CA, NY)"), }, async ({ state }) => { const stateCode = state.toUpperCase(); const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`; const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl); if (!alertsData) { return { content: [ { type: "text", text: "Failed to retrieve alerts data", }, ], }; } const features = alertsData.features || []; if (features.length === 0) { return { content: [ { type: "text", text: `No active alerts for ${stateCode}`, }, ], }; } const formattedAlerts = features.map(formatAlert); const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join("\n")}`; return { content: [ { type: "text", text: alertsText, }, ], }; },);server.tool( "get-forecast", "Get weather forecast for a location", { latitude: z.number().min(-90).max(90).describe("Latitude of the location"), longitude: z.number().min(-180).max(180).describe("Longitude of the location"), }, async ({ latitude, longitude }) => { // Get grid point data const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`; const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl); if (!pointsData) { return { content: [ { type: "text", text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`, }, ], }; } const forecastUrl = pointsData.properties?.forecast; if (!forecastUrl) { return { content: [ { type: "text", text: "Failed to get forecast URL from grid point data", }, ], }; } // Get forecast data const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl); if (!forecastData) { return { content: [ { type: "text", text: "Failed to retrieve forecast data", }, ], }; } const periods = forecastData.properties?.periods || []; if (periods.length === 0) { return { content: [ { type: "text", text: "No forecast periods available", }, ], }; } // Format forecast periods const formattedForecast = periods.map((period: ForecastPeriod) => [ `${period.name || "Unknown"}:`, `Temperature: ${period.temperature || "Unknown"}°${period.temperatureUnit || "F"}`, `Wind: ${period.windSpeed || "Unknown"} ${period.windDirection || ""}`, `${period.shortForecast || "No forecast available"}`, "---", ].join("\n"), ); const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join("\n")}`; return { content: [ { type: "text", text: forecastText, }, ], }; },);
运行服务器
最后,实现运行服务器的主函数:
async function main() { const transport = new StdioServerTransport(); await server.connect(transport); console.error("Weather MCP Server running on stdio");}main().catch((error) => { console.error("Fatal error in main():", error); process.exit(1);});
请确保运行 npm run build 来构建你的服务器!这是让你的服务器成功连接的关键一步。现在让我们从现有的 MCP 宿主程序 Claude for Desktop 测试你的服务器。
使用 Claude for Desktop 测试你的服务器
Claude for Desktop 尚未在 Linux 上可用。Linux 用户可以继续阅读构建客户端教程,以构建连接到我们刚刚构建的服务器的 MCP 客户端。
首先,确保你已经安装了 Claude for Desktop。你可以在这里安装最新版本。 如果你已经安装了 Claude for Desktop,请确保它已更新到最新版本。我们需要为你想使用的任何 MCP 服务器配置 Claude for Desktop。为此,请在文本编辑器中打开你的 Claude for Desktop 应用配置,路径为 ~/Library/Application Support/Claude/claude_desktop_config.json。如果文件不存在,请确保创建它。例如,如果你安装了 VS Code:
@Servicepublic class WeatherService { private final RestClient restClient; public WeatherService() { this.restClient = RestClient.builder() .baseUrl("https://api.weather.gov") .defaultHeader("Accept", "application/geo+json") .defaultHeader("User-Agent", "WeatherApiClient/1.0 (your@email.com)") .build(); } @Tool(description = "Get weather forecast for a specific latitude/longitude") public String getWeatherForecastByLocation( double latitude, // Latitude coordinate double longitude // Longitude coordinate ) { // Returns detailed forecast including: // - Temperature and unit // - Wind speed and direction // - Detailed forecast description } @Tool(description = "Get weather alerts for a US state") public String getAlerts( @ToolParam(description = "Two-letter US state code (e.g. CA, NY)" String state ) { // Returns active alerts including: // - Event type // - Affected area // - Severity // - Description // - Safety instructions } // ......}
@Service 注解会自动在你的应用程序上下文中注册该服务。
Spring AI @Tool 注解使得创建和维护 MCP 工具变得容易。自动配置将自动向 MCP 服务器注册这些工具。
创建你的 Boot 应用程序
@SpringBootApplicationpublic class McpServerApplication { public static void main(String[] args) { SpringApplication.run(McpServerApplication.class, args); } @Bean public ToolCallbackProvider weatherTools(WeatherService weatherService) { return MethodToolCallbackProvider.builder().toolObjects(weatherService).build(); }}
这将在 target 文件夹内生成一个 mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar 文件。现在让我们从现有的 MCP 宿主程序 Claude for Desktop 测试你的服务器。
使用 Claude for Desktop 测试你的服务器
Claude for Desktop 尚未在 Linux 上可用。
首先,确保你已经安装了 Claude for Desktop。
你可以在这里安装最新版本。 如果你已经安装了 Claude for Desktop,请确保它已更新到最新版本。我们需要为你想使用的任何 MCP 服务器配置 Claude for Desktop。
为此,请在文本编辑器中打开你的 Claude for Desktop 应用配置,路径为 ~/Library/Application Support/Claude/claude_desktop_config.json。
如果文件不存在,请确保创建它。例如,如果你安装了 VS Code:
plugins { kotlin("plugin.serialization") version "your_version_of_kotlin" id("com.github.johnrengelman.shadow") version "8.1.1"}
plugins { id 'org.jetbrains.kotlin.plugin.serialization' version 'your_version_of_kotlin' id 'com.github.johnrengelman.shadow' version '8.1.1'}
现在让我们开始构建你的服务器。
Building your server
设置实例
添加一个服务器初始化函数:
// 运行 MCP 服务器的主函数fun `run mcp server`() { // 使用基本实现创建 MCP 服务器实例 val server = Server( Implementation( name = "weather", // Tool name is "weather" version = "1.0.0" // Version of the implementation ), ServerOptions( capabilities = ServerCapabilities(tools = ServerCapabilities.Tools(listChanged = true)) ) ) // 使用标准 IO 创建用于服务器通信的传输 val transport = StdioServerTransport( System.`in`.asInput(), System.out.asSink().buffered() ) runBlocking { server.connect(transport) val done = Job() server.onClose { done.complete() } done.join() }}
天气 API 辅助函数
接下来,让我们添加用于查询和转换来自国家气象局 API 响应的函数和数据类:
// 用于获取给定纬度和经度的天气预报信息的扩展函数suspend fun HttpClient.getForecast(latitude: Double, longitude: Double): List<String> { val points = this.get("/points/$latitude,$longitude").body<Points>() val forecast = this.get(points.properties.forecast).body<Forecast>() return forecast.properties.periods.map { period -> """ ${period.name}: Temperature: ${period.temperature} ${period.temperatureUnit} Wind: ${period.windSpeed} ${period.windDirection} Forecast: ${period.detailedForecast} """.trimIndent() }}// 用于获取给定州的天气警报的扩展函数suspend fun HttpClient.getAlerts(state: String): List<String> { val alerts = this.get("/alerts/active/area/$state").body<Alert>() return alerts.features.map { feature -> """ Event: ${feature.properties.event} Area: ${feature.properties.areaDesc} Severity: ${feature.properties.severity} Description: ${feature.properties.description} Instruction: ${feature.properties.instruction} """.trimIndent() }}@Serializabledata class Points( val properties: Properties) { @Serializable data class Properties(val forecast: String)}@Serializabledata class Forecast( val properties: Properties) { @Serializable data class Properties(val periods: List<Period>) @Serializable data class Period( val number: Int, val name: String, val startTime: String, val endTime: String, val isDaytime: Boolean, val temperature: Int, val temperatureUnit: String, val temperatureTrend: String, val probabilityOfPrecipitation: JsonObject, val windSpeed: String, val windDirection: String, val shortForecast: String, val detailedForecast: String, )}@Serializabledata class Alert( val features: List<Feature>) { @Serializable data class Feature( val properties: Properties ) @Serializable data class Properties( val event: String, val areaDesc: String, val severity: String, val description: String, val instruction: String?, )}
实现工具执行
工具执行处理程序负责实际执行每个工具的逻辑。让我们添加它:
// 创建一个具有默认请求配置和 JSON 内容协商的 HTTP 客户端val httpClient = HttpClient { defaultRequest { url("https://api.weather.gov") headers { append("Accept", "application/geo+json") append("User-Agent", "WeatherApiClient/1.0") } contentType(ContentType.Application.Json) } // 安装用于 JSON 序列化/反序列化的内容协商插件 install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) }}// 注册一个按州获取天气警报的工具server.addTool( name = "get_alerts", description = """ Get weather alerts for a US state. Input is Two-letter US state code (e.g. CA, NY) """.trimIndent(), inputSchema = Tool.Input( properties = buildJsonObject { putJsonObject("state") { put("type", "string") put("description", "Two-letter US state code (e.g. CA, NY)") } }, required = listOf("state") )) { request -> val state = request.arguments["state"]?.jsonPrimitive?.content if (state == null) { return@addTool CallToolResult( content = listOf(TextContent("The 'state' parameter is required.")) ) } val alerts = httpClient.getAlerts(state) CallToolResult(content = alerts.map { TextContent(it) })}// 注册一个按纬度和经度获取天气预报的工具server.addTool( name = "get_forecast", description = """ Get weather forecast for a specific latitude/longitude """.trimIndent(), inputSchema = Tool.Input( properties = buildJsonObject { putJsonObject("latitude") { put("type", "number") } putJsonObject("longitude") { put("type", "number") } }, required = listOf("latitude", "longitude") )) { request -> val latitude = request.arguments["latitude"]?.jsonPrimitive?.doubleOrNull val longitude = request.arguments["longitude"]?.jsonPrimitive?.doubleOrNull if (latitude == null || longitude == null) { return@addTool CallToolResult( content = listOf(TextContent("The 'latitude' and 'longitude' parameters are required.")) ) } val forecast = httpClient.getForecast(latitude, longitude) CallToolResult(content = forecast.map { TextContent(it) })}
运行服务器
最后,实现运行服务器的主函数:
fun main() = `run mcp server`()
请确保运行 ./gradlew build 来构建你的服务器。这是让你的服务器成功连接的关键一步。现在让我们从现有的 MCP 宿主程序 Claude for Desktop 测试你的服务器。
使用 Claude for Desktop 测试你的服务器
Claude for Desktop 尚未在 Linux 上可用。Linux 用户可以继续阅读构建客户端教程,以构建连接到我们刚刚构建的服务器的 MCP 客户端。
首先,确保你已经安装了 Claude for Desktop。你可以在这里安装最新版本。 如果你已经安装了 Claude for Desktop,请确保它已更新到最新版本。我们需要为你想使用的任何 MCP 服务器配置 Claude for Desktop。
为此,请在文本编辑器中打开你的 Claude for Desktop 应用配置,路径为 ~/Library/Application Support/Claude/claude_desktop_config.json。
如果文件不存在,请确保创建它。例如,如果你安装了 VS Code:
using ModelContextProtocol.Server;using System.ComponentModel;using System.Net.Http.Json;using System.Text.Json;namespace QuickstartWeatherServer.Tools;[McpServerToolType]public static class WeatherTools{ [McpServerTool, Description("Get weather alerts for a US state.")] public static async Task<string> GetAlerts( HttpClient client, [Description("The US state to get alerts for.")] string state) { var jsonElement = await client.GetFromJsonAsync<JsonElement>($"/alerts/active/area/{state}"); var alerts = jsonElement.GetProperty("features").EnumerateArray(); if (!alerts.Any()) { return "No active alerts for this state."; } return string.Join("\n--\n", alerts.Select(alert => { JsonElement properties = alert.GetProperty("properties"); return $""" Event: {properties.GetProperty("event").GetString()} Area: {properties.GetProperty("areaDesc").GetString()} Severity: {properties.GetProperty("severity").GetString()} Description: {properties.GetProperty("description").GetString()} Instruction: {properties.GetProperty("instruction").GetString()} """; })); } [McpServerTool, Description("Get weather forecast for a location.")] public static async Task<string> GetForecast( HttpClient client, [Description("Latitude of the location.")] double latitude, [Description("Longitude of the location.")] double longitude) { var jsonElement = await client.GetFromJsonAsync<JsonElement>($"/points/{latitude},{longitude}"); var periods = jsonElement.GetProperty("properties").GetProperty("periods").EnumerateArray(); return string.Join("\n---\n", periods.Select(period => $""" {period.GetProperty("name").GetString()} Temperature: {period.GetProperty("temperature").GetInt32()}°F Wind: {period.GetProperty("windSpeed").GetString()} {period.GetProperty("windDirection").GetString()} Forecast: {period.GetProperty("detailedForecast").GetString()} """)); }}
运行服务器
最后,使用以下命令运行服务器:
dotnet run
这将启动服务器并在标准输入/输出上侦听传入请求。
使用 Claude for Desktop 测试你的服务器
Claude for Desktop 尚未在 Linux 上可用。Linux 用户可以继续阅读构建客户端教程,以构建连接到我们刚刚构建的服务器的 MCP 客户端。
首先,确保你已经安装了 Claude for Desktop。你可以在这里安装最新版本。 如果你已经安装了 Claude for Desktop,请确保它已更新到最新版本。我们需要为你想使用的任何 MCP 服务器配置 Claude for Desktop。
为此,请在文本编辑器中打开你的 Claude for Desktop 应用配置,路径为 ~/Library/Application Support/Claude/claude_desktop_config.json。
如果文件不存在,请确保创建它。例如,如果你安装了 VS Code: