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
use crate::error::{TransportError, TransportResult};
use crate::schema::{
schema_utils::{
self, ClientMessage, ClientMessages, McpMessage, RpcMessage, ServerMessage, ServerMessages,
},
JsonrpcErrorResponse,
};
use crate::schema::{RequestId, RpcError};
use crate::utils::await_timeout;
use crate::McpDispatch;
use async_trait::async_trait;
use futures::future::join_all;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use tokio::sync::oneshot::{self};
use tokio::sync::Mutex;
/// Provides a dispatcher for sending MCP messages and handling responses.
///
/// `MessageDispatcher` facilitates MCP communication by managing message sending, request tracking,
/// and response handling. It supports both client-to-server and server-to-client message flows through
/// implementations of the `McpDispatch` trait. The dispatcher uses a transport mechanism
/// (e.g., stdin/stdout) to serialize and send messages, and it tracks pending requests with
/// a configurable timeout mechanism for asynchronous responses.
pub struct MessageDispatcher<R> {
pending_requests: Arc<Mutex<HashMap<RequestId, oneshot::Sender<R>>>>,
writable_std: Option<Mutex<Pin<Box<dyn tokio::io::AsyncWrite + Send + Sync>>>>,
writable_tx: Option<
tokio::sync::mpsc::Sender<(
String,
tokio::sync::oneshot::Sender<crate::error::TransportResult<()>>,
)>,
>,
request_timeout: Duration,
}
impl<R> MessageDispatcher<R> {
/// Creates a new `MessageDispatcher` instance with the given configuration.
///
/// # Arguments
/// * `pending_requests` - A thread-safe map for storing pending request IDs and their response channels.
/// * `writable_std` - A mutex-protected, pinned writer (e.g., stdout) for sending serialized messages.
/// * `message_id_counter` - An atomic counter for generating unique request IDs.
/// * `request_timeout` - The timeout duration in milliseconds for awaiting responses.
///
/// # Returns
/// A new `MessageDispatcher` instance configured for MCP message handling.
pub fn new(
pending_requests: Arc<Mutex<HashMap<RequestId, oneshot::Sender<R>>>>,
writable_std: Mutex<Pin<Box<dyn tokio::io::AsyncWrite + Send + Sync>>>,
request_timeout: Duration,
) -> Self {
Self {
pending_requests,
writable_std: Some(writable_std),
writable_tx: None,
request_timeout,
}
}
pub fn new_with_acknowledgement(
pending_requests: Arc<Mutex<HashMap<RequestId, oneshot::Sender<R>>>>,
writable_tx: tokio::sync::mpsc::Sender<(
String,
tokio::sync::oneshot::Sender<crate::error::TransportResult<()>>,
)>,
request_timeout: Duration,
) -> Self {
Self {
pending_requests,
writable_tx: Some(writable_tx),
writable_std: None,
request_timeout,
}
}
async fn store_pending_request(
&self,
request_id: RequestId,
) -> tokio::sync::oneshot::Receiver<R> {
let (tx_response, rx_response) = oneshot::channel::<R>();
let mut pending_requests = self.pending_requests.lock().await;
// store request id in the hashmap while waiting for a matching response
pending_requests.insert(request_id.clone(), tx_response);
rx_response
}
async fn store_pending_request_for_message<M: McpMessage + RpcMessage>(
&self,
message: &M,
) -> Option<tokio::sync::oneshot::Receiver<R>> {
if message.is_request() {
if let Some(request_id) = message.request_id() {
Some(self.store_pending_request(request_id.clone()).await)
} else {
None
}
} else {
None
}
}
}
// Client side dispatcher
#[async_trait]
impl McpDispatch<ServerMessages, ClientMessages, ServerMessage, ClientMessage>
for MessageDispatcher<ServerMessage>
{
/// Sends a message from the client to the server and awaits a response if applicable.
///
/// Serializes the `ClientMessages` to JSON, writes it to the transport, and waits for a
/// `ServerMessages` response if the message is a request. Notifications and responses return
/// `Ok(None)`.
///
/// # Arguments
/// * `messages` - The client message to send, coulld be a single message or batch.
///
/// # Returns
/// A `TransportResult` containing `Some(ServerMessages)` for requests with a response,
/// or `None` for notifications/responses, or an error if the operation fails.
///
/// # Errors
/// Returns a `TransportError` if serialization, writing, or timeout occurs.
async fn send_message(
&self,
messages: ClientMessages,
request_timeout: Option<Duration>,
) -> TransportResult<Option<ServerMessages>> {
match messages {
ClientMessages::Single(message) => {
let rx_response: Option<tokio::sync::oneshot::Receiver<ServerMessage>> =
self.store_pending_request_for_message(&message).await;
//serialize the message and write it to the writable_std
let message_payload = serde_json::to_string(&message).map_err(|_| {
crate::error::TransportError::JsonrpcError(RpcError::parse_error())
})?;
self.write_str(message_payload.as_str(), true).await?;
if let Some(rx) = rx_response {
// Wait for the response with timeout
match await_timeout(rx, request_timeout.unwrap_or(self.request_timeout)).await {
Ok(response) => Ok(Some(ServerMessages::Single(response))),
Err(error) => match error {
TransportError::ChannelClosed(_) => {
Err(schema_utils::SdkError::connection_closed().into())
}
_ => Err(error),
},
}
} else {
Ok(None)
}
}
ClientMessages::Batch(client_messages) => {
let (request_ids, pending_tasks): (Vec<_>, Vec<_>) = client_messages
.iter()
.filter(|message| message.is_request())
.map(|message| {
(
message.request_id(),
self.store_pending_request_for_message(message),
)
})
.unzip();
// Ensure all request IDs are stored before sending the request
let tasks = join_all(pending_tasks).await;
// send the batch messages to the server
let message_payload = serde_json::to_string(&client_messages).map_err(|_| {
crate::error::TransportError::JsonrpcError(RpcError::parse_error())
})?;
self.write_str(message_payload.as_str(), true).await?;
// no request in the batch, no need to wait for the result
if request_ids.is_empty() {
return Ok(None);
}
let timeout_wrapped_futures = tasks.into_iter().filter_map(|rx| {
rx.map(|rx| await_timeout(rx, request_timeout.unwrap_or(self.request_timeout)))
});
let results: Vec<_> = join_all(timeout_wrapped_futures)
.await
.into_iter()
.zip(request_ids)
.map(|(res, request_id)| match res {
Ok(response) => response,
Err(error) => ServerMessage::Error(JsonrpcErrorResponse::new(
RpcError::internal_error().with_message(error.to_string()),
request_id.cloned(),
)),
})
.collect();
Ok(Some(ServerMessages::Batch(results)))
}
}
}
async fn send(
&self,
message: ClientMessage,
request_timeout: Option<Duration>,
) -> TransportResult<Option<ServerMessage>> {
let response = self.send_message(message.into(), request_timeout).await?;
match response {
Some(r) => Ok(Some(r.as_single()?)),
None => Ok(None),
}
}
/// Writes a string payload to the underlying asynchronous writable stream,
/// appending a newline character and flushing the stream afterward.
///
async fn write_str(&self, payload: &str, _skip_store: bool) -> TransportResult<()> {
if let Some(writable_std) = self.writable_std.as_ref() {
let mut writable_std = writable_std.lock().await;
writable_std.write_all(payload.as_bytes()).await?;
writable_std.write_all(b"\n").await?; // new line
writable_std.flush().await?;
return Ok(());
};
if let Some(writable_tx) = self.writable_tx.as_ref() {
let (resp_tx, resp_rx) = oneshot::channel();
writable_tx
.send((payload.to_string(), resp_tx))
.await
.map_err(|err| TransportError::Internal(format!("{err}")))?; // Send fails if channel closed
return resp_rx.await?; // Await the POST result; propagates the error if POST failed
}
Err(TransportError::Internal("Invalid dispatcher!".to_string()))
}
}
// Server side dispatcher, Sends S and Returns R
#[async_trait]
impl McpDispatch<ClientMessages, ServerMessages, ClientMessage, ServerMessage>
for MessageDispatcher<ClientMessage>
{
/// Sends a message from the server to the client and awaits a response if applicable.
///
/// Serializes the `ServerMessages` to JSON, writes it to the transport, and waits for a
/// `ClientMessages` response if the message is a request. Notifications and responses return
/// `Ok(None)`.
///
/// # Arguments
/// * `messages` - The client message to send, coulld be a single message or batch.
///
/// # Returns
/// A `TransportResult` containing `Some(ClientMessages)` for requests with a response,
/// or `None` for notifications/responses, or an error if the operation fails.
///
/// # Errors
/// Returns a `TransportError` if serialization, writing, or timeout occurs.
async fn send_message(
&self,
messages: ServerMessages,
request_timeout: Option<Duration>,
) -> TransportResult<Option<ClientMessages>> {
match messages {
ServerMessages::Single(message) => {
let rx_response: Option<tokio::sync::oneshot::Receiver<ClientMessage>> =
self.store_pending_request_for_message(&message).await;
let message_payload = serde_json::to_string(&message).map_err(|_| {
crate::error::TransportError::JsonrpcError(RpcError::parse_error())
})?;
self.write_str(message_payload.as_str(), false).await?;
if let Some(rx) = rx_response {
match await_timeout(rx, request_timeout.unwrap_or(self.request_timeout)).await {
Ok(response) => Ok(Some(ClientMessages::Single(response))),
Err(error) => Err(error),
}
} else {
Ok(None)
}
}
ServerMessages::Batch(server_messages) => {
let (request_ids, pending_tasks): (Vec<_>, Vec<_>) = server_messages
.iter()
.filter(|message| message.is_request())
.map(|message| {
(
message.request_id(),
self.store_pending_request_for_message(message),
)
})
.unzip();
// send the batch messages to the client
let message_payload = serde_json::to_string(&server_messages).map_err(|_| {
crate::error::TransportError::JsonrpcError(RpcError::parse_error())
})?;
self.write_str(message_payload.as_str(), false).await?;
// no request in the batch, no need to wait for the result
if pending_tasks.is_empty() {
return Ok(None);
}
let tasks = join_all(pending_tasks).await;
let timeout_wrapped_futures = tasks.into_iter().filter_map(|rx| {
rx.map(|rx| await_timeout(rx, request_timeout.unwrap_or(self.request_timeout)))
});
let results: Vec<_> = join_all(timeout_wrapped_futures)
.await
.into_iter()
.zip(request_ids)
.map(|(res, request_id)| match res {
Ok(response) => response,
Err(error) => ClientMessage::Error(JsonrpcErrorResponse::new(
RpcError::internal_error().with_message(error.to_string()),
request_id.cloned(),
)),
})
.collect();
Ok(Some(ClientMessages::Batch(results)))
}
}
}
async fn send(
&self,
message: ServerMessage,
request_timeout: Option<Duration>,
) -> TransportResult<Option<ClientMessage>> {
let response = self.send_message(message.into(), request_timeout).await?;
match response {
Some(r) => Ok(Some(r.as_single()?)),
None => Ok(None),
}
}
async fn write_str(&self, payload: &str, _skip_store: bool) -> TransportResult<()> {
if let Some(writable_std) = self.writable_std.as_ref() {
let mut writable_std = writable_std.lock().await;
writable_std.write_all(payload.as_bytes()).await?;
writable_std.write_all(b"\n").await?; // new line
writable_std.flush().await?;
return Ok(());
};
if let Some(writable_tx) = self.writable_tx.as_ref() {
let (resp_tx, resp_rx) = oneshot::channel();
writable_tx
.send((payload.to_string(), resp_tx))
.await
.map_err(|err| TransportError::Internal(err.to_string()))?; // Send fails if channel closed
return resp_rx.await?; // Await the POST result; propagates the error if POST failed
}
Err(TransportError::Internal("Invalid dispatcher!".to_string()))
}
}