sse/
sse.rs

1use anyhow::Result;
2use mcp_client::client::{ClientCapabilities, ClientInfo, McpClient, McpClientTrait};
3use mcp_client::transport::{SseTransport, Transport};
4use mcp_client::McpService;
5use std::collections::HashMap;
6use std::time::Duration;
7use tracing_subscriber::EnvFilter;
8
9#[tokio::main]
10async fn main() -> Result<()> {
11    // Initialize logging
12    tracing_subscriber::fmt()
13        .with_env_filter(
14            EnvFilter::from_default_env()
15                .add_directive("mcp_client=debug".parse().unwrap())
16                .add_directive("eventsource_client=info".parse().unwrap()),
17        )
18        .init();
19
20    // Create the base transport
21    let transport = SseTransport::new("http://localhost:8000/sse", HashMap::new());
22
23    // Start transport
24    let handle = transport.start().await?;
25
26    // Create the service with timeout middleware
27    let service = McpService::with_timeout(handle, Duration::from_secs(3));
28
29    // Create client
30    let mut client = McpClient::new(service);
31    println!("Client created\n");
32
33    // Initialize
34    let server_info = client
35        .initialize(
36            ClientInfo {
37                name: "test-client".into(),
38                version: "1.0.0".into(),
39            },
40            ClientCapabilities::default(),
41        )
42        .await?;
43    println!("Connected to server: {server_info:?}\n");
44
45    // Sleep for 100ms to allow the server to start - surprisingly this is required!
46    tokio::time::sleep(Duration::from_millis(500)).await;
47
48    // List tools
49    let tools = client.list_tools(None).await?;
50    println!("Available tools: {tools:?}\n");
51
52    // Call tool
53    let tool_result = client
54        .call_tool(
55            "echo_tool",
56            serde_json::json!({ "message": "Client with SSE transport - calling a tool" }),
57        )
58        .await?;
59    println!("Tool result: {tool_result:?}\n");
60
61    // List resources
62    let resources = client.list_resources(None).await?;
63    println!("Resources: {resources:?}\n");
64
65    // Read resource
66    let resource = client.read_resource("echo://fixedresource").await?;
67    println!("Resource: {resource:?}\n");
68
69    Ok(())
70}