1use super::discovery::{
10 ListError, McpDiscoveryLimits, escape_for_display, list_pages, list_tools, unroutable_name,
11 within,
12};
13use super::parked::{McpCallOutcome, ParkedCallKind, ParkedMcpCall};
14use super::reconnect::{
15 DEFAULT_RETRY_TOOL_CALLS, is_auth_rejection, is_connection_closed, should_retry_mcp_operation,
16};
17use super::schema_limits::McpSchemaLimits;
18use super::task::{McpTaskConfig, TaskError};
19use super::{ConnectionFactory, RefreshConfig, should_refresh_connection};
20use adk_core::{
21 AdkError, ErrorCategory, ErrorComponent, ReadonlyContext, Result, Tool, ToolContext,
22 ToolEffect, Toolset,
23};
24use async_trait::async_trait;
25use base64::{Engine as _, engine::general_purpose::STANDARD};
26use futures::StreamExt;
27use rmcp::{
28 RoleClient, ServiceError,
29 model::{
30 CallToolRequest, CallToolRequestParams, CallToolResponse, CancelTaskParams,
31 CancelledNotification, CancelledNotificationParam, ClientRequest, CompletionContext,
32 CompletionInfo, ContentBlock, ErrorCode, GetPromptRequestParams, GetPromptResult,
33 GetTaskParams, GetTaskRequest, InputRequest, InputRequests, InputResponses,
34 PaginatedRequestParams, Prompt, ReadResourceRequestParams, RequestId, Resource,
35 ResourceContents, ResourceTemplate, ServerResult, SubscribeRequestParams, TaskPayload,
36 ToolAnnotations, UnsubscribeRequestParams, UpdateTaskParams, UpdateTaskRequest,
37 },
38 service::{Peer, PeerRequestOptions, RunningService},
39};
40use serde_json::{Value, json};
41use std::collections::{BTreeMap, BTreeSet, HashSet};
42use std::sync::Arc;
43use std::sync::atomic::{AtomicBool, Ordering};
44use std::time::{Duration, Instant};
45use tokio::sync::{Mutex, RwLock};
46use tracing::{debug, warn};
47
48type DynConnectionFactory<S> = Arc<dyn ConnectionFactory<S>>;
50
51type Connection<S> = Arc<RunningService<RoleClient, S>>;
54
55const DEFAULT_TOOL_LIST_CACHE_TTL: Duration = Duration::from_secs(60);
57
58const DEFAULT_CLOSE_TIMEOUT: Duration = Duration::from_secs(5);
61
62const CLOSE_POLL_INTERVAL: Duration = Duration::from_millis(10);
64
65const CLOSED_CODE: &str = "tool.mcp.closed";
67
68const NOT_RUN_CODE: &str = "tool.mcp.not_run";
71
72fn closed_error(toolset: &str) -> AdkError {
74 AdkError::new(
75 ErrorComponent::Tool,
76 ErrorCategory::Cancelled,
77 CLOSED_CODE,
78 format!(
79 "MCP toolset '{toolset}' is closed, so it sends nothing to its server; build a new \
80 McpToolset to connect again"
81 ),
82 )
83}
84
85struct SharedClient<S>
91where
92 S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
93{
94 current: RwLock<(Connection<S>, u64)>,
96 refresh: Mutex<()>,
99 closed: AtomicBool,
101 #[cfg(feature = "mcp-sampling")]
104 sampling_scopes: Arc<crate::sampling::SamplingScopes>,
105 elicitation_scopes: Arc<super::elicitation::ElicitationScopes>,
108}
109
110impl<S> SharedClient<S>
111where
112 S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
113{
114 fn new(client: RunningService<RoleClient, S>) -> Self {
115 #[cfg(feature = "mcp-sampling")]
116 let sampling_scopes = adk_client_handler(&client)
117 .map(super::elicitation::AdkClientHandler::sampling_scopes)
118 .unwrap_or_default();
119 let elicitation_scopes = adk_client_handler(&client)
120 .map(super::elicitation::AdkClientHandler::elicitation_scopes)
121 .unwrap_or_default();
122 Self {
123 current: RwLock::new((Arc::new(client), 0)),
124 refresh: Mutex::new(()),
125 closed: AtomicBool::new(false),
126 #[cfg(feature = "mcp-sampling")]
127 sampling_scopes,
128 elicitation_scopes,
129 }
130 }
131
132 async fn connection(&self) -> Connection<S> {
133 Arc::clone(&self.current.read().await.0)
134 }
135
136 async fn open_connection(&self, toolset: &str) -> Result<Connection<S>> {
138 if self.closed.load(Ordering::SeqCst) {
139 return Err(closed_error(toolset));
140 }
141 Ok(self.connection().await)
142 }
143
144 async fn connection_with_generation(&self) -> (Connection<S>, u64) {
146 let current = self.current.read().await;
147 (Arc::clone(¤t.0), current.1)
148 }
149
150 async fn live_connection(
156 &self,
157 toolset: &str,
158 factory: Option<&DynConnectionFactory<S>>,
159 subscriptions: &RwLock<BTreeSet<String>>,
160 ) -> Result<(Connection<S>, u64)> {
161 if self.closed.load(Ordering::SeqCst) {
162 return Err(closed_error(toolset));
163 }
164 let (connection, generation) = self.connection_with_generation().await;
165 if factory.is_none() || !is_connection_closed(&connection) {
166 return Ok((connection, generation));
167 }
168 debug!("MCP connection closed; reconnecting before the next request");
169 self.refresh(toolset, &connection, factory, subscriptions).await?;
170 Ok(self.connection_with_generation().await)
171 }
172
173 async fn refresh(
181 &self,
182 toolset: &str,
183 failed: &Connection<S>,
184 factory: Option<&DynConnectionFactory<S>>,
185 subscriptions: &RwLock<BTreeSet<String>>,
186 ) -> Result<bool> {
187 let Some(factory) = factory else {
188 return Ok(false);
189 };
190 let _refreshing = self.refresh.lock().await;
191 if self.closed.load(Ordering::SeqCst) {
192 return Err(closed_error(toolset));
193 }
194 if !Arc::ptr_eq(&self.current.read().await.0, failed) {
195 return Ok(true);
196 }
197
198 let new_client = factory
199 .create_connection()
200 .await
201 .map_err(|e| AdkError::tool(format!("Failed to refresh MCP connection: {e}")))?;
202 restore_subscriptions(&new_client, subscriptions).await?;
203 if let Some(handler) = adk_client_handler(&new_client) {
204 #[cfg(feature = "mcp-sampling")]
205 handler.share_sampling_scopes(Arc::clone(&self.sampling_scopes));
206 handler.share_elicitation_scopes(Arc::clone(&self.elicitation_scopes));
207 }
208
209 let mut current = self.current.write().await;
210 if self.closed.load(Ordering::SeqCst) {
214 return Err(closed_error(toolset));
215 }
216 current.0 = Arc::new(new_client);
217 current.1 += 1;
218 Ok(true)
219 }
220}
221
222#[derive(Default)]
224struct ToolListCache {
225 entry: Option<CachedToolList>,
226 invalidations: u64,
229}
230
231struct CachedToolList {
233 generation: u64,
235 list_changes: u64,
237 fetched_at: Instant,
238 tools: Vec<rmcp::model::Tool>,
239}
240
241fn adk_client_handler<S>(
243 connection: &RunningService<RoleClient, S>,
244) -> Option<&super::elicitation::AdkClientHandler>
245where
246 S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
247{
248 (connection.service() as &dyn std::any::Any)
249 .downcast_ref::<super::elicitation::AdkClientHandler>()
250}
251
252fn tool_list_changes<S>(connection: &RunningService<RoleClient, S>) -> u64
256where
257 S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
258{
259 adk_client_handler(connection)
260 .map_or(0, super::elicitation::AdkClientHandler::tool_list_changes)
261}
262
263enum CancelTarget {
265 Request(RequestId),
267 Task(String),
269}
270
271struct CancelOnDrop {
274 peer: Option<Peer<RoleClient>>,
275 target: CancelTarget,
276}
277
278impl CancelOnDrop {
279 fn disarm(mut self) {
280 self.peer = None;
281 }
282}
283
284impl Drop for CancelOnDrop {
285 fn drop(&mut self) {
286 let Some(peer) = self.peer.take() else {
287 return;
288 };
289 let Ok(runtime) = tokio::runtime::Handle::try_current() else {
291 return;
292 };
293 match &self.target {
294 CancelTarget::Request(request_id) => {
295 let request_id = request_id.clone();
296 runtime.spawn(async move {
297 let notification = CancelledNotification::new(CancelledNotificationParam::new(
298 Some(request_id.clone()),
299 Some("the client stopped waiting for this tools/call".to_string()),
300 ));
301 match tokio::time::timeout(
302 TASK_CANCEL_TIMEOUT,
303 peer.send_notification(notification.into()),
304 )
305 .await
306 {
307 Ok(Ok(())) => {
308 debug!(request.id = %request_id, "sent MCP tools/call cancellation")
309 }
310 Ok(Err(error)) => debug!(
311 request.id = %request_id,
312 error = %error,
313 "could not send MCP tools/call cancellation"
314 ),
315 Err(_) => debug!(
316 request.id = %request_id,
317 "MCP tools/call cancellation was not sent before the timeout"
318 ),
319 }
320 });
321 }
322 CancelTarget::Task(task_id) => {
323 let task_id = task_id.clone();
324 runtime.spawn(async move {
327 let cancel = peer.cancel_task(CancelTaskParams::new(&task_id));
328 match tokio::time::timeout(TASK_CANCEL_TIMEOUT, cancel).await {
329 Ok(Ok(())) => debug!(task_id, "cancelled MCP task of a dropped tools/call"),
330 Ok(Err(error)) if is_unknown_or_finished_task(&error) => {}
331 Ok(Err(error)) => warn!(
332 task_id,
333 error = %error,
334 "failed to cancel MCP task of a dropped tools/call"
335 ),
336 Err(_) => warn!(
337 task_id,
338 timeout_ms = TASK_CANCEL_TIMEOUT.as_millis(),
339 "MCP server did not acknowledge tasks/cancel for a dropped tools/call"
340 ),
341 }
342 });
343 }
344 }
345 }
346}
347
348async fn send_tool_call(
353 peer: &Peer<RoleClient>,
354 params: CallToolRequestParams,
355) -> std::result::Result<CallToolResponse, ServiceError> {
356 let handle = peer
357 .send_cancellable_request(
358 ClientRequest::CallToolRequest(CallToolRequest::new(params)),
359 PeerRequestOptions::no_options(),
360 )
361 .await?;
362 let cancel = CancelOnDrop {
363 peer: Some(handle.peer.clone()),
364 target: CancelTarget::Request(handle.id.clone()),
365 };
366 let response = handle.await_response().await;
367 cancel.disarm();
368 match response? {
369 ServerResult::CallToolResult(result) => Ok(CallToolResponse::Complete(result)),
370 ServerResult::InputRequiredResult(result) => Ok(CallToolResponse::InputRequired(result)),
371 ServerResult::CreateTaskResult(result) => Ok(CallToolResponse::Task(result)),
372 _ => Err(ServiceError::UnexpectedResponse),
373 }
374}
375
376const MAX_TASK_ID_BYTES: usize = 16 * 1024;
378
379const MAX_INPUT_REQUESTS_PER_ROUND: usize = 64;
381
382const MAX_CONCURRENT_TASK_CLEANUPS: usize = 16;
384
385const TASK_CANCEL_TIMEOUT: Duration = Duration::from_secs(2);
388
389fn is_unknown_or_finished_task(error: &rmcp::ServiceError) -> bool {
394 matches!(
395 error,
396 rmcp::ServiceError::McpError(error)
397 if error.code == ErrorCode::INVALID_PARAMS || error.code == ErrorCode::RESOURCE_NOT_FOUND
398 )
399}
400
401async fn restore_subscriptions<S: rmcp::service::Service<RoleClient>>(
402 client: &RunningService<RoleClient, S>,
403 subscriptions: &RwLock<BTreeSet<String>>,
404) -> Result<()> {
405 for uri in subscriptions.read().await.iter() {
406 #[allow(deprecated)]
408 client.subscribe(SubscribeRequestParams::new(uri.clone())).await.map_err(|error| {
409 AdkError::tool(format!("Failed to restore MCP resource subscription '{uri}': {error}"))
410 })?;
411 }
412 Ok(())
413}
414
415fn mcp_tool_effect(annotations: Option<&ToolAnnotations>) -> ToolEffect {
418 match annotations {
419 Some(hints) if hints.read_only_hint == Some(true) => ToolEffect::ReadOnly,
420 Some(hints) if hints.idempotent_hint == Some(true) => ToolEffect::Idempotent,
421 _ => ToolEffect::NonIdempotent,
422 }
423}
424
425const MAX_SERVER_ERROR_BYTES: usize = 8 * 1024;
427
428fn server_error_response(tool_name: &str, result: &rmcp::model::CallToolResult) -> Value {
436 let text: Vec<&str> = result
437 .content
438 .iter()
439 .filter_map(|content| content.as_text())
440 .map(|t| t.text.as_str())
441 .collect();
442 let mut detail = if !text.is_empty() {
443 text.join("\n")
444 } else if let Some(structured) = &result.structured_content {
445 structured.to_string()
447 } else {
448 format!("MCP tool '{tool_name}' reported an error without a message")
449 };
450 if detail.len() > MAX_SERVER_ERROR_BYTES {
451 detail.truncate(detail.floor_char_boundary(MAX_SERVER_ERROR_BYTES));
452 detail.push_str(" [truncated]");
453 }
454 json!({ "error": detail })
455}
456
457fn call_tool_result_to_adk_value(
460 result: &rmcp::model::CallToolResult,
461) -> std::result::Result<Value, String> {
462 let mut text_parts = Vec::new();
463 let mut inline_data = Vec::new();
464 let mut file_data = Vec::new();
465
466 for content in &result.content {
467 match content {
468 ContentBlock::Text(text) => text_parts.push(text.text.clone()),
469 ContentBlock::Image(image) => {
470 let data = STANDARD
471 .decode(&image.data)
472 .map_err(|error| format!("invalid MCP image base64: {error}"))?;
473 inline_data.push(json!({ "mime_type": image.mime_type, "data": data }));
474 }
475 ContentBlock::Audio(audio) => {
476 let data = STANDARD
477 .decode(&audio.data)
478 .map_err(|error| format!("invalid MCP audio base64: {error}"))?;
479 inline_data.push(json!({ "mime_type": audio.mime_type, "data": data }));
480 }
481 ContentBlock::Resource(resource) => match &resource.resource {
482 ResourceContents::TextResourceContents { uri, mime_type, text, .. } => {
483 text_parts.push(text.clone());
484 file_data.push(json!({
485 "mime_type": mime_type.as_deref().unwrap_or("text/plain"),
486 "file_uri": uri,
487 }));
488 }
489 ResourceContents::BlobResourceContents { uri, mime_type, blob, .. } => {
490 let data = STANDARD
491 .decode(blob)
492 .map_err(|error| format!("invalid MCP resource base64: {error}"))?;
493 inline_data.push(json!({
494 "mime_type": mime_type.as_deref().unwrap_or("application/octet-stream"),
495 "data": data,
496 }));
497 file_data.push(json!({
498 "mime_type": mime_type.as_deref().unwrap_or("application/octet-stream"),
499 "file_uri": uri,
500 }));
501 }
502 _ => return Err("unsupported MCP embedded resource content".to_string()),
503 },
504 ContentBlock::ResourceLink(link) => file_data.push(json!({
505 "mime_type": link.mime_type.as_deref().unwrap_or("application/octet-stream"),
506 "file_uri": link.uri,
507 })),
508 _ => {}
509 }
510 }
511
512 let output = match (&result.structured_content, text_parts.is_empty()) {
513 (Some(structured), true) => json!({ "output": structured }),
514 (Some(structured), false) => json!({ "output": structured, "text": text_parts }),
515 (None, false) => json!({ "output": text_parts.join("\n") }),
516 (None, true) if !inline_data.is_empty() || !file_data.is_empty() => Value::Null,
517 (None, true) => json!({ "output": "" }),
520 };
521
522 if inline_data.is_empty() && file_data.is_empty() {
523 Ok(output)
524 } else {
525 Ok(json!({
526 "response": output,
527 "inline_data": inline_data,
528 "file_data": file_data,
529 }))
530 }
531}
532
533pub type ToolFilter = Arc<dyn Fn(&str) -> bool + Send + Sync>;
535
536fn mcp_tool_call_error(
537 tool_name: &str,
538 error: &ServiceError,
539 has_connection_factory: bool,
540 replay_allowed: bool,
541) -> AdkError {
542 if has_connection_factory
543 && !replay_allowed
544 && should_refresh_connection(error)
545 && !is_auth_rejection(error)
546 {
547 AdkError::tool(format!(
548 "MCP tool '{tool_name}' result is uncertain and was not replayed: {error}. \
549 Enable tool-call retries only for replay-safe operations"
550 ))
551 } else {
552 AdkError::tool(format!("Failed to call MCP tool '{tool_name}': {error}"))
553 }
554}
555
556fn is_method_not_found(err: &rmcp::ServiceError) -> bool {
559 matches!(
560 err,
561 rmcp::ServiceError::McpError(e) if e.code == ErrorCode::METHOD_NOT_FOUND
562 )
563}
564
565pub struct McpToolset<S = ()>
600where
601 S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
602{
603 client: Arc<SharedClient<S>>,
605 tool_list: Arc<Mutex<ToolListCache>>,
607 tool_list_ttl: Duration,
609 tool_filter: Option<ToolFilter>,
611 name: String,
613 task_config: McpTaskConfig,
615 active_tasks: Arc<Mutex<BTreeSet<String>>>,
617 connection_factory: Option<DynConnectionFactory<S>>,
619 refresh_config: RefreshConfig,
621 retry_tool_calls: bool,
623 resource_subscriptions: Arc<RwLock<BTreeSet<String>>>,
625 mrtr_handler: Option<super::elicitation::AdkClientHandler>,
627 schema_limits: McpSchemaLimits,
629 discovery_limits: McpDiscoveryLimits,
631 close_timeout: Duration,
633}
634
635impl<S> Clone for McpToolset<S>
636where
637 S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
638{
639 fn clone(&self) -> Self {
640 Self {
641 client: Arc::clone(&self.client),
642 tool_list: Arc::clone(&self.tool_list),
643 tool_list_ttl: self.tool_list_ttl,
644 tool_filter: self.tool_filter.clone(),
645 name: self.name.clone(),
646 task_config: self.task_config.clone(),
647 active_tasks: self.active_tasks.clone(),
648 connection_factory: self.connection_factory.clone(),
649 refresh_config: self.refresh_config.clone(),
650 retry_tool_calls: self.retry_tool_calls,
651 resource_subscriptions: Arc::clone(&self.resource_subscriptions),
652 mrtr_handler: self.mrtr_handler.clone(),
653 schema_limits: self.schema_limits,
654 discovery_limits: self.discovery_limits,
655 close_timeout: self.close_timeout,
656 }
657 }
658}
659
660impl<S> McpToolset<S>
661where
662 S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
663{
664 pub fn new(client: RunningService<RoleClient, S>) -> Self {
687 let mrtr_handler = (client.service() as &dyn std::any::Any)
690 .downcast_ref::<super::elicitation::AdkClientHandler>()
691 .cloned();
692 Self {
693 client: Arc::new(SharedClient::new(client)),
694 tool_list: Arc::new(Mutex::new(ToolListCache::default())),
695 tool_list_ttl: DEFAULT_TOOL_LIST_CACHE_TTL,
696 tool_filter: None,
697 name: "mcp_toolset".to_string(),
698 task_config: McpTaskConfig::default(),
699 active_tasks: Arc::new(Mutex::new(BTreeSet::new())),
700 connection_factory: None,
701 refresh_config: RefreshConfig::default(),
702 retry_tool_calls: DEFAULT_RETRY_TOOL_CALLS,
703 resource_subscriptions: Arc::new(RwLock::new(BTreeSet::new())),
704 mrtr_handler,
705 schema_limits: McpSchemaLimits::default(),
706 discovery_limits: McpDiscoveryLimits::default(),
707 close_timeout: DEFAULT_CLOSE_TIMEOUT,
708 }
709 }
710
711 pub fn with_client_handler(client: RunningService<RoleClient, S>) -> Self {
725 Self::new(client)
726 }
727
728 #[cfg(feature = "mcp-sampling")]
747 pub fn with_sampling_scope(self, scope: adk_core::ModelCallScope) -> Self {
748 self.client.sampling_scopes.set_fallback(Some(scope));
749 self
750 }
751
752 pub fn with_elicitation_scope(self, scope: super::elicitation::ElicitationScope) -> Self {
770 self.client.elicitation_scopes.set_fallback(Some(scope));
771 self
772 }
773
774 pub fn with_name(mut self, name: impl Into<String>) -> Self {
776 self.name = name.into();
777 self
778 }
779
780 pub fn with_task_support(mut self, config: McpTaskConfig) -> Self {
816 self.task_config = config;
817 self
818 }
819
820 pub fn with_schema_limits(mut self, limits: McpSchemaLimits) -> Self {
840 self.schema_limits = limits;
841 self
842 }
843
844 pub fn with_discovery_limits(mut self, limits: McpDiscoveryLimits) -> Self {
865 self.discovery_limits = limits;
866 self
867 }
868
869 pub fn with_tool_list_cache_ttl(mut self, ttl: Duration) -> Self {
895 self.tool_list_ttl = ttl;
896 self
897 }
898
899 pub fn with_close_timeout(mut self, timeout: Duration) -> Self {
918 self.close_timeout = timeout;
919 self
920 }
921
922 pub async fn invalidate_tool_list_cache(&self) {
944 self.client.connection().await.peer().clear_response_cache().await;
946 let mut cache = self.tool_list.lock().await;
947 cache.invalidations += 1;
948 cache.entry = None;
949 }
950
951 pub(crate) fn with_mrtr_handler(
953 mut self,
954 handler: super::elicitation::AdkClientHandler,
955 ) -> Self {
956 self.mrtr_handler = Some(handler);
957 self
958 }
959
960 pub fn with_connection_factory<F>(mut self, factory: Arc<F>) -> Self
962 where
963 F: ConnectionFactory<S> + 'static,
964 {
965 self.connection_factory = Some(factory);
966 self
967 }
968
969 pub fn with_refresh_config(mut self, config: RefreshConfig) -> Self {
971 self.refresh_config = config;
972 self
973 }
974
975 pub fn with_tool_call_retries(mut self) -> Self {
991 self.retry_tool_calls = true;
992 self
993 }
994
995 pub fn with_filter<F>(mut self, filter: F) -> Self
1009 where
1010 F: Fn(&str) -> bool + Send + Sync + 'static,
1011 {
1012 self.tool_filter = Some(Arc::new(filter));
1013 self
1014 }
1015
1016 pub fn with_tools(self, tool_names: &[&str]) -> Self {
1025 let names: Vec<String> = tool_names.iter().map(|s| s.to_string()).collect();
1026 self.with_filter(move |name| names.iter().any(|n| n == name))
1027 }
1028
1029 pub async fn cancellation_token(&self) -> rmcp::service::RunningServiceCancellationToken {
1048 self.client.connection().await.cancellation_token()
1049 }
1050
1051 pub async fn is_closed(&self) -> bool {
1068 self.client.closed.load(Ordering::SeqCst)
1069 || is_connection_closed(&*self.client.connection().await)
1070 }
1071
1072 pub(crate) async fn close_within(&self, timeout: Duration) {
1081 let deadline = tokio::time::Instant::now() + timeout;
1082 if !self.client.closed.swap(true, Ordering::SeqCst) {
1083 match tokio::time::timeout(timeout / 2, self.cancel_pending_tasks()).await {
1084 Ok(Ok(())) => {}
1085 Ok(Err(error)) => warn!(
1086 toolset.name = %self.name,
1087 error = %error,
1088 "MCP tasks did not confirm cancellation before the toolset closed"
1089 ),
1090 Err(_) => warn!(
1091 toolset.name = %self.name,
1092 close.timeout_ms = timeout.as_millis(),
1093 "MCP task cancellation did not finish within half of the close timeout"
1094 ),
1095 }
1096 }
1097 let connection = Arc::clone(&self.client.current.write().await.0);
1100 connection.cancellation_token().cancel();
1101 let closed = tokio::time::timeout_at(deadline, async {
1103 while !connection.peer().is_transport_closed() {
1104 tokio::time::sleep(CLOSE_POLL_INTERVAL).await;
1105 }
1106 })
1107 .await;
1108 match closed {
1109 Ok(()) => debug!(toolset.name = %self.name, "closed MCP connection"),
1110 Err(_) => warn!(
1111 toolset.name = %self.name,
1112 close.timeout_ms = timeout.as_millis(),
1113 "MCP connection did not finish closing within the close timeout; its transport \
1114 keeps closing in the background"
1115 ),
1116 }
1117 }
1118
1119 pub async fn call_tool_value(
1127 &self,
1128 name: &str,
1129 arguments: serde_json::Map<String, Value>,
1130 ) -> Result<Value> {
1131 self.direct_tool(name).await?.execute_value(Value::Object(arguments), None).await
1132 }
1133
1134 pub async fn call_tool_resumable(
1172 &self,
1173 call_id: Option<&str>,
1174 name: &str,
1175 arguments: serde_json::Map<String, Value>,
1176 ) -> Result<McpCallOutcome> {
1177 let tool = self.direct_tool(name).await?;
1178 let params = tool.call_params(Value::Object(arguments))?;
1179 let spec = CallSpec {
1180 call_id: call_id.map(str::to_string),
1181 mode: InputMode::Park,
1182 input_rounds: 0,
1183 };
1184 tool.run(params, &spec).await
1185 }
1186
1187 pub async fn reissue(
1230 &self,
1231 parked: &ParkedMcpCall,
1232 responses: InputResponses,
1233 ) -> Result<McpCallOutcome> {
1234 let refused = |reason: String| {
1235 AdkError::new(
1236 ErrorComponent::Tool,
1237 ErrorCategory::InvalidInput,
1238 "tool.mcp.reissue_refused",
1239 format!(
1240 "parked call of MCP tool '{}' was not re-issued: {reason}",
1241 escape_for_display(&parked.tool_name)
1242 ),
1243 )
1244 };
1245 if parked.server_id != self.name {
1246 return Err(refused(format!(
1247 "it was made through toolset '{}', not '{}'; re-issue it on that server's toolset",
1248 parked.server_id, self.name
1249 )));
1250 }
1251 if !parked.is_intact() {
1252 return Err(refused(
1253 "its input requests do not match their digest, so the answers cannot be bound \
1254 to them"
1255 .to_string(),
1256 ));
1257 }
1258 if let Some(key) = responses.keys().find(|key| !parked.input_requests.contains_key(*key)) {
1259 return Err(refused(format!(
1260 "the answer '{}' has no input request of that key",
1261 escape_for_display(key)
1262 )));
1263 }
1264
1265 let mut tool = self.direct_tool(&parked.tool_name).await?;
1266 let mut params =
1267 tool.call_params(Value::Object(parked.arguments.clone().unwrap_or_default()))?;
1268 let spec = CallSpec {
1269 call_id: parked.call_id.clone(),
1270 mode: InputMode::Park,
1271 input_rounds: parked.input_rounds,
1272 };
1273 match &parked.kind {
1274 ParkedCallKind::Mrtr => {
1275 params.input_responses = (!responses.is_empty()).then_some(responses);
1276 params.request_state = parked.request_state.clone();
1277 tool.run(params, &spec).await
1278 }
1279 ParkedCallKind::Task { task_id } => {
1280 if !tool.task_config.enable_tasks || !tool.server_supports_tasks {
1281 return Err(refused(format!(
1282 "task '{}' needs task support on toolset '{}' and its server; build the \
1283 toolset with `McpToolset::with_task_support(McpTaskConfig::enabled())` \
1284 on a connection that declares the tasks extension",
1285 escape_for_display(task_id),
1286 self.name
1287 )));
1288 }
1289 let answered = parked
1292 .input_requests
1293 .iter()
1294 .filter_map(|(key, request)| {
1295 responses
1296 .get(key)
1297 .map(|answer| (key.clone(), (request.clone(), answer.clone())))
1298 })
1299 .collect();
1300 let peer = self.client.open_connection(&self.name).await?.peer().clone();
1301 let cancel_on_drop =
1302 CancelOnDrop { peer: Some(peer), target: CancelTarget::Task(task_id.clone()) };
1303 self.active_tasks.lock().await.insert(task_id.clone());
1304 let mut call = ParkedMcpCall::of_call(&self.name, ¶ms, spec.call_id.as_deref());
1305 call.input_rounds = parked.input_rounds;
1306 let outcome =
1307 tool.poll_task(task_id.clone(), None, spec.mode, call, answered).await;
1308 cancel_on_drop.disarm();
1309 outcome.map_err(|error| AdkError::tool(format!("Task execution failed: {error}")))
1310 }
1311 ParkedCallKind::Legacy => {
1312 let connection = self.client.open_connection(&self.name).await?;
1314 let listed = tokio::time::timeout(
1315 self.discovery_limits.timeout,
1316 list_tools(connection.peer(), self.discovery_limits.max_pages),
1317 )
1318 .await
1319 .map_err(|_| ListError::Timeout {
1320 method: "tools/list",
1321 timeout: self.discovery_limits.timeout,
1322 })
1323 .and_then(|listed| listed)
1324 .map_err(|error| {
1325 AdkError::tool(format!(
1326 "Failed to list MCP tools from '{}': {error}",
1327 self.name
1328 ))
1329 })?;
1330 tool.annotations = listed
1331 .into_iter()
1332 .find(|listed| listed.name == parked.tool_name)
1333 .and_then(|listed| listed.annotations);
1334 if !mcp_tool_effect(tool.annotations.as_ref()).is_retry_safe() {
1335 return Err(AdkError::new(
1336 ErrorComponent::Tool,
1337 ErrorCategory::Cancelled,
1338 NOT_RUN_CODE,
1339 format!(
1340 "MCP tool '{}' was not run: its call to server '{}' was lost with the \
1341 connection, and the tool declares neither readOnlyHint nor \
1342 idempotentHint, so running it again could repeat its effect",
1343 escape_for_display(&parked.tool_name),
1344 self.name
1345 ),
1346 ));
1347 }
1348 tool.run(params, &spec).await
1349 }
1350 }
1351 }
1352
1353 pub(crate) fn enter_call_scopes(&self, ctx: &dyn ToolContext) -> CallScopes {
1357 #[cfg(feature = "mcp-sampling")]
1358 let sampling = ctx
1359 .run_config()
1360 .map(|config| {
1361 adk_core::ModelCallScope::for_run(config, ctx.app_name(), ctx.agent_name())
1362 })
1363 .filter(|scope| !scope.is_unmetered())
1364 .map(|scope| self.client.sampling_scopes.enter(scope));
1365 CallScopes {
1366 #[cfg(feature = "mcp-sampling")]
1367 _sampling: sampling,
1368 _elicitation: self
1369 .client
1370 .elicitation_scopes
1371 .enter(super::elicitation::ElicitationScope::for_call(ctx)),
1372 }
1373 }
1374
1375 async fn direct_tool(&self, name: &str) -> Result<McpTool<S>> {
1379 if let Some(filter) = &self.tool_filter
1380 && !filter(name)
1381 {
1382 return Err(AdkError::tool(format!(
1383 "MCP tool '{}' is excluded by the tool filter of toolset '{}'",
1384 escape_for_display(name),
1385 self.name
1386 )));
1387 }
1388 let server_supports_tasks = self
1389 .client
1390 .open_connection(&self.name)
1391 .await?
1392 .peer_info()
1393 .is_some_and(|info| info.capabilities.supports_tasks());
1394 Ok(McpTool {
1395 name: name.into(),
1396 origin: format!("mcp:{}", self.name),
1397 description: String::new(),
1398 input_schema: None,
1399 output_schema: None,
1400 client: self.client.clone(),
1401 connection_factory: self.connection_factory.clone(),
1402 refresh_config: self.refresh_config.clone(),
1403 retry_tool_calls: self.retry_tool_calls,
1404 annotations: None,
1405 annotations_json: None,
1406 server_supports_tasks,
1407 task_config: self.task_config.clone(),
1408 active_tasks: self.active_tasks.clone(),
1409 mrtr_handler: self.mrtr_handler.clone(),
1410 resource_subscriptions: self.resource_subscriptions.clone(),
1411 #[cfg(feature = "mcp-apps")]
1413 ui: None,
1414 })
1415 }
1416
1417 pub async fn cancel_pending_tasks(&self) -> Result<()> {
1462 let ids: Vec<_> = self.active_tasks.lock().await.iter().cloned().collect();
1463 if ids.is_empty() {
1464 return Ok(());
1465 }
1466 let client = self.client.connection().await.peer().clone();
1467 let settled = |id: String| {
1468 let client = client.clone();
1469 async move {
1470 match client.get_task(GetTaskParams::new(&id)).await {
1471 Ok(status) if status.task.task.task_id != id => Err(AdkError::tool(format!(
1472 "MCP server answered tasks/get for task '{id}' with task '{}'",
1473 status.task.task.task_id
1474 ))),
1475 Ok(status) => Ok(status.task.status().is_terminal()),
1476 Err(error) if is_unknown_or_finished_task(&error) => Ok(true),
1477 Err(error) => Err(AdkError::tool(format!(
1478 "MCP task '{id}' status is unavailable: {error}"
1479 ))),
1480 }
1481 }
1482 };
1483 let results: Vec<Result<()>> = futures::stream::iter(ids)
1484 .map(|id| {
1485 let client = &client;
1486 let settled = &settled;
1487 async move {
1488 if !settled(id.clone()).await? {
1489 if let Err(error) = client.cancel_task(CancelTaskParams::new(&id)).await
1490 && !is_unknown_or_finished_task(&error)
1491 {
1492 return Err(AdkError::tool(format!(
1493 "MCP task '{id}' cancellation outcome is unknown: {error}"
1494 )));
1495 }
1496 if !settled(id.clone()).await? {
1497 return Err(AdkError::tool(format!(
1498 "MCP task '{id}' has not confirmed termination after tasks/cancel; \
1499 call cancel_pending_tasks again to re-check it"
1500 )));
1501 }
1502 }
1503 self.active_tasks.lock().await.remove(&id);
1504 Ok(())
1505 }
1506 })
1507 .buffer_unordered(MAX_CONCURRENT_TASK_CLEANUPS)
1508 .collect()
1509 .await;
1510 for result in results {
1511 result?;
1512 }
1513 Ok(())
1514 }
1515
1516 pub async fn list_resources(&self) -> Result<Vec<Resource>> {
1528 let client = self.client.open_connection(&self.name).await?;
1529 let limits = self.discovery_limits;
1530 let method = "resources/list";
1531 let listing = list_pages(method, limits.max_pages, |cursor| {
1532 let client = Arc::clone(&client);
1533 async move {
1534 let page = client
1535 .list_resources(Some(PaginatedRequestParams::default().with_cursor(cursor)))
1536 .await?;
1537 Ok((page.resources, page.next_cursor))
1538 }
1539 });
1540 match within(method, limits.timeout, listing).await {
1541 Ok(resources) => Ok(resources),
1542 Err(ListError::Service(error)) if is_method_not_found(&error) => Ok(Vec::new()),
1543 Err(error) => Err(AdkError::tool(format!(
1544 "Failed to list MCP resources from '{}': {error}",
1545 self.name
1546 ))),
1547 }
1548 }
1549
1550 pub async fn list_resource_templates(&self) -> Result<Vec<ResourceTemplate>> {
1562 let client = self.client.open_connection(&self.name).await?;
1563 let limits = self.discovery_limits;
1564 let method = "resources/templates/list";
1565 let listing = list_pages(method, limits.max_pages, |cursor| {
1566 let client = Arc::clone(&client);
1567 async move {
1568 let page = client
1569 .list_resource_templates(Some(
1570 PaginatedRequestParams::default().with_cursor(cursor),
1571 ))
1572 .await?;
1573 Ok((page.resource_templates, page.next_cursor))
1574 }
1575 });
1576 match within(method, limits.timeout, listing).await {
1577 Ok(templates) => Ok(templates),
1578 Err(ListError::Service(error)) if is_method_not_found(&error) => Ok(Vec::new()),
1579 Err(error) => Err(AdkError::tool(format!(
1580 "Failed to list MCP resource templates from '{}': {error}",
1581 self.name
1582 ))),
1583 }
1584 }
1585
1586 pub async fn read_resource(&self, uri: &str) -> Result<Vec<ResourceContents>> {
1597 let client = self.client.open_connection(&self.name).await?;
1598 let params = ReadResourceRequestParams::new(uri.to_string());
1599 match client.read_resource(params).await {
1600 Ok(result) => Ok(result.contents),
1601 Err(e) => {
1602 if is_method_not_found(&e) {
1603 Err(AdkError::tool(format!("resource not found: {uri}")))
1604 } else {
1605 Err(AdkError::tool(format!("Failed to read MCP resource '{uri}': {e}")))
1606 }
1607 }
1608 }
1609 }
1610
1611 #[cfg(feature = "mcp-apps")]
1628 pub async fn ui_bindings(&self) -> Result<Vec<super::apps::McpUiBinding>> {
1629 let listed = self.listed_tools().await?;
1630 Ok(listed.iter().filter_map(super::apps::McpUiBinding::of_tool).collect())
1631 }
1632
1633 #[cfg(feature = "mcp-apps")]
1650 pub async fn tool_visibility(&self) -> Result<Vec<(String, super::apps::McpUiVisibility)>> {
1651 let listed = self.listed_tools().await?;
1652 Ok(listed
1653 .iter()
1654 .map(|tool| (tool.name.to_string(), super::apps::McpUiVisibility::of_tool(tool)))
1655 .collect())
1656 }
1657
1658 #[cfg(feature = "mcp-apps")]
1660 async fn listed_tools(&self) -> Result<Vec<rmcp::model::Tool>> {
1661 let connection = self.client.open_connection(&self.name).await?;
1662 tokio::time::timeout(
1663 self.discovery_limits.timeout,
1664 list_tools(connection.peer(), self.discovery_limits.max_pages),
1665 )
1666 .await
1667 .map_err(|_| ListError::Timeout {
1668 method: "tools/list",
1669 timeout: self.discovery_limits.timeout,
1670 })
1671 .and_then(|listed| listed)
1672 .map_err(|error| {
1673 AdkError::tool(format!("Failed to list MCP tools from '{}': {error}", self.name))
1674 })
1675 }
1676
1677 #[cfg(feature = "mcp-apps")]
1692 pub async fn read_app(&self, uri: &str) -> Result<super::apps::McpAppResource> {
1693 if !uri.starts_with("ui://") {
1694 return Err(AdkError::tool(format!(
1695 "'{}' is not an MCP App resource: apps are ui:// resources",
1696 escape_for_display(uri)
1697 )));
1698 }
1699 let contents = self.read_resource(uri).await?;
1700 super::apps::McpAppResource::from_contents(uri, &contents)
1701 }
1702
1703 pub async fn list_prompts(&self) -> Result<Vec<Prompt>> {
1712 let client = self.client.open_connection(&self.name).await?;
1713 let limits = self.discovery_limits;
1714 let method = "prompts/list";
1715 let listing = list_pages(method, limits.max_pages, |cursor| {
1716 let client = Arc::clone(&client);
1717 async move {
1718 let page = client
1719 .list_prompts(Some(PaginatedRequestParams::default().with_cursor(cursor)))
1720 .await?;
1721 Ok((page.prompts, page.next_cursor))
1722 }
1723 });
1724 match within(method, limits.timeout, listing).await {
1725 Ok(prompts) => Ok(prompts),
1726 Err(ListError::Service(error)) if is_method_not_found(&error) => Ok(Vec::new()),
1727 Err(error) => Err(AdkError::tool(format!(
1728 "failed to list MCP prompts from '{}': {error}",
1729 self.name
1730 ))),
1731 }
1732 }
1733
1734 pub async fn get_prompt(
1736 &self,
1737 name: &str,
1738 arguments: Option<serde_json::Map<String, Value>>,
1739 ) -> Result<GetPromptResult> {
1740 let mut params = GetPromptRequestParams::new(name);
1741 if let Some(arguments) = arguments {
1742 params = params.with_arguments(arguments);
1743 }
1744 let client = self.client.open_connection(&self.name).await?;
1745 client
1746 .get_prompt(params)
1747 .await
1748 .map_err(|error| AdkError::tool(format!("failed to get MCP prompt '{name}': {error}")))
1749 }
1750
1751 pub async fn complete_prompt_argument(
1753 &self,
1754 prompt_name: &str,
1755 argument_name: &str,
1756 current_value: &str,
1757 context: Option<CompletionContext>,
1758 ) -> Result<CompletionInfo> {
1759 let client = self.client.open_connection(&self.name).await?;
1760 client
1761 .complete_prompt_argument(prompt_name, argument_name, current_value, context)
1762 .await
1763 .map_err(|error| {
1764 AdkError::tool(format!(
1765 "failed to complete MCP prompt argument '{argument_name}': {error}"
1766 ))
1767 })
1768 }
1769
1770 pub async fn complete_resource_argument(
1772 &self,
1773 uri_template: &str,
1774 argument_name: &str,
1775 current_value: &str,
1776 context: Option<CompletionContext>,
1777 ) -> Result<CompletionInfo> {
1778 let client = self.client.open_connection(&self.name).await?;
1779 client
1780 .complete_resource_argument(uri_template, argument_name, current_value, context)
1781 .await
1782 .map_err(|error| {
1783 AdkError::tool(format!(
1784 "failed to complete MCP resource argument '{argument_name}': {error}"
1785 ))
1786 })
1787 }
1788
1789 pub async fn subscribe_resource(&self, uri: &str) -> Result<()> {
1791 let client = self.client.open_connection(&self.name).await?;
1792 #[allow(deprecated)]
1796 client.subscribe(SubscribeRequestParams::new(uri)).await.map_err(|error| {
1797 AdkError::tool(format!("failed to subscribe to MCP resource '{uri}': {error}"))
1798 })?;
1799 self.resource_subscriptions.write().await.insert(uri.to_string());
1800 Ok(())
1801 }
1802
1803 pub async fn unsubscribe_resource(&self, uri: &str) -> Result<()> {
1805 let client = self.client.open_connection(&self.name).await?;
1806 #[allow(deprecated)]
1808 client.unsubscribe(UnsubscribeRequestParams::new(uri)).await.map_err(|error| {
1809 AdkError::tool(format!("failed to unsubscribe MCP resource '{uri}': {error}"))
1810 })?;
1811 self.resource_subscriptions.write().await.remove(uri);
1812 Ok(())
1813 }
1814}
1815
1816#[async_trait]
1817impl<S> Toolset for McpToolset<S>
1818where
1819 S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
1820{
1821 fn name(&self) -> &str {
1822 &self.name
1823 }
1824
1825 async fn tools(&self, _ctx: Arc<dyn ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>> {
1826 let limits = self.discovery_limits;
1827 let list_error = |error: ListError| {
1828 AdkError::tool(format!("Failed to list MCP tools from '{}': {error}", self.name))
1829 };
1830 let discovery = async {
1831 let (mut connection, mut generation) = self
1832 .client
1833 .live_connection(
1834 &self.name,
1835 self.connection_factory.as_ref(),
1836 &self.resource_subscriptions,
1837 )
1838 .await?;
1839 let mut list_changes = tool_list_changes(&connection);
1842 let (cached, invalidations) = {
1843 let cache = self.tool_list.lock().await;
1844 let cached = cache
1845 .entry
1846 .as_ref()
1847 .filter(|cached| {
1848 !self.tool_list_ttl.is_zero()
1849 && cached.generation == generation
1850 && cached.list_changes == list_changes
1851 && cached.fetched_at.elapsed() < self.tool_list_ttl
1852 })
1853 .map(|cached| cached.tools.clone());
1854 (cached, cache.invalidations)
1855 };
1856 if let Some(tools) = cached {
1857 return Ok((connection, tools));
1858 }
1859
1860 let mut attempt = 0u32;
1861 let has_connection_factory = self.connection_factory.is_some();
1862 let fetched = loop {
1863 let error = match list_tools(connection.peer(), limits.max_pages).await {
1864 Ok(tools) => break tools,
1865 Err(ListError::Service(error)) => error,
1866 Err(bound) => return Err(list_error(bound)),
1868 };
1869 if !should_retry_mcp_operation(
1870 &error,
1871 attempt,
1872 &self.refresh_config,
1873 has_connection_factory,
1874 true,
1875 ) {
1876 return Err(list_error(ListError::Service(error)));
1877 }
1878
1879 let retry_attempt = attempt + 1;
1880 if self.refresh_config.log_reconnections {
1881 warn!(
1882 attempt = retry_attempt,
1883 max_attempts = self.refresh_config.max_attempts,
1884 error = %error,
1885 "MCP tools/list failed; reconnecting and retrying"
1886 );
1887 }
1888
1889 if self.refresh_config.retry_delay_ms > 0 {
1890 tokio::time::sleep(tokio::time::Duration::from_millis(
1891 self.refresh_config.retry_delay_ms,
1892 ))
1893 .await;
1894 }
1895
1896 if !self
1897 .client
1898 .refresh(
1899 &self.name,
1900 &connection,
1901 self.connection_factory.as_ref(),
1902 &self.resource_subscriptions,
1903 )
1904 .await?
1905 {
1906 return Err(list_error(ListError::Service(error)));
1907 }
1908 (connection, generation) = self.client.connection_with_generation().await;
1909 list_changes = tool_list_changes(&connection);
1910 attempt += 1;
1911 };
1912 if !self.tool_list_ttl.is_zero() {
1913 let mut cache = self.tool_list.lock().await;
1914 if cache.invalidations == invalidations {
1915 cache.entry = Some(CachedToolList {
1916 generation,
1917 list_changes,
1918 fetched_at: Instant::now(),
1919 tools: fetched.clone(),
1920 });
1921 }
1922 }
1923 Ok::<_, AdkError>((connection, fetched))
1924 };
1925 let (connection, mcp_tools) = match tokio::time::timeout(limits.timeout, discovery).await {
1926 Ok(discovered) => discovered?,
1927 Err(_) => {
1928 return Err(list_error(ListError::Timeout {
1929 method: "tools/list",
1930 timeout: limits.timeout,
1931 }));
1932 }
1933 };
1934
1935 let mut tools: Vec<Arc<dyn Tool>> = Vec::new();
1937 let mut seen = HashSet::new();
1938 let server_supports_tasks =
1939 connection.peer_info().is_some_and(|info| info.capabilities.supports_tasks());
1940
1941 for mcp_tool in mcp_tools {
1942 let tool_name = mcp_tool.name.to_string();
1943
1944 if let Some(ref filter) = self.tool_filter
1946 && !filter(&tool_name)
1947 {
1948 continue;
1949 }
1950
1951 let logged_name = escape_for_display(&tool_name);
1953 if let Some(reason) = unroutable_name(&tool_name) {
1954 warn!(
1955 toolset.name = %self.name,
1956 tool.name = %logged_name,
1957 reason,
1958 "skipping MCP tool whose name no model provider can call"
1959 );
1960 continue;
1961 }
1962 #[cfg(feature = "mcp-apps")]
1965 let ui = super::apps::McpUiBinding::of_tool(&mcp_tool);
1966 #[cfg(feature = "mcp-apps")]
1967 if !super::apps::McpUiVisibility::of_tool(&mcp_tool).model {
1968 debug!(
1969 toolset.name = %self.name,
1970 tool.name = %logged_name,
1971 "leaving out an MCP tool only its app may call"
1972 );
1973 continue;
1974 }
1975 if !seen.insert(tool_name.clone()) {
1977 warn!(
1978 toolset.name = %self.name,
1979 tool.name = %logged_name,
1980 "skipping MCP tool that repeats the name of an earlier tool on the same \
1981 server; the first definition is kept"
1982 );
1983 continue;
1984 }
1985 let limits = self.schema_limits;
1987 let measured = limits
1988 .measure(&mcp_tool.input_schema)
1989 .map_err(|size| ("input", size))
1990 .and_then(|input| {
1991 mcp_tool
1992 .output_schema
1993 .as_deref()
1994 .map(|schema| limits.measure(schema))
1995 .transpose()
1996 .map(|output| (input, output))
1997 .map_err(|size| ("output", size))
1998 });
1999 let (input_size, output_size) = match measured {
2000 Ok(sizes) => sizes,
2001 Err((kind, size)) => {
2002 warn!(
2003 toolset.name = %self.name,
2004 tool.name = %logged_name,
2005 schema.kind = kind,
2006 schema.bytes = size.bytes,
2007 schema.nodes = size.nodes,
2008 schema.max_bytes = limits.max_bytes,
2009 schema.max_nodes = limits.max_nodes,
2010 "skipping MCP tool whose schema exceeds the size limits; \
2011 raise them with McpToolset::with_schema_limits if the server is trusted"
2012 );
2013 continue;
2014 }
2015 };
2016 debug!(
2017 toolset.name = %self.name,
2018 tool.name = %logged_name,
2019 schema.bytes = input_size.bytes,
2020 schema.nodes = input_size.nodes,
2021 output_schema.bytes = output_size.map(|size| size.bytes),
2022 output_schema.nodes = output_size.map(|size| size.nodes),
2023 "registering MCP tool"
2024 );
2025 let annotations_json =
2026 mcp_tool.annotations.as_ref().and_then(|hints| serde_json::to_value(hints).ok());
2027 let mut description = mcp_tool.description.map(|d| d.to_string()).unwrap_or_default();
2028 if let Some(kept) = limits.truncate_description(&description) {
2029 warn!(
2030 toolset.name = %self.name,
2031 tool.name = %logged_name,
2032 description.bytes = description.len(),
2033 description.max_bytes = limits.max_description_bytes,
2034 "truncating MCP tool description that exceeds the size limit; raise it with \
2035 McpSchemaLimits::with_max_description_bytes if the server is trusted"
2036 );
2037 description = kept.to_string();
2038 }
2039 let adk_tool = McpTool {
2040 name: tool_name,
2041 origin: format!("mcp:{}", self.name),
2042 description,
2043 input_schema: Some(Value::Object(Arc::unwrap_or_clone(mcp_tool.input_schema))),
2044 output_schema: mcp_tool
2045 .output_schema
2046 .map(|schema| Value::Object(Arc::unwrap_or_clone(schema))),
2047 client: self.client.clone(),
2048 connection_factory: self.connection_factory.clone(),
2049 refresh_config: self.refresh_config.clone(),
2050 retry_tool_calls: self.retry_tool_calls,
2051 annotations: mcp_tool.annotations,
2052 annotations_json,
2053 server_supports_tasks,
2054 task_config: self.task_config.clone(),
2055 active_tasks: self.active_tasks.clone(),
2056 mrtr_handler: self.mrtr_handler.clone(),
2057 resource_subscriptions: self.resource_subscriptions.clone(),
2058 #[cfg(feature = "mcp-apps")]
2059 ui,
2060 };
2061
2062 tools.push(Arc::new(adk_tool) as Arc<dyn Tool>);
2063 }
2064
2065 Ok(tools)
2066 }
2067
2068 async fn close(&self) {
2082 self.close_within(self.close_timeout).await;
2083 }
2084}
2085
2086impl McpToolset<super::elicitation::AdkClientHandler> {
2087 pub async fn with_elicitation_handler<T, E, A>(
2131 transport: T,
2132 handler: std::sync::Arc<dyn super::elicitation::ElicitationHandler>,
2133 ) -> Result<Self>
2134 where
2135 T: rmcp::transport::IntoTransport<rmcp::RoleClient, E, A> + Send + 'static,
2136 E: std::error::Error + Send + Sync + 'static,
2137 {
2138 use rmcp::ServiceExt;
2139 let adk_handler = super::elicitation::AdkClientHandler::new(handler);
2140 let client = adk_handler
2141 .serve(transport)
2142 .await
2143 .map_err(|e| AdkError::tool(format!("failed to connect MCP server: {e}")))?;
2144 Ok(Self::new(client))
2145 }
2146
2147 pub async fn with_handlers<T, E, A>(
2152 transport: T,
2153 elicitation_handler: std::sync::Arc<dyn super::elicitation::ElicitationHandler>,
2154 resource_notification_handler: std::sync::Arc<
2155 dyn super::resource_notifications::ResourceNotificationHandler,
2156 >,
2157 ) -> Result<Self>
2158 where
2159 T: rmcp::transport::IntoTransport<rmcp::RoleClient, E, A> + Send + 'static,
2160 E: std::error::Error + Send + Sync + 'static,
2161 {
2162 use rmcp::ServiceExt;
2163 let adk_handler = super::elicitation::AdkClientHandler::new(elicitation_handler)
2164 .with_resource_notification_handler(resource_notification_handler);
2165 let client = adk_handler
2166 .serve(transport)
2167 .await
2168 .map_err(|error| AdkError::tool(format!("failed to connect MCP server: {error}")))?;
2169 Ok(Self::new(client))
2170 }
2171
2172 #[cfg(feature = "mcp-sampling")]
2204 pub async fn with_sampling_handler<T, E, A>(
2205 transport: T,
2206 elicitation_handler: std::sync::Arc<dyn super::elicitation::ElicitationHandler>,
2207 sampling_handler: std::sync::Arc<dyn crate::sampling::SamplingHandler>,
2208 ) -> Result<Self>
2209 where
2210 T: rmcp::transport::IntoTransport<rmcp::RoleClient, E, A> + Send + 'static,
2211 E: std::error::Error + Send + Sync + 'static,
2212 {
2213 use rmcp::ServiceExt;
2214 let adk_handler = super::elicitation::AdkClientHandler::new(elicitation_handler)
2215 .with_sampling_handler(sampling_handler);
2216 let client = adk_handler
2217 .serve(transport)
2218 .await
2219 .map_err(|e| AdkError::tool(format!("failed to connect MCP server: {e}")))?;
2220 Ok(Self::new(client))
2221 }
2222
2223 #[cfg(feature = "mcp-sampling")]
2225 pub async fn with_sampling_and_resource_handlers<T, E, A>(
2226 transport: T,
2227 elicitation_handler: std::sync::Arc<dyn super::elicitation::ElicitationHandler>,
2228 sampling_handler: std::sync::Arc<dyn crate::sampling::SamplingHandler>,
2229 resource_notification_handler: std::sync::Arc<
2230 dyn super::resource_notifications::ResourceNotificationHandler,
2231 >,
2232 ) -> Result<Self>
2233 where
2234 T: rmcp::transport::IntoTransport<rmcp::RoleClient, E, A> + Send + 'static,
2235 E: std::error::Error + Send + Sync + 'static,
2236 {
2237 use rmcp::ServiceExt;
2238 let adk_handler = super::elicitation::AdkClientHandler::new(elicitation_handler)
2239 .with_sampling_handler(sampling_handler)
2240 .with_resource_notification_handler(resource_notification_handler);
2241 let client = adk_handler
2242 .serve(transport)
2243 .await
2244 .map_err(|error| AdkError::tool(format!("failed to connect MCP server: {error}")))?;
2245 Ok(Self::new(client))
2246 }
2247}
2248
2249#[derive(Clone, Copy, PartialEq, Eq)]
2251enum InputMode {
2252 Answer,
2254 Park,
2256}
2257
2258pub(crate) struct CallScopes {
2261 #[cfg(feature = "mcp-sampling")]
2262 _sampling: Option<crate::sampling::SamplingScopeGuard>,
2263 _elicitation: super::elicitation::ElicitationScopeGuard,
2264}
2265
2266struct CallSpec {
2268 call_id: Option<String>,
2270 mode: InputMode,
2271 input_rounds: usize,
2273}
2274
2275struct McpTool<S>
2279where
2280 S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
2281{
2282 name: String,
2283 origin: String,
2285 description: String,
2286 input_schema: Option<Value>,
2287 output_schema: Option<Value>,
2288 client: Arc<SharedClient<S>>,
2289 connection_factory: Option<DynConnectionFactory<S>>,
2290 refresh_config: RefreshConfig,
2291 retry_tool_calls: bool,
2292 annotations: Option<ToolAnnotations>,
2294 annotations_json: Option<Value>,
2296 server_supports_tasks: bool,
2298 task_config: McpTaskConfig,
2300 active_tasks: Arc<Mutex<BTreeSet<String>>>,
2301 resource_subscriptions: Arc<RwLock<BTreeSet<String>>>,
2302 mrtr_handler: Option<super::elicitation::AdkClientHandler>,
2304 #[cfg(feature = "mcp-apps")]
2306 ui: Option<super::apps::McpUiBinding>,
2307}
2308
2309impl<S> McpTool<S>
2310where
2311 S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
2312{
2313 fn toolset_name(&self) -> &str {
2315 self.origin.strip_prefix("mcp:").unwrap_or(&self.origin)
2316 }
2317
2318 async fn execute_value(&self, args: Value, call_id: Option<String>) -> Result<Value> {
2320 let params = self.call_params(args)?;
2321 let spec = CallSpec { call_id, mode: InputMode::Answer, input_rounds: 0 };
2322 match self.run(params, &spec).await? {
2323 McpCallOutcome::Completed(value) => Ok(value),
2324 McpCallOutcome::Parked(_) => Err(AdkError::tool(format!(
2325 "MCP tool '{}' parked a call whose input is answered in process",
2326 self.name
2327 ))),
2328 }
2329 }
2330
2331 fn call_params(&self, args: Value) -> Result<CallToolRequestParams> {
2333 let mut params = CallToolRequestParams::new(self.name.clone());
2334 if !(args.is_null() || args == json!({})) {
2335 match args {
2336 Value::Object(map) => params = params.with_arguments(map),
2337 _ => return Err(AdkError::tool("Tool arguments must be an object")),
2338 }
2339 }
2340 Ok(params)
2341 }
2342
2343 async fn run(&self, params: CallToolRequestParams, spec: &CallSpec) -> Result<McpCallOutcome> {
2345 let mut call =
2348 ParkedMcpCall::of_call(self.toolset_name(), ¶ms, spec.call_id.as_deref());
2349 let (response, peer, input_rounds) = self.call_tool_with_retry(params, spec).await?;
2350 call.input_rounds = input_rounds;
2351 let result = match response {
2352 CallToolResponse::Complete(result) => result,
2353 CallToolResponse::Task(created) => {
2354 let task_id = created.task.task_id.clone();
2355 if task_id.is_empty() || task_id.len() > MAX_TASK_ID_BYTES {
2356 return Err(AdkError::tool(format!(
2357 "MCP tool '{}' returned a task id of {} bytes; expected 1 to \
2358 {MAX_TASK_ID_BYTES}",
2359 self.name,
2360 task_id.len()
2361 )));
2362 }
2363 let cancel_on_drop =
2366 CancelOnDrop { peer: Some(peer), target: CancelTarget::Task(task_id.clone()) };
2367 self.active_tasks.lock().await.insert(task_id.clone());
2368 if !self.task_config.enable_tasks || !self.server_supports_tasks {
2369 self.cancel_task(&task_id).await;
2371 cancel_on_drop.disarm();
2372 let remedy = if self.task_config.enable_tasks {
2373 "the server did not negotiate the tasks capability"
2374 } else {
2375 "task support is disabled on this toolset; enable it with \
2376 `McpToolset::with_task_support(McpTaskConfig::enabled())`"
2377 };
2378 return Err(AdkError::tool(format!(
2379 "MCP tool '{}' returned task '{task_id}', which was cancelled because \
2380 {remedy}",
2381 self.name
2382 )));
2383 }
2384 debug!(tool = self.name, task_id, "MCP server materialized a task");
2385 let outcome = self
2386 .poll_task(
2387 task_id,
2388 created.task.poll_interval_ms,
2389 spec.mode,
2390 call,
2391 BTreeMap::new(),
2392 )
2393 .await;
2394 cancel_on_drop.disarm();
2395 return outcome
2396 .map_err(|error| AdkError::tool(format!("Task execution failed: {error}")));
2397 }
2398 CallToolResponse::InputRequired(required) if spec.mode == InputMode::Park => {
2400 return Ok(McpCallOutcome::Parked(call.waiting(
2401 ParkedCallKind::Mrtr,
2402 required.request_state,
2403 required.input_requests.unwrap_or_default(),
2404 input_rounds,
2405 )));
2406 }
2407 CallToolResponse::InputRequired(_) => {
2408 return Err(AdkError::tool(format!(
2409 "MCP tool '{}' returned an unresolved MRTR input request",
2410 self.name
2411 )));
2412 }
2413 response => {
2414 return Err(AdkError::tool(format!(
2415 "MCP tool '{}' returned an unsupported response: {response:?}",
2416 self.name
2417 )));
2418 }
2419 };
2420
2421 if result.is_error.unwrap_or(false) {
2422 debug!(tool = self.name, "MCP server answered the call with isError");
2423 return Ok(McpCallOutcome::Completed(server_error_response(&self.name, &result)));
2424 }
2425
2426 call_tool_result_to_adk_value(&result).map(McpCallOutcome::Completed).map_err(|error| {
2427 AdkError::tool(format!("MCP tool '{}' result invalid: {error}", self.name))
2428 })
2429 }
2430
2431 async fn call_tool_with_retry(
2442 &self,
2443 mut params: CallToolRequestParams,
2444 spec: &CallSpec,
2445 ) -> Result<(CallToolResponse, Peer<RoleClient>, usize)> {
2446 let has_connection_factory = self.connection_factory.is_some();
2447 let metadata_allows_replay = mcp_tool_effect(self.annotations.as_ref()).is_retry_safe();
2448 let replay_allowed = self.retry_tool_calls || metadata_allows_replay;
2449 let mut attempt = 0u32;
2450 let call = ParkedMcpCall::of_call(self.toolset_name(), ¶ms, spec.call_id.as_deref());
2451
2452 let mut input_rounds = spec.input_rounds;
2453 let mut state_only_rounds = 0u32;
2454 loop {
2455 let (connection, _) = self
2456 .client
2457 .live_connection(
2458 self.toolset_name(),
2459 self.connection_factory.as_ref(),
2460 &self.resource_subscriptions,
2461 )
2462 .await?;
2463 let in_flight = self.client.elicitation_scopes.enter_call(call.clone().waiting(
2465 ParkedCallKind::Legacy,
2466 None,
2467 InputRequests::new(),
2468 input_rounds,
2469 ));
2470 let call_result = send_tool_call(connection.peer(), params.clone()).await;
2471 drop(in_flight);
2472
2473 match call_result {
2474 Ok(CallToolResponse::InputRequired(mut required)) => {
2475 input_rounds += 1;
2476 if input_rounds > self.task_config.max_input_rounds {
2477 return Err(AdkError::tool(format!(
2478 "MCP tool '{}' exceeded {} MRTR input rounds",
2479 self.name, self.task_config.max_input_rounds
2480 )));
2481 }
2482 let requests =
2484 required.input_requests.take().filter(|requests| !requests.is_empty());
2485 if requests.is_none() && required.request_state.is_none() {
2486 return Err(AdkError::tool(format!(
2487 "MCP tool '{}' returned input_required with neither input requests \
2488 nor request state",
2489 self.name
2490 )));
2491 }
2492 let responses = match requests {
2493 Some(requests) if spec.mode == InputMode::Park => {
2494 required.input_requests = Some(requests);
2495 return Ok((
2496 CallToolResponse::InputRequired(required),
2497 connection.peer().clone(),
2498 input_rounds,
2499 ));
2500 }
2501 Some(requests) => {
2502 state_only_rounds = 0;
2503 let parked = call.clone().waiting(
2504 ParkedCallKind::Mrtr,
2505 required.request_state.clone(),
2506 requests.clone(),
2507 input_rounds,
2508 );
2509 parked.within(self.fulfill_input(requests)).await.map_err(|error| {
2510 AdkError::tool(format!(
2511 "MCP tool '{}' input request failed: {error}",
2512 self.name
2513 ))
2514 })?
2515 }
2516 None => {
2517 let delay_ms = (50u64 << state_only_rounds.min(3)).min(250);
2519 tokio::time::sleep(Duration::from_millis(delay_ms)).await;
2520 state_only_rounds += 1;
2521 InputResponses::new()
2522 }
2523 };
2524 params.input_responses = (!responses.is_empty()).then_some(responses);
2525 params.request_state = required.request_state;
2526 attempt = 0;
2527 }
2528 Ok(result) => return Ok((result, connection.peer().clone(), input_rounds)),
2529 Err(error) => {
2530 if !should_retry_mcp_operation(
2531 &error,
2532 attempt,
2533 &self.refresh_config,
2534 has_connection_factory,
2535 replay_allowed,
2536 ) {
2537 return Err(mcp_tool_call_error(
2538 &self.name,
2539 &error,
2540 has_connection_factory,
2541 replay_allowed,
2542 ));
2543 }
2544
2545 let retry_attempt = attempt + 1;
2546 if self.refresh_config.log_reconnections {
2547 warn!(
2548 tool = %self.name,
2549 attempt = retry_attempt,
2550 max_attempts = self.refresh_config.max_attempts,
2551 error = %error,
2552 "MCP call_tool failed; reconnecting and retrying"
2553 );
2554 }
2555
2556 if self.refresh_config.retry_delay_ms > 0 {
2557 tokio::time::sleep(tokio::time::Duration::from_millis(
2558 self.refresh_config.retry_delay_ms,
2559 ))
2560 .await;
2561 }
2562
2563 if !self
2564 .client
2565 .refresh(
2566 self.toolset_name(),
2567 &connection,
2568 self.connection_factory.as_ref(),
2569 &self.resource_subscriptions,
2570 )
2571 .await?
2572 {
2573 return Err(mcp_tool_call_error(
2574 &self.name,
2575 &error,
2576 has_connection_factory,
2577 replay_allowed,
2578 ));
2579 }
2580 attempt += 1;
2581 }
2582 }
2583 }
2584 }
2585
2586 async fn fulfill_input(
2588 &self,
2589 requests: InputRequests,
2590 ) -> std::result::Result<InputResponses, String> {
2591 if requests.is_empty() {
2592 return Err("the server sent an empty input request batch".to_string());
2593 }
2594 if requests.len() > MAX_INPUT_REQUESTS_PER_ROUND {
2595 return Err(format!(
2596 "the server sent {} input requests in one round; at most \
2597 {MAX_INPUT_REQUESTS_PER_ROUND} are accepted",
2598 requests.len()
2599 ));
2600 }
2601 match &self.mrtr_handler {
2602 Some(handler) => handler.fulfill_input_requests(requests).await,
2603 None => {
2604 let client = self.client.connection().await;
2605 super::input::fulfill(&client, requests).await
2606 }
2607 }
2608 }
2609
2610 async fn send_task_request(
2611 &self,
2612 request: ClientRequest,
2613 ) -> std::result::Result<ServerResult, TaskError> {
2614 let client = self.client.connection().await;
2615 client.send_request(request).await.map_err(|error| TaskError::PollFailed(error.to_string()))
2616 }
2617
2618 async fn update_task(
2620 &self,
2621 task_id: &str,
2622 responses: InputResponses,
2623 ) -> std::result::Result<(), TaskError> {
2624 let request = ClientRequest::UpdateTaskRequest(UpdateTaskRequest::new(
2625 UpdateTaskParams::new(task_id, responses),
2626 ));
2627 match self.send_task_request(request).await? {
2628 ServerResult::TaskAckResult(_) => Ok(()),
2629 response => Err(TaskError::PollFailed(format!(
2630 "tasks/update returned an unexpected response: {response:?}"
2631 ))),
2632 }
2633 }
2634
2635 async fn cancel_task(&self, task_id: &str) {
2638 let cancel = async {
2639 let peer = self.client.connection().await.peer().clone();
2640 peer.cancel_task(CancelTaskParams::new(task_id)).await
2641 };
2642 match tokio::time::timeout(TASK_CANCEL_TIMEOUT, cancel).await {
2643 Ok(Ok(())) => {}
2644 Ok(Err(error)) if is_unknown_or_finished_task(&error) => {}
2646 Ok(Err(error)) => warn!(task_id, error = %error, "failed to cancel MCP task"),
2647 Err(_) => warn!(
2648 task_id,
2649 timeout_ms = TASK_CANCEL_TIMEOUT.as_millis(),
2650 "MCP server did not acknowledge tasks/cancel"
2651 ),
2652 }
2653 }
2654
2655 async fn poll_task(
2661 &self,
2662 task_id: String,
2663 poll_interval_ms: Option<u64>,
2664 mode: InputMode,
2665 call: ParkedMcpCall,
2666 mut answered: BTreeMap<String, (InputRequest, Value)>,
2667 ) -> std::result::Result<McpCallOutcome, TaskError> {
2668 let mut poll_interval_ms =
2669 poll_interval_ms.unwrap_or(self.task_config.poll_interval_ms).max(1);
2670 let start = Instant::now();
2671 let mut attempts = 0u32;
2672 let mut input_rounds = call.input_rounds;
2673
2674 loop {
2675 if let Some(timeout_ms) = self.task_config.timeout_ms {
2676 let elapsed = start.elapsed().as_millis() as u64;
2677 if elapsed >= timeout_ms {
2678 self.cancel_task(&task_id).await;
2679 return Err(TaskError::Timeout { task_id, elapsed_ms: elapsed });
2680 }
2681 }
2682
2683 if let Some(max_attempts) = self.task_config.max_poll_attempts
2684 && attempts >= max_attempts
2685 {
2686 self.cancel_task(&task_id).await;
2687 return Err(TaskError::MaxAttemptsExceeded { task_id, attempts });
2688 }
2689
2690 tokio::time::sleep(tokio::time::Duration::from_millis(poll_interval_ms)).await;
2691 attempts += 1;
2692
2693 debug!(task_id, attempt = attempts, "polling MCP task status");
2694 let request =
2695 ClientRequest::GetTaskRequest(GetTaskRequest::new(GetTaskParams::new(&task_id)));
2696 let detailed = match self.send_task_request(request).await? {
2697 ServerResult::GetTaskResult(result) => result.task,
2698 response => {
2699 return Err(TaskError::PollFailed(format!(
2700 "tasks/get returned an unexpected response: {response:?}"
2701 )));
2702 }
2703 };
2704 let (task, payload) = (detailed.task, detailed.payload);
2705 if task.task_id != task_id {
2706 return Err(TaskError::PollFailed("MCP task identity changed".into()));
2707 }
2708 if task.status.is_terminal() {
2709 self.active_tasks.lock().await.remove(&task_id);
2710 }
2711 poll_interval_ms = task.poll_interval_ms.unwrap_or(poll_interval_ms).max(1);
2712
2713 match payload {
2714 TaskPayload::Completed { result } => {
2717 debug!(task_id, "MCP task completed successfully");
2718 let call_result: rmcp::model::CallToolResult =
2719 serde_json::from_value(Value::Object(result)).map_err(|error| {
2720 TaskError::PollFailed(format!(
2721 "tasks/get returned a result that is not a CallToolResult: {error}"
2722 ))
2723 })?;
2724 if call_result.is_error == Some(true) {
2725 debug!(task_id, "MCP task completed with an isError result");
2726 return Ok(McpCallOutcome::Completed(server_error_response(
2727 &self.name,
2728 &call_result,
2729 )));
2730 }
2731 return call_tool_result_to_adk_value(&call_result)
2732 .map(McpCallOutcome::Completed)
2733 .map_err(TaskError::PollFailed);
2734 }
2735 TaskPayload::Failed { error } => {
2736 return Err(TaskError::TaskFailed {
2737 task_id,
2738 error: task
2739 .status_message
2740 .unwrap_or_else(|| Value::Object(error).to_string()),
2741 });
2742 }
2743 TaskPayload::Cancelled => {
2744 return Err(TaskError::Cancelled(task_id));
2745 }
2746 TaskPayload::InputRequired { input_requests } => {
2747 if input_requests.is_empty() {
2748 return Err(TaskError::PollFailed(format!(
2749 "task '{task_id}' reported input_required without any input requests"
2750 )));
2751 }
2752 let mut pending = InputRequests::new();
2753 let mut responses = InputResponses::new();
2754 for (key, request) in &input_requests {
2755 if let Some((previous, response)) = answered.get(key) {
2756 if previous != request {
2757 return Err(TaskError::PollFailed(format!(
2758 "task '{task_id}' changed input request '{key}' after it \
2759 was answered"
2760 )));
2761 }
2762 responses.insert(key.clone(), response.clone());
2763 } else {
2764 pending.insert(key.clone(), request.clone());
2765 }
2766 }
2767 if !pending.is_empty() {
2769 input_rounds += 1;
2770 if input_rounds > self.task_config.max_input_rounds {
2771 return Err(TaskError::PollFailed(format!(
2772 "task '{task_id}' exceeded {} input rounds",
2773 self.task_config.max_input_rounds
2774 )));
2775 }
2776 let kind = ParkedCallKind::Task { task_id: task_id.clone() };
2777 let parked =
2778 call.clone().waiting(kind, None, pending.clone(), input_rounds);
2779 if mode == InputMode::Park {
2780 if !responses.is_empty() {
2781 self.update_task(&task_id, responses).await?;
2782 }
2783 self.active_tasks.lock().await.remove(&task_id);
2786 return Ok(McpCallOutcome::Parked(parked));
2787 }
2788 let received = parked
2789 .within(self.fulfill_input(pending))
2790 .await
2791 .map_err(TaskError::PollFailed)?;
2792 for (key, response) in received {
2793 answered.insert(
2794 key.clone(),
2795 (input_requests[&key].clone(), response.clone()),
2796 );
2797 responses.insert(key, response);
2798 }
2799 }
2800 self.update_task(&task_id, responses).await?;
2801 }
2802 TaskPayload::Working => {
2803 debug!(task_id, "MCP task is still working");
2804 answered.clear();
2806 }
2807 _ => {
2808 return Err(TaskError::PollFailed(
2809 "server returned an unsupported MCP task status".to_string(),
2810 ));
2811 }
2812 }
2813 }
2814 }
2815}
2816
2817#[async_trait]
2818impl<S> Tool for McpTool<S>
2819where
2820 S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
2821{
2822 fn name(&self) -> &str {
2823 &self.name
2824 }
2825
2826 fn description(&self) -> &str {
2827 &self.description
2828 }
2829
2830 fn is_long_running(&self) -> bool {
2834 self.task_config.enable_tasks && self.server_supports_tasks
2835 }
2836
2837 fn is_read_only(&self) -> bool {
2838 mcp_tool_effect(self.annotations.as_ref()) == ToolEffect::ReadOnly
2839 }
2840
2841 fn is_concurrency_safe(&self) -> bool {
2842 mcp_tool_effect(self.annotations.as_ref()).is_retry_safe()
2843 }
2844
2845 fn effect(&self) -> ToolEffect {
2846 mcp_tool_effect(self.annotations.as_ref())
2847 }
2848
2849 fn annotations(&self) -> Option<&Value> {
2850 self.annotations_json.as_ref()
2851 }
2852
2853 fn origin(&self) -> &str {
2854 &self.origin
2855 }
2856
2857 fn parameters_schema(&self) -> Option<Value> {
2858 self.input_schema.clone()
2859 }
2860
2861 fn response_schema(&self) -> Option<Value> {
2862 self.output_schema.clone()
2863 }
2864
2865 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
2866 #[cfg(feature = "mcp-sampling")]
2868 let _sampling_scope = ctx
2869 .run_config()
2870 .map(|config| {
2871 adk_core::ModelCallScope::for_run(config, ctx.app_name(), ctx.agent_name())
2872 })
2873 .filter(|scope| !scope.is_unmetered())
2874 .map(|scope| self.client.sampling_scopes.enter(scope));
2875 let _elicitation_scope = self
2878 .client
2879 .elicitation_scopes
2880 .enter(super::elicitation::ElicitationScope::for_call(ctx.as_ref()));
2881 let call_id = Some(ctx.function_call_id().to_string()).filter(|id| !id.is_empty());
2882 #[cfg(feature = "mcp-apps")]
2883 let record =
2884 self.ui.as_ref().zip(call_id.clone()).map(|(ui, call_id)| super::apps::McpAppRecord {
2885 server: self.toolset_name().to_string(),
2886 tool: self.name.clone(),
2887 resource_uri: ui.resource_uri.clone(),
2888 call_id,
2889 });
2890 let value = self.execute_value(args, call_id).await?;
2891 #[cfg(feature = "mcp-apps")]
2894 if let Some(record) = record
2895 && value.get("error").is_none()
2896 {
2897 let mut actions = ctx.actions();
2898 actions.state_delta.insert(super::apps::MCP_APP_STATE_KEY.to_string(), json!(record));
2899 ctx.set_actions(actions);
2900 }
2901 Ok(value)
2902 }
2903}
2904
2905#[cfg(test)]
2911mod tests {
2912 use super::*;
2913
2914 #[test]
2922 fn mcp_tool_is_send_and_sync() {
2923 fn require_send_sync<T: Send + Sync>() {}
2924
2925 require_send_sync::<McpTool<()>>();
2932 require_send_sync::<McpToolset<()>>();
2933 }
2934
2935 fn broken_pipe() -> ServiceError {
2936 ServiceError::TransportSend(rmcp::transport::DynamicTransportError::from_parts(
2937 "test",
2938 std::any::TypeId::of::<()>(),
2939 Box::new(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "pipe closed")),
2940 ))
2941 }
2942
2943 #[test]
2944 fn test_should_retry_mcp_operation_reconnectable_errors() {
2945 let config = RefreshConfig::default().with_max_attempts(3);
2946 assert!(should_retry_mcp_operation(&ServiceError::TransportClosed, 0, &config, true, true));
2947 assert!(should_retry_mcp_operation(&broken_pipe(), 1, &config, true, true));
2948 }
2949
2950 #[test]
2951 fn mcp_tool_effect_defaults_to_non_idempotent() {
2952 assert_eq!(mcp_tool_effect(None), ToolEffect::NonIdempotent);
2953 assert_eq!(mcp_tool_effect(Some(&ToolAnnotations::default())), ToolEffect::NonIdempotent);
2954 let destructive = ToolAnnotations::new().destructive(true).idempotent(false);
2955 assert_eq!(mcp_tool_effect(Some(&destructive)), ToolEffect::NonIdempotent);
2956 }
2957
2958 #[test]
2959 fn mcp_tool_effect_maps_read_only_and_idempotent_hints() {
2960 let read_only = ToolAnnotations::new().read_only(true).idempotent(true);
2961 assert_eq!(mcp_tool_effect(Some(&read_only)), ToolEffect::ReadOnly);
2962
2963 let idempotent = ToolAnnotations::new().idempotent(true);
2964 assert_eq!(mcp_tool_effect(Some(&idempotent)), ToolEffect::Idempotent);
2965 }
2966
2967 #[test]
2968 fn test_should_retry_mcp_operation_stops_at_max_attempts() {
2969 let config = RefreshConfig::default().with_max_attempts(2);
2970 assert!(!should_retry_mcp_operation(
2971 &ServiceError::TransportClosed,
2972 2,
2973 &config,
2974 true,
2975 true
2976 ));
2977 }
2978
2979 #[test]
2980 fn test_should_retry_mcp_operation_requires_factory() {
2981 let config = RefreshConfig::default().with_max_attempts(3);
2982 assert!(!should_retry_mcp_operation(
2983 &ServiceError::TransportClosed,
2984 0,
2985 &config,
2986 false,
2987 true
2988 ));
2989 }
2990
2991 #[test]
2992 fn test_should_retry_mcp_operation_non_reconnectable_error() {
2993 let config = RefreshConfig::default().with_max_attempts(3);
2994 let invalid = ServiceError::McpError(rmcp::ErrorData::invalid_params(
2995 "invalid arguments for tool; EOF",
2996 None,
2997 ));
2998 assert!(!should_retry_mcp_operation(&invalid, 0, &config, true, true));
2999 }
3000
3001 #[test]
3007 fn tool_call_replay_is_disabled_by_default() {
3008 let config = RefreshConfig::default();
3009 assert!(
3010 !should_retry_mcp_operation(
3011 &ServiceError::TransportClosed,
3012 0,
3013 &config,
3014 true,
3015 DEFAULT_RETRY_TOOL_CALLS
3016 ),
3017 "a connection-level error must not replay tools/call under the default; see #504"
3018 );
3019 }
3020
3021 #[test]
3022 fn test_should_retry_mcp_operation_requires_explicit_replay() {
3023 let config = RefreshConfig::default().with_max_attempts(3);
3024 assert!(!should_retry_mcp_operation(&broken_pipe(), 0, &config, true, false));
3025 }
3026
3027 #[test]
3028 fn test_ambiguous_tool_call_error_explains_no_replay() {
3029 let error =
3030 mcp_tool_call_error("create_record", &ServiceError::TransportClosed, true, false);
3031 let message = error.to_string();
3032 assert!(message.contains("result is uncertain and was not replayed"));
3033 assert!(message.contains("replay-safe operations"));
3034 }
3035
3036 #[test]
3037 fn mcp_result_preserves_structured_text_and_image_content() {
3038 let mut result = rmcp::model::CallToolResult::success(vec![
3039 rmcp::model::ContentBlock::text("observation"),
3040 rmcp::model::ContentBlock::image(STANDARD.encode([1_u8, 2, 3]), "image/png"),
3041 ]);
3042 result.structured_content = Some(json!({ "observation_id": "obs-1" }));
3043
3044 let value = call_tool_result_to_adk_value(&result).unwrap();
3045 let response = adk_core::FunctionResponseData::from_tool_result("screenshot", value);
3046
3047 assert_eq!(
3048 response.response,
3049 json!({ "output": { "observation_id": "obs-1" }, "text": ["observation"] })
3050 );
3051 assert_eq!(response.inline_data.len(), 1);
3052 assert_eq!(response.inline_data[0].mime_type, "image/png");
3053 assert_eq!(response.inline_data[0].data, vec![1, 2, 3]);
3054 }
3055
3056 #[derive(Clone)]
3058 struct CatalogServer(Vec<rmcp::model::Tool>);
3059
3060 impl rmcp::ServerHandler for CatalogServer {
3061 fn get_info(&self) -> rmcp::model::InitializeResult {
3062 rmcp::model::InitializeResult::new(
3063 rmcp::model::ServerCapabilities::builder().enable_tools().build(),
3064 )
3065 }
3066
3067 async fn list_tools(
3068 &self,
3069 _params: Option<rmcp::model::PaginatedRequestParams>,
3070 _context: rmcp::service::RequestContext<rmcp::RoleServer>,
3071 ) -> std::result::Result<rmcp::model::ListToolsResult, rmcp::ErrorData> {
3072 Ok(rmcp::model::ListToolsResult::with_all_items(self.0.clone()))
3073 }
3074 }
3075
3076 async fn discover(
3078 catalog: Vec<rmcp::model::Tool>,
3079 limits: McpSchemaLimits,
3080 ) -> Vec<Arc<dyn Tool>> {
3081 use rmcp::ServiceExt;
3082
3083 let (server_io, client_io) = tokio::io::duplex(4096);
3084 tokio::spawn(async move {
3085 if let Ok(running) = CatalogServer(catalog).serve(server_io).await {
3086 let _ = running.waiting().await;
3087 }
3088 });
3089 let client = ().serve(client_io).await.unwrap();
3090 let toolset = McpToolset::new(client).with_name("catalog").with_schema_limits(limits);
3091 let ctx = Arc::new(crate::SimpleToolContext::new("schema-limits-test"));
3092 toolset.tools(ctx).await.unwrap()
3093 }
3094
3095 fn schema_object(value: Value) -> serde_json::Map<String, Value> {
3096 match value {
3097 Value::Object(map) => map,
3098 other => panic!("expected a JSON object, got {other}"),
3099 }
3100 }
3101
3102 fn small_schema() -> serde_json::Map<String, Value> {
3103 schema_object(json!({
3104 "type": "object",
3105 "properties": { "id": { "type": "string" } },
3106 "required": ["id"]
3107 }))
3108 }
3109
3110 #[tokio::test]
3111 async fn discovery_skips_oversized_schemas_and_registers_the_other_tools() {
3112 let long_text = "x".repeat(300 * 1024);
3113 let wide: serde_json::Map<String, Value> =
3114 (0..6_000).map(|index| (format!("p{index}"), json!({ "type": "string" }))).collect();
3115 let output = schema_object(json!({ "type": "object" }));
3116 let catalog = vec![
3117 rmcp::model::Tool::new("before", "Valid.", small_schema()),
3118 rmcp::model::Tool::new(
3119 "long_string",
3120 "Input schema over the byte limit.",
3121 schema_object(json!({ "type": "object", "description": long_text })),
3122 ),
3123 rmcp::model::Tool::new(
3124 "wide",
3125 "Input schema over the node limit.",
3126 schema_object(json!({ "type": "object", "properties": wide })),
3127 ),
3128 rmcp::model::Tool::new(
3129 "long_output",
3130 "Output schema over the byte limit.",
3131 small_schema(),
3132 )
3133 .with_raw_output_schema(Arc::new(schema_object(json!({ "description": long_text })))),
3134 rmcp::model::Tool::new("after", "Valid.", small_schema())
3135 .with_raw_output_schema(Arc::new(output.clone())),
3136 ];
3137
3138 let tools = discover(catalog, McpSchemaLimits::default()).await;
3139
3140 let registered: Vec<_> = tools
3141 .iter()
3142 .map(|tool| (tool.name(), tool.parameters_schema(), tool.response_schema()))
3143 .collect();
3144 assert_eq!(
3145 registered,
3146 vec![
3147 ("before", Some(Value::Object(small_schema())), None),
3148 ("after", Some(Value::Object(small_schema())), Some(Value::Object(output))),
3149 ]
3150 );
3151 }
3152
3153 #[tokio::test]
3154 async fn discovery_accepts_a_schema_exactly_at_the_configured_limits() {
3155 let schema = small_schema();
3156 let bytes = serde_json::to_string(&schema).unwrap().len();
3157 let nodes = 7;
3159 let catalog = vec![rmcp::model::Tool::new("lookup", "Valid.", schema)];
3160 let at = McpSchemaLimits::default().with_max_bytes(bytes).with_max_nodes(nodes);
3161
3162 let names = |tools: Vec<Arc<dyn Tool>>| {
3163 tools.iter().map(|tool| tool.name().to_string()).collect::<Vec<_>>()
3164 };
3165 assert_eq!(names(discover(catalog.clone(), at).await), vec!["lookup"]);
3166 assert!(discover(catalog.clone(), at.with_max_bytes(bytes - 1)).await.is_empty());
3167 assert!(discover(catalog, at.with_max_nodes(nodes - 1)).await.is_empty());
3168 }
3169
3170 #[test]
3171 fn an_is_error_result_keeps_its_text_for_the_model() {
3172 let result = rmcp::model::CallToolResult::error(vec![
3173 ContentBlock::text("order IDs look like ORD-1234"),
3174 ContentBlock::text("retry with ORD-7781"),
3175 ]);
3176 assert_eq!(
3177 server_error_response("lookup", &result),
3178 json!({ "error": "order IDs look like ORD-1234\nretry with ORD-7781" })
3179 );
3180
3181 let mut structured = rmcp::model::CallToolResult::error(vec![]);
3182 structured.structured_content = Some(json!({ "field": "order_id" }));
3183 assert_eq!(
3184 server_error_response("lookup", &structured),
3185 json!({ "error": "{\"field\":\"order_id\"}" })
3186 );
3187
3188 let empty = rmcp::model::CallToolResult::error(vec![]);
3189 assert_eq!(
3190 server_error_response("lookup", &empty),
3191 json!({ "error": "MCP tool 'lookup' reported an error without a message" })
3192 );
3193 }
3194
3195 #[test]
3196 fn an_is_error_text_over_the_limit_is_cut_at_a_character_boundary() {
3197 let result = rmcp::model::CallToolResult::error(vec![ContentBlock::text(
3198 "é".repeat(MAX_SERVER_ERROR_BYTES),
3199 )]);
3200 let response = server_error_response("lookup", &result);
3201 let text = response["error"].as_str().unwrap();
3202 let kept = text.strip_suffix(" [truncated]").expect("a truncation marker");
3203 assert!(kept.len() <= MAX_SERVER_ERROR_BYTES);
3204 assert!(kept.chars().all(|c| c == 'é'));
3205 }
3206
3207 #[test]
3208 fn a_successful_result_without_content_is_an_empty_output() {
3209 let result = rmcp::model::CallToolResult::success(vec![]);
3210 assert_eq!(call_tool_result_to_adk_value(&result), Ok(json!({ "output": "" })));
3211 }
3212
3213 #[tokio::test]
3214 async fn discovery_truncates_descriptions_over_the_limit_and_keeps_the_tool() {
3215 let catalog = vec![
3216 rmcp::model::Tool::new("huge", "é".repeat(600_000), small_schema()),
3217 rmcp::model::Tool::new("short", "Valid.", small_schema()),
3218 ];
3219
3220 let tools = discover(catalog, McpSchemaLimits::default()).await;
3221
3222 let registered: Vec<_> = tools
3223 .iter()
3224 .map(|tool| (tool.name().to_string(), tool.description().to_string()))
3225 .collect();
3226 assert_eq!(
3227 registered,
3228 vec![
3229 (
3230 "huge".to_string(),
3231 "é".repeat(McpSchemaLimits::DEFAULT_MAX_DESCRIPTION_BYTES / 2)
3232 ),
3233 ("short".to_string(), "Valid.".to_string()),
3234 ]
3235 );
3236 }
3237
3238 #[test]
3239 fn mcp_result_rejects_invalid_image_base64() {
3240 let result = rmcp::model::CallToolResult::success(vec![rmcp::model::ContentBlock::image(
3241 "not-base64!",
3242 "image/png",
3243 )]);
3244 assert!(call_tool_result_to_adk_value(&result).is_err());
3245 }
3246
3247 #[tokio::test]
3248 async fn discovery_skips_repeated_and_unroutable_names_and_keeps_the_rest() {
3249 let long = |suffix: &str| format!("{}{suffix}", "n".repeat(64));
3250 let catalog = vec![
3251 rmcp::model::Tool::new("dup", "First.", small_schema()),
3252 rmcp::model::Tool::new("dup", "Second.", small_schema()),
3253 rmcp::model::Tool::new("line\nbreak\u{1b}[31m", "Control characters.", small_schema()),
3254 rmcp::model::Tool::new("", "Empty.", small_schema()),
3255 rmcp::model::Tool::new(long("_a"), "Long a.", small_schema()),
3256 rmcp::model::Tool::new(long("_b"), "Long b.", small_schema()),
3257 rmcp::model::Tool::new("n".repeat(64), "Exactly 64 bytes.", small_schema()),
3258 rmcp::model::Tool::new("lookup", "Valid.", small_schema()),
3259 ];
3260
3261 let tools = discover(catalog, McpSchemaLimits::default()).await;
3262
3263 let registered: Vec<_> = tools
3264 .iter()
3265 .map(|tool| (tool.name().to_string(), tool.description().to_string()))
3266 .collect();
3267 assert_eq!(
3268 registered,
3269 vec![
3270 ("dup".to_string(), "First.".to_string()),
3271 ("n".repeat(64), "Exactly 64 bytes.".to_string()),
3272 ("lookup".to_string(), "Valid.".to_string()),
3273 ]
3274 );
3275 }
3276
3277 #[tokio::test]
3278 async fn discovered_tools_carry_their_effect_and_annotations() {
3279 let annotated = |name: &str, hints: ToolAnnotations| {
3280 rmcp::model::Tool::new(name.to_string(), "Annotated.", small_schema()).annotate(hints)
3281 };
3282 let catalog = vec![
3283 annotated(
3284 "set_thermostat",
3285 ToolAnnotations::with_title("Set thermostat")
3286 .idempotent(true)
3287 .destructive(false)
3288 .open_world(false),
3289 ),
3290 annotated("read_temperature", ToolAnnotations::new().read_only(true)),
3291 annotated("delete_logs", ToolAnnotations::new().destructive(true)),
3292 rmcp::model::Tool::new("plain", "No annotations.", small_schema()),
3293 ];
3294
3295 let tools = discover(catalog, McpSchemaLimits::default()).await;
3296
3297 let described: Vec<_> = tools
3298 .iter()
3299 .map(|tool| {
3300 (
3301 tool.name(),
3302 tool.effect(),
3303 tool.is_read_only(),
3304 tool.is_concurrency_safe(),
3305 tool.annotations().cloned(),
3306 )
3307 })
3308 .collect();
3309 assert_eq!(
3310 described,
3311 vec![
3312 (
3313 "set_thermostat",
3314 ToolEffect::Idempotent,
3315 false,
3316 true,
3317 Some(json!({
3318 "title": "Set thermostat",
3319 "idempotentHint": true,
3320 "destructiveHint": false,
3321 "openWorldHint": false
3322 })),
3323 ),
3324 (
3325 "read_temperature",
3326 ToolEffect::ReadOnly,
3327 true,
3328 true,
3329 Some(json!({ "readOnlyHint": true }))
3330 ),
3331 (
3332 "delete_logs",
3333 ToolEffect::NonIdempotent,
3334 false,
3335 false,
3336 Some(json!({ "destructiveHint": true })),
3337 ),
3338 ("plain", ToolEffect::NonIdempotent, false, false, None),
3339 ]
3340 );
3341 }
3342
3343 #[derive(Clone, Default)]
3345 struct CallCounter(Arc<std::sync::atomic::AtomicUsize>);
3346
3347 impl rmcp::ServerHandler for CallCounter {
3348 fn get_info(&self) -> rmcp::model::InitializeResult {
3349 rmcp::model::InitializeResult::new(
3350 rmcp::model::ServerCapabilities::builder().enable_tools().build(),
3351 )
3352 }
3353
3354 async fn call_tool(
3355 &self,
3356 params: CallToolRequestParams,
3357 _context: rmcp::service::RequestContext<rmcp::RoleServer>,
3358 ) -> std::result::Result<CallToolResponse, rmcp::ErrorData> {
3359 self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
3360 Ok(rmcp::model::CallToolResult::success(vec![ContentBlock::text(
3361 params.name.to_string(),
3362 )])
3363 .into())
3364 }
3365 }
3366
3367 #[derive(Clone)]
3369 struct Refusing;
3370
3371 impl rmcp::ServerHandler for Refusing {
3372 fn get_info(&self) -> rmcp::model::InitializeResult {
3373 rmcp::model::InitializeResult::new(
3374 rmcp::model::ServerCapabilities::builder().enable_tools().build(),
3375 )
3376 }
3377
3378 async fn list_tools(
3379 &self,
3380 _params: Option<rmcp::model::PaginatedRequestParams>,
3381 _context: rmcp::service::RequestContext<rmcp::RoleServer>,
3382 ) -> std::result::Result<rmcp::model::ListToolsResult, rmcp::ErrorData> {
3383 Ok(rmcp::model::ListToolsResult::with_all_items(vec![rmcp::model::Tool::new(
3384 "lookup",
3385 "Looks up an order.",
3386 small_schema(),
3387 )]))
3388 }
3389
3390 async fn call_tool(
3391 &self,
3392 _params: CallToolRequestParams,
3393 _context: rmcp::service::RequestContext<rmcp::RoleServer>,
3394 ) -> std::result::Result<CallToolResponse, rmcp::ErrorData> {
3395 Ok(rmcp::model::CallToolResult::error(vec![ContentBlock::text(
3396 "order 7781 moved; call lookup with id MIG-7781",
3397 )])
3398 .into())
3399 }
3400 }
3401
3402 #[tokio::test]
3403 async fn a_server_is_error_result_is_the_tools_response() {
3404 use rmcp::ServiceExt;
3405
3406 let (server_io, client_io) = tokio::io::duplex(4096);
3407 tokio::spawn(async move {
3408 if let Ok(running) = Refusing.serve(server_io).await {
3409 let _ = running.waiting().await;
3410 }
3411 });
3412 let toolset = McpToolset::new(().serve(client_io).await.unwrap()).with_name("orders");
3413 let ctx = Arc::new(crate::SimpleToolContext::new("is-error-test"));
3414 let tools = toolset.tools(ctx.clone()).await.unwrap();
3415
3416 let response = tools[0].execute(ctx, json!({ "id": "7781" })).await.unwrap();
3417 assert_eq!(response, json!({ "error": "order 7781 moved; call lookup with id MIG-7781" }));
3418 }
3419
3420 #[tokio::test]
3421 async fn call_tool_value_refuses_a_tool_the_filter_excludes() {
3422 use rmcp::ServiceExt;
3423
3424 let server = CallCounter::default();
3425 let calls = Arc::clone(&server.0);
3426 let (server_io, client_io) = tokio::io::duplex(4096);
3427 tokio::spawn(async move {
3428 if let Ok(running) = server.serve(server_io).await {
3429 let _ = running.waiting().await;
3430 }
3431 });
3432 let toolset = McpToolset::new(().serve(client_io).await.unwrap())
3433 .with_name("filtered")
3434 .with_tools(&["public"]);
3435
3436 let refused = toolset.call_tool_value("secret", Default::default()).await.unwrap_err();
3437 assert!(refused.to_string().contains("excluded by the tool filter"), "{refused}");
3438 assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);
3439
3440 let allowed = toolset.call_tool_value("public", Default::default()).await.unwrap();
3441 assert_eq!(allowed, json!({ "output": "public" }));
3442 assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
3443 }
3444}