1use futures::{
4 SinkExt, StreamExt,
5 channel::{mpsc, oneshot},
6 future::{self, BoxFuture, Either},
7};
8use schemars::JsonSchema;
9use serde::{Serialize, de::DeserializeOwned};
10use std::sync::{Arc, Mutex};
11
12use crate::{ConnectionTo, Error, Role, RunWithConnectionTo};
13
14use super::{McpConnectionTo, McpTool};
15
16struct ToolCall<P, R, MyRole: Role> {
17 params: P,
18 mcp_connection: McpConnectionTo<MyRole>,
19 result_tx: futures::channel::oneshot::Sender<Result<R, Error>>,
20 done_tx: oneshot::Sender<()>,
21}
22
23struct QueuedCall<P, R, MyRole: Role>(Arc<Mutex<Option<ToolCall<P, R, MyRole>>>>);
28
29impl<P, R, MyRole: Role> QueuedCall<P, R, MyRole> {
30 fn share(&self) -> Self {
31 Self(self.0.clone())
32 }
33
34 fn take(&self) -> Option<ToolCall<P, R, MyRole>> {
35 self.0.lock().unwrap().take()
36 }
37}
38
39impl<P, R, MyRole: Role> Drop for QueuedCall<P, R, MyRole> {
40 fn drop(&mut self) {
41 if let Some(ToolCall {
42 params,
43 mcp_connection,
44 result_tx,
45 done_tx,
46 }) = self.take()
47 {
48 drop(params);
51 drop(mcp_connection);
52 drop(result_tx);
53 let _finished = done_tx.send(());
54 }
55 }
56}
57
58struct CallResult<P, R, MyRole: Role> {
59 result_rx: oneshot::Receiver<Result<R, Error>>,
62 queued_call: QueuedCall<P, R, MyRole>,
63}
64
65async fn run_call<R>(
68 future: impl Future<Output = Result<R, Error>>,
69 mut result_tx: oneshot::Sender<Result<R, Error>>,
70 done_tx: oneshot::Sender<()>,
71) {
72 let result = {
73 let cancelled = result_tx.cancellation();
74 futures::pin_mut!(future, cancelled);
75 match future::select(cancelled, future).await {
76 Either::Left(_) => None,
77 Either::Right((result, _)) => Some(result),
78 }
79 };
80 if let Some(result) = result {
81 drop(result_tx.send(result));
83 }
84 let _finished = done_tx.send(());
85}
86
87type InvokeMut<F, P, R, Counterpart> = dyn for<'a> Fn(&'a mut F, P, McpConnectionTo<Counterpart>) -> BoxFuture<'a, Result<R, Error>>
88 + Send;
89
90struct ToolFnMutRunner<F, P, R, Counterpart: Role> {
91 func: F,
92 call_rx: mpsc::Receiver<QueuedCall<P, R, Counterpart>>,
93 tool_future_fn: Box<InvokeMut<F, P, R, Counterpart>>,
94}
95
96impl<F, P, R, Counterpart, Counterpart1> RunWithConnectionTo<Counterpart1>
97 for ToolFnMutRunner<F, P, R, Counterpart>
98where
99 Counterpart: Role,
100 Counterpart1: Role,
101 P: Send,
102 R: Send,
103 F: Send,
104{
105 async fn run_with_connection_to(
106 self,
107 _connection: ConnectionTo<Counterpart1>,
108 ) -> Result<(), Error> {
109 let ToolFnMutRunner {
110 mut func,
111 mut call_rx,
112 tool_future_fn,
113 } = self;
114 while let Some(queued_call) = call_rx.next().await {
115 let Some(ToolCall {
116 params,
117 mcp_connection,
118 result_tx,
119 done_tx,
120 }) = queued_call.take()
121 else {
122 continue;
123 };
124 if result_tx.is_canceled() {
125 drop(params);
126 drop(mcp_connection);
127 let _finished = done_tx.send(());
128 continue;
129 }
130 run_call(
131 tool_future_fn(&mut func, params, mcp_connection),
132 result_tx,
133 done_tx,
134 )
135 .await;
136 }
137 Ok(())
138 }
139}
140
141type Invoke<F, P, R, Counterpart> = dyn for<'a> Fn(&'a F, P, McpConnectionTo<Counterpart>) -> BoxFuture<'a, Result<R, Error>>
142 + Send
143 + Sync;
144
145struct ToolFnRunner<F, P, R, Counterpart: Role> {
146 func: F,
147 call_rx: mpsc::Receiver<QueuedCall<P, R, Counterpart>>,
148 tool_future_fn: Box<Invoke<F, P, R, Counterpart>>,
149}
150
151impl<F, P, R, Counterpart, Counterpart1> RunWithConnectionTo<Counterpart1>
152 for ToolFnRunner<F, P, R, Counterpart>
153where
154 Counterpart: Role,
155 Counterpart1: Role,
156 P: Send,
157 R: Send,
158 F: Send + Sync,
159{
160 async fn run_with_connection_to(
161 self,
162 _connection: ConnectionTo<Counterpart1>,
163 ) -> Result<(), Error> {
164 let ToolFnRunner {
165 func,
166 call_rx,
167 tool_future_fn,
168 } = self;
169 crate::util::process_stream_concurrently(
170 call_rx,
171 async |tool_call| {
172 fn hack<'a, F, P, R, MyRole>(
173 func: &'a F,
174 params: P,
175 mcp_connection: McpConnectionTo<MyRole>,
176 tool_future_fn: &'a Invoke<F, P, R, MyRole>,
177 result_tx: oneshot::Sender<Result<R, Error>>,
178 done_tx: oneshot::Sender<()>,
179 ) -> BoxFuture<'a, ()>
180 where
181 MyRole: Role,
182 P: Send,
183 R: Send,
184 F: Send + Sync,
185 {
186 Box::pin(async move {
187 if result_tx.is_canceled() {
188 drop(params);
189 drop(mcp_connection);
190 let _finished = done_tx.send(());
191 return;
192 }
193 run_call(
194 tool_future_fn(func, params, mcp_connection),
195 result_tx,
196 done_tx,
197 )
198 .await;
199 })
200 }
201
202 let Some(ToolCall {
203 params,
204 mcp_connection,
205 result_tx,
206 done_tx,
207 }) = tool_call.take()
208 else {
209 return Ok(());
210 };
211
212 hack(
213 &func,
214 params,
215 mcp_connection,
216 &*tool_future_fn,
217 result_tx,
218 done_tx,
219 )
220 .await;
221 Ok(())
222 },
223 |a, b| Box::pin(a(b)),
224 )
225 .await
226 }
227}
228
229struct ToolFnTool<P, Ret, R: Role> {
230 name: String,
231 description: String,
232 call_tx: mpsc::Sender<QueuedCall<P, Ret, R>>,
233}
234
235impl<P, Ret, R> McpTool<R> for ToolFnTool<P, Ret, R>
236where
237 R: Role,
238 P: JsonSchema + DeserializeOwned + 'static + Send,
239 Ret: JsonSchema + Serialize + 'static + Send,
240{
241 type Input = P;
242 type Output = Ret;
243
244 fn name(&self) -> String {
245 self.name.clone()
246 }
247
248 fn description(&self) -> String {
249 self.description.clone()
250 }
251
252 async fn call_tool(&self, params: P, mcp_connection: McpConnectionTo<R>) -> Result<Ret, Error> {
253 let (result_tx, result_rx) = oneshot::channel();
254 let (done_tx, done_rx) = oneshot::channel();
255 #[cfg(feature = "unstable_mcp_over_acp")]
256 mcp_connection.register_cleanup(done_rx);
257 #[cfg(not(feature = "unstable_mcp_over_acp"))]
258 let _done_rx = done_rx;
259
260 let mut call = CallResult {
261 result_rx,
262 queued_call: QueuedCall(Arc::new(Mutex::new(Some(ToolCall {
263 params,
264 mcp_connection,
265 result_tx,
266 done_tx,
267 })))),
268 };
269 self.call_tx
270 .clone()
271 .send(call.queued_call.share())
272 .await
273 .map_err(crate::util::internal_error)?;
274
275 (&mut call.result_rx)
276 .await
277 .map_err(crate::util::internal_error)?
278 }
279}
280
281pub fn tool_fn_mut<P, Ret, F, Counterpart>(
285 name: impl ToString,
286 description: impl ToString,
287 func: F,
288 tool_future_fn: impl for<'a> Fn(
289 &'a mut F,
290 P,
291 McpConnectionTo<Counterpart>,
292 ) -> BoxFuture<'a, Result<Ret, Error>>
293 + Send
294 + 'static,
295) -> (
296 impl McpTool<Counterpart> + 'static,
297 impl RunWithConnectionTo<Counterpart>,
298)
299where
300 Counterpart: Role,
301 P: JsonSchema + DeserializeOwned + 'static + Send,
302 Ret: JsonSchema + Serialize + 'static + Send,
303 F: AsyncFnMut(P, McpConnectionTo<Counterpart>) -> Result<Ret, Error> + Send,
304{
305 let (call_tx, call_rx) = mpsc::channel(128);
306 (
307 ToolFnTool {
308 name: name.to_string(),
309 description: description.to_string(),
310 call_tx,
311 },
312 ToolFnMutRunner {
313 func,
314 call_rx,
315 tool_future_fn: Box::new(tool_future_fn),
316 },
317 )
318}
319
320pub fn tool_fn<P, Ret, F, Counterpart>(
322 name: impl ToString,
323 description: impl ToString,
324 func: F,
325 tool_future_fn: impl for<'a> Fn(
326 &'a F,
327 P,
328 McpConnectionTo<Counterpart>,
329 ) -> BoxFuture<'a, Result<Ret, Error>>
330 + Send
331 + Sync
332 + 'static,
333) -> (
334 impl McpTool<Counterpart> + 'static,
335 impl RunWithConnectionTo<Counterpart>,
336)
337where
338 Counterpart: Role,
339 P: JsonSchema + DeserializeOwned + 'static + Send,
340 Ret: JsonSchema + Serialize + 'static + Send,
341 F: AsyncFn(P, McpConnectionTo<Counterpart>) -> Result<Ret, Error> + Send + Sync + 'static,
342{
343 let (call_tx, call_rx) = mpsc::channel(128);
344 (
345 ToolFnTool {
346 name: name.to_string(),
347 description: description.to_string(),
348 call_tx,
349 },
350 ToolFnRunner {
351 func,
352 call_rx,
353 tool_future_fn: Box::new(tool_future_fn),
354 },
355 )
356}
357
358#[cfg(test)]
359mod tests {
360 use std::{
361 pin::Pin,
362 sync::Mutex,
363 task::{Context, Poll},
364 };
365
366 use futures::FutureExt as _;
367
368 use super::*;
369 use crate::{Channel, mcp_server::McpConnectionContext, role::mcp};
370
371 type ResultReceiver = CallResult<u32, u32, mcp::Client>;
372
373 #[derive(Default)]
374 struct State {
375 entered: Mutex<Vec<u32>>,
376 dropped: Mutex<Vec<u32>>,
377 discard_result: Mutex<Option<ResultReceiver>>,
378 }
379
380 struct UserFuture<'a> {
382 state: &'a State,
383 id: u32,
384 }
385
386 impl Future for UserFuture<'_> {
387 type Output = Result<u32, Error>;
388
389 fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
390 if self.id == 0 {
391 Poll::Pending
392 } else {
393 drop(self.state.discard_result.lock().unwrap().take());
397 Poll::Ready(Ok(self.id))
398 }
399 }
400 }
401
402 impl Drop for UserFuture<'_> {
403 fn drop(&mut self) {
404 self.state.dropped.lock().unwrap().push(self.id);
405 }
406 }
407
408 #[derive(Clone, Copy)]
409 enum Mode {
410 Mutable,
411 Concurrent,
412 }
413
414 fn runner(
415 mode: Mode,
416 state: &State,
417 call_rx: mpsc::Receiver<QueuedCall<u32, u32, mcp::Client>>,
418 connection: ConnectionTo<mcp::Client>,
419 ) -> BoxFuture<'_, Result<(), Error>> {
420 match mode {
421 Mode::Mutable => Box::pin(
422 ToolFnMutRunner {
423 func: (state, Vec::<u32>::new()),
426 call_rx,
427 tool_future_fn: Box::new(|func, id, _connection| {
428 func.0.entered.lock().unwrap().push(id);
429 Box::pin(async move {
430 let result = UserFuture { state: func.0, id }.await;
431 func.1.push(id);
432 result
433 })
434 }),
435 }
436 .run_with_connection_to(connection),
437 ),
438 Mode::Concurrent => Box::pin(
439 ToolFnRunner {
440 func: state,
441 call_rx,
442 tool_future_fn: Box::new(|state, id, _connection| {
443 state.entered.lock().unwrap().push(id);
445 Box::pin(UserFuture { state, id })
446 }),
447 }
448 .run_with_connection_to(connection),
449 ),
450 }
451 }
452
453 async fn enqueue(
454 tool: &ToolFnTool<u32, u32, mcp::Client>,
455 id: u32,
456 connection: &McpConnectionTo<mcp::Client>,
457 ) -> ResultReceiver {
458 let (result_tx, result_rx) = oneshot::channel();
459 let (done_tx, done_rx) = oneshot::channel();
460 drop(done_rx);
461 let call = CallResult {
462 result_rx,
463 queued_call: QueuedCall(Arc::new(Mutex::new(Some(ToolCall {
464 params: id,
465 mcp_connection: connection.clone(),
466 result_tx,
467 done_tx,
468 })))),
469 };
470 tool.call_tx
473 .clone()
474 .send(call.queued_call.share())
475 .await
476 .unwrap();
477 call
478 }
479
480 fn assert_pending(future: impl Future) {
481 assert!(future.now_or_never().is_none());
482 }
483
484 #[derive(Clone, Copy)]
485 enum Case {
486 Running,
487 Queued,
488 DeliveryRace,
489 ConcurrentProgress,
490 }
491
492 fn check(mode: Mode, case: Case) {
493 let (channel, _peer) = Channel::duplex();
494 futures::executor::block_on(mcp::Server.builder().connect_with(
495 channel,
496 async |connection| {
497 let context = McpConnectionTo {
498 context: McpConnectionContext::Standalone,
499 connection: connection.clone(),
500 #[cfg(feature = "unstable_mcp_over_acp")]
501 cleanup: None,
502 };
503 let state = State::default();
504 let (call_tx, call_rx) = mpsc::channel(128);
505 let tool = ToolFnTool {
506 name: "test".into(),
507 description: "test".into(),
508 call_tx,
509 };
510 let mut runner = runner(mode, &state, call_rx, connection);
511
512 match case {
513 Case::Running | Case::ConcurrentProgress => {
514 let mut first = Box::pin(tool.call_tool(0, context.clone()));
515 assert_pending(first.as_mut());
516 assert_pending(runner.as_mut());
517 assert_eq!(*state.entered.lock().unwrap(), [0]);
518 assert!(state.dropped.lock().unwrap().is_empty());
519
520 if matches!(case, Case::ConcurrentProgress) {
521 let mut next = enqueue(&tool, 1, &context).await;
522 assert_pending(runner.as_mut());
523 assert_eq!(next.result_rx.try_recv().unwrap().unwrap().unwrap(), 1);
524 assert_eq!(*state.dropped.lock().unwrap(), [1]);
527 }
528
529 drop(first);
530 assert_pending(runner.as_mut());
531 assert!(state.dropped.lock().unwrap().contains(&0));
532 }
533 Case::Queued => {
534 drop(enqueue(&tool, 2, &context).await);
535 assert!(state.entered.lock().unwrap().is_empty());
536
537 let first = enqueue(&tool, 0, &context).await;
538 assert_pending(runner.as_mut());
539 assert_eq!(*state.entered.lock().unwrap(), [0]);
540 assert!(state.dropped.lock().unwrap().is_empty());
541
542 let queued_context = context.clone();
546 #[cfg(feature = "unstable_mcp_over_acp")]
547 let queued_context = McpConnectionTo {
548 cleanup: Some(Arc::new(Mutex::new(Vec::new()))),
549 ..queued_context
550 };
551 let mut queued = Box::pin(tool.call_tool(3, queued_context.clone()));
552 assert_pending(queued.as_mut());
553 drop(queued);
554 #[cfg(feature = "unstable_mcp_over_acp")]
555 queued_context.wait_cleanup().now_or_never().unwrap();
556 assert_eq!(*state.entered.lock().unwrap(), [0]);
557 assert!(state.dropped.lock().unwrap().is_empty());
558 drop(first);
559 assert_pending(runner.as_mut());
560 assert_eq!(*state.entered.lock().unwrap(), [0]);
561 assert_eq!(*state.dropped.lock().unwrap(), [0]);
562 }
563 Case::DeliveryRace => {
564 let receiver = enqueue(&tool, 4, &context).await;
565 *state.discard_result.lock().unwrap() = Some(receiver);
566 assert_pending(runner.as_mut());
567 assert!(state.discard_result.lock().unwrap().is_none());
568 assert_eq!(*state.entered.lock().unwrap(), [4]);
569 assert_eq!(*state.dropped.lock().unwrap(), [4]);
570 }
571 }
572
573 let mut next = Box::pin(tool.call_tool(5, context));
575 assert_pending(next.as_mut());
576 assert_pending(runner.as_mut());
577 assert_eq!(next.now_or_never().unwrap().unwrap(), 5);
578 assert_eq!(state.entered.lock().unwrap().last(), Some(&5));
579 assert_eq!(state.dropped.lock().unwrap().last(), Some(&5));
580 drop(tool);
581 runner.now_or_never().unwrap().unwrap();
582 Ok(())
583 },
584 ))
585 .unwrap();
586 }
587
588 #[test]
589 fn mutable_running_cancellation_drops_user_future_and_allows_next_call() {
590 check(Mode::Mutable, Case::Running);
591 }
592
593 #[test]
594 fn concurrent_running_cancellation_drops_user_future_and_allows_next_call() {
595 check(Mode::Concurrent, Case::Running);
596 }
597
598 #[test]
599 fn mutable_cancelled_queued_calls_never_enter_closure() {
600 check(Mode::Mutable, Case::Queued);
601 }
602
603 #[test]
604 fn concurrent_cancelled_queued_calls_never_enter_closure() {
605 check(Mode::Concurrent, Case::Queued);
606 }
607
608 #[test]
609 fn mutable_failed_result_delivery_does_not_stop_runner() {
610 check(Mode::Mutable, Case::DeliveryRace);
611 }
612
613 #[test]
614 fn concurrent_failed_result_delivery_does_not_stop_runner() {
615 check(Mode::Concurrent, Case::DeliveryRace);
616 }
617
618 #[test]
619 fn concurrent_borrowed_futures_make_independent_progress() {
620 check(Mode::Concurrent, Case::ConcurrentProgress);
621 }
622
623 #[cfg(feature = "unstable_mcp_over_acp")]
624 #[derive(serde::Deserialize, JsonSchema)]
625 struct DropParams {
626 #[serde(skip)]
627 #[schemars(skip)]
628 on_drop: Option<Box<dyn FnOnce() + Send>>,
629 }
630
631 #[cfg(feature = "unstable_mcp_over_acp")]
632 impl Drop for DropParams {
633 fn drop(&mut self) {
634 if let Some(on_drop) = self.on_drop.take() {
635 on_drop();
636 }
637 }
638 }
639
640 #[cfg(feature = "unstable_mcp_over_acp")]
641 #[test]
642 fn cancellation_during_enqueue_destroys_payload_before_cleanup_ack() {
643 let (channel, _peer) = Channel::duplex();
644 futures::executor::block_on(mcp::Server.builder().connect_with(
645 channel,
646 async |connection| {
647 type QueueState = Mutex<Option<ToolCall<DropParams, u32, mcp::Client>>>;
648
649 let cleanup = Arc::new(Mutex::new(Vec::<oneshot::Receiver<()>>::new()));
650 let context = McpConnectionTo {
651 context: McpConnectionContext::Standalone,
652 connection,
653 cleanup: Some(cleanup.clone()),
654 };
655 let (call_tx, mut call_rx) = mpsc::channel(0);
658 let tool = ToolFnTool::<DropParams, u32, _> {
659 name: "test".into(),
660 description: "test".into(),
661 call_tx,
662 };
663 let dropped = Arc::new(Mutex::new(false));
664 let queue_state = Arc::new(Mutex::new(None::<std::sync::Weak<QueueState>>));
665 let params = DropParams {
666 on_drop: Some(Box::new({
667 let dropped = dropped.clone();
668 let cleanup = cleanup.clone();
669 let queue_state = queue_state.clone();
670 move || {
671 assert!(
672 cleanup.lock().unwrap()[0].try_recv().unwrap().is_none(),
673 "cleanup ack preceded queued params destructor"
674 );
675 let queue = queue_state
676 .lock()
677 .unwrap()
678 .as_ref()
679 .unwrap()
680 .upgrade()
681 .unwrap();
682 assert!(
683 queue.try_lock().is_ok(),
684 "params destructor ran under queue lock"
685 );
686 *dropped.lock().unwrap() = true;
687 }
688 })),
689 };
690 let mut call = Box::pin(tool.call_tool(params, context.clone()));
691 assert_pending(call.as_mut());
692 assert_eq!(cleanup.lock().unwrap().len(), 1);
693 let queued = call_rx.next().now_or_never().unwrap().unwrap();
694 *queue_state.lock().unwrap() = Some(Arc::downgrade(&queued.0));
695 drop(call);
698 assert!(*dropped.lock().unwrap());
699 assert!(
700 queued.take().is_none(),
701 "cancelled payload retained by queue"
702 );
703 assert_eq!(
704 Arc::strong_count(&cleanup),
705 2,
706 "queued host context survived cleanup acknowledgment"
707 );
708 context.wait_cleanup().now_or_never().unwrap();
709 Ok(())
710 },
711 ))
712 .unwrap();
713 }
714
715 #[test]
716 fn running_cleanup_ack_follows_actual_future_destructor() {
717 struct PendingUser {
718 done: Arc<Mutex<oneshot::Receiver<()>>>,
719 dropped: Arc<Mutex<bool>>,
720 }
721 impl Future for PendingUser {
722 type Output = Result<(), Error>;
723 fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
724 Poll::Pending
725 }
726 }
727 impl Drop for PendingUser {
728 fn drop(&mut self) {
729 assert!(self.done.lock().unwrap().try_recv().unwrap().is_none());
730 *self.dropped.lock().unwrap() = true;
731 }
732 }
733 let (result_tx, result_rx) = oneshot::channel();
734 let (done_tx, done_rx) = oneshot::channel();
735 let done = Arc::new(Mutex::new(done_rx));
736 let dropped = Arc::new(Mutex::new(false));
737 let mut call = Box::pin(run_call(
738 PendingUser {
739 done: done.clone(),
740 dropped: dropped.clone(),
741 },
742 result_tx,
743 done_tx,
744 ));
745 assert_pending(call.as_mut());
746 drop(result_rx);
747 call.now_or_never().unwrap();
748 assert!(*dropped.lock().unwrap());
749 assert_eq!(done.lock().unwrap().try_recv().unwrap(), Some(()));
750 }
751}