mcpx 0.1.5

A Rust SDK for the Model Context Protocol (MCP)
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
//! Full-featured MCP client example
//!
//! This example demonstrates most of the client API features.

use mcpx::{
    client::{Client, ClientBuilder, ClientEvent, CompletionReferenceType, ResourceContent},
    protocol::{
        logging::LoggingLevel,
        tools::ToolCallContent,
    },
    error::Error,
};
use tokio::sync::mpsc;
use std::collections::HashMap;
use std::time::Duration;

// Function to handle client events
async fn handle_events(mut receiver: mpsc::Receiver<ClientEvent>) {
    println!("Starting event handler...");

    while let Some(event) = receiver.recv().await {
        match event {
            ClientEvent::Connected {
                server_info,
                protocol_version,
                capabilities,
                instructions,
            } => {
                println!("✅ Connected to server: {} {}", server_info.name, server_info.version);
                println!("✅ Protocol version: {}", protocol_version);
                println!("✅ Server capabilities:");
                println!("   - Logging: {}", capabilities.logging);
                println!("   - Completions: {}", capabilities.completions);
                println!("   - Prompts: {}", capabilities.prompts);
                println!("   - Resources: {}", capabilities.resources);
                println!("   - Tools: {}", capabilities.tools);

                if let Some(instructions) = instructions {
                    println!("✅ Server instructions: {}", instructions);
                }
            }
            ClientEvent::Disconnected { reason } => {
                println!("❌ Disconnected from server: {}", reason);
                break;
            }
            ClientEvent::ResourcesChanged => {
                println!("📄 Resources changed");
            }
            ClientEvent::PromptsChanged => {
                println!("📝 Prompts changed");
            }
            ClientEvent::ToolsChanged => {
                println!("🔧 Tools changed");
            }
            ClientEvent::RootsChanged => {
                println!("📁 Roots changed");
            }
            ClientEvent::ResourceUpdated { uri } => {
                println!("📄 Resource updated: {}", uri);
            }
            ClientEvent::LogMessage {
                level,
                logger,
                data,
            } => {
                let logger_str = logger.as_deref().unwrap_or("server");
                let level_icon = match level {
                    LoggingLevel::Debug => "🔍",
                    LoggingLevel::Info => "ℹ️",
                    LoggingLevel::Notice => "📢",
                    LoggingLevel::Warning => "⚠️",
                    LoggingLevel::Error => "",
                    LoggingLevel::Critical => "🔥",
                    LoggingLevel::Alert => "🚨",
                    LoggingLevel::Emergency => "☢️",
                };
                println!("{} [{}] [{}] {}", level_icon, level_icon, logger_str, data);
            }
            ClientEvent::Progress {
                request_id: _,
                token: _,
                progress,
                total,
                message,
            } => {
                let total_str = total.map_or("?".to_string(), |t| t.to_string());
                let message_str = message.as_deref().unwrap_or("");
                println!(
                    "⏳ Progress: {:.1}% ({}/{}) {}",
                    if let Some(t) = total { progress / t * 100.0 } else { progress },
                    progress,
                    total_str,
                    message_str
                );
            }
            ClientEvent::Error { error } => {
                println!("❌ Error: {}", error);
            }
        }
    }

    println!("Event handler stopped");
}

async fn demo_resources(client: &Client) -> Result<(), Error> {
    println!("\n📄 === RESOURCES DEMO ===");

    // List resources
    println!("📄 Listing resources...");
    match client.list_resources().await {
        Ok(resources) => {
            println!("📄 Found {} resources:", resources.len());
            for resource in resources {
                println!("   - {} ({})", resource.name, resource.uri);

                // Read each resource
                match client.read_resource(&resource.uri).await {
                    Ok(contents) => {
                        for content in contents {
                            match content {
                                ResourceContent::Text(text) => {
                                    println!("     Content: {} ({})", text.text, text.mime_type.unwrap_or_default());
                                }
                                ResourceContent::Blob(blob) => {
                                    println!("     Binary content: {} bytes ({})",
                                        blob.blob.len(),
                                        blob.mime_type.unwrap_or_default()
                                    );
                                }
                            }
                        }
                    }
                    Err(e) => {
                        println!("     Failed to read resource: {}", e);
                    }
                }

                // Try to subscribe to resource updates
                match client.subscribe_resource(&resource.uri).await {
                    Ok(_) => {
                        println!("     Subscribed to updates");
                    }
                    Err(e) => {
                        println!("     Failed to subscribe: {}", e);
                    }
                }
            }
        }
        Err(e) => {
            println!("❌ Failed to list resources: {}", e);
        }
    }

    Ok(())
}

async fn demo_prompts(client: &Client) -> Result<(), Error> {
    println!("\n📝 === PROMPTS DEMO ===");

    // List prompts
    println!("📝 Listing prompts...");
    match client.list_prompts().await {
        Ok(prompts) => {
            println!("📝 Found {} prompts:", prompts.len());
            for prompt in prompts {
                println!("   - {}", prompt.name);
                if let Some(desc) = &prompt.description {
                    println!("     Description: {}", desc);
                }

                if let Some(args) = &prompt.arguments {
                    println!("     Arguments:");
                    for arg in args {
                        println!("       - {} ({})",
                            arg.name,
                            if arg.required.unwrap_or(false) { "required" } else { "optional" }
                        );
                        if let Some(desc) = &arg.description {
                            println!("         Description: {}", desc);
                        }
                    }

                    // Try to get the prompt with some arguments
                    let mut arguments = HashMap::new();
                    arguments.insert("name".to_string(), "User".to_string());
                    arguments.insert("topic".to_string(), "Model Context Protocol".to_string());

                    match client.get_prompt(&prompt.name, Some(arguments)).await {
                        Ok(messages) => {
                            println!("     Got prompt with {} messages:", messages.len());
                            for message in messages {
                                println!("       - {:?} message", message.role);
                                // We're simplifying here - in a real application you'd handle different content types
                            }
                        }
                        Err(e) => {
                            println!("     Failed to get prompt: {}", e);
                        }
                    }
                }
            }
        }
        Err(e) => {
            println!("❌ Failed to list prompts: {}", e);
        }
    }

    Ok(())
}

async fn demo_tools(client: &Client) -> Result<(), Error> {
    println!("\n🔧 === TOOLS DEMO ===");

    // List tools
    println!("🔧 Listing tools...");
    match client.list_tools().await {
        Ok(tools) => {
            println!("🔧 Found {} tools:", tools.len());
            for tool in tools {
                println!("   - {}", tool.name);
                if let Some(desc) = &tool.description {
                    println!("     Description: {}", desc);
                }

                let annotations = if let Some(annotations) = &tool.annotations {
                    let mut hints = Vec::new();
                    if let Some(title) = &annotations.title {
                        hints.push(format!("title: {}", title));
                    }
                    if let Some(read_only) = annotations.read_only_hint {
                        hints.push(format!("read-only: {}", read_only));
                    }
                    if let Some(destructive) = annotations.destructive_hint {
                        hints.push(format!("destructive: {}", destructive));
                    }
                    if let Some(idempotent) = annotations.idempotent_hint {
                        hints.push(format!("idempotent: {}", idempotent));
                    }
                    if let Some(open_world) = annotations.open_world_hint {
                        hints.push(format!("open-world: {}", open_world));
                    }

                    if hints.is_empty() {
                        "".to_string()
                    } else {
                        format!(" ({})", hints.join(", "))
                    }
                } else {
                    "".to_string()
                };

                println!("     Annotations:{}", annotations);

                // Try to call the tool
                if tool.name == "search" {
                    let arguments = serde_json::json!({
                        "query": "Model Context Protocol"
                    });

                    match client.call_tool(&tool.name, Some(arguments)).await {
                        Ok(result) => {
                            println!("     Called tool successfully");
                            println!("     Result content ({}):", result.content.len());
                            for content in result.content {
                                match content {
                                    ToolCallContent::Text(text) => {
                                        println!("       Text: {}", text.text);
                                    }
                                    ToolCallContent::Image(_) => {
                                        println!("       Image");
                                    }
                                    ToolCallContent::Audio(_) => {
                                        println!("       Audio");
                                    }
                                    ToolCallContent::Resource(_) => {
                                        println!("       Resource");
                                    }
                                }
                            }
                        }
                        Err(e) => {
                            println!("     Failed to call tool: {}", e);
                        }
                    }
                }
            }
        }
        Err(e) => {
            println!("❌ Failed to list tools: {}", e);
        }
    }

    Ok(())
}

async fn demo_completions(client: &Client) -> Result<(), Error> {
    println!("\n🔍 === COMPLETIONS DEMO ===");

    // Try to get completions for a prompt argument
    println!("🔍 Getting completions for a prompt argument...");

    match client.get_completions(
        CompletionReferenceType::Prompt,
        "example-prompt",
        "topic",
        "mo",
    ).await {
        Ok(result) => {
            println!("🔍 Completion suggestions:");
            for value in result.completion.values {
                println!("   - {}", value);
            }

            if let Some(total) = result.completion.total {
                println!("   Total available: {}", total);
            }

            if let Some(true) = result.completion.has_more {
                println!("   More suggestions available");
            }
        }
        Err(e) => {
            println!("❌ Failed to get completions: {}", e);
        }
    }

    Ok(())
}

async fn demo_logging(client: &Client) -> Result<(), Error> {
    println!("\n📝 === LOGGING DEMO ===");

    // Set logging level
    println!("📝 Setting logging level to debug...");
    match client.set_logging_level(LoggingLevel::Debug).await {
        Ok(_) => {
            println!("✅ Logging level set to debug");
        }
        Err(e) => {
            println!("❌ Failed to set logging level: {}", e);
        }
    }

    // Wait for some log messages
    println!("📝 Waiting for log messages (3 seconds)...");
    tokio::time::sleep(Duration::from_secs(3)).await;

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    // Initialize logging
    tracing_subscriber::fmt()
        .with_env_filter("mcpx=debug")
        .init();

    // Create client
    let (client, event_receiver) = ClientBuilder::new()
        .with_implementation("full-client", "0.1.0")
        .with_roots(true)
        .with_roots_list_changed(true)
        .with_sampling(true)
        .with_websocket_url("ws://localhost:3000")
        .build()?;

    // Start event handler
    let event_handler = tokio::spawn(handle_events(event_receiver));

    // Connect to server
    println!("🔌 Connecting to server...");
    client.connect().await?;

    // Wait a moment for initialization to complete
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Run demo functions sequentially
    demo_resources(&client).await?;
    demo_prompts(&client).await?;
    demo_tools(&client).await?;
    demo_completions(&client).await?;
    demo_logging(&client).await?;

    // All demos completed successfully

    // Ping the server
    println!("\n🏓 Pinging server...");
    match client.ping().await {
        Ok(_) => {
            println!("✅ Server responded to ping");
        }
        Err(e) => {
            println!("❌ Ping failed: {}", e);
        }
    }

    // Disconnect from server
    println!("\n🔌 Disconnecting from server...");
    client.disconnect().await?;
    println!("✅ Disconnected");

    // Wait for event handler to finish
    event_handler.await.unwrap();

    Ok(())
}