Skip to main content

adk_tool/mcp/
toolset.rs

1// MCP (Model Context Protocol) Toolset Integration
2//
3// Based on Go implementation: adk-go/tool/mcptoolset/
4// Uses official Rust SDK: https://github.com/modelcontextprotocol/rust-sdk
5//
6// The McpToolset connects to an MCP server, discovers available tools,
7// and exposes them as ADK-compatible tools for use with LlmAgent.
8
9use 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
48/// Shared factory object used to recreate MCP connections for refresh/retry.
49type DynConnectionFactory<S> = Arc<dyn ConnectionFactory<S>>;
50
51/// One live MCP connection. Callers hold a clone for the length of a request,
52/// so a refresh never pulls a connection out from under an in-flight call.
53type Connection<S> = Arc<RunningService<RoleClient, S>>;
54
55/// How long a `tools/list` result is reused before discovery asks the server again.
56const DEFAULT_TOOL_LIST_CACHE_TTL: Duration = Duration::from_secs(60);
57
58/// How long [`Toolset::close`] waits for the connection to finish closing. rmcp kills a
59/// stdio server that has not exited 3 seconds after its input closed, within this bound.
60const DEFAULT_CLOSE_TIMEOUT: Duration = Duration::from_secs(5);
61
62/// How often `close` checks whether the connection's service loop has ended.
63const CLOSE_POLL_INTERVAL: Duration = Duration::from_millis(10);
64
65/// The error code of a request made through a toolset after [`Toolset::close`].
66const CLOSED_CODE: &str = "tool.mcp.closed";
67
68/// The error code of a parked legacy call that is not re-issued because it is not retry-safe
69/// (spec 3.2 §10 T2).
70const NOT_RUN_CODE: &str = "tool.mcp.not_run";
71
72/// The error for a request made through toolset `toolset` after it was closed.
73fn 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
85/// The connection shared by a toolset, its clones, and every tool it produced.
86///
87/// The lock guards only the swap: callers take a clone of the current
88/// [`Connection`] and release the lock before sending anything, so concurrent
89/// requests never wait on each other here.
90struct SharedClient<S>
91where
92    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
93{
94    /// The current connection and the number of times it has been replaced.
95    current: RwLock<(Connection<S>, u64)>,
96    /// Held while a replacement connects, so concurrent failures replace a
97    /// dead connection once instead of once per caller.
98    refresh: Mutex<()>,
99    /// Set by `close`; no request is sent and no connection is made afterwards.
100    closed: AtomicBool,
101    /// Run scopes that sampling requests count against, shared with every
102    /// connection's [`AdkClientHandler`](super::AdkClientHandler).
103    #[cfg(feature = "mcp-sampling")]
104    sampling_scopes: Arc<crate::sampling::SamplingScopes>,
105    /// The tool calls in flight, which an elicitation is attributed to, shared with
106    /// every connection's handler (spec 3.1 §10 T1).
107    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    /// Returns the current connection, or the closed error once `toolset` was closed.
137    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    /// Returns the current connection with its generation, which changes on every refresh.
145    async fn connection_with_generation(&self) -> (Connection<S>, u64) {
146        let current = self.current.read().await;
147        (Arc::clone(&current.0), current.1)
148    }
149
150    /// Returns the current connection with its generation, first replacing it when it
151    /// has already closed and a factory is configured.
152    ///
153    /// Nothing was sent on a closed connection, so replacing it here never turns the
154    /// caller's next request into a replay. Fails once `toolset` was closed.
155    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    /// Replaces `failed` with a connection from `factory`.
174    ///
175    /// Returns `Ok(false)` when no factory is configured. When another caller
176    /// already replaced `failed`, this returns `Ok(true)` without reconnecting,
177    /// and the caller retries on the connection that caller installed. The old
178    /// connection closes once the last in-flight request on it finishes. Fails,
179    /// without installing a connection, once `toolset` was closed.
180    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        // `close` sets the flag before it takes this lock to read the connection, so a
211        // connection made during a close is either refused here or cancelled by it.
212        // Dropping a refused connection cancels it.
213        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/// The cached `tools/list` result, and how many times it has been invalidated.
223#[derive(Default)]
224struct ToolListCache {
225    entry: Option<CachedToolList>,
226    /// Bumped by `invalidate_tool_list_cache`; a fetch stores its result only when
227    /// this has not changed since the fetch began.
228    invalidations: u64,
229}
230
231/// One `tools/list` result and the state it was fetched under.
232struct CachedToolList {
233    /// Connection generation the list came from; a reconnect invalidates it.
234    generation: u64,
235    /// `notifications/tools/list_changed` count observed before the fetch.
236    list_changes: u64,
237    fetched_at: Instant,
238    tools: Vec<rmcp::model::Tool>,
239}
240
241/// The [`AdkClientHandler`](super::AdkClientHandler) serving `connection`, if it uses one.
242fn 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
252/// Counts `notifications/tools/list_changed` on connections served by
253/// [`AdkClientHandler`](super::AdkClientHandler). Other handlers report zero,
254/// so their cached list expires only by TTL or explicit invalidation.
255fn 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
263/// What a [`CancelOnDrop`] guard asks the server to stop.
264enum CancelTarget {
265    /// A `tools/call` still awaiting its response, stopped with `notifications/cancelled`.
266    Request(RequestId),
267    /// A task the server created for a `tools/call`, stopped with `tasks/cancel`.
268    Task(String),
269}
270
271/// Asks the server to stop work the caller stopped waiting for, such as a call an
272/// agent-level tool timeout dropped, instead of finishing it for nobody.
273struct 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        // Without a runtime there is no transport left to carry the cancellation.
290        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                // The task stays in the pending set until a status confirms it, as with
325                // every other `tasks/cancel`, so `cancel_pending_tasks` still checks it.
326                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
348/// Sends one `tools/call` and returns the response envelope unchanged.
349///
350/// Mirrors rmcp's `call_tool_once`, but keeps the request id so that dropping
351/// the returned future cancels the request on the server.
352async 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
376/// Longest server-issued task id retained in the pending-task set.
377const MAX_TASK_ID_BYTES: usize = 16 * 1024;
378
379/// Most input requests answered in one MRTR or in-task input round.
380const MAX_INPUT_REQUESTS_PER_ROUND: usize = 64;
381
382/// Most tasks `cancel_pending_tasks` checks or cancels at once.
383const MAX_CONCURRENT_TASK_CLEANUPS: usize = 16;
384
385/// Longest wait for a `tasks/cancel` acknowledgement, so an unresponsive
386/// server cannot hold a call far past its own deadline.
387const TASK_CANCEL_TIMEOUT: Duration = Duration::from_secs(2);
388
389/// Returns `true` when a task request failed because the server no longer
390/// tracks the task, or (for `tasks/cancel`) because it already finished.
391/// The specification reports both as `-32602`; `-32002` is the older
392/// not-found code.
393fn 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        // Existing resource callbacks use the negotiated legacy subscription API.
407        #[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
415/// The effect a tool's `readOnlyHint` and `idempotentHint` declare; a tool that
416/// declares neither is treated as non-idempotent.
417fn 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
425/// Most UTF-8 bytes of an `isError` result's text passed to the model.
426const MAX_SERVER_ERROR_BYTES: usize = 8 * 1024;
427
428/// The function response for a call the server answered with `isError: true`.
429///
430/// An `isError` result is the tool's own output, written for the model so it can correct
431/// the call, so its text is passed through as `{"error": text}` rather than failing the
432/// call: a failed call reaches the model only as its error code. Transport and protocol
433/// failures stay errors. The text is cut to [`MAX_SERVER_ERROR_BYTES`] at a character
434/// boundary.
435fn 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-only errors carry their detail outside the text blocks.
446        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
457/// Preserve every MCP content block in ADK's multimodal tool-result envelope.
458/// `FunctionResponseData::from_tool_result` consumes this shape in the agent loop.
459fn 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        // A successful call may return nothing; reporting it as a failure would invite a
518        // retry of a tool that already ran.
519        (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
533/// Type alias for tool filter predicate
534pub 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
556/// Returns `true` when the `ServiceError` wraps an MCP `MethodNotFound` (-32601)
557/// JSON-RPC error, indicating the server does not implement the requested method.
558fn 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
565/// MCP Toolset - connects to an MCP server and exposes its tools as ADK tools.
566///
567/// This toolset implements the ADK `Toolset` trait and bridges the gap between
568/// MCP servers and ADK agents. It:
569/// 1. Connects to an MCP server via the provided transport
570/// 2. Discovers available tools from the server
571/// 3. Converts MCP tools to ADK-compatible `Tool` implementations
572/// 4. Proxies tool execution calls to the MCP server
573///
574/// # Example
575///
576/// ```rust,ignore
577/// use adk_tool::{
578///     McpToolset,
579///     mcp::rmcp::{ServiceExt, transport::TokioChildProcess},
580/// };
581/// use tokio::process::Command;
582///
583/// // Create MCP client connection to a local server
584/// let client = ().serve(TokioChildProcess::new(
585///     Command::new("/opt/company/bin/workspace-mcp")
586///         .arg("--stdio")
587///         .arg("--root")
588///         .arg("/srv/workspace")
589/// )?).await?;
590///
591/// // Create toolset from the client
592/// let toolset = McpToolset::new(client);
593///
594/// // Add to agent
595/// let agent = LlmAgentBuilder::new("assistant")
596///     .toolset(Arc::new(toolset))
597///     .build()?;
598/// ```
599pub struct McpToolset<S = ()>
600where
601    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
602{
603    /// The running MCP client service
604    client: Arc<SharedClient<S>>,
605    /// The last `tools/list` result, shared by clones of this toolset.
606    tool_list: Arc<Mutex<ToolListCache>>,
607    /// How long `tool_list` is reused; zero disables the cache.
608    tool_list_ttl: Duration,
609    /// Optional filter to select which tools to expose
610    tool_filter: Option<ToolFilter>,
611    /// Name of this toolset
612    name: String,
613    /// Task configuration for long-running operations
614    task_config: McpTaskConfig,
615    /// Remote tasks whose terminal state has not been observed.
616    active_tasks: Arc<Mutex<BTreeSet<String>>>,
617    /// Optional connection factory used for reconnection on transport failures.
618    connection_factory: Option<DynConnectionFactory<S>>,
619    /// Reconnection/retry configuration.
620    refresh_config: RefreshConfig,
621    /// Whether ambiguous tool-call outcomes may be replayed after reconnection.
622    retry_tool_calls: bool,
623    /// Resource subscriptions restored after an automatic connection refresh.
624    resource_subscriptions: Arc<RwLock<BTreeSet<String>>>,
625    /// Policy bridge used to fulfil stateless MRTR and in-task input requests.
626    mrtr_handler: Option<super::elicitation::AdkClientHandler>,
627    /// Size limits checked against each discovered tool schema.
628    schema_limits: McpSchemaLimits,
629    /// Bounds on each catalog listing.
630    discovery_limits: McpDiscoveryLimits,
631    /// How long [`Toolset::close`] waits for the connection to finish closing.
632    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    /// Create a new MCP toolset from a running MCP client service.
665    ///
666    /// The client should already be connected and initialized.
667    /// Use `adk_tool::mcp::rmcp::ServiceExt::serve()` to create the client.
668    ///
669    /// MRTR and in-task input requests follow ADK's input policy when the client
670    /// runs on [`AdkClientHandler`](super::AdkClientHandler), which rejects
671    /// sampling and roots. Any other handler receives elicitation requests, and
672    /// sampling or roots requests only when it declared those capabilities.
673    ///
674    /// # Example
675    ///
676    /// ```rust,ignore
677    /// use adk_tool::mcp::rmcp::{ServiceExt, transport::TokioChildProcess};
678    /// use tokio::process::Command;
679    ///
680    /// let client = ().serve(TokioChildProcess::new(
681    ///     Command::new("my-mcp-server")
682    /// )?).await?;
683    ///
684    /// let toolset = McpToolset::new(client);
685    /// ```
686    pub fn new(client: RunningService<RoleClient, S>) -> Self {
687        // A client served on ADK's own handler keeps ADK's MRTR input policy, however
688        // it was built, so a configured sampling handler stays unreachable through MRTR.
689        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    /// Create a McpToolset from a RunningService with a custom ClientHandler.
712    ///
713    /// This is functionally identical to `new()` but makes the intent explicit
714    /// when using a custom `ClientHandler` type.
715    ///
716    /// # Example
717    ///
718    /// ```rust,ignore
719    /// use adk_tool::{McpToolset, mcp::rmcp::ServiceExt};
720    ///
721    /// let client = my_custom_handler.serve(transport).await?;
722    /// let toolset = McpToolset::with_client_handler(client);
723    /// ```
724    pub fn with_client_handler(client: RunningService<RoleClient, S>) -> Self {
725        Self::new(client)
726    }
727
728    /// Meters sampling requests that arrive outside any run's tool call against `scope`.
729    ///
730    /// Requests that arrive while a tool call from a run is in flight count against that
731    /// run's budget and spend ledger instead. Without a scope, such requests are unmetered.
732    /// See [sampling metering](crate::sampling#metering).
733    ///
734    /// # Example
735    ///
736    /// ```rust,ignore
737    /// use adk_core::{InMemorySpendLedger, ModelCallScope};
738    ///
739    /// let scope = ModelCallScope::new()
740    ///     .with_spend_ledger(Arc::new(InMemorySpendLedger::default()), "acme")
741    ///     .with_agent("mcp-sampling");
742    /// let toolset = McpToolset::with_sampling_handler(transport, elicitation, sampling)
743    ///     .await?
744    ///     .with_sampling_scope(scope);
745    /// ```
746    #[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    /// Attributes elicitations that arrive outside any tool call of this toolset to
753    /// `scope` (spec 3.1 §10 T1).
754    ///
755    /// Elicitations that arrive while one of this toolset's tool calls is in flight belong
756    /// to that call: the connection's handler answers them inside
757    /// [`ElicitationScope::for_call`](super::ElicitationScope::for_call) of the call, which
758    /// a handler reads with [`ElicitationScope::current`](super::ElicitationScope::current).
759    ///
760    /// # Example
761    ///
762    /// ```rust,ignore
763    /// use adk_tool::mcp::ElicitationScope;
764    ///
765    /// let toolset = McpToolset::with_elicitation_handler(transport, handler)
766    ///     .await?
767    ///     .with_elicitation_scope(ElicitationScope::new("app", "operator", "console"));
768    /// ```
769    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    /// Set a custom name for this toolset.
775    pub fn with_name(mut self, name: impl Into<String>) -> Self {
776        self.name = name.into();
777        self
778    }
779
780    /// Enable MCP task support (SEP-2663) for long-running operations.
781    ///
782    /// Tools no longer declare task support: every call is one `tools/call`, and the
783    /// server decides per call whether to answer with a task. When it does, this toolset
784    /// polls `tasks/get` at the server's `pollIntervalMs` (else `config`'s interval) until the
785    /// task completes, reading the result inlined in the status response, and answers
786    /// in-task input requests through the connection's handler.
787    ///
788    /// Tasks need all three sides: this configuration, a client that declares the
789    /// `io.modelcontextprotocol/tasks` extension
790    /// ([`AdkClientHandler::with_tasks`](crate::mcp::AdkClientHandler::with_tasks); a plain
791    /// `()` client never does), and a server that declares the tasks capability. A task
792    /// returned while any of them is missing is cancelled, and the call fails with the reason.
793    /// Every tool of the toolset reports
794    /// [`is_long_running`](adk_core::Tool::is_long_running) when tasks are enabled and
795    /// negotiated.
796    ///
797    /// # Example
798    ///
799    /// ```rust
800    /// use std::time::Duration;
801    ///
802    /// use adk_tool::mcp::{AdkClientHandler, McpTaskConfig, McpToolset};
803    /// use rmcp::service::RunningService;
804    ///
805    /// fn tasks_toolset(
806    ///     client: RunningService<rmcp::RoleClient, AdkClientHandler>,
807    /// ) -> McpToolset<AdkClientHandler> {
808    ///     McpToolset::new(client).with_task_support(
809    ///         McpTaskConfig::enabled()
810    ///             .poll_interval(Duration::from_secs(2))
811    ///             .timeout(Duration::from_secs(300)),
812    ///     )
813    /// }
814    /// ```
815    pub fn with_task_support(mut self, config: McpTaskConfig) -> Self {
816        self.task_config = config;
817        self
818    }
819
820    /// Set the size limits checked against each discovered tool schema.
821    ///
822    /// Discovery measures every input and output schema before copying or logging
823    /// it. A tool whose schema exceeds a limit is skipped with a warning naming
824    /// this toolset and the tool, and the remaining tools are still registered.
825    /// See [`McpSchemaLimits`] for how size is measured and why the defaults are
826    /// what they are.
827    ///
828    /// # Example
829    ///
830    /// ```
831    /// use adk_tool::mcp::{McpSchemaLimits, McpToolset};
832    ///
833    /// fn admit_larger_schemas(toolset: McpToolset) -> McpToolset {
834    ///     toolset.with_schema_limits(
835    ///         McpSchemaLimits::default().with_max_bytes(1024 * 1024).with_max_nodes(40_000),
836    ///     )
837    /// }
838    /// ```
839    pub fn with_schema_limits(mut self, limits: McpSchemaLimits) -> Self {
840        self.schema_limits = limits;
841        self
842    }
843
844    /// Set the bounds on each catalog listing: `tools/list`, `resources/list`,
845    /// `resources/templates/list`, and `prompts/list`.
846    ///
847    /// A listing fails with `AdkError::Tool` when the server still returns a
848    /// `nextCursor` after `max_pages` pages, returns a cursor it already returned,
849    /// or takes longer than `timeout`, reconnects included. See
850    /// [`McpDiscoveryLimits`] for the defaults.
851    ///
852    /// # Example
853    ///
854    /// ```
855    /// use adk_tool::mcp::{McpDiscoveryLimits, McpToolset};
856    /// use std::time::Duration;
857    ///
858    /// fn fail_fast(toolset: McpToolset) -> McpToolset {
859    ///     toolset.with_discovery_limits(
860    ///         McpDiscoveryLimits::default().with_max_pages(16).with_timeout(Duration::from_secs(5)),
861    ///     )
862    /// }
863    /// ```
864    pub fn with_discovery_limits(mut self, limits: McpDiscoveryLimits) -> Self {
865        self.discovery_limits = limits;
866        self
867    }
868
869    /// Set how long a `tools/list` result is reused before discovery asks the
870    /// server again. The default is 60 seconds; `Duration::ZERO` disables this
871    /// cache, so every [`Toolset::tools`] call sends `tools/list`, except for a page
872    /// the server marked fresh with `ttlMs`, which rmcp's response cache answers.
873    ///
874    /// An agent resolves its toolsets before every model turn, so without the
875    /// cache each turn costs one `tools/list` round trip per MCP server. The
876    /// cached list is dropped before the TTL elapses when:
877    ///
878    /// | Event | Applies to |
879    /// |-------|------------|
880    /// | The connection is refreshed | Every toolset with a connection factory |
881    /// | The server sends `notifications/tools/list_changed` | Connections served by [`AdkClientHandler`](super::AdkClientHandler) |
882    /// | [`invalidate_tool_list_cache`](Self::invalidate_tool_list_cache) is called | Every toolset, including a fetch already in flight |
883    ///
884    /// # Example
885    ///
886    /// ```
887    /// use adk_tool::mcp::McpToolset;
888    /// use std::time::Duration;
889    ///
890    /// fn rediscover_every_turn(toolset: McpToolset) -> McpToolset {
891    ///     toolset.with_tool_list_cache_ttl(Duration::ZERO)
892    /// }
893    /// ```
894    pub fn with_tool_list_cache_ttl(mut self, ttl: Duration) -> Self {
895        self.tool_list_ttl = ttl;
896        self
897    }
898
899    /// Set how long [`Toolset::close`] waits for the connection to finish closing.
900    /// The default is 5 seconds.
901    ///
902    /// Remote tasks the toolset started get at most half of it to confirm their
903    /// cancellation; the session gets the rest. A connection still closing when the
904    /// timeout elapses keeps closing in the background: rmcp kills a stdio server
905    /// that is still running 3 seconds after its input closed.
906    ///
907    /// # Example
908    ///
909    /// ```
910    /// use adk_tool::mcp::McpToolset;
911    /// use std::time::Duration;
912    ///
913    /// fn close_fast(toolset: McpToolset) -> McpToolset {
914    ///     toolset.with_close_timeout(Duration::from_secs(1))
915    /// }
916    /// ```
917    pub fn with_close_timeout(mut self, timeout: Duration) -> Self {
918        self.close_timeout = timeout;
919        self
920    }
921
922    /// Drop the cached `tools/list` result, so the next [`Toolset::tools`] call
923    /// asks the server again.
924    ///
925    /// This also clears the connection's rmcp response cache, which keeps pages
926    /// the server marked fresh with `ttlMs`, and stops a `tools/list` already in
927    /// flight from caching its result: that call still returns what it fetched,
928    /// and the next call fetches again.
929    ///
930    /// Call this from a custom `ClientHandler`'s `on_tool_list_changed` when the
931    /// connection does not run on [`AdkClientHandler`](super::AdkClientHandler),
932    /// which invalidates the cache on its own.
933    ///
934    /// # Example
935    ///
936    /// ```
937    /// use adk_tool::mcp::McpToolset;
938    ///
939    /// async fn on_catalog_changed(toolset: &McpToolset) {
940    ///     toolset.invalidate_tool_list_cache().await;
941    /// }
942    /// ```
943    pub async fn invalidate_tool_list_cache(&self) {
944        // Cleared first, so a fetch that starts after the bump below reads the server.
945        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    /// Reuse the connection's client policy for stateless MRTR and task input.
952    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    /// Provide a connection factory to enable automatic MCP reconnection.
961    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    /// Configure MCP reconnect/retry behavior.
970    pub fn with_refresh_config(mut self, config: RefreshConfig) -> Self {
971        self.refresh_config = config;
972        self
973    }
974
975    /// Allow MCP tool calls to be replayed after reconnecting.
976    ///
977    /// A transport failure after request transmission is an ambiguous outcome:
978    /// a mutating tool may have completed its external effect before the
979    /// response was lost. Enable this only for read-only tools or operations
980    /// protected by a stable provider idempotency guarantee. Discovery and
981    /// resource operations keep their normal reconnect behavior without this.
982    ///
983    /// # Example
984    ///
985    /// ```rust,ignore
986    /// let toolset = McpToolset::new(client)
987    ///     .with_connection_factory(Arc::new(factory))
988    ///     .with_tool_call_retries();
989    /// ```
990    pub fn with_tool_call_retries(mut self) -> Self {
991        self.retry_tool_calls = true;
992        self
993    }
994
995    /// Add a filter to select which tools to expose.
996    ///
997    /// The filter function receives a tool name and returns true if the tool
998    /// should be included.
999    ///
1000    /// # Example
1001    ///
1002    /// ```rust,ignore
1003    /// let toolset = McpToolset::new(client)
1004    ///     .with_filter(|name| {
1005    ///         matches!(name, "read_file" | "list_directory" | "search_files")
1006    ///     });
1007    /// ```
1008    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    /// Add a filter that only includes tools with the specified names.
1017    ///
1018    /// # Example
1019    ///
1020    /// ```rust,ignore
1021    /// let toolset = McpToolset::new(client)
1022    ///     .with_tools(&["read_file", "write_file"]);
1023    /// ```
1024    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    /// Get a cancellation token that can be used to shutdown the MCP server.
1030    ///
1031    /// Call `cancel()` on the returned token to cleanly shutdown the MCP server.
1032    /// This should be called before exiting to avoid EPIPE errors. Cancelling does
1033    /// not wait for the server to exit; [`Toolset::close`] does, and also stops the
1034    /// toolset from reconnecting.
1035    ///
1036    /// # Example
1037    ///
1038    /// ```rust,ignore
1039    /// let toolset = McpToolset::new(client);
1040    /// let cancel_token = toolset.cancellation_token().await;
1041    ///
1042    /// // ... use the toolset ...
1043    ///
1044    /// // Before exiting:
1045    /// cancel_token.cancel();
1046    /// ```
1047    pub async fn cancellation_token(&self) -> rmcp::service::RunningServiceCancellationToken {
1048        self.client.connection().await.cancellation_token()
1049    }
1050
1051    /// Check whether the underlying MCP service connection has been closed or cancelled.
1052    ///
1053    /// Returns `true` once the transport has closed, as it does when a stdio server
1054    /// process exits, the connection's cancellation token has fired, or the toolset
1055    /// was closed with [`Toolset::close`]. This is useful for health monitoring — a
1056    /// closed connection indicates the server process has crashed or the transport
1057    /// has been lost. With a connection factory, the next request replaces a closed
1058    /// connection before sending, unless the toolset was closed.
1059    ///
1060    /// # Example
1061    ///
1062    /// ```rust,ignore
1063    /// if toolset.is_closed().await {
1064    ///     tracing::warn!("MCP server connection lost");
1065    /// }
1066    /// ```
1067    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    /// Closes the toolset, waiting at most `timeout` for its connection to finish closing.
1073    ///
1074    /// Marks the toolset closed first, so no new request starts and no connection
1075    /// factory reconnects, then cancels the remote tasks it started (within half of
1076    /// `timeout`) and the rmcp service. The service loop closes the transport before it
1077    /// ends: a stdio server's input is closed and the process waited for, or killed after
1078    /// 3 seconds; a Streamable HTTP session is ended with `DELETE`. A second call only
1079    /// waits for that to finish.
1080    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        // Read under the write lock, which a reconnect holds while it installs a
1098        // connection, so a connection made during this close is the one cancelled here.
1099        let connection = Arc::clone(&self.client.current.write().await.0);
1100        connection.cancellation_token().cancel();
1101        // The peer's channel closes when the service loop ends, after its transport closed.
1102        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    /// Call one MCP tool and preserve structured, text, image, audio, and resource content
1120    /// in the same ADK multimodal value shape used by model-facing tool execution.
1121    ///
1122    /// # Errors
1123    ///
1124    /// Returns `AdkError::Tool` without contacting the server when the toolset's
1125    /// [filter](Self::with_filter) excludes `name`, and when the call fails.
1126    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    /// Calls MCP tool `name`, ending the call with its parked form when the server needs
1135    /// input instead of answering it in process (spec 3.2 §10 T2).
1136    ///
1137    /// A server that answers `input_required` with input requests, or a task that reports
1138    /// `input_required`, parks the call: the result is [`McpCallOutcome::Parked`], nothing
1139    /// waits in this process, and a parked task keeps waiting on the server and is not
1140    /// cancelled by [`cancel_pending_tasks`](Self::cancel_pending_tasks). Persist the
1141    /// [`ParkedMcpCall`], ask the person, and pass the answers to
1142    /// [`reissue`](Self::reissue) — from this toolset or one built after a restart. A
1143    /// state-only `input_required` asks nothing and is retried in place, as in every call. A
1144    /// server before 2026-07-28 asks with `elicitation/create` while the call runs, which the
1145    /// connection's handler answers in process (see [`ParkedMcpCall::current`]). `call_id` is
1146    /// recorded in the parked call.
1147    ///
1148    /// # Errors
1149    ///
1150    /// Returns `AdkError::Tool` without contacting the server when the toolset's
1151    /// [filter](Self::with_filter) excludes `name`, when the call fails, and when it takes more
1152    /// than [`McpTaskConfig::max_input_rounds`] input rounds.
1153    ///
1154    /// # Example
1155    ///
1156    /// ```rust
1157    /// use adk_tool::mcp::{McpCallOutcome, McpToolset};
1158    ///
1159    /// async fn send(toolset: &McpToolset) -> adk_core::Result<Option<String>> {
1160    ///     let arguments = serde_json::json!({ "draftId": "d-7" }).as_object().unwrap().clone();
1161    ///     Ok(match toolset.call_tool_resumable(Some("call-1"), "send_draft", arguments).await? {
1162    ///         McpCallOutcome::Completed(value) => Some(value.to_string()),
1163    ///         // Persist it beside the approval that asks the person.
1164    ///         McpCallOutcome::Parked(parked) => {
1165    ///             let _checkpoint = serde_json::to_string(&parked).unwrap();
1166    ///             None
1167    ///         }
1168    ///     })
1169    /// }
1170    /// ```
1171    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    /// Re-issues a parked call with the answers to its input requests (spec 3.2 §7.7, §10 T2).
1188    ///
1189    /// `responses` maps keys of [`ParkedMcpCall::input_requests`] to the answers, as
1190    /// `inputResponses` carry them (an elicitation's answer is its `ElicitResult` as JSON).
1191    /// What happens depends on [`ParkedMcpCall::kind`]:
1192    ///
1193    /// | Kind | Re-issue |
1194    /// |---|---|
1195    /// | [`Mrtr`](ParkedCallKind::Mrtr) | A new `tools/call` with `inputResponses` and the stored `requestState`. The server ended the first request at `input_required`, so this is the call's first execution |
1196    /// | [`Task`](ParkedCallKind::Task) | `tasks/get` on the stored task; outstanding requests equal to the parked ones are answered through `tasks/update`, and polling continues until the task ends. Needs task support on this toolset |
1197    /// | [`Legacy`](ParkedCallKind::Legacy) | Refused as not run unless the tool the server publishes now declares `readOnlyHint` or `idempotentHint`; then the original call runs again, without `responses`, and its new questions park again |
1198    ///
1199    /// A server that answers with new input requests — for example because the
1200    /// `requestState` lapsed — parks the call again: the result is
1201    /// [`McpCallOutcome::Parked`] with the next round, under
1202    /// [`McpTaskConfig::max_input_rounds`] counted across re-issues.
1203    ///
1204    /// # Errors
1205    ///
1206    /// Returns `AdkError::Tool` when `parked` names another toolset, its input requests do
1207    /// not match their digest, `responses` answers a request it does not hold, the
1208    /// [filter](Self::with_filter) excludes the tool, a task is re-issued on a toolset or
1209    /// server without task support, or the call fails. A `Legacy` call that is not
1210    /// retry-safe fails with code `tool.mcp.not_run` without contacting the tool.
1211    ///
1212    /// # Example
1213    ///
1214    /// ```rust
1215    /// use adk_tool::mcp::{McpCallOutcome, McpToolset, ParkedMcpCall};
1216    /// use rmcp::model::{ElicitResult, ElicitationAction, InputResponses};
1217    ///
1218    /// async fn resume(toolset: &McpToolset, checkpoint: &str) -> adk_core::Result<McpCallOutcome> {
1219    ///     let parked: ParkedMcpCall = serde_json::from_str(checkpoint).unwrap();
1220    ///     let approved = ElicitResult::new(ElicitationAction::Accept);
1221    ///     let responses: InputResponses = parked
1222    ///         .input_requests
1223    ///         .keys()
1224    ///         .map(|key| (key.clone(), serde_json::to_value(&approved).unwrap()))
1225    ///         .collect();
1226    ///     toolset.reissue(&parked, responses).await
1227    /// }
1228    /// ```
1229    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                // Answers bind to the questions they were given for: a request the server
1290                // changed or added is asked again.
1291                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, &params, 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                // The tool's effect as the server publishes it now decides the replay.
1313                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    /// Enters the scopes an agent's call made with `ctx` runs in, as a tool of this toolset
1354    /// enters them: sampling requests the server sends meanwhile count against the run, and
1355    /// elicitations belong to the call (spec 3.2 §7.7). The scopes end with the guard.
1356    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    /// A tool for `name` without its declaration, for calls made outside discovery.
1376    ///
1377    /// Fails without contacting the server when the filter excludes `name`.
1378    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            // A re-issued call finishes one an app was already shown for, or not.
1412            #[cfg(feature = "mcp-apps")]
1413            ui: None,
1414        })
1415    }
1416
1417    /// Cancels every remote task this toolset started and has not seen finish.
1418    ///
1419    /// The set covers tasks whose tool-call future was dropped and tasks an
1420    /// in-flight call is still polling, so this also cancels in-flight calls:
1421    /// each one returns a task error once the server reports the cancellation.
1422    ///
1423    /// Each task is checked with `tasks/get` first. A task that is already
1424    /// terminal, or that the server no longer knows (its TTL expired, or the
1425    /// connection was refreshed into a new session), is released without a
1426    /// cancel request. Any other task receives `tasks/cancel` and a second
1427    /// `tasks/get`. A task stays tracked until a terminal status or an
1428    /// unknown-task response confirms it, so calling this again re-checks it.
1429    ///
1430    /// Nothing else prunes the set: every task whose call ended before it saw a
1431    /// terminal status stays tracked until this runs, so a long-lived toolset
1432    /// that drops calls should call it periodically as well as at shutdown.
1433    ///
1434    /// Cancellation is cooperative on the server side, so bound this call
1435    /// with the shutdown deadline. [`McpServerManager`](super::McpServerManager)
1436    /// runs it within its grace period before closing a managed session.
1437    ///
1438    /// # Errors
1439    ///
1440    /// Returns `AdkError::Tool` naming a task whose outcome is not confirmed:
1441    /// `tasks/get` or `tasks/cancel` failed for a reason other than an unknown
1442    /// or finished task, or the task is still running after the cancel request.
1443    /// Tasks confirmed by the same call are released regardless.
1444    ///
1445    /// # Example
1446    ///
1447    /// ```no_run
1448    /// use adk_tool::mcp::McpToolset;
1449    /// use std::time::Duration;
1450    ///
1451    /// async fn shutdown(toolset: &McpToolset) {
1452    ///     let cleanup = toolset.cancel_pending_tasks();
1453    ///     match tokio::time::timeout(Duration::from_secs(5), cleanup).await {
1454    ///         Ok(Ok(())) => {}
1455    ///         Ok(Err(error)) => tracing::warn!(%error, "remote MCP tasks may still run"),
1456    ///         Err(_) => tracing::warn!("MCP task cleanup exceeded the shutdown deadline"),
1457    ///     }
1458    ///     toolset.cancellation_token().await.cancel();
1459    /// }
1460    /// ```
1461    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    /// List static resources from the connected MCP server.
1517    ///
1518    /// Returns the list of resources advertised by the server via the
1519    /// `resources/list` protocol method. Returns an empty `Vec` when the
1520    /// server does not support resources (i.e. responds with
1521    /// `MethodNotFound`).
1522    ///
1523    /// # Errors
1524    ///
1525    /// Returns `AdkError::Tool` on transport or unexpected server errors, and when
1526    /// the listing exceeds the [discovery limits](Self::with_discovery_limits).
1527    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    /// List URI template resources from the connected MCP server.
1551    ///
1552    /// Returns the list of resource templates advertised by the server via
1553    /// the `resourceTemplates/list` protocol method. Returns an empty `Vec`
1554    /// when the server does not support resource templates (i.e. responds
1555    /// with `MethodNotFound`).
1556    ///
1557    /// # Errors
1558    ///
1559    /// Returns `AdkError::Tool` on transport or unexpected server errors, and when
1560    /// the listing exceeds the [discovery limits](Self::with_discovery_limits).
1561    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    /// Read a resource by URI from the connected MCP server.
1587    ///
1588    /// Delegates to the `resources/read` protocol method. Returns the
1589    /// resource contents on success.
1590    ///
1591    /// # Errors
1592    ///
1593    /// Returns `AdkError::Tool("resource not found: {uri}")` when the URI
1594    /// does not match any resource on the server. Returns a generic
1595    /// `AdkError::Tool` on transport or other server errors.
1596    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    /// The apps this server's tools show (spec 3.3 §6.1 `genui-apps`): each tool's
1612    /// `_meta.ui`, including the tools only an app may call, which
1613    /// [`tools`](Toolset::tools) leaves out.
1614    ///
1615    /// # Example
1616    ///
1617    /// ```rust,ignore
1618    /// for binding in toolset.ui_bindings().await? {
1619    ///     println!("{} shows {} (model: {})", binding.tool, binding.resource_uri, binding.visibility.model);
1620    /// }
1621    /// ```
1622    ///
1623    /// # Errors
1624    ///
1625    /// Returns `AdkError::Tool` when the server cannot be reached or its listing exceeds the
1626    /// [discovery limits](Self::with_discovery_limits).
1627    #[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    /// Who may call each tool this server publishes, by its name on the server, in the
1634    /// server's order: its `_meta.ui.visibility`, or the model and the app when it declares
1635    /// none (spec 3.3 §6.1 `genui-apps`; see [`McpUiVisibility::of_tool`](super::apps::McpUiVisibility::of_tool)).
1636    ///
1637    /// # Example
1638    ///
1639    /// ```rust,ignore
1640    /// for (tool, visibility) in toolset.tool_visibility().await? {
1641    ///     println!("{tool}: model {}, app {}", visibility.model, visibility.app);
1642    /// }
1643    /// ```
1644    ///
1645    /// # Errors
1646    ///
1647    /// Returns `AdkError::Tool` when the server cannot be reached or its listing exceeds the
1648    /// [discovery limits](Self::with_discovery_limits).
1649    #[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    /// Every tool the server lists now, uncached, within the discovery limits.
1659    #[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    /// Reads the app at `uri`, a `ui://` resource, with what its `_meta.ui` declares
1678    /// (spec 3.3 §6.1 `genui-apps`). A host still checks it before it shows it.
1679    ///
1680    /// # Example
1681    ///
1682    /// ```rust,ignore
1683    /// let app = toolset.read_app("ui://weather/app").await?;
1684    /// assert_eq!(app.mime_type, adk_tool::mcp::MCP_APP_MIME_TYPE);
1685    /// ```
1686    ///
1687    /// # Errors
1688    ///
1689    /// Returns `AdkError::Tool` when `uri` is not a `ui://` URI, the resource cannot be read,
1690    /// or it is not an MCP App's HTML.
1691    #[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    /// Return the prompt templates published by the connected MCP server.
1704    ///
1705    /// Returns an empty `Vec` when the server does not support prompts.
1706    ///
1707    /// # Errors
1708    ///
1709    /// Returns `AdkError::Tool` on transport or unexpected server errors, and when
1710    /// the listing exceeds the [discovery limits](Self::with_discovery_limits).
1711    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    /// Resolve one published MCP prompt with optional typed arguments.
1735    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    /// Request completion suggestions for one prompt argument.
1752    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    /// Request completion suggestions for one resource-template argument.
1771    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    /// Subscribe to change notifications for a resource URI.
1790    pub async fn subscribe_resource(&self, uri: &str) -> Result<()> {
1791        let client = self.client.open_connection(&self.name).await?;
1792        // `subscriptions/listen` replaces this in 2026-07-28, but we negotiate
1793        // 2025-11-25, and `listen` also stops routing notifications through
1794        // `ClientHandler`, which this crate's resource callbacks rely on.
1795        #[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    /// Remove a resource subscription created by [`subscribe_resource`](Self::subscribe_resource).
1804    pub async fn unsubscribe_resource(&self, uri: &str) -> Result<()> {
1805        let client = self.client.open_connection(&self.name).await?;
1806        // Paired with `subscribe_resource`; see the note there.
1807        #[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            // Read before fetching, so a change notified or an invalidation made mid-fetch
1840            // keeps the result out of the cache.
1841            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                    // A server that pages without end would do the same on a new connection.
1867                    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        // Convert MCP tools to ADK tools
1936        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            // Apply filter if present
1945            if let Some(ref filter) = self.tool_filter
1946                && !filter(&tool_name)
1947            {
1948                continue;
1949            }
1950
1951            // The server chooses the name as well as the schema, so logs show it escaped.
1952            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            // A tool only an app may call, with an app of its own or not, is never the model's
1963            // (spec 3.3 §6.1 `genui-apps`).
1964            #[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            // The first definition of a name wins, whatever happens to it below.
1976            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            // Measured from the server's document before anything copies or logs it.
1986            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    /// Ends the MCP session and the server process behind it, waiting at most the
2069    /// [close timeout](McpToolset::with_close_timeout).
2070    ///
2071    /// Pending remote tasks are cancelled first, then the rmcp service. A stdio server's
2072    /// input is closed and its process waited for, or killed if it is still running 3
2073    /// seconds later; a Streamable HTTP session is ended with `DELETE`.
2074    ///
2075    /// Closing is final and shared: clones of this toolset and every tool it produced
2076    /// stop with it. Afterwards [`tools`](Toolset::tools), tool calls, and the resource
2077    /// and prompt methods fail with an `AdkError` whose code is `tool.mcp.closed`, and a
2078    /// [connection factory](McpToolset::with_connection_factory) is not used to
2079    /// reconnect. Build a new toolset to reach the server again. Closing again only waits
2080    /// for the first close to finish.
2081    async fn close(&self) {
2082        self.close_within(self.close_timeout).await;
2083    }
2084}
2085
2086impl McpToolset<super::elicitation::AdkClientHandler> {
2087    /// Create a McpToolset with elicitation support from a transport.
2088    ///
2089    /// This creates the MCP client using `AdkClientHandler`, which advertises
2090    /// elicitation capabilities and delegates requests to the provided handler.
2091    ///
2092    /// # Example
2093    ///
2094    /// ```rust,ignore
2095    /// use adk_tool::{McpToolset, ElicitationHandler, AutoDeclineElicitationHandler};
2096    /// use adk_tool::mcp::rmcp::transport::TokioChildProcess;
2097    /// use tokio::process::Command;
2098    /// use std::sync::Arc;
2099    ///
2100    /// let transport = TokioChildProcess::new(Command::new("my-mcp-server"))?;
2101    /// let handler = Arc::new(AutoDeclineElicitationHandler);
2102    /// let toolset = McpToolset::with_elicitation_handler(transport, handler).await?;
2103    /// ```
2104    ///
2105    /// # ConnectionFactory with Elicitation
2106    ///
2107    /// To preserve elicitation across reconnections, clone the `Arc<dyn ElicitationHandler>`
2108    /// into your `ConnectionFactory` implementation:
2109    ///
2110    /// ```rust,ignore
2111    /// use adk_tool::{McpToolset, ElicitationHandler};
2112    /// use adk_tool::mcp::ConnectionFactory;
2113    /// use adk_tool::mcp::rmcp::{
2114    ///     ServiceExt,
2115    ///     service::{RoleClient, RunningService},
2116    ///     transport::TokioChildProcess,
2117    /// };
2118    /// use tokio::process::Command;
2119    /// use std::sync::Arc;
2120    ///
2121    /// struct MyReconnectFactory {
2122    ///     handler: Arc<dyn ElicitationHandler>,
2123    ///     server_command: String,
2124    /// }
2125    ///
2126    /// // The factory creates a fresh AdkClientHandler on each reconnection,
2127    /// // so the new connection advertises elicitation capabilities.
2128    /// // The ConnectionFactory trait itself is unchanged.
2129    /// ```
2130    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    /// Create an MCP toolset with elicitation and resource notification handlers.
2148    ///
2149    /// Both handlers are installed before the protocol handshake, so resource
2150    /// update notifications can be received immediately after subscribing.
2151    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    /// Create a McpToolset with MCP sampling support from a transport.
2173    ///
2174    /// This creates the MCP client using `AdkClientHandler`, which advertises
2175    /// both elicitation and sampling capabilities. When the connected MCP server
2176    /// sends a `sampling/createMessage` request, it is delegated to the provided
2177    /// [`SamplingHandler`](crate::sampling::SamplingHandler).
2178    ///
2179    /// An elicitation handler is also required because `AdkClientHandler` always
2180    /// advertises elicitation. Use [`AutoDeclineElicitationHandler`](super::elicitation::AutoDeclineElicitationHandler) if you don't
2181    /// need custom elicitation behavior.
2182    ///
2183    /// # Example
2184    ///
2185    /// ```rust,ignore
2186    /// use adk_tool::{McpToolset, AutoDeclineElicitationHandler};
2187    /// use adk_tool::sampling::LlmSamplingHandler;
2188    /// use adk_tool::mcp::rmcp::transport::TokioChildProcess;
2189    /// use tokio::process::Command;
2190    /// use std::sync::Arc;
2191    ///
2192    /// let transport = TokioChildProcess::new(Command::new("my-mcp-server"))?;
2193    /// let elicitation = Arc::new(AutoDeclineElicitationHandler);
2194    /// let sampling = Arc::new(LlmSamplingHandler::new(my_llm.clone()));
2195    /// let toolset = McpToolset::with_sampling_handler(transport, elicitation, sampling).await?;
2196    /// ```
2197    ///
2198    /// # ConnectionFactory with Sampling
2199    ///
2200    /// To preserve sampling across reconnections, clone both handler `Arc`s
2201    /// into your `ConnectionFactory` implementation and rebuild the
2202    /// `AdkClientHandler` on each reconnection.
2203    #[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    /// Create a toolset with elicitation, sampling, and resource notifications.
2224    #[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/// How a call answers the server's input requests (spec 3.2 §10 T2).
2250#[derive(Clone, Copy, PartialEq, Eq)]
2251enum InputMode {
2252    /// Through the connection's handler, in process: the single-process fast path.
2253    Answer,
2254    /// By ending the call with its parked form.
2255    Park,
2256}
2257
2258/// The scopes of an agent's call, entered by [`McpToolset::enter_call_scopes`]; they end
2259/// when this is dropped.
2260pub(crate) struct CallScopes {
2261    #[cfg(feature = "mcp-sampling")]
2262    _sampling: Option<crate::sampling::SamplingScopeGuard>,
2263    _elicitation: super::elicitation::ElicitationScopeGuard,
2264}
2265
2266/// A call's identity and input policy, kept across its rounds.
2267struct CallSpec {
2268    /// The agent's function call ID, recorded in the parked form.
2269    call_id: Option<String>,
2270    mode: InputMode,
2271    /// Input rounds taken before this attempt; nonzero for a re-issue.
2272    input_rounds: usize,
2273}
2274
2275/// Individual MCP tool wrapper that implements the ADK `Tool` trait.
2276///
2277/// This struct wraps an MCP tool and proxies execution calls to the MCP server.
2278struct McpTool<S>
2279where
2280    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
2281{
2282    name: String,
2283    /// `mcp:{toolset name}`, the identity approvals of this tool's calls bind to.
2284    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    /// Safety hints published by the MCP server for this tool.
2293    annotations: Option<ToolAnnotations>,
2294    /// `annotations` as the JSON object the server sent, for [`Tool::annotations`].
2295    annotations_json: Option<Value>,
2296    /// Whether the negotiated server capabilities permit task-augmented tool calls.
2297    server_supports_tasks: bool,
2298    /// Task configuration
2299    task_config: McpTaskConfig,
2300    active_tasks: Arc<Mutex<BTreeSet<String>>>,
2301    resource_subscriptions: Arc<RwLock<BTreeSet<String>>>,
2302    /// Policy bridge used to fulfil MRTR input without keeping server state.
2303    mrtr_handler: Option<super::elicitation::AdkClientHandler>,
2304    /// The app the tool shows, from its `_meta.ui` (spec 3.3 §6.1 `genui-apps`).
2305    #[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    /// The name of the toolset that produced this tool.
2314    fn toolset_name(&self) -> &str {
2315        self.origin.strip_prefix("mcp:").unwrap_or(&self.origin)
2316    }
2317
2318    /// Runs one call whose input the connection's handler answers in process.
2319    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    /// The `tools/call` parameters for `args`, which must be an object or null.
2332    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    /// Runs the call `params` describes to its outcome under `spec`.
2344    async fn run(&self, params: CallToolRequestParams, spec: &CallSpec) -> Result<McpCallOutcome> {
2345        // SEP-2663 moved the task decision to the server, so one request shape
2346        // covers both modes and the response says which one happened.
2347        let mut call =
2348            ParkedMcpCall::of_call(self.toolset_name(), &params, 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                // Armed before the first await, so dropping the call from here on cancels a
2364                // task that nothing would poll.
2365                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                    // Nothing polls this task, so stop it rather than leave it running remotely.
2370                    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            // `call_tool_with_retry` returns input requests only to a call that parks.
2399            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    /// Sends `tools/call` and returns the response envelope unchanged.
2432    ///
2433    /// Sends one request per round rather than using rmcp's `call_tool`: the
2434    /// latter fulfils SEP-2322 `input_required` rounds on its own and rejects a
2435    /// task response outright, which would break every server that
2436    /// materializes a task.
2437    ///
2438    /// Returns the response with the peer of the connection that answered it and the input
2439    /// rounds the call has taken. A call that parks gets an `input_required` with input
2440    /// requests back instead of having them answered.
2441    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(), &params, 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            // A legacy `elicitation/create` arriving meanwhile belongs to this call.
2464            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                    // The same checks rmcp's `call_tool` applies to each round.
2483                    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                            // A state-only round asks nothing, so back off before resending it.
2518                            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    /// Answers one MRTR or in-task input batch through the connection's policy.
2587    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    /// Answers task `task_id`'s input requests through `tasks/update`.
2619    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    /// Requests cancellation once; the pending-task set keeps the task until a
2636    /// status confirms it.
2637    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            // The task already finished or the server dropped it; nothing to cancel.
2645            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    /// Poll a protocol-level MCP task until completion or timeout.
2656    ///
2657    /// `call` is the call the task runs, with the input rounds taken so far; `answered` holds
2658    /// answers to re-send while the server still lists their requests. A call that parks
2659    /// returns its parked form when the task asks something not yet answered.
2660    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                // SEP-2663 inlines the result in the status response, so a
2715                // completed task needs no second round trip.
2716                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                    // Re-sending cached answers is not a new round of questions.
2768                    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                            // The task waits for its answers durably; it is no longer this
2784                            // toolset's to cancel.
2785                            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                    // The server consumed every answer, so a later key reuse is a new question.
2805                    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    /// SEP-2663 removed the per-tool task contract, so the server decides per
2831    /// call whether to materialize a task. The remaining signal is therefore
2832    /// per-connection: any call may return a task when both sides allow it.
2833    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        // Sampling requests the server sends while this call is in flight count against the run.
2867        #[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        // Elicitations the server sends while this call is in flight belong to it
2876        // (spec 3.1 §10 T1).
2877        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        // The call that shows an app says so in its own event, so a host shows the app only
2892        // for a call this tool made (spec 3.3 §6.1 `genui-apps`).
2893        #[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// McpTool<S> is Send + Sync when S: Send + Sync because all fields are
2906// composed of Send + Sync primitives (String, Arc<Mutex<_>>, Arc<dyn Send + Sync>, etc.).
2907// The compiler enforces this through the Tool trait bound (Tool: Send + Sync).
2908// No unsafe impl needed — the previous unsafe impl was removed as unnecessary.
2909
2910#[cfg(test)]
2911mod tests {
2912    use super::*;
2913
2914    /// Proves that `McpTool<S>` is `Send + Sync` for any service `S: Send + Sync`
2915    /// without requiring `unsafe impl`. The compiler rejects this test at build
2916    /// time if any field breaks the auto-trait derivation.
2917    ///
2918    /// This replaced a previous `unsafe impl Send/Sync for McpTool<S>` that was
2919    /// unnecessary — all fields (String, Arc<Mutex<_>>, Arc<dyn Send+Sync>, bool)
2920    /// are naturally Send + Sync.
2921    #[test]
2922    fn mcp_tool_is_send_and_sync() {
2923        fn require_send_sync<T: Send + Sync>() {}
2924
2925        // The compiler proves Send + Sync for McpTool<S> and McpToolset<S> by
2926        // type-checking these function bodies. If any field were !Send or !Sync,
2927        // this would be a compile error — no unsafe needed.
2928        //
2929        // () satisfies Service<RoleClient> via the ClientHandler blanket impl
2930        // in rmcp, so this is a valid concrete instantiation.
2931        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    /// The default must stay off.
3002    ///
3003    /// The opt-in *is* the security boundary of #504. The other tests pass `false` explicitly,
3004    /// so they verify the gate honours the flag but not that the flag starts closed — flipping
3005    /// every constructor to `true` left the whole suite green. This is the guard for that.
3006    #[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    /// Publishes a fixed tool catalog over `tools/list`.
3057    #[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    /// Runs discovery against `catalog` over an in-process pipe.
3077    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        // The root, "type", "properties", the "id" object and its "type", "required", "id".
3158        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    /// Counts `tools/call` requests so a refused call can be shown never to reach the server.
3344    #[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    /// Answers every call with `isError` and guidance for the model.
3368    #[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}