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
//! Example demonstrating type-safe tools with automatic schema generation
//!
//! This example shows how to:
//! - Create typed tools with automatic schema generation
//! - Use SimpleTool with schema generation from types
//! - Validate and handle typed arguments automatically
use anyhow::Result;
use async_trait::async_trait;
use pmcp::{
RequestHandlerExtra, ServerBuilder, ServerCapabilities, SimpleToolExt, ToolHandler,
TypedSyncTool, TypedTool,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tracing::info;
// Define argument types with automatic schema generation
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
struct CalculatorArgs {
/// The operation to perform
operation: Operation,
/// First number
a: f64,
/// Second number
b: f64,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
enum Operation {
Add,
Subtract,
Multiply,
Divide,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
struct SearchArgs {
/// The search query
query: String,
/// Maximum number of results to return
#[serde(default = "default_limit")]
limit: Option<u32>,
/// Include archived items in search
#[serde(default)]
include_archived: bool,
}
#[allow(clippy::unnecessary_wraps)]
fn default_limit() -> Option<u32> {
Some(10)
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
struct FileOperationArgs {
/// The file path to operate on
path: String,
/// The operation to perform
operation: FileOp,
/// Content for write operations
content: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
enum FileOp {
Read,
Write,
Delete,
List,
}
#[tokio::main]
async fn main() -> Result<()> {
// Initialize logging
tracing_subscriber::fmt()
.with_max_level(tracing::Level::INFO)
.init();
info!("Starting typed tools example server");
// Create a server with typed tools
let server = ServerBuilder::new()
.name("typed-tools-example")
.version("1.0.0")
.capabilities(ServerCapabilities::tools_only())
// TypedTool with async handler and automatic schema generation
.tool(
"calculator",
TypedTool::new("calculator", |args: CalculatorArgs, _extra| {
Box::pin(async move {
let result = match args.operation {
Operation::Add => args.a + args.b,
Operation::Subtract => args.a - args.b,
Operation::Multiply => args.a * args.b,
Operation::Divide => {
if args.b == 0.0 {
return Err(pmcp::Error::Validation(
"Division by zero".to_string(),
));
}
args.a / args.b
}
};
Ok(json!({
"result": result,
"operation": format!("{:?}", args.operation).to_lowercase(),
"expression": format!("{} {:?} {} = {}", args.a, args.operation, args.b, result)
}))
})
})
.with_description("Perform basic arithmetic operations"),
)
// TypedSyncTool with synchronous handler
.tool(
"search",
TypedSyncTool::new("search", |args: SearchArgs, _extra| {
// Simulate a search operation
let limit = args.limit.unwrap_or(10);
let mut results = vec![];
// Mock search results
for i in 0..limit.min(5) {
if args.query.to_lowercase().contains("test")
|| args.include_archived
|| i < 3
{
results.push(json!({
"id": i + 1,
"title": format!("Result {} for '{}'", i + 1, args.query),
"archived": i >= 3
}));
}
}
Ok(json!({
"query": args.query,
"results": results,
"total": results.len(),
"limit": limit,
"include_archived": args.include_archived
}))
})
.with_description("Search for items with filtering options"),
)
// SimpleTool with schema generation from type
.tool(
"file_operation",
pmcp::SimpleTool::new("file_operation", |args, _extra| {
Box::pin(async move {
// Parse the typed arguments
let typed_args: FileOperationArgs = serde_json::from_value(args)?;
let result = match typed_args.operation {
FileOp::Read => {
json!({
"operation": "read",
"path": typed_args.path,
"content": "Mock file content here..."
})
}
FileOp::Write => {
if typed_args.content.is_none() {
return Err(pmcp::Error::Validation(
"Content required for write operation".to_string(),
));
}
json!({
"operation": "write",
"path": typed_args.path,
"bytes_written": typed_args.content.unwrap().len()
})
}
FileOp::Delete => {
json!({
"operation": "delete",
"path": typed_args.path,
"deleted": true
})
}
FileOp::List => {
json!({
"operation": "list",
"path": typed_args.path,
"files": ["file1.txt", "file2.rs", "file3.json"]
})
}
};
Ok(result)
})
})
.with_description("Perform file operations")
.with_schema_from::<FileOperationArgs>(),
)
// Custom tool with manual validation
.tool("custom_validated", CustomValidatedTool)
.build()?;
info!("Server initialized with typed tools");
info!("Tools will have automatically generated JSON schemas");
// Run the server
server.run_stdio().await?;
Ok(())
}
// Custom tool with manual validation
struct CustomValidatedTool;
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
struct CustomArgs {
/// User's name
name: String,
/// User's age
#[serde(default)]
age: Option<u32>,
/// User's email
email: String,
}
#[async_trait]
impl ToolHandler for CustomValidatedTool {
async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> Result<Value, pmcp::Error> {
// Parse and validate the arguments
let typed_args: CustomArgs = serde_json::from_value(args)
.map_err(|e| pmcp::Error::Validation(format!("Invalid arguments: {}", e)))?;
// Additional custom validation
if !typed_args.email.contains('@') {
return Err(pmcp::Error::Validation("Invalid email format".to_string()));
}
if let Some(age) = typed_args.age {
if age < 18 {
return Err(pmcp::Error::Validation(
"User must be 18 or older".to_string(),
));
}
}
Ok(json!({
"message": format!("Hello, {}!", typed_args.name),
"email": typed_args.email,
"age": typed_args.age,
"validated": true
}))
}
fn metadata(&self) -> Option<pmcp::types::ToolInfo> {
// Generate schema for the custom tool
let schema = schemars::schema_for!(CustomArgs);
Some(pmcp::types::ToolInfo::new(
"custom_validated",
Some("Custom tool with validation".to_string()),
serde_json::to_value(&schema).unwrap_or_else(|_| {
json!({
"type": "object",
"properties": {}
})
}),
))
}
}
// Example usage instructions
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_schema_generation() {
// Test that schemas are generated correctly
let schema = schemars::schema_for!(CalculatorArgs);
let json_schema = serde_json::to_value(&schema).unwrap();
// Verify the schema contains the expected fields
assert!(json_schema.get("properties").is_some());
let properties = &json_schema["properties"];
assert!(properties.get("operation").is_some());
assert!(properties.get("a").is_some());
assert!(properties.get("b").is_some());
}
#[test]
fn test_search_args_defaults() {
// Test default values in SearchArgs
let json = json!({
"query": "test query"
});
let args: SearchArgs = serde_json::from_value(json).unwrap();
assert_eq!(args.query, "test query");
assert_eq!(args.limit, Some(10)); // Default value
assert_eq!(args.include_archived, false); // Default value
}
}