forked from paiml/rust-mcp-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path48_structured_output_schema.rs
More file actions
354 lines (316 loc) Β· 10.6 KB
/
48_structured_output_schema.rs
File metadata and controls
354 lines (316 loc) Β· 10.6 KB
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
//! Structured Output Schema Example
//!
//! This example demonstrates how to create MCP tools with structured output schemas.
//! Per MCP spec 2025-06-18, `outputSchema` is a top-level field on `ToolInfo`
//! (sibling to `inputSchema`), enabling type-safe server composition.
//!
//! For typed tools, use `TypedToolWithOutput` which automatically generates
//! the top-level `outputSchema` from Rust types deriving `JsonSchema`.
//!
//! Run with: cargo run --example 48_structured_output_schema --features full
use async_trait::async_trait;
use pmcp::{RequestHandlerExtra, Result, Server, ServerCapabilities, ToolHandler};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
/// Weather conditions enum
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "lowercase")]
enum WeatherCondition {
Sunny,
Cloudy,
Rainy,
Stormy,
Snowy,
}
/// Temperature data structure
#[derive(Debug, Serialize, Deserialize, Clone)]
struct Temperature {
celsius: f64,
fahrenheit: f64,
}
/// Wind data structure
#[derive(Debug, Serialize, Deserialize, Clone)]
struct Wind {
speed_kmh: f64,
direction: String,
}
/// Complete weather data structure
#[derive(Debug, Serialize, Deserialize, Clone)]
struct WeatherData {
temperature: Temperature,
conditions: WeatherCondition,
humidity: f64, // 0-100
wind: Wind,
location: String,
timestamp: String,
}
/// Product information structure
#[derive(Debug, Serialize, Deserialize, Clone)]
struct Product {
id: String,
name: String,
price: f64,
currency: String,
category: String,
in_stock: bool,
rating: f64, // 0-5
}
/// User profile structure
#[derive(Debug, Serialize, Deserialize, Clone)]
struct UserProfile {
user_id: String,
username: String,
email: String,
full_name: String,
age: u32,
preferences: HashMap<String, Value>,
is_premium: bool,
join_date: String,
}
/// Weather tool handler
struct WeatherTool;
#[async_trait]
impl ToolHandler for WeatherTool {
async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> Result<Value> {
// Parse input arguments
let city = args
.get("city")
.and_then(|v| v.as_str())
.unwrap_or("Unknown City");
let country = args
.get("country")
.and_then(|v| v.as_str())
.unwrap_or("Unknown");
// Generate structured weather data (in a real implementation, this would call a weather API)
let weather_data = WeatherData {
temperature: Temperature {
celsius: 22.5,
fahrenheit: 72.5,
},
conditions: WeatherCondition::Sunny,
humidity: 65.0,
wind: Wind {
speed_kmh: 15.2,
direction: "NW".to_string(),
},
location: format!("{}, {}", city, country),
timestamp: chrono::Utc::now().to_rfc3339(),
};
// Return structured data in MCP format
Ok(json!({
"content": [{
"type": "text",
"text": format!("Weather data for {}", weather_data.location)
}],
"structuredContent": weather_data,
"isError": false
}))
}
}
/// Product lookup tool handler
struct ProductTool;
#[async_trait]
impl ToolHandler for ProductTool {
async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> Result<Value> {
let product_id = args
.get("product_id")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
// Generate structured product data (mock data)
let product = Product {
id: product_id.to_string(),
name: format!("Product {}", product_id),
price: 99.99,
currency: "USD".to_string(),
category: "Electronics".to_string(),
in_stock: true,
rating: 4.5,
};
Ok(json!({
"content": [{
"type": "text",
"text": format!("Product information for {}", product.name)
}],
"structuredContent": product,
"isError": false
}))
}
}
/// User profile tool handler
struct UserProfileTool;
#[async_trait]
impl ToolHandler for UserProfileTool {
async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> Result<Value> {
let user_id = args
.get("user_id")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
// Generate structured user profile (mock data)
let mut preferences = HashMap::new();
preferences.insert("theme".to_string(), json!("dark"));
preferences.insert("notifications".to_string(), json!(true));
preferences.insert("language".to_string(), json!("en"));
let user_profile = UserProfile {
user_id: user_id.to_string(),
username: format!("user_{}", user_id),
email: format!("user_{}@example.com", user_id),
full_name: "John Doe".to_string(),
age: 30,
preferences,
is_premium: true,
join_date: "2024-01-15T10:30:00Z".to_string(),
};
Ok(json!({
"content": [{
"type": "text",
"text": format!("User profile for {}", user_profile.username)
}],
"structuredContent": user_profile,
"isError": false
}))
}
}
/// Data validation tool that shows schema validation
struct ValidatedDataTool;
#[async_trait]
impl ToolHandler for ValidatedDataTool {
async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> Result<Value> {
// Demonstrate input validation with structured error responses
let required_fields = ["name", "email", "age"];
let mut missing_fields = Vec::new();
for field in &required_fields {
if args.get(field).is_none() {
missing_fields.push(field.to_string());
}
}
if !missing_fields.is_empty() {
// Return structured error
return Ok(json!({
"content": [{
"type": "text",
"text": format!("Validation failed: missing required fields: {}",
missing_fields.join(", "))
}],
"structuredContent": {
"validation_result": {
"is_valid": false,
"missing_fields": missing_fields,
"error_code": "MISSING_REQUIRED_FIELDS"
}
},
"isError": true
}));
}
// Valid data - return success structure
Ok(json!({
"content": [{
"type": "text",
"text": "Data validation passed successfully"
}],
"structuredContent": {
"validation_result": {
"is_valid": true,
"validated_data": args,
"timestamp": chrono::Utc::now().to_rfc3339()
}
},
"isError": false
}))
}
}
#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
// Initialize logging
tracing_subscriber::fmt()
.with_max_level(tracing::Level::INFO)
.init();
println!("ποΈ Structured Output Schema Example");
println!("====================================");
// Create server with capabilities
let server = Server::builder()
.name("structured-output-schema-server")
.version("1.0.0")
.capabilities(ServerCapabilities::tools_only())
// Register weather tool
.tool("get_weather", WeatherTool)
// Register product tool
.tool("get_product", ProductTool)
// Register user profile tool
.tool("get_user_profile", UserProfileTool)
// Register validation tool
.tool("validate_data", ValidatedDataTool)
.build()?;
println!("π Available tools with structured output:");
println!(" β’ get_weather - Returns structured weather data");
println!(" β’ get_product - Returns structured product information");
println!(" β’ get_user_profile - Returns structured user profiles");
println!(" β’ validate_data - Demonstrates structured validation");
println!();
println!("π Server starting on stdio...");
println!("π‘ Each tool returns both human-readable content and structured data");
println!("π Structured data includes type information and validation");
println!();
// Run the server
server.run_stdio().await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_weather_data_serialization() {
let weather = WeatherData {
temperature: Temperature {
celsius: 20.0,
fahrenheit: 68.0,
},
conditions: WeatherCondition::Sunny,
humidity: 50.0,
wind: Wind {
speed_kmh: 10.0,
direction: "N".to_string(),
},
location: "Test City".to_string(),
timestamp: "2024-01-15T10:30:00Z".to_string(),
};
let json_str = serde_json::to_string(&weather).unwrap();
let deserialized: WeatherData = serde_json::from_str(&json_str).unwrap();
assert_eq!(weather.location, deserialized.location);
assert_eq!(
weather.temperature.celsius,
deserialized.temperature.celsius
);
}
#[test]
fn test_product_data_validation() {
let product = Product {
id: "test-123".to_string(),
name: "Test Product".to_string(),
price: 29.99,
currency: "USD".to_string(),
category: "Test".to_string(),
in_stock: true,
rating: 4.0,
};
assert!(product.rating >= 0.0 && product.rating <= 5.0);
assert!(product.price >= 0.0);
assert!(!product.id.is_empty());
}
#[test]
fn test_weather_conditions_serialization() {
let conditions = vec![
WeatherCondition::Sunny,
WeatherCondition::Cloudy,
WeatherCondition::Rainy,
WeatherCondition::Stormy,
WeatherCondition::Snowy,
];
for condition in conditions {
let json = serde_json::to_value(&condition).unwrap();
let deserialized: WeatherCondition = serde_json::from_value(json).unwrap();
// We can't directly compare enums, but serialization round-trip should work
let _ = deserialized;
}
}
}