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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
use std::{collections::HashMap, process::Stdio, sync::Arc, time::Duration};
use async_trait::async_trait;
use futures::{SinkExt, StreamExt};
use serde::{Serialize, de::DeserializeOwned};
use tokio::{
io::{AsyncRead, AsyncWrite},
process::{Child, Command},
sync::{Mutex, mpsc},
};
use tracing::{debug, error, info, warn};
use crate::{
auth::OAuth2Client,
connection::ClientHandler,
context::ClientCtx,
error::{Error, Result},
http::HttpClientTransport,
jsonrpc::{create_jsonrpc_notification, result_to_jsonrpc_response},
request_handler::RequestHandler,
schema::*,
transport::{
GenericDuplex, StdioTransport, StreamTransport, TcpClientTransport, Transport,
TransportStream,
},
};
/// Default no-op implementation of ClientHandler for unit type
#[async_trait]
impl ClientHandler for () {
// All methods use default implementations
}
/// MCP Client implementation
pub struct Client<C = ()>
where
C: ClientHandler + Send,
{
/// Tracks requests and routes responses.
request_handler: RequestHandler,
/// Connection callbacks for server-initiated requests (wrapped in Arc for sharing).
connection: Arc<C>,
/// Context used for connection callbacks.
context: Option<ClientCtx>,
/// Client name reported during initialization.
name: String,
/// Client version reported during initialization.
version: String,
/// Capabilities advertised to the server.
client_capabilities: ClientCapabilities,
/// Tracks whether on_connect has been invoked for this connection.
on_connect_called: bool,
}
/// Handle to an MCP server spawned as a subprocess.
///
/// Returned by [`Client::connect_process`] after successfully spawning and
/// initializing an MCP server. Contains the process handle for lifecycle
/// management and the server's initialization response.
pub struct SpawnedServer {
/// The spawned server process.
///
/// Use this to manage the process lifecycle (wait, kill, check status).
pub process: Child,
/// Server initialization result.
///
/// Contains the server's name, version, and advertised capabilities.
pub server_info: InitializeResult,
}
impl Client<()> {
/// Create a new MCP client with default configuration.
pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
Self {
request_handler: RequestHandler::new(None, "req".to_string()),
connection: Arc::new(()),
context: None,
name: name.into(),
version: version.into(),
client_capabilities: ClientCapabilities::default(),
on_connect_called: false,
}
}
/// Set a custom handler for server-initiated requests.
///
/// This method uses a **type state pattern**: it transforms `Client<()>` into
/// `Client<C>` where `C` implements [`ClientHandler`]. This compile-time change
/// ensures the handler is set before connecting, rather than allowing runtime
/// failures from missing handlers.
///
/// The handler receives callbacks when the server initiates requests:
/// - [`ClientHandler::pong`] - Server health checks
/// - [`ClientHandler::create_message`] - LLM sampling requests (if capability enabled)
/// - [`ClientHandler::list_roots`] - Filesystem root discovery
/// - [`ClientHandler::elicit`] - User input requests
///
/// Without a custom handler, the default `()` handler returns errors for
/// server-initiated requests, which is appropriate for clients that don't
/// need to respond to server callbacks.
pub fn with_handler<C: ClientHandler>(self, handler: C) -> Client<C> {
Client {
request_handler: self.request_handler,
connection: Arc::new(handler),
context: self.context,
name: self.name,
version: self.version,
client_capabilities: self.client_capabilities,
on_connect_called: self.on_connect_called,
}
}
/// Set the client capabilities.
pub fn with_capabilities(mut self, capabilities: ClientCapabilities) -> Self {
self.client_capabilities = capabilities;
self
}
/// Set the request timeout duration.
pub fn with_request_timeout(mut self, timeout: Duration) -> Self {
self.request_handler = self
.request_handler
.with_timeout(timeout.as_millis() as u64);
self
}
}
impl<C> Client<C>
where
C: ClientHandler + Send + 'static,
{
/// Connect using the provided transport
pub(crate) async fn connect(&mut self, mut transport: Box<dyn Transport>) -> Result<()> {
self.context = None;
self.on_connect_called = false;
transport.connect().await?;
let stream = transport.framed()?;
// Start the message handler task before storing transport
self.start_message_handler(stream).await?;
info!("MCP client connected");
Ok(())
}
/// Initialize the connection with the server
///
/// This is a convenience method that uses the client's configured name, version,
/// and capabilities with the latest protocol version.
///
/// Calling `init` triggers the `ClientHandler::on_connect` callback after the
/// initialization handshake completes.
pub async fn init(&mut self) -> Result<InitializeResult>
where
C: Sync,
{
let client_info = Implementation::new(self.name.clone(), self.version.clone());
self.initialize(
LATEST_PROTOCOL_VERSION.to_string(),
self.client_capabilities.clone(),
client_info,
)
.await
}
/// Connect to a TCP server and initialize the connection
///
/// This is a convenience method that creates a TCP transport,
/// connects to the server, and performs the initialization handshake.
///
/// # Arguments
/// * `addr` - Server address in the format "host:port" (e.g., "localhost:3000", "127.0.0.1:8080")
pub async fn connect_tcp(&mut self, addr: impl Into<String>) -> Result<InitializeResult> {
let transport = Box::new(TcpClientTransport::new(addr));
self.connect(transport).await?;
self.init().await
}
/// Connect via stdio and initialize the connection
///
/// This is a convenience method that creates a stdio transport,
/// connects to the server, and performs the initialization handshake.
pub async fn connect_stdio(&mut self) -> Result<InitializeResult> {
let transport = Box::new(StdioTransport);
self.connect(transport).await?;
self.init().await
}
/// Connect via HTTP/HTTPS and initialize the connection
///
/// This is a convenience method that creates an HTTP transport,
/// connects to the server, and performs the initialization handshake.
/// Both HTTP and HTTPS protocols are supported.
///
/// # Arguments
/// * `endpoint` - Server URL including protocol and path (e.g., "http://localhost:3000", "<https://api.example.com/mcp>")
pub async fn connect_http(&mut self, endpoint: impl Into<String>) -> Result<InitializeResult> {
let transport = Box::new(HttpClientTransport::new(endpoint));
self.connect(transport).await?;
self.init().await
}
/// Connect via HTTP/HTTPS with OAuth authentication and initialize the connection
///
/// This method creates an HTTP transport with OAuth authentication support.
/// The OAuth client should be pre-configured with valid tokens or ready to
/// perform the OAuth flow.
///
/// # Arguments
/// * `endpoint` - Server URL including protocol and path
/// * `oauth_client` - Pre-configured OAuth2Client instance
pub async fn connect_http_with_oauth(
&mut self,
endpoint: impl Into<String>,
oauth_client: Arc<OAuth2Client>,
) -> Result<InitializeResult> {
let transport = Box::new(HttpClientTransport::new(endpoint).with_oauth(oauth_client));
self.connect(transport).await?;
self.init().await
}
/// Connect using generic AsyncRead and AsyncWrite streams and initialize the connection.
///
/// This method allows you to connect to a server using any pair of
/// AsyncRead and AsyncWrite streams, such as process stdio, pipes,
/// or custom implementations.
///
/// Use [`connect_stream_raw`](Self::connect_stream_raw) if you need to
/// control initialization manually.
pub async fn connect_stream<R, W>(&mut self, reader: R, writer: W) -> Result<InitializeResult>
where
R: AsyncRead + Send + Sync + Unpin + 'static,
W: AsyncWrite + Send + Sync + Unpin + 'static,
{
self.connect_stream_raw(reader, writer).await?;
self.init().await
}
/// Connect using generic AsyncRead and AsyncWrite streams without initialization.
///
/// This method establishes a transport connection but does not perform the MCP
/// initialization handshake.
pub async fn connect_stream_raw<R, W>(&mut self, reader: R, writer: W) -> Result<()>
where
R: AsyncRead + Send + Sync + Unpin + 'static,
W: AsyncWrite + Send + Sync + Unpin + 'static,
{
let duplex = GenericDuplex::new(reader, writer);
let transport = Box::new(StreamTransport::new(duplex));
self.connect(transport).await
}
/// Spawn a process, connect to it, and initialize the MCP handshake.
///
/// This method spawns a new process, establishes an MCP connection
/// through its standard input and output streams, and runs the initialize
/// handshake.
///
/// # Arguments
/// * `command` - A configured tokio::process::Command ready to be spawned
///
/// # Returns
/// Returns a [`SpawnedServer`] containing the process handle and server info.
pub async fn connect_process(&mut self, command: Command) -> Result<SpawnedServer> {
let mut process = self.connect_process_raw(command).await?;
match self.init().await {
Ok(server_info) => Ok(SpawnedServer {
process,
server_info,
}),
Err(err) => {
if let Err(kill_err) = process.kill().await {
warn!("Failed to kill process after init error: {}", kill_err);
}
Err(err)
}
}
}
/// Spawn a process and connect to it via its stdin/stdout without initialization.
///
/// This method spawns a new process and establishes an MCP connection
/// through its standard input and output streams.
///
/// # Arguments
/// * `command` - A configured tokio::process::Command ready to be spawned
///
/// # Returns
/// Returns the spawned Child process handle, allowing you to manage the
/// process lifecycle (e.g., wait for completion, kill it, etc.)
pub async fn connect_process_raw(&mut self, mut command: Command) -> Result<Child> {
// Configure the command to use piped stdio
command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit()); // Let stderr pass through for debugging
// Spawn the process
let mut child = command
.spawn()
.map_err(|e| Error::Transport(format!("Failed to spawn process: {e}")))?;
// Take ownership of stdin and stdout
let stdin = child
.stdin
.take()
.ok_or_else(|| Error::Transport("Failed to capture process stdin".to_string()))?;
let stdout = child
.stdout
.take()
.ok_or_else(|| Error::Transport("Failed to capture process stdout".to_string()))?;
// Connect using the process streams
// Note: We swap the order here - the child's stdout is our reader,
// and the child's stdin is our writer
self.connect_stream_raw(stdout, stdin).await?;
Ok(child)
}
/// Send a request and wait for response
async fn request<T>(&self, request: ClientRequest) -> Result<T>
where
T: DeserializeOwned,
{
self.request_handler.request(request).await
}
/// Send a notification to the server
async fn send_notification(
&self,
method: &str,
params: Option<serde_json::Value>,
) -> Result<()> {
self.request_handler.send_notification(method, params).await
}
/// Invoke the connection callback if it has not run yet.
async fn call_on_connect(&mut self) -> Result<()> {
if self.on_connect_called {
return Ok(());
}
let context = self.context.as_ref().ok_or_else(|| {
Error::InternalError("Client context not available for on_connect".into())
})?;
self.connection.on_connect(context).await?;
self.on_connect_called = true;
Ok(())
}
/// Start the background task that handles incoming messages
async fn start_message_handler(&mut self, stream: Box<dyn TransportStream>) -> Result<()> {
let request_handler = self.request_handler.clone();
// Split the transport stream into read and write halves
let (tx, mut rx) = stream.split();
// Wrap the sink in an Arc<Mutex> for sharing
let tx = Arc::new(Mutex::new(tx));
// Store the sender half for sending messages
self.request_handler.set_transport(tx.clone());
// Clone the connection for use in the handler
let connection = self.connection.clone();
// Create mpsc channel for client notifications
let (client_notification_tx, mut client_notification_rx) = mpsc::unbounded_channel();
// Create the context for the connection
let context = ClientCtx::new(client_notification_tx);
self.context = Some(context.clone());
// Clone sink for notification handler
let notification_sink = tx.clone();
// Spawn a task to handle incoming messages
tokio::spawn(async move {
debug!("Message handler started");
loop {
tokio::select! {
// Handle incoming messages from server
result = rx.next() => {
match result {
Some(Ok(message)) => {
debug!("Received message: {:?}", message);
match message {
JSONRPCMessage::Response(response) => {
request_handler.handle_response(response).await;
}
JSONRPCMessage::Notification(notification) => {
// Convert the JSON-RPC notification into a typed
// ServerNotification and pass it to the connection handler.
if let Err(err) = handle_server_notification(connection.as_ref(), &context, notification).await {
error!("Failed to handle server notification: {}", err);
}
}
JSONRPCMessage::Request(request) => {
tracing::info!("Client received request from server: {:?}", request.id);
let response = handle_server_request(connection.as_ref(), &context, request).await;
let response_id = match &response {
JSONRPCMessage::Response(r) => match r {
JSONRPCResponse::Result(result) => {
format!("{:?}", result.id)
}
JSONRPCResponse::Error(error) => {
format!("{:?}", error.id)
}
},
_ => "Unknown".to_string(),
};
tracing::info!(
"Client sending response to server: {:?}",
response_id
);
let mut sink = tx.lock().await;
if let Err(e) = sink.send(response).await {
error!("Failed to send response to server: {}", e);
break;
}
}
}
}
Some(Err(e)) => {
error!("Error receiving message: {}", e);
break;
}
None => {
info!("Server disconnected");
break;
}
}
}
// Forward client notifications to server
Some(notification) = client_notification_rx.recv() => {
let jsonrpc_notification = create_jsonrpc_notification(¬ification);
let mut sink = notification_sink.lock().await;
if let Err(e) = sink.send(JSONRPCMessage::Notification(jsonrpc_notification)).await {
error!("Error sending notification to server: {}", e);
break;
}
}
}
}
// Clean up connection
if let Err(e) = connection.on_shutdown(&context).await {
error!("Error during client shutdown: {}", e);
}
info!("Message handler stopped");
});
Ok(())
}
}
/// MCP protocol methods for server interaction.
///
/// These methods implement the client-side MCP protocol operations
/// for communicating with an MCP server.
impl<C> Client<C>
where
C: ClientHandler + Send + Sync + 'static,
{
/// Initialize the connection with protocol version and capabilities
pub async fn initialize(
&mut self,
protocol_version: String,
capabilities: ClientCapabilities,
client_info: Implementation,
) -> Result<InitializeResult> {
let request = ClientRequest::initialize(protocol_version, capabilities, client_info);
let result: InitializeResult = self.request(request).await?;
// Send the initialized notification to complete the handshake
self.send_notification("notifications/initialized", None)
.await?;
self.call_on_connect().await?;
Ok(result)
}
/// Respond to ping requests
pub async fn ping(&mut self) -> Result<()> {
let _: EmptyResult = self.request(ClientRequest::ping()).await?;
Ok(())
}
/// List available tools with optional pagination
pub async fn list_tools(
&mut self,
cursor: impl Into<Option<Cursor>> + Send,
) -> Result<ListToolsResult> {
self.request(ClientRequest::list_tools(cursor.into())).await
}
/// Call a tool with the given name and arguments.
///
/// Arguments can be any serializable type. For tools that take no arguments, pass `()`
/// which serializes to an empty JSON object `{}`. This is the idiomatic way to call
/// parameter-less tools.
///
/// # Example
///
/// ```ignore
/// // With a struct
/// #[derive(Serialize)]
/// struct EchoArgs { message: String }
/// let result = client.call_tool("echo", EchoArgs { message: "hello".into() }).await?;
///
/// // With no arguments - () serializes to {}
/// let result = client.call_tool("ping", ()).await?;
///
/// // HashMap also works for dynamic arguments
/// let mut args = HashMap::new();
/// args.insert("key", "value");
/// let result = client.call_tool("dynamic", args).await?;
/// ```
pub async fn call_tool(
&mut self,
name: impl Into<String> + Send,
arguments: impl Serialize + Send,
) -> Result<CallToolResult> {
let args = crate::Arguments::from_struct(arguments)?;
let request = ClientRequest::call_tool(name, Some(args), None);
self.request(request).await
}
/// Call a tool with arguments and task metadata.
///
/// Use this when you need to pass task metadata for progress tracking.
pub async fn call_tool_with_task(
&mut self,
name: impl Into<String> + Send,
arguments: impl Serialize + Send,
task: Option<TaskMetadata>,
) -> Result<CallToolResult> {
let args = crate::Arguments::from_struct(arguments)?;
let request = ClientRequest::call_tool(name, Some(args), task);
self.request(request).await
}
/// Call a tool and deserialize the JSON text response into a typed result.
///
/// This is a convenience method for tools that return JSON in their text content.
/// It:
/// 1. Serializes the arguments
/// 2. Calls the tool
/// 3. Extracts the first text content block
/// 4. Parses it as JSON and deserializes into type `R`
///
/// # Example
///
/// ```ignore
/// #[derive(Serialize)]
/// struct CalcArgs { a: i32, b: i32 }
///
/// #[derive(Deserialize)]
/// struct CalcResult { sum: i32 }
///
/// let result: CalcResult = client.call_tool_json("add", CalcArgs { a: 1, b: 2 }).await?;
/// ```
pub async fn call_tool_json<R: DeserializeOwned>(
&mut self,
name: impl Into<String> + Send,
arguments: impl Serialize + Send,
) -> Result<R> {
let tool_name = name.into();
let result = self.call_tool(tool_name.clone(), arguments).await?;
if result.is_error.unwrap_or(false) {
let message = if !result.content.is_empty() {
result.all_text()
} else if let Some(structured) = &result.structured_content {
serde_json::to_string(structured).unwrap_or_default()
} else {
"Unknown error".to_string()
};
return Err(Error::tool_execution_failed(tool_name, message));
}
let text = result
.text()
.ok_or_else(|| Error::Protocol("Tool returned no text content".into()))?;
serde_json::from_str(text).map_err(|e| Error::JsonParse {
message: format!("Failed to parse tool response: {e}"),
})
}
/// Call a tool and deserialize the structured content into a typed result.
///
/// This is a convenience method for tools that return structured content.
pub async fn call_tool_structured<R: DeserializeOwned>(
&mut self,
name: impl Into<String> + Send,
arguments: impl Serialize + Send,
) -> Result<R> {
let tool_name = name.into();
let result = self.call_tool(tool_name.clone(), arguments).await?;
if result.is_error.unwrap_or(false) {
let message = if !result.content.is_empty() {
result.all_text()
} else if let Some(structured) = &result.structured_content {
serde_json::to_string(structured).unwrap_or_default()
} else {
"Unknown error".to_string()
};
return Err(Error::tool_execution_failed(tool_name, message));
}
result.structured_as().map_err(|e| Error::JsonParse {
message: format!("Failed to parse tool structured content: {e}"),
})
}
/// List available resources with optional pagination
pub async fn list_resources(
&mut self,
cursor: impl Into<Option<Cursor>> + Send,
) -> Result<ListResourcesResult> {
self.request(ClientRequest::list_resources(cursor.into()))
.await
}
/// List resource templates with optional pagination
pub async fn list_resource_templates(
&mut self,
cursor: impl Into<Option<Cursor>> + Send,
) -> Result<ListResourceTemplatesResult> {
self.request(ClientRequest::list_resource_templates(cursor.into()))
.await
}
/// Read a resource by URI
pub async fn resources_read(
&mut self,
uri: impl Into<String> + Send,
) -> Result<ReadResourceResult> {
self.request(ClientRequest::read_resource(uri)).await
}
/// Subscribe to resource updates
pub async fn resources_subscribe(&mut self, uri: impl Into<String> + Send) -> Result<()> {
let _: EmptyResult = self.request(ClientRequest::subscribe(uri)).await?;
Ok(())
}
/// Unsubscribe from resource updates
pub async fn resources_unsubscribe(&mut self, uri: impl Into<String> + Send) -> Result<()> {
let _: EmptyResult = self.request(ClientRequest::unsubscribe(uri)).await?;
Ok(())
}
/// List available prompts with optional pagination
pub async fn list_prompts(
&mut self,
cursor: impl Into<Option<Cursor>> + Send,
) -> Result<ListPromptsResult> {
self.request(ClientRequest::list_prompts(cursor.into()))
.await
}
/// Get a prompt by name with optional arguments
pub async fn get_prompt(
&mut self,
name: impl Into<String> + Send,
arguments: Option<HashMap<String, String>>,
) -> Result<GetPromptResult> {
self.request(ClientRequest::get_prompt(name, arguments))
.await
}
/// Handle completion requests
pub async fn complete(
&mut self,
reference: Reference,
argument: ArgumentInfo,
context: Option<CompleteContext>,
) -> Result<CompleteResult> {
self.request(ClientRequest::complete(reference, argument, context))
.await
}
/// Set the logging level
pub async fn set_level(&mut self, level: LoggingLevel) -> Result<()> {
let _: EmptyResult = self.request(ClientRequest::set_level(level)).await?;
Ok(())
}
/// Retrieve the state of a task.
pub async fn get_task(&mut self, task_id: impl Into<String> + Send) -> Result<GetTaskResult> {
self.request(ClientRequest::get_task(task_id)).await
}
/// Retrieve the result of a completed task.
pub async fn get_task_payload(
&mut self,
task_id: impl Into<String> + Send,
) -> Result<GetTaskPayloadResult> {
self.request(ClientRequest::get_task_payload(task_id)).await
}
/// List tasks with optional pagination.
pub async fn list_tasks(
&mut self,
cursor: impl Into<Option<Cursor>> + Send,
) -> Result<ListTasksResult> {
self.request(ClientRequest::list_tasks(cursor.into())).await
}
/// Cancel a task by ID.
pub async fn cancel_task(
&mut self,
task_id: impl Into<String> + Send,
) -> Result<CancelTaskResult> {
self.request(ClientRequest::cancel_task(task_id)).await
}
}
/// Handle a request from the server using the ClientHandler trait
async fn handle_server_request<C: ClientHandler>(
connection: &C,
context: &ClientCtx,
request: JSONRPCRequest,
) -> JSONRPCMessage {
// Create a context with the request ID
let ctx_with_request = context.with_request_id(request.id.clone());
let result = handle_server_request_inner(connection, &ctx_with_request, request.clone()).await;
result_to_jsonrpc_response(request.id, result)
}
/// Inner handler that returns Result<serde_json::Value>
async fn handle_server_request_inner<C: ClientHandler>(
connection: &C,
ctx: &ClientCtx,
request: JSONRPCRequest,
) -> Result<serde_json::Value> {
let mut request_obj = serde_json::Map::new();
request_obj.insert(
"method".to_string(),
serde_json::Value::String(request.request.method.clone()),
);
if let Some(params) = request.request.params {
if let Some(meta) = params._meta {
request_obj.insert("_meta".to_string(), serde_json::to_value(meta)?);
}
for (key, value) in params.other {
request_obj.insert(key, value);
}
}
let server_request =
match serde_json::from_value::<ServerRequest>(serde_json::Value::Object(request_obj)) {
Ok(req) => req,
Err(err) => {
// Check if it's an unknown method or invalid parameters
let err_str = err.to_string();
if err_str.contains("unknown variant") {
return Err(Error::MethodNotFound(request.request.method.clone()));
} else {
// It's a known method with invalid parameters
return Err(Error::InvalidParams(format!(
"Invalid parameters for {}: {}",
request.request.method, err
)));
}
}
};
connection
.handle_request(ctx, server_request, &request.request.method)
.await
}
/// Convert a JSON-RPC notification into a typed ServerNotification and pass it
/// to the connection implementation for further handling.
async fn handle_server_notification<C: ClientHandler>(
connection: &C,
context: &ClientCtx,
notification: JSONRPCNotification,
) -> Result<()> {
// Build a serde_json::Value representing the notification in the shape
// expected by the ServerNotification enum (which is `{"method": "...", ...}`).
use serde_json::Value;
let mut obj = serde_json::Map::new();
obj.insert(
"method".to_string(),
Value::String(notification.notification.method.clone()),
);
if let Some(params) = notification.notification.params {
for (k, v) in params.other {
obj.insert(k, v);
}
}
let value = Value::Object(obj);
match serde_json::from_value::<ServerNotification>(value) {
Ok(typed) => connection.notification(context, typed).await,
Err(e) => Err(Error::InvalidParams(format!(
"Failed to parse server notification: {e}",
))),
}
}
#[cfg(test)]
mod tests {
use std::{
collections::HashMap,
sync::{Arc, Mutex as StdMutex},
time::Instant,
};
use tokio::{
io::duplex,
process::Command,
sync::{Mutex, oneshot},
time::{Duration, sleep, timeout},
};
use super::*;
#[test]
fn test_pagination_api() {
// This test just verifies the API is ergonomic - it doesn't run async code
let mut client = Client::new("test-client", "1.0.0");
// These should all compile cleanly
drop(async {
// Simple calls without cursors - passing None
client.list_tools(None).await.unwrap();
client.list_resources(None).await.unwrap();
client.list_prompts(None).await.unwrap();
client.list_resource_templates(None).await.unwrap();
// Calls with cursor as Cursor type
let cursor = Cursor::from("cursor");
client.list_tools(cursor.clone()).await.unwrap();
client.list_resources(cursor.clone()).await.unwrap();
client.list_prompts(cursor.clone()).await.unwrap();
client.list_resource_templates(cursor).await.unwrap();
// Calls with explicit Some(Cursor)
client
.list_tools(Some(Cursor::from("some_cursor")))
.await
.unwrap();
client
.list_resources(Some(Cursor::from("some_cursor")))
.await
.unwrap();
client
.list_prompts(Some(Cursor::from("some_cursor")))
.await
.unwrap();
client
.list_resource_templates(Some(Cursor::from("some_cursor")))
.await
.unwrap();
});
}
#[test]
fn test_call_tool_api() {
// Define struct for testing Serialize arguments
#[derive(serde::Serialize)]
struct MyParams {
key: String,
}
// This test just verifies the API is ergonomic - it doesn't run async code
let mut client = Client::new("test-client", "1.0.0");
// These should all compile cleanly
drop(async {
// Call without arguments - pass () which serializes to empty object
client.call_tool("my_tool", ()).await.unwrap();
// Call with String for tool name
let tool_name = "another_tool".to_string();
client.call_tool(tool_name, ()).await.unwrap();
// Call with &String
let tool_name = "third_tool".to_string();
client.call_tool(&tool_name, ()).await.unwrap();
// Call with HashMap arguments directly (implements Serialize)
let mut args = HashMap::new();
args.insert("param".to_string(), serde_json::json!("value"));
client.call_tool("tool_with_args", args).await.unwrap();
// Call with a struct that implements Serialize
let params = MyParams {
key: "value".to_string(),
};
client.call_tool("tool_with_struct", params).await.unwrap();
});
}
use crate::{
connection::{ClientHandler as ClientHandlerTrait, ServerHandler as ServerHandlerTrait},
context::{ClientCtx as ClientCtxType, ServerCtx},
schema::{ClientNotification, ServerNotification},
server::{Server, ServerHandle},
transport::{GenericDuplex, StreamTransport, TestTransport},
};
async fn setup_client_server() -> (Client, ServerHandle) {
// Create a minimal test connection
#[derive(Debug, Default)]
struct TestConnection;
#[async_trait::async_trait]
impl ServerHandlerTrait for TestConnection {
async fn initialize(
&self,
_context: &ServerCtx,
_protocol_version: String,
_capabilities: ClientCapabilities,
_client_info: Implementation,
) -> Result<InitializeResult> {
Ok(InitializeResult::new("test-server").with_version("1.0.0"))
}
}
let (client_transport, server_transport) = TestTransport::create_pair();
let server = Server::new(TestConnection::default);
let server_handle = ServerHandle::new(server, server_transport)
.await
.expect("Failed to start server");
let mut client = Client::new("test-client", "1.0.0");
client
.connect(client_transport)
.await
.expect("Failed to connect");
client.init().await.expect("Failed to initialize");
(client, server_handle)
}
// Test that a ClientHandler implementation receives notifications sent
// by the server.
#[tokio::test]
async fn test_client_receives_server_notification() {
// Custom client connection that records notifications
struct NotifClientHandler {
tx: Arc<Mutex<Option<oneshot::Sender<()>>>>,
}
#[async_trait::async_trait]
impl ClientHandlerTrait for NotifClientHandler {
async fn notification(
&self,
_context: &ClientCtxType,
notification: ServerNotification,
) -> Result<()> {
if matches!(
notification,
ServerNotification::ToolListChanged { _meta: _ }
) {
let mut tx_guard = self.tx.lock().await;
if let Some(tx) = tx_guard.take() {
tx.send(()).ok();
}
}
Ok(())
}
}
// Server handler that advertises tools capability (with list_changed)
#[derive(Debug, Default)]
struct DummyServerHandler;
#[async_trait::async_trait]
impl ServerHandlerTrait for DummyServerHandler {
async fn initialize(
&self,
_context: &ServerCtx,
_protocol_version: String,
_capabilities: ClientCapabilities,
_client_info: Implementation,
) -> Result<InitializeResult> {
// Return capabilities that include tools with list_changed
Ok(InitializeResult::new("test-server")
.with_version("1.0.0")
.with_tools(true))
}
}
// Channel to signal when notification is received
let (tx_notif, rx_notif) = oneshot::channel::<()>();
// Create transport pair
let (client_transport, server_transport) = TestTransport::create_pair();
// Start server - capabilities come from handler's initialize response
let server = Server::new(DummyServerHandler::default);
let server_handle = ServerHandle::new(server, server_transport)
.await
.expect("Failed to start server");
// Create client with notif handler
let mut client = Client::new("test-client", "1.0.0").with_handler(NotifClientHandler {
tx: Arc::new(Mutex::new(Some(tx_notif))),
});
// Connect and initialize
client
.connect(client_transport)
.await
.expect("Failed to connect");
client.init().await.expect("Failed to initialize");
// Send server notification
server_handle.send_server_notification(&ServerNotification::tool_list_changed());
// Wait for notification to be received
timeout(Duration::from_secs(1), rx_notif)
.await
.expect("Notification not received")
.expect("Receiver dropped");
}
/// Ensure notifications are not forwarded when the server lacks the corresponding capability.
#[tokio::test]
async fn test_server_notification_filtered_without_capability() {
struct NotifClientHandler {
tx: Arc<Mutex<Option<oneshot::Sender<()>>>>,
}
#[async_trait::async_trait]
impl ClientHandlerTrait for NotifClientHandler {
async fn notification(
&self,
_context: &ClientCtxType,
_notification: ServerNotification,
) -> Result<()> {
let mut tx_guard = self.tx.lock().await;
if let Some(tx) = tx_guard.take() {
tx.send(()).ok();
}
Ok(())
}
}
#[derive(Debug, Default)]
struct DummyServerHandler;
#[async_trait::async_trait]
impl ServerHandlerTrait for DummyServerHandler {
async fn initialize(
&self,
_context: &ServerCtx,
_protocol_version: String,
_capabilities: ClientCapabilities,
_client_info: Implementation,
) -> Result<InitializeResult> {
Ok(InitializeResult::new("test-server"))
}
}
let (tx_notif, rx_notif) = oneshot::channel::<()>();
let (client_transport, server_transport) = TestTransport::create_pair();
// Start server without tools capability
let server = Server::new(DummyServerHandler::default);
let server_handle = ServerHandle::new(server, server_transport)
.await
.expect("Failed to start server");
let mut client = Client::new("test-client", "1.0.0").with_handler(NotifClientHandler {
tx: Arc::new(Mutex::new(Some(tx_notif))),
});
client
.connect(client_transport)
.await
.expect("Failed to connect");
client.init().await.expect("Failed to initialize");
server_handle.send_server_notification(&ServerNotification::tool_list_changed());
let res = timeout(Duration::from_millis(200), rx_notif).await;
assert!(res.is_err(), "Notification should be filtered");
}
// Test that a ServerHandler implementation receives notifications sent
// by the client.
#[tokio::test]
async fn test_server_receives_client_notification() {
// Server connection that records notification
#[derive(Debug, Default)]
struct NotifyServerHandler {
tx: Arc<StdMutex<Option<oneshot::Sender<()>>>>,
}
#[async_trait::async_trait]
impl ServerHandlerTrait for NotifyServerHandler {
async fn initialize(
&self,
_context: &ServerCtx,
_protocol_version: String,
_capabilities: ClientCapabilities,
_client_info: Implementation,
) -> Result<InitializeResult> {
Ok(InitializeResult::new("test-server").with_version("1.0.0"))
}
async fn notification(
&self,
_context: &ServerCtx,
notification: ClientNotification,
) -> Result<()> {
if matches!(notification, ClientNotification::Initialized { _meta: _ }) {
let maybe_tx = self.tx.lock().unwrap().take();
if let Some(tx) = maybe_tx {
tx.send(()).ok();
}
}
Ok(())
}
}
// Client connection that sends a notification on connect
#[derive(Clone)]
struct NotifyClientHandler;
#[async_trait::async_trait]
impl ClientHandlerTrait for NotifyClientHandler {
async fn on_connect(&self, context: &ClientCtxType) -> Result<()> {
context.notify(ClientNotification::initialized())?;
Ok(())
}
}
// Channel to notify when server receives notification
let (tx_notif, rx_notif) = oneshot::channel();
// Create transport pair
let (client_transport, server_transport) = TestTransport::create_pair();
let shared_tx: Arc<StdMutex<Option<oneshot::Sender<()>>>> =
Arc::new(StdMutex::new(Some(tx_notif)));
// Start server with notif connection
let server = {
let tx_clone = shared_tx.clone();
Server::new(move || NotifyServerHandler {
tx: tx_clone.clone(),
})
};
let server_handle = ServerHandle::new(server, server_transport)
.await
.expect("Failed to start server");
// Create client with notifier connection
let mut client = Client::new("test-client", "1.0.0").with_handler(NotifyClientHandler);
// Connect and initialize
client
.connect(client_transport)
.await
.expect("Failed to connect");
client.init().await.expect("Failed to initialize");
// Wait for server to receive notification
timeout(Duration::from_secs(1), rx_notif)
.await
.expect("Server did not receive notification")
.expect("Receiver dropped");
drop(server_handle);
}
#[test]
fn test_client_creation() {
let client = Client::new("test-client", "1.0.0");
assert_eq!(client.name, "test-client");
assert_eq!(client.version, "1.0.0");
}
#[tokio::test]
async fn test_client_ping_server() {
let (mut client, _server) = setup_client_server().await;
client.ping().await.expect("Ping failed");
}
#[tokio::test]
async fn test_multiple_client_pings() {
let (mut client, _server) = setup_client_server().await;
for i in 0..20 {
client
.ping()
.await
.unwrap_or_else(|_| panic!("Ping {i} failed"));
}
}
#[tokio::test]
async fn test_ping_performance() {
let (mut client, _server) = setup_client_server().await;
let start = Instant::now();
let num_pings = 50;
for _ in 0..num_pings {
client.ping().await.expect("Ping failed");
}
let duration = start.elapsed();
let pings_per_second = num_pings as f64 / duration.as_secs_f64();
println!(
"Client->Server: {num_pings} pings in {duration:?} ({pings_per_second:.1} pings/sec)"
);
assert!(
pings_per_second > 50.0,
"Too slow: {pings_per_second:.1} pings/sec"
);
}
#[tokio::test]
async fn test_connect_stream() {
// Create a minimal test connection
#[derive(Debug, Default)]
struct TestStreamHandler;
#[async_trait::async_trait]
impl ServerHandlerTrait for TestStreamHandler {
async fn initialize(
&self,
_context: &ServerCtx,
_protocol_version: String,
_capabilities: ClientCapabilities,
_client_info: Implementation,
) -> Result<InitializeResult> {
Ok(InitializeResult::new("test-server")
.with_version("1.0.0")
.with_tools(true))
}
}
// Create a pair of duplex streams for testing
let (client_reader, server_writer) = duplex(8192);
let (server_reader, client_writer) = duplex(8192);
// Create server - capabilities come from handler's initialize response
let server = Server::new(TestStreamHandler::default);
// Create server transport from the streams
let server_duplex = GenericDuplex::new(server_reader, server_writer);
let server_transport = Box::new(StreamTransport::new(server_duplex));
let _server_handle = ServerHandle::new(server, server_transport)
.await
.expect("Failed to start server");
// Create and connect client using connect_stream
let mut client = Client::new("test-client", "1.0.0");
let result = client
.connect_stream(client_reader, client_writer)
.await
.expect("Failed to connect client");
assert_eq!(result.server_info.name, "test-server");
// Test that we can ping
client.ping().await.expect("Ping failed");
}
#[tokio::test]
async fn test_connect_process() {
// This test would require an actual MCP server binary to spawn
// For now, we'll just test that the API compiles and handles errors correctly
let mut client = Client::new("test-client", "1.0.0");
// Try to spawn a non-existent process
let cmd = Command::new("non-existent-mcp-server");
let result = client.connect_process(cmd).await;
// Should fail with a transport error
assert!(result.is_err());
if let Err(Error::Transport(msg)) = result {
assert!(msg.contains("Failed to spawn process"));
} else {
panic!("Expected Transport error");
}
}
#[tokio::test]
async fn test_reconnect_works() {
// Create a minimal test connection
#[derive(Debug, Default)]
struct TestConnection;
#[async_trait::async_trait]
impl ServerHandlerTrait for TestConnection {
async fn initialize(
&self,
_context: &ServerCtx,
_protocol_version: String,
_capabilities: ClientCapabilities,
_client_info: Implementation,
) -> Result<InitializeResult> {
Ok(InitializeResult::new("test-server").with_version("1.0.0"))
}
}
// Test that we can connect multiple times (e.g., after disconnect)
let (mut client, server1) = setup_client_server().await;
// First connection is already established by setup_client_server
client.ping().await.expect("First ping failed");
// Drop the first server to simulate disconnect
drop(server1);
// Wait a bit for the connection to close
sleep(Duration::from_millis(100)).await;
// Now create a new server and reconnect
let (client_transport, server_transport) = TestTransport::create_pair();
// Create a new test server
let server = Server::new(TestConnection::default);
let _server2 = ServerHandle::new(server, server_transport)
.await
.expect("Failed to start second server");
// Reconnect the client
client
.connect(client_transport)
.await
.expect("Reconnect failed");
// Initialize and test the new connection
client.init().await.expect("Re-initialize failed");
client.ping().await.expect("Ping after reconnect failed");
}
#[tokio::test]
async fn test_request_timeout() {
let (client_transport, _server_transport) = TestTransport::create_pair();
let mut client =
Client::new("test", "1.0").with_request_timeout(Duration::from_millis(100));
client
.connect(client_transport)
.await
.expect("Failed to connect");
// init() sends initialize request.
// Since server transport is not read, it won't respond.
// So it should timeout after 100ms.
let result = client.init().await;
assert!(result.is_err());
match result {
Err(Error::Timeout { .. }) => {}
_ => panic!("Expected timeout error, got {:?}", result),
}
}
#[tokio::test]
async fn test_call_tool_json_error() {
#[derive(Debug, Default)]
struct ErrorConnection;
#[async_trait::async_trait]
impl ServerHandlerTrait for ErrorConnection {
async fn initialize(
&self,
_context: &ServerCtx,
_protocol_version: String,
_capabilities: ClientCapabilities,
_client_info: Implementation,
) -> Result<InitializeResult> {
Ok(InitializeResult::new("test-server").with_version("1.0.0"))
}
async fn call_tool(
&self,
_context: &ServerCtx,
name: String,
_arguments: Option<crate::Arguments>,
_task: Option<TaskMetadata>,
) -> Result<CallToolResult> {
if name == "fail" {
// Return a tool error (isError: true) with structured content
Ok(CallToolResult::error("ERR", "Tool failed details"))
} else {
Ok(CallToolResult::new().with_text_content("{}"))
}
}
}
let (client_transport, server_transport) = TestTransport::create_pair();
let server = Server::new(ErrorConnection::default);
let _server_handle = ServerHandle::new(server, server_transport)
.await
.expect("Failed to start server");
let mut client = Client::new("test-client", "1.0.0");
client
.connect(client_transport)
.await
.expect("Failed to connect");
client.init().await.expect("Failed to initialize");
// Call the failing tool
let result: Result<serde_json::Value> = client.call_tool_json("fail", ()).await;
match result {
Err(Error::ToolExecutionFailed { tool, message }) => {
assert_eq!(tool, "fail");
// The message should come from the structured content since text is empty
assert!(message.contains("Tool failed details"));
}
_ => panic!("Expected ToolExecutionFailed, got {:?}", result),
}
}
}