1#[doc(hidden)]
5pub mod grpc;
6
7use super::AtlasClient;
8use crate::pb;
9use anyhow::{Context, Result, bail, ensure};
10use rmcp::ServiceExt;
11use serde_json::{Value, json};
12use std::any::Any;
13use std::collections::HashMap;
14use std::future::Future;
15use std::marker::PhantomData;
16use std::sync::{Arc, Mutex, Weak};
17use std::time::Duration;
18use tokio::sync::watch;
19use tokio::sync::{Mutex as AsyncMutex, OwnedSemaphorePermit, Semaphore};
20
21type McpClient = rmcp::service::RunningService<rmcp::RoleClient, ()>;
22
23pub trait ChannelContract: Clone + Send + Sync + 'static {
25 type Input: Send + 'static;
26 type Output: Send + 'static;
27 type StatusResponse: Send + 'static;
28 type CancelResponse: Send + 'static;
29
30 const TRANSPORT: pb::Transport;
31 const ID: &'static str = "";
33 const MODE: &'static str = "rpc";
34 const SERVICE: &'static str = "";
35 const METHOD: &'static str = "";
36 const IDL: &'static str = "";
37
38 fn matches_contract(contract: &pb::ContractDescriptor) -> bool {
39 Self::ID.is_empty() || contract.id == Self::ID
40 }
41
42 fn validate_companion(_contract: &pb::ContractDescriptor, _status: bool) -> Result<()> {
43 bail!("channel binding has no status/cancel contracts; regenerate its bindings")
44 }
45
46 fn validate_input(_request: &Self::Input) -> Result<()> {
47 Ok(())
48 }
49
50 fn invoke(
51 channel: Channel<Self>,
52 request: Self::Input,
53 ) -> impl Future<Output = Result<Self::Output>> + Send;
54
55 fn execution(_response: &Self::Output) -> Result<(bool, String)> {
56 Ok((true, String::new()))
57 }
58
59 fn status(
60 _channel: Channel<Self>,
61 ) -> impl Future<Output = Result<Self::StatusResponse>> + Send {
62 async { bail!("capability is synchronous") }
63 }
64
65 fn cancel(
66 _channel: Channel<Self>,
67 ) -> impl Future<Output = Result<Self::CancelResponse>> + Send {
68 async { bail!("capability is synchronous") }
69 }
70
71 fn status_state(_response: &Self::StatusResponse) -> Result<&str> {
72 bail!("capability is synchronous")
73 }
74}
75
76pub fn validate_contract<C: ChannelContract>(contract: &pb::ContractDescriptor) -> Result<()> {
77 ensure!(
78 C::matches_contract(contract),
79 "contract does not match channel binding: {}",
80 contract.id
81 );
82 ensure!(
83 contract.mode == C::MODE,
84 "contract mode does not match channel binding"
85 );
86 if !C::IDL.is_empty() {
87 ensure!(
88 contract.io_srv_type == C::IDL || contract.io_msg_type == C::IDL,
89 "contract IDL does not match channel binding"
90 );
91 }
92 Ok(())
93}
94
95#[derive(Clone)]
97pub struct Mcp;
98
99impl ChannelContract for Mcp {
100 type Input = Value;
101 type Output = Value;
102 type StatusResponse = Value;
103 type CancelResponse = Value;
104 const TRANSPORT: pb::Transport = pb::Transport::Mcp;
105
106 fn validate_companion(contract: &pb::ContractDescriptor, _status: bool) -> Result<()> {
107 validate_contract::<Self>(contract)
108 }
109
110 fn validate_input(request: &Value) -> Result<()> {
111 ensure!(request.is_object(), "request must be a JSON object");
112 Ok(())
113 }
114
115 async fn invoke(channel: Channel<Self>, request: Value) -> Result<Value> {
116 let response = channel.invoke_mcp(request).await?;
117 let (accepted, run_id) = Self::execution(&response)?;
118 channel.complete(accepted, run_id);
119 Ok(response)
120 }
121
122 fn execution(response: &Value) -> Result<(bool, String)> {
123 let run_id = match response.get("run_id") {
124 None | Some(Value::Null) => String::new(),
125 Some(Value::String(id)) => id.clone(),
126 _ => bail!("run_id must be a string"),
127 };
128 Ok((
129 response.get("accepted") != Some(&Value::Bool(false)),
130 run_id,
131 ))
132 }
133
134 async fn status(channel: Channel<Self>) -> Result<Value> {
135 channel
136 .companion_call::<Self>(true, |run_id| Ok(companion_request(run_id)))
137 .await
138 }
139
140 async fn cancel(channel: Channel<Self>) -> Result<Value> {
141 channel
142 .companion_call::<Self>(false, |run_id| Ok(companion_request(run_id)))
143 .await
144 }
145
146 fn status_state(response: &Value) -> Result<&str> {
147 response
148 .get("state")
149 .and_then(Value::as_str)
150 .context("status response missing state")
151 }
152}
153
154fn companion_request(run_id: String) -> Value {
155 if run_id.is_empty() {
156 json!({})
157 } else {
158 json!({"run_id": run_id})
159 }
160}
161
162pub(super) struct Channels {
164 live: Mutex<HashMap<String, Box<dyn Any + Send + Sync>>>,
166 capacity: Arc<Semaphore>,
168 companion_capacity: Arc<Semaphore>,
170}
171
172const DEFAULT_CHANNEL_LIMIT: usize = 1024;
174const COMPANION_SLOTS: usize = 2;
176
177fn channel_limit() -> usize {
178 let Ok(raw) = std::env::var("ROBONIX_ATLAS_CHANNEL_LIMIT") else {
179 return DEFAULT_CHANNEL_LIMIT;
180 };
181 match raw.trim().parse::<usize>() {
182 Ok(limit) if limit > COMPANION_SLOTS => limit,
183 _ => {
184 robonix_scribe::warn!(
185 "[atlas-client] ignoring ROBONIX_ATLAS_CHANNEL_LIMIT={raw:?}; \
186 expected an integer above {COMPANION_SLOTS}, using {DEFAULT_CHANNEL_LIMIT}"
187 );
188 DEFAULT_CHANNEL_LIMIT
189 }
190 }
191}
192
193impl Default for Channels {
194 fn default() -> Self {
195 Self {
196 live: Mutex::new(HashMap::new()),
197 capacity: Arc::new(Semaphore::new(channel_limit() - COMPANION_SLOTS)),
198 companion_capacity: Arc::new(Semaphore::new(COMPANION_SLOTS)),
199 }
200 }
201}
202
203#[derive(Clone)]
205pub struct Channel<C: ChannelContract = Mcp> {
206 contract: PhantomData<C>,
208 pub provider_id: String,
210 pub contract_id: String,
212 pub transport: pb::Transport,
214 pub endpoint: String,
216 pub channel_id: String,
218 pub params: pb::TransportParams,
220 execution: Arc<Execution>,
222}
223
224struct Execution {
226 atlas: pb::atlas_client::AtlasClient<tonic::transport::Channel>,
228 channels: Weak<Channels>,
230 consumer_id: String,
232 companions: Option<(String, String)>,
234 session: AsyncMutex<Option<McpClient>>,
236 grpc: AsyncMutex<Option<grpc::Binding>>,
238 stop_stream: watch::Sender<bool>,
240 close_lock: AsyncMutex<()>,
242 progress: Mutex<Progress>,
244}
245
246struct Progress {
248 started: bool,
250 run_id: Option<String>,
252 terminal: bool,
254 closed: bool,
256 closing: bool,
258 permit: Option<OwnedSemaphorePermit>,
260}
261
262impl AtlasClient {
263 pub fn connect_channel<'a, C: ChannelContract>(
265 &'a self,
266 consumer_id: &'a str,
267 provider_id: &'a str,
268 contract_id: &'a str,
269 transport: pb::Transport,
270 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Channel<C>>> + Send + 'a>> {
271 Box::pin(async move {
272 ensure!(
273 transport == C::TRANSPORT,
274 "transport does not match channel binding"
275 );
276 let atlas = self.clone();
277 let (consumer, provider, contract) = (
278 consumer_id.to_owned(),
279 provider_id.to_owned(),
280 contract_id.to_owned(),
281 );
282 let (sender, receiver) = tokio::sync::oneshot::channel();
284 let (acknowledge, received) = tokio::sync::oneshot::channel();
285 tokio::spawn(async move {
286 let result = atlas
287 .prepare_channel::<C>(consumer, provider, contract, transport)
288 .await;
289 let cleanup = result.as_ref().ok().cloned();
290 if sender.send(result).is_ok() && received.await.is_ok() {
291 return;
292 }
293 if let Some(channel) = cleanup
294 && let Err(error) = channel.close().await
295 {
296 robonix_scribe::warn!(
297 "[atlas-client] abandoned setup cleanup failed: {error:#}"
298 );
299 }
300 });
301 let result = receiver.await?;
302 let _ = acknowledge.send(());
303 result
304 })
305 }
306
307 pub fn get_channel<C: ChannelContract>(&self, channel_id: &str) -> Result<Option<Channel<C>>> {
309 self.channels
310 .live
311 .lock()
312 .unwrap()
313 .get(channel_id)
314 .map(|value| {
315 value
316 .downcast_ref::<Channel<C>>()
317 .cloned()
318 .context("channel binding does not match retained execution")
319 })
320 .transpose()
321 }
322
323 async fn prepare_channel<C: ChannelContract>(
324 mut self,
325 consumer: String,
326 provider: String,
327 contract: String,
328 transport: pb::Transport,
329 ) -> Result<Channel<C>> {
330 let companion = matches!(contract.rsplit('/').next(), Some("status" | "cancel"));
331 let permit = self.channels.capacity.clone()
332 .try_acquire_owned()
333 .or_else(|error| if companion {
334 self.channels.companion_capacity.clone().try_acquire_owned()
335 } else { Err(error) })
336 .context("Atlas client channel capacity exhausted (two slots reserved for companions); close existing channels or raise ROBONIX_ATLAS_CHANNEL_LIMIT")?;
337 let descriptor =
338 tokio::time::timeout(Duration::from_secs(30), self.query_contract(&contract))
339 .await
340 .context("Atlas contract query timed out")??
341 .with_context(|| format!("unknown contract: {contract}"))?;
342 ensure!(
343 descriptor.id == contract,
344 "Atlas returned a different contract"
345 );
346 validate_contract::<C>(&descriptor)?;
347 let companions = if descriptor.mode != "rpc"
348 || matches!(contract.rsplit('/').next(), Some("status" | "cancel"))
349 {
350 None
351 } else {
352 let providers = tokio::time::timeout(
353 Duration::from_secs(30),
354 self.query_capabilities(&provider, "", pb::Transport::Unspecified),
355 )
356 .await
357 .context("Atlas capability query timed out")??;
358 let available: Vec<_> = providers.iter().flat_map(|p| &p.capabilities).collect();
359 let status = format!("{contract}/status");
360 let cancel = format!("{contract}/cancel");
361 match (
362 available.iter().any(|c| c.contract_id == status),
363 available.iter().any(|c| c.contract_id == cancel),
364 ) {
365 (false, false) => None,
366 (true, true) => {
367 for cid in [&status, &cancel] {
368 ensure!(
369 available
370 .iter()
371 .any(|c| c.contract_id == *cid && c.transport == transport as i32),
372 "async companion {cid} must support {transport:?}"
373 );
374 let desc =
375 tokio::time::timeout(Duration::from_secs(30), self.query_contract(cid))
376 .await
377 .context("Atlas companion contract query timed out")??
378 .with_context(|| format!("unknown contract: {cid}"))?;
379 ensure!(desc.id == *cid, "Atlas returned a different contract");
380 C::validate_companion(&desc, cid == &status)?;
381 }
382 Some((status, cancel))
383 }
384 _ => bail!("async capability '{contract}' must declare both /status and /cancel"),
385 }
386 };
387 let (channel_id, endpoint, params) = tokio::time::timeout(
388 Duration::from_secs(30),
389 self.allocate_channel(&consumer, &provider, &contract, transport),
390 )
391 .await
392 .context("ConnectCapability allocation outcome unconfirmed after timeout")?
393 .context("ConnectCapability failed")?;
394 let ch = Channel {
395 contract: PhantomData,
396 provider_id: provider,
397 contract_id: contract,
398 transport,
399 endpoint,
400 channel_id,
401 params,
402 execution: Arc::new(Execution {
403 atlas: self.inner.clone(),
404 channels: Arc::downgrade(&self.channels),
405 consumer_id: consumer,
406 companions,
407 session: AsyncMutex::new(None),
408 grpc: AsyncMutex::new(None),
409 stop_stream: watch::channel(false).0,
410 close_lock: AsyncMutex::new(()),
411 progress: Mutex::new(Progress {
412 started: false,
413 run_id: None,
414 terminal: false,
415 closed: false,
416 closing: false,
417 permit: Some(permit),
418 }),
419 }),
420 };
421 let setup = async {
422 if transport == pb::Transport::Mcp {
423 *ch.execution.session.lock().await = Some(connect_mcp(&ch.endpoint).await?);
424 } else {
425 let binding =
426 grpc::Binding::connect::<C>(&ch.endpoint, &ch.params, &descriptor).await?;
427 *ch.execution.grpc.lock().await = Some(binding);
428 }
429 Ok::<_, anyhow::Error>(())
430 };
431 if let Err(error) = tokio::time::timeout(Duration::from_secs(30), setup)
432 .await
433 .context("channel initialization timed out")
434 .and_then(|r| r)
435 {
436 if let Err(cleanup) = ch.close().await {
437 self.channels
438 .live
439 .lock()
440 .unwrap()
441 .insert(ch.channel_id.clone(), Box::new(ch.clone()));
442 bail!("channel setup failed: {error:#}; cleanup failed: {cleanup:#}");
443 }
444 return Err(error);
445 }
446 self.channels
447 .live
448 .lock()
449 .unwrap()
450 .insert(ch.channel_id.clone(), Box::new(ch.clone()));
451 robonix_scribe::debug!("[atlas-client] prepared channel {}", ch.channel_id);
452 Ok(ch)
453 }
454}
455
456impl<C: ChannelContract> Channel<C> {
457 pub fn is_async(&self) -> bool {
458 self.execution.companions.is_some()
459 }
460
461 pub fn run_id(&self) -> Option<String> {
462 self.execution.progress.lock().unwrap().run_id.clone()
463 }
464
465 pub fn is_terminal(&self) -> bool {
466 self.execution.progress.lock().unwrap().terminal
467 }
468
469 pub fn is_closed(&self) -> bool {
470 self.execution.progress.lock().unwrap().closed
471 }
472
473 pub async fn call(&self, request: C::Input) -> Result<C::Output> {
475 C::validate_input(&request)?;
476 self.start()?;
477 let channel = self.clone();
478 tokio::spawn(async move {
479 C::invoke(channel.clone(), request)
480 .await
481 .map_err(|error| channel.retained(&format!("request failed: {error:#}")))
482 })
483 .await?
484 }
485
486 fn start(&self) -> Result<()> {
487 let mut p = self.execution.progress.lock().unwrap();
488 ensure!(
489 !p.started && !p.closing && !p.closed,
490 "a channel can execute only one capability call"
491 );
492 p.started = true;
493 Ok(())
494 }
495
496 fn complete(&self, accepted: bool, run_id: String) {
497 let mut progress = self.execution.progress.lock().unwrap();
498 if self.is_async() && !accepted {
499 progress.terminal = true;
500 return;
501 }
502 progress.run_id = Some(run_id);
503 progress.terminal = !self.is_async();
504 }
505
506 async fn invoke_mcp(&self, request: Value) -> Result<Value> {
507 let session = self.execution.session.lock().await;
508 let client = session.as_ref().context("MCP session unavailable")?;
509 let name = self
510 .contract_id
511 .rsplit('/')
512 .next()
513 .unwrap_or(&self.contract_id);
514 let result = client
515 .call_tool(
516 rmcp::model::CallToolRequestParams::new(name.to_owned())
517 .with_arguments(request.as_object().cloned().unwrap()),
518 )
519 .await
520 .context("MCP protocol error")?;
521 let text = result
522 .content
523 .iter()
524 .filter_map(|c| match &c.raw {
525 rmcp::model::RawContent::Text(t) => Some(t.text.as_str()),
526 _ => None,
527 })
528 .collect::<Vec<_>>()
529 .join("\n");
530 let rejected = result.is_error.unwrap_or(false);
531 if rejected || !self.is_async() {
533 self.execution.progress.lock().unwrap().terminal = true;
534 }
535 ensure!(!rejected, "MCP tool error: {text}");
536 let value = match result.structured_content {
537 Some(v) => {
538 if v.as_object().is_some_and(|object| object.len() == 1)
540 && let Some(inner) = v.get("result").filter(|inner| inner.is_object())
541 && let Ok(flat) = parse_tool_text(&text)
542 && &flat == inner
543 {
544 flat
545 } else {
546 v
547 }
548 }
549 None => parse_tool_text(&text).context("MCP result decoding failed")?,
550 };
551 ensure!(value.is_object(), "MCP response must be a JSON object");
552 Ok(value)
553 }
554
555 pub async fn status(&self) -> Result<C::StatusResponse> {
556 let channel = self.clone();
557 tokio::spawn(async move {
558 let response = C::status(channel.clone()).await?;
559 let state = C::status_state(&response)?;
560 let terminal = match state.to_ascii_uppercase().as_str() {
561 "SUCCEEDED" | "FAILED" | "CANCELED" | "CANCELLED" | "TIMEOUT" => true,
562 "PENDING" | "RUNNING" | "PAUSED" => false,
563 _ => return Err(channel.retained(&format!("unknown capability state: {state}"))),
564 };
565 channel.execution.progress.lock().unwrap().terminal |= terminal;
566 Ok(response)
567 })
568 .await?
569 }
570
571 pub async fn cancel(&self) -> Result<C::CancelResponse> {
572 let channel = self.clone();
573 tokio::spawn(async move { C::cancel(channel).await }).await?
574 }
575
576 #[doc(hidden)]
577 pub async fn companion_call<S: ChannelContract>(
578 &self,
579 status: bool,
580 request: impl FnOnce(String) -> Result<S::Input> + Send,
581 ) -> Result<S::Output> {
582 let run_id = {
583 let progress = self.execution.progress.lock().unwrap();
584 ensure!(!progress.closed, "channel already closed");
585 progress
586 .run_id
587 .clone()
588 .ok_or_else(|| self.retained("no confirmed async execution"))?
589 };
590 let (status_id, cancel_id) = self
591 .execution
592 .companions
593 .as_ref()
594 .context("capability is synchronous")?;
595 let cid = if status { status_id } else { cancel_id };
596 let request = request(run_id)
597 .map_err(|error| self.retained(&format!("invalid companion request: {error:#}")))?;
598 let atlas = AtlasClient {
599 inner: self.execution.atlas.clone(),
600 channels: self
601 .execution
602 .channels
603 .upgrade()
604 .context("Atlas client no longer available")?,
605 };
606 let channel = atlas
607 .connect_channel::<S>(
608 &self.execution.consumer_id,
609 &self.provider_id,
610 cid,
611 self.transport,
612 )
613 .await?;
614 let result = channel.call(request).await;
615 let cleanup = channel.close().await;
616 let response = result.map_err(|error| {
617 self.retained(&format!(
618 "companion failed: {error:#}; cleanup: {cleanup:?}"
619 ))
620 })?;
621 cleanup?;
622 Ok(response)
623 }
624
625 pub async fn close(&self) -> Result<()> {
627 self.close_with_timeout(Duration::from_secs(5)).await
628 }
629
630 pub fn close_with_timeout(
631 &self,
632 timeout: Duration,
633 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + '_>> {
634 Box::pin(async move {
635 {
636 let mut p = self.execution.progress.lock().unwrap();
637 if p.closed {
638 return Ok(());
639 }
640 p.closing = true;
641 }
642 let ch = self.clone();
643 tokio::spawn(async move {
644 let _closing = ch.execution.close_lock.lock().await;
645 if ch.execution.progress.lock().unwrap().closed {
646 return Ok(());
647 }
648 let result = ch.finish_close(timeout).await;
649 ch.execution.progress.lock().unwrap().closing = false;
650 result.map_err(|e| ch.retained(&format!("close failed: {e:#}")))
651 })
652 .await?
653 })
654 }
655
656 async fn finish_close(&self, timeout: Duration) -> Result<()> {
657 let active = {
658 let p = self.execution.progress.lock().unwrap();
659 p.started && !p.terminal
660 };
661 if active {
662 self.execution.stop_stream.send_replace(true);
663 tokio::time::timeout(timeout, async {
664 if self.is_async() {
665 self.cancel().await?;
666 }
667 loop {
668 if self.is_async() {
669 self.status().await?;
670 }
671 if self.is_terminal() {
672 return Ok::<_, anyhow::Error>(());
673 }
674 tokio::time::sleep(if self.is_async() {
675 Duration::from_secs(2)
676 } else {
677 Duration::from_millis(50)
678 })
679 .await;
680 }
681 })
682 .await
683 .context("timed out waiting for execution termination")??;
684 }
685 *self.execution.grpc.lock().await = None;
686 {
687 let mut session =
688 tokio::time::timeout(Duration::from_secs(5), self.execution.session.lock())
689 .await
690 .context("MCP session still in use during cleanup")?;
691 if let Some(client) = session.as_mut() {
692 client
693 .close_with_timeout(Duration::from_secs(5))
694 .await
695 .context("MCP session cleanup failed")?
696 .context("MCP session cleanup timed out")?;
697 }
698 *session = None;
699 }
700 let mut atlas = self.execution.atlas.clone();
701 tokio::time::timeout(
702 Duration::from_secs(5),
703 atlas.disconnect_capability(pb::DisconnectCapabilityRequest {
704 channel_id: self.channel_id.clone(),
705 }),
706 )
707 .await
708 .context("Atlas disconnect timed out")??;
709 let mut p = self.execution.progress.lock().unwrap();
710 p.closed = true;
711 p.permit.take();
712 if let Some(channels) = self.execution.channels.upgrade() {
713 channels.live.lock().unwrap().remove(&self.channel_id);
714 }
715 Ok(())
716 }
717
718 fn retained(&self, message: &str) -> anyhow::Error {
719 anyhow::anyhow!(
720 "{message}; channel {} retained; use get_channel() to recover",
721 self.channel_id
722 )
723 }
724}
725
726fn parse_tool_text(text: &str) -> serde_json::Result<Value> {
730 let mut json = String::with_capacity(text.len());
731 let (mut rest, mut in_string, mut escaped) = (text, false, false);
732 while let Some(c) = rest.chars().next() {
733 if !in_string
734 && let Some(token) = ["-Infinity", "Infinity", "NaN"]
735 .into_iter()
736 .find(|token| rest.starts_with(token))
737 {
738 json.push_str("null");
739 rest = &rest[token.len()..];
740 continue;
741 }
742 if in_string {
743 if escaped {
744 escaped = false;
745 } else if c == '\\' {
746 escaped = true;
747 } else if c == '"' {
748 in_string = false;
749 }
750 } else if c == '"' {
751 in_string = true;
752 }
753 json.push(c);
754 rest = &rest[c.len_utf8()..];
755 }
756 serde_json::from_str(&json)
757}
758
759async fn connect_mcp(endpoint: &str) -> Result<McpClient> {
760 let base = if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
761 endpoint.to_owned()
762 } else {
763 format!("http://{endpoint}")
764 };
765 let mut uri = reqwest::Url::parse(&base).context("invalid MCP endpoint")?;
766 if uri.path() == "/" {
767 uri.set_path("/mcp");
768 }
769 let config =
771 rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig::with_uri(
772 uri.as_str(),
773 )
774 .reinit_on_expired_session(false);
775 let http = reqwest::Client::builder().no_proxy().build()?;
776 ().serve(
777 rmcp::transport::streamable_http_client::StreamableHttpClientTransport::with_client(
778 http, config,
779 ),
780 )
781 .await
782 .context("MCP HTTP initialization failed")
783}
784
785#[cfg(test)]
786mod tests {
787 use super::*;
788
789 #[test]
790 fn tool_text_reads_non_finite_floats_as_null() {
791 let value = parse_tool_text(
792 r#"{"ranges": [0.5, Infinity, -Infinity, NaN], "note": "NaN \"Infinity\""}"#,
793 )
794 .unwrap();
795 assert_eq!(
796 value,
797 json!({"ranges": [0.5, null, null, null], "note": "NaN \"Infinity\""})
798 );
799 assert!(parse_tool_text("{\"x\": Inf}").is_err());
800 }
801}