@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)
Claude for Desktop 尚未在 Linux 上可用。Linux 用户可以继续进行 构建客户端 教程,以构建连接到我们刚刚构建的服务器的 MCP 客户端。
首先,确保您已安装 Claude for Desktop。您可以在此处安装最新版本。 如果您已经有 Claude for Desktop,请确保它已更新到最新版本。
我们需要为您想要使用的 MCP 服务器配置 Claude for Desktop。为此,请在文本编辑器中打开 ~/Library/Application Support/Claude/claude_desktop_config.json 中的 Claude for Desktop 应用配置。如果文件不存在,请确保创建它。
@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)
Claude for Desktop 尚未在 Linux 上可用。Linux 用户可以继续进行 构建客户端 教程,以构建连接到我们刚刚构建的服务器的 MCP 客户端。
首先,确保您已安装 Claude for Desktop。您可以在此处安装最新版本。 如果您已经有 Claude for Desktop,请确保它已更新到最新版本。
我们需要为您想要使用的 MCP 服务器配置 Claude for Desktop。为此,请在文本编辑器中打开 ~/Library/Application Support/Claude/claude_desktop_config.json 中的 Claude for Desktop 应用配置。如果文件不存在,请确保创建它。
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);});
Claude for Desktop 尚未在 Linux 上可用。Linux 用户可以继续进行 构建客户端 教程,以构建连接到我们刚刚构建的服务器的 MCP 客户端。
首先,确保您已安装 Claude for Desktop。您可以在此处安装最新版本。 如果您已经有 Claude for Desktop,请确保它已更新到最新版本。
我们需要为您想要使用的 MCP 服务器配置 Claude for Desktop。为此,请在文本编辑器中打开 ~/Library/Application Support/Claude/claude_desktop_config.json 中的 Claude for Desktop 应用配置。如果文件不存在,请确保创建它。
@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 工具变得容易。
首先,确保您已安装 Claude for Desktop。
您可以在此处安装最新版本。 如果您已经有 Claude for Desktop,请确保它已更新到最新版本。
我们需要为您想要使用的 MCP 服务器配置 Claude for Desktop。
为此,请在文本编辑器中打开 ~/Library/Application Support/Claude/claude_desktop_config.json 中的 Claude for Desktop 应用配置。
如果文件不存在,请确保创建它。
// 扩展函数,用于获取给定纬度和经度的天气预报信息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?, )}
Claude for Desktop 尚未在 Linux 上可用。Linux 用户可以继续进行 构建客户端 教程,以构建连接到我们刚刚构建的服务器的 MCP 客户端。
首先,确保您已安装 Claude for Desktop。您可以在此处安装最新版本。 如果您已经有 Claude for Desktop,请确保它已更新到最新版本。
我们需要为您想要使用的 MCP 服务器配置 Claude for Desktop。为此,请在文本编辑器中打开 ~/Library/Application Support/Claude/claude_desktop_config.json 中的 Claude for Desktop 应用配置。如果文件不存在,请确保创建它。
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()} """)); }}
Claude for Desktop 尚未在 Linux 上可用。Linux 用户可以继续进行 构建客户端 教程,以构建连接到我们刚刚构建的服务器的 MCP 客户端。
首先,确保您已安装 Claude for Desktop。您可以在此处安装最新版本。 如果您已经有 Claude for Desktop,请确保它已更新到最新版本。
我们需要为您想要使用的 MCP 服务器配置 Claude for Desktop。为此,请在文本编辑器中打开 ~/Library/Application Support/Claude/claude_desktop_config.json 中的 Claude for Desktop 应用配置。如果文件不存在,请确保创建它。
例如,如果您已安装 VS Code: