Skip to main content

strands/mcp/
mcp_tool.rs

1//! [`McpTool`], a tool that proxies calls to an MCP server.
2
3use std::fmt;
4
5use super::client::{McpCallToolOptions, McpClient};
6use super::error::{McpError, URL_ELICITATION_REQUIRED};
7use crate::error::Error;
8use crate::tools::{Tool, ToolContext, ToolOutcome, ToolStream, create_error_result};
9use crate::types::media::base64_bytes;
10use crate::types::{
11    ImageBlock, ImageFormat, ImageSource, JsonObject, JsonSchema, JsonValue, ToolResultBlock, ToolResultContent,
12    ToolSpec,
13};
14
15const NO_OUTPUT: &str = "Tool execution completed successfully with no output.";
16
17/// What an [`McpTool`] is built from (`McpToolConfig`).
18#[derive(Debug, Clone, bon::Builder)]
19#[builder(on(String, into))]
20#[non_exhaustive]
21pub struct McpToolConfig {
22    /// The agent-facing tool name.
23    pub name: String,
24    /// What the tool does.
25    pub description: String,
26    /// JSON Schema for the input.
27    pub input_schema: JsonSchema,
28    /// JSON Schema for the output.
29    pub output_schema: Option<JsonSchema>,
30    /// The server's behaviour hints, such as `readOnlyHint`.
31    pub annotations: Option<JsonObject>,
32    /// The client that runs the tool.
33    pub client: McpClient,
34}
35
36/// A tool that proxies calls to an MCP server (`McpTool`).
37///
38/// [`McpClient::list_tools`] builds these. The tool is invoked under its server-side name, which
39/// differs from [`name`](Tool::name) when the client sets a prefix.
40#[derive(Clone)]
41pub struct McpTool {
42    name: String,
43    description: String,
44    tool_spec: ToolSpec,
45    server_tool_name: String,
46    client: McpClient,
47}
48
49impl McpTool {
50    /// Creates a tool invoked on the server under `config.name`.
51    #[must_use]
52    pub fn new(config: McpToolConfig) -> Self {
53        let server_tool_name = config.name.clone();
54        Self::listed(config, server_tool_name)
55    }
56
57    pub(crate) fn listed(config: McpToolConfig, server_tool_name: String) -> Self {
58        let mut tool_spec =
59            ToolSpec::new(config.name.clone(), config.description.clone()).with_input_schema(config.input_schema);
60        tool_spec.output_schema = config.output_schema;
61        tool_spec.annotations = config.annotations;
62        Self {
63            name: config.name,
64            description: config.description,
65            tool_spec,
66            server_tool_name,
67            client: config.client,
68        }
69    }
70
71    /// The MCP client this tool belongs to.
72    #[must_use]
73    pub fn mcp_client(&self) -> &McpClient {
74        &self.client
75    }
76
77    /// The name the server lists the tool under.
78    #[must_use]
79    pub fn server_tool_name(&self) -> &str {
80        &self.server_tool_name
81    }
82}
83
84impl fmt::Debug for McpTool {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        f.debug_struct("McpTool")
87            .field("name", &self.name)
88            .field("server_tool_name", &self.server_tool_name)
89            .finish_non_exhaustive()
90    }
91}
92
93impl Tool for McpTool {
94    fn name(&self) -> &str {
95        &self.name
96    }
97
98    fn description(&self) -> &str {
99        &self.description
100    }
101
102    fn tool_spec(&self) -> ToolSpec {
103        self.tool_spec.clone()
104    }
105
106    fn stream(&self, context: ToolContext) -> ToolStream {
107        let tool = self.clone();
108        ToolStream::from_future(async move {
109            let tool_use_id = context.tool_use().tool_use_id.clone();
110            let options = McpCallToolOptions {
111                cancel_signal: Some(context.cancel_signal().clone()),
112                ..McpCallToolOptions::default()
113            };
114            let result = tool
115                .client
116                .call_tool(&tool, context.tool_use().input.clone(), options)
117                .await;
118            ToolOutcome::Result(tool_result(tool_use_id, result))
119        })
120    }
121}
122
123/// Translates a `tools/call` outcome into a tool result.
124pub(crate) fn tool_result(tool_use_id: String, result: Result<JsonValue, Error>) -> ToolResultBlock {
125    let raw = match result {
126        Ok(raw) => raw,
127        Err(error) => return error_result(tool_use_id, error),
128    };
129    let Some(items) = raw.get("content").and_then(JsonValue::as_array) else {
130        return create_error_result(
131            "Invalid tool result from MCP Client: missing content array",
132            tool_use_id,
133        );
134    };
135    let mut content: Vec<ToolResultContent> = items.iter().map(map_content).collect();
136    if content.is_empty() {
137        content.push(ToolResultContent::text(NO_OUTPUT));
138    }
139    let is_error = raw.get("isError").is_some_and(is_truthy);
140    if is_error {
141        ToolResultBlock::error(tool_use_id, content)
142    } else {
143        ToolResultBlock::success(tool_use_id, content)
144    }
145}
146
147fn is_truthy(value: &JsonValue) -> bool {
148    match value {
149        JsonValue::Null => false,
150        JsonValue::Bool(value) => *value,
151        JsonValue::Number(number) => number.as_f64().is_some_and(|n| n != 0.0 && !n.is_nan()),
152        JsonValue::String(text) => !text.is_empty(),
153        JsonValue::Array(_) | JsonValue::Object(_) => true,
154    }
155}
156
157fn error_result(tool_use_id: String, error: Error) -> ToolResultBlock {
158    if let Error::Mcp(mcp) = &error
159        && let Some(elicitations) = url_elicitations(mcp)
160    {
161        let text = format!(
162            "MCP Elicitation required: [{}] with data {}",
163            mcp.to_js_string(),
164            JsonValue::Array(elicitations.clone())
165        );
166        return ToolResultBlock::error(tool_use_id, vec![ToolResultContent::text(text)]);
167    }
168    create_error_result(error, tool_use_id)
169}
170
171fn url_elicitations(error: &McpError) -> Option<&Vec<JsonValue>> {
172    let McpError::Protocol {
173        code: URL_ELICITATION_REQUIRED,
174        data: Some(data),
175        ..
176    } = error
177    else {
178        return None;
179    };
180    data.get("elicitations")
181        .and_then(JsonValue::as_array)
182        .filter(|elicitations| !elicitations.is_empty())
183}
184
185/// Maps one MCP content item to tool result content.
186pub(crate) fn map_content(item: &JsonValue) -> ToolResultContent {
187    let Some(record) = item.as_object() else {
188        return ToolResultContent::json(item.clone());
189    };
190    match record.get("type").and_then(JsonValue::as_str) {
191        Some("text") => match record.get("text").and_then(JsonValue::as_str) {
192            Some(text) => ToolResultContent::text(text),
193            None => ToolResultContent::json(item.clone()),
194        },
195        Some("image") => map_image(record, item),
196        Some("resource") => map_embedded_resource(record, item),
197        _ => ToolResultContent::json(item.clone()),
198    }
199}
200
201fn image_format(mime_type: &str) -> Option<ImageFormat> {
202    let format = crate::mime::to_media_format(mime_type)?;
203    serde_json::from_value(JsonValue::String(format.to_owned())).ok()
204}
205
206fn image_block(format: ImageFormat, data: &str) -> Option<ToolResultContent> {
207    let bytes = base64_bytes::decode(data).ok()?;
208    Some(ToolResultContent::Image(ImageBlock::new(
209        format,
210        ImageSource::Bytes(bytes),
211    )))
212}
213
214fn map_image(record: &JsonObject, item: &JsonValue) -> ToolResultContent {
215    let data = record.get("data").and_then(JsonValue::as_str);
216    let mime_type = record.get("mimeType").and_then(JsonValue::as_str);
217    let (Some(data), Some(mime_type)) = (data, mime_type) else {
218        tracing::warn!("content_type=<image> | mcp image content missing data or mimeType, falling back to json");
219        return ToolResultContent::json(item.clone());
220    };
221    let Some(format) = image_format(mime_type) else {
222        tracing::warn!("mime_type=<{mime_type}> | unsupported mcp image mime type, falling back to json");
223        return ToolResultContent::json(item.clone());
224    };
225    image_block(format, data).unwrap_or_else(|| ToolResultContent::json(item.clone()))
226}
227
228fn map_embedded_resource(record: &JsonObject, item: &JsonValue) -> ToolResultContent {
229    let Some(resource) = record.get("resource").and_then(JsonValue::as_object) else {
230        return ToolResultContent::json(item.clone());
231    };
232    if let Some(text) = resource.get("text").and_then(JsonValue::as_str) {
233        return ToolResultContent::text(text);
234    }
235    let blob = resource.get("blob").and_then(JsonValue::as_str);
236    let mime_type = resource.get("mimeType").and_then(JsonValue::as_str);
237    let (Some(blob), Some(mime_type)) = (blob, mime_type) else {
238        return ToolResultContent::json(item.clone());
239    };
240    if let Some(block) = image_format(mime_type).and_then(|format| image_block(format, blob)) {
241        return block;
242    }
243    tracing::warn!("mime_type=<{mime_type}> | unsupported mcp resource blob mime type, falling back to json");
244    ToolResultContent::json(item.clone())
245}