fastmcp-rust 0.3.1

Fast, cancel-correct MCP framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Example: Weather Server
//!
//! A mock weather service MCP server demonstrating:
//! - Multiple related tools working together
//! - Resource templates and dynamic URIs
//! - Real-world data patterns (JSON responses)
//! - Progress reporting for "slow" operations
//! - Error handling for invalid inputs
//!
//! Run with:
//! ```bash
//! cargo run --example weather_server
//! ```
//!
//! Test with MCP Inspector:
//! ```bash
//! npx @anthropic-ai/mcp-inspector cargo run --example weather_server
//! ```
//!
//! Note: This is a mock server - all weather data is simulated.

#![allow(clippy::needless_pass_by_value)]
#![allow(
    clippy::cast_sign_loss,
    clippy::cast_precision_loss,
    clippy::map_unwrap_or
)]

use std::collections::HashMap;

use fastmcp_rust::prelude::*;

// ============================================================================
// Mock Data
// ============================================================================

/// Mock weather data for cities.
fn get_mock_weather(city: &str) -> Option<serde_json::Value> {
    let city_lower = city.to_lowercase();
    let data: HashMap<&str, serde_json::Value> = HashMap::from([
        (
            "new york",
            serde_json::json!({
                "city": "New York",
                "country": "US",
                "temperature_c": 18,
                "temperature_f": 64,
                "condition": "Partly Cloudy",
                "humidity": 65,
                "wind_speed_kmh": 15,
                "wind_direction": "NW",
                "uv_index": 4,
                "visibility_km": 10
            }),
        ),
        (
            "london",
            serde_json::json!({
                "city": "London",
                "country": "UK",
                "temperature_c": 12,
                "temperature_f": 54,
                "condition": "Rainy",
                "humidity": 85,
                "wind_speed_kmh": 20,
                "wind_direction": "SW",
                "uv_index": 2,
                "visibility_km": 5
            }),
        ),
        (
            "tokyo",
            serde_json::json!({
                "city": "Tokyo",
                "country": "JP",
                "temperature_c": 22,
                "temperature_f": 72,
                "condition": "Sunny",
                "humidity": 55,
                "wind_speed_kmh": 10,
                "wind_direction": "E",
                "uv_index": 6,
                "visibility_km": 15
            }),
        ),
        (
            "sydney",
            serde_json::json!({
                "city": "Sydney",
                "country": "AU",
                "temperature_c": 25,
                "temperature_f": 77,
                "condition": "Clear",
                "humidity": 50,
                "wind_speed_kmh": 18,
                "wind_direction": "NE",
                "uv_index": 8,
                "visibility_km": 20
            }),
        ),
        (
            "paris",
            serde_json::json!({
                "city": "Paris",
                "country": "FR",
                "temperature_c": 15,
                "temperature_f": 59,
                "condition": "Overcast",
                "humidity": 70,
                "wind_speed_kmh": 12,
                "wind_direction": "W",
                "uv_index": 3,
                "visibility_km": 8
            }),
        ),
    ]);

    data.get(city_lower.as_str()).cloned()
}

/// Mock forecast data.
fn get_mock_forecast(city: &str, days: i64) -> Option<serde_json::Value> {
    get_mock_weather(city).map(|current| {
        let base_temp = current["temperature_c"].as_i64().unwrap_or(20);
        #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
        let forecasts: Vec<serde_json::Value> = (1..=days)
            .map(|day| {
                // Vary temperature slightly each day
                let temp_variation = (day * 2) % 5 - 2;
                let temp_c = base_temp + temp_variation;
                let conditions = ["Sunny", "Partly Cloudy", "Cloudy", "Rainy", "Clear"];
                let condition = conditions[(day as usize) % conditions.len()];

                serde_json::json!({
                    "day": day,
                    "high_c": temp_c + 5,
                    "low_c": temp_c - 3,
                    "condition": condition,
                    "precipitation_chance": (day as u64 * 15) % 100
                })
            })
            .collect();

        serde_json::json!({
            "city": current["city"],
            "country": current["country"],
            "forecast": forecasts
        })
    })
}

// ============================================================================
// Weather Tools
// ============================================================================

/// Get current weather for a city.
#[tool(description = "Get current weather conditions for a city")]
fn get_weather(_ctx: &McpContext, city: String) -> String {
    match get_mock_weather(&city) {
        Some(weather) => serde_json::to_string_pretty(&weather)
            .unwrap_or_else(|_| format!("Error formatting weather data for {city}")),
        None => format!(
            "Error: City '{city}' not found. Available cities: New York, London, Tokyo, Sydney, Paris"
        ),
    }
}

/// Get weather forecast for multiple days.
#[tool(description = "Get weather forecast for a city (1-7 days)")]
fn get_forecast(ctx: &McpContext, city: String, days: i64) -> String {
    if !(1..=7).contains(&days) {
        return "Error: Days must be between 1 and 7".to_string();
    }

    // Simulate a slow operation with progress
    #[allow(clippy::cast_precision_loss)]
    for i in 1..=days {
        if ctx.is_cancelled() {
            return "Cancelled".to_string();
        }
        // Report progress
        ctx.report_progress_with_total(i as f64, days as f64, None);
    }

    match get_mock_forecast(&city, days) {
        Some(forecast) => serde_json::to_string_pretty(&forecast)
            .unwrap_or_else(|_| format!("Error formatting forecast for {city}")),
        None => format!(
            "Error: City '{city}' not found. Available cities: New York, London, Tokyo, Sydney, Paris"
        ),
    }
}

/// Compare weather between two cities.
#[tool(description = "Compare current weather between two cities")]
fn compare_weather(_ctx: &McpContext, city1: String, city2: String) -> String {
    let weather1 = get_mock_weather(&city1);
    let weather2 = get_mock_weather(&city2);

    match (weather1, weather2) {
        (Some(w1), Some(w2)) => {
            let temp_diff = w1["temperature_c"].as_i64().unwrap_or(0)
                - w2["temperature_c"].as_i64().unwrap_or(0);
            let humidity_diff =
                w1["humidity"].as_i64().unwrap_or(0) - w2["humidity"].as_i64().unwrap_or(0);

            serde_json::to_string_pretty(&serde_json::json!({
                "cities": [w1["city"], w2["city"]],
                "comparison": {
                    "temperature_diff_c": temp_diff,
                    "warmer_city": if temp_diff > 0 { &w1["city"] } else { &w2["city"] },
                    "humidity_diff": humidity_diff,
                    "more_humid_city": if humidity_diff > 0 { &w1["city"] } else { &w2["city"] }
                },
                "city1_weather": w1,
                "city2_weather": w2
            }))
            .unwrap_or_else(|_| "Error formatting comparison".into())
        }
        (None, _) => format!("Error: City '{city1}' not found"),
        (_, None) => format!("Error: City '{city2}' not found"),
    }
}

/// Convert temperature between Celsius and Fahrenheit.
#[tool(
    description = "Convert temperature between Celsius and Fahrenheit. Use 'c' or 'f' for unit."
)]
fn convert_temp(_ctx: &McpContext, value: f64, from_unit: String) -> String {
    match from_unit.to_lowercase().as_str() {
        "c" | "celsius" => {
            let fahrenheit = (value * 9.0 / 5.0) + 32.0;
            format!("{value}°C = {fahrenheit:.1}°F")
        }
        "f" | "fahrenheit" => {
            let celsius = (value - 32.0) * 5.0 / 9.0;
            format!("{value}°F = {celsius:.1}°C")
        }
        _ => "Error: Unit must be 'c' (Celsius) or 'f' (Fahrenheit)".to_string(),
    }
}

/// Get weather alerts for a city.
#[tool(description = "Check for weather alerts and warnings for a city")]
fn weather_alerts(_ctx: &McpContext, city: String) -> String {
    match get_mock_weather(&city) {
        Some(weather) => {
            let mut alerts = vec![];

            // Generate mock alerts based on conditions
            let temp = weather["temperature_c"].as_i64().unwrap_or(20);
            let humidity = weather["humidity"].as_i64().unwrap_or(50);
            let uv = weather["uv_index"].as_i64().unwrap_or(5);
            let wind = weather["wind_speed_kmh"].as_i64().unwrap_or(10);

            if temp > 35 {
                alerts.push(serde_json::json!({
                    "type": "Heat Warning",
                    "severity": "high",
                    "message": "Extreme heat expected. Stay hydrated and avoid outdoor activities."
                }));
            } else if temp < 0 {
                alerts.push(serde_json::json!({
                    "type": "Freeze Warning",
                    "severity": "medium",
                    "message": "Freezing temperatures expected. Protect pipes and plants."
                }));
            }

            if humidity > 80 {
                alerts.push(serde_json::json!({
                    "type": "Humidity Advisory",
                    "severity": "low",
                    "message": "High humidity may cause discomfort."
                }));
            }

            if uv > 7 {
                alerts.push(serde_json::json!({
                    "type": "UV Warning",
                    "severity": "medium",
                    "message": "High UV index. Use sunscreen and protective clothing."
                }));
            }

            if wind > 50 {
                alerts.push(serde_json::json!({
                    "type": "Wind Advisory",
                    "severity": "high",
                    "message": "Strong winds expected. Secure loose objects."
                }));
            }

            let response = serde_json::json!({
                "city": weather["city"],
                "alerts_count": alerts.len(),
                "alerts": if alerts.is_empty() {
                    vec![serde_json::json!({"type": "None", "message": "No active weather alerts"})]
                } else {
                    alerts
                }
            });

            serde_json::to_string_pretty(&response)
                .unwrap_or_else(|_| "Error formatting alerts".into())
        }
        None => format!(
            "Error: City '{city}' not found. Available cities: New York, London, Tokyo, Sydney, Paris"
        ),
    }
}

/// List all available cities.
#[tool(description = "List all cities with available weather data")]
fn list_cities(_ctx: &McpContext) -> String {
    serde_json::to_string_pretty(&serde_json::json!({
        "available_cities": [
            {"name": "New York", "country": "US", "timezone": "EST"},
            {"name": "London", "country": "UK", "timezone": "GMT"},
            {"name": "Tokyo", "country": "JP", "timezone": "JST"},
            {"name": "Sydney", "country": "AU", "timezone": "AEST"},
            {"name": "Paris", "country": "FR", "timezone": "CET"}
        ]
    }))
    .unwrap_or_else(|_| "Error listing cities".into())
}

// ============================================================================
// Resources
// ============================================================================

/// Returns API documentation.
#[resource(
    uri = "weather://docs",
    name = "Weather API Docs",
    description = "Documentation for the weather server API"
)]
fn weather_docs(_ctx: &McpContext) -> String {
    r#"{
    "description": "Mock weather data server for demonstration",
    "available_cities": ["New York", "London", "Tokyo", "Sydney", "Paris"],
    "tools": {
        "get_weather": "Get current conditions (temp, humidity, wind, etc.)",
        "get_forecast": "Get 1-7 day forecast with daily highs/lows",
        "compare_weather": "Compare conditions between two cities",
        "convert_temp": "Convert between Celsius and Fahrenheit",
        "weather_alerts": "Check for weather warnings and advisories",
        "list_cities": "List all available cities with metadata"
    },
    "data_fields": {
        "temperature_c": "Temperature in Celsius",
        "temperature_f": "Temperature in Fahrenheit",
        "condition": "Weather condition (Sunny, Cloudy, Rainy, etc.)",
        "humidity": "Relative humidity percentage",
        "wind_speed_kmh": "Wind speed in km/h",
        "wind_direction": "Cardinal wind direction",
        "uv_index": "UV index (1-11+)",
        "visibility_km": "Visibility in kilometers"
    },
    "note": "This is a mock server. All data is simulated for demonstration purposes."
}"#
    .to_string()
}

/// Returns weather condition icons mapping.
#[resource(
    uri = "weather://icons",
    name = "Weather Icons",
    description = "Mapping of weather conditions to emoji icons"
)]
fn weather_icons(_ctx: &McpContext) -> String {
    r#"{
    "conditions": {
        "Sunny": "☀️",
        "Clear": "🌙",
        "Partly Cloudy": "⛅",
        "Cloudy": "☁️",
        "Overcast": "🌥️",
        "Rainy": "🌧️",
        "Stormy": "⛈️",
        "Snowy": "❄️",
        "Foggy": "🌫️",
        "Windy": "💨"
    }
}"#
    .to_string()
}

// ============================================================================
// Prompts
// ============================================================================

/// A prompt for weather-based activity suggestions.
#[prompt(description = "Get activity suggestions based on weather conditions")]
fn suggest_activities(
    _ctx: &McpContext,
    city: String,
    activity_type: String,
) -> Vec<PromptMessage> {
    let weather_info = get_mock_weather(&city)
        .map(|w| serde_json::to_string_pretty(&w).unwrap_or_default())
        .unwrap_or_else(|| "Weather data not available".to_string());

    vec![PromptMessage {
        role: Role::User,
        content: Content::Text {
            text: format!(
                "Based on the following weather conditions in {city}:\n\n{weather_info}\n\n\
                 Please suggest appropriate {activity_type} activities. Consider:\n\
                 - Temperature and how to dress\n\
                 - Any weather-related precautions\n\
                 - Best times of day for the activities\n\
                 - Indoor alternatives if weather is unfavorable"
            ),
        },
    }]
}

/// A prompt for packing suggestions.
#[prompt(description = "Get packing suggestions for a trip based on weather")]
fn packing_list(
    _ctx: &McpContext,
    destination: String,
    duration_days: String,
) -> Vec<PromptMessage> {
    let weather_info = get_mock_weather(&destination)
        .map(|w| serde_json::to_string_pretty(&w).unwrap_or_default())
        .unwrap_or_else(|| "Weather data not available".to_string());

    vec![PromptMessage {
        role: Role::User,
        content: Content::Text {
            text: format!(
                "I'm traveling to {destination} for {duration_days} days. \
                 The current weather conditions are:\n\n{weather_info}\n\n\
                 Please create a comprehensive packing list that includes:\n\
                 - Appropriate clothing for the weather\n\
                 - Weather-specific items (umbrella, sunscreen, etc.)\n\
                 - Travel essentials\n\
                 - Quantities based on the trip duration"
            ),
        },
    }]
}

// ============================================================================
// Main
// ============================================================================

fn main() {
    Server::new("weather-server", "1.0.0")
        // Weather tools
        .tool(GetWeather)
        .tool(GetForecast)
        .tool(CompareWeather)
        .tool(ConvertTemp)
        .tool(WeatherAlerts)
        .tool(ListCities)
        // Resources
        .resource(WeatherDocsResource)
        .resource(WeatherIconsResource)
        // Prompts
        .prompt(SuggestActivitiesPrompt)
        .prompt(PackingListPrompt)
        // Config
        .request_timeout(60)
        .instructions(
            "A mock weather server for demonstration. Get current weather with 'get_weather', \
             forecasts with 'get_forecast', or compare cities with 'compare_weather'. \
             Available cities: New York, London, Tokyo, Sydney, Paris. \
             Check 'weather://docs' for full API documentation.",
        )
        .build()
        .run_stdio();
}