Skip to main content

trusty_code/mcp/
tool.rs

1//! One configured MCP server's tool, as a `ToolExecutor` (#5428).
2//!
3//! Why: a tool discovered over `tools/list` has to sit in the same
4//! [`crate::tools::ToolRegistry`] as every in-process tool so the agent loop
5//! dispatches it identically — the seam `trusty_agents::tools::mcp_live` uses
6//! for the same job.
7//! What: [`McpBridgeTool`] holds the composed registry name, the tool's REAL
8//! name on the server, and a shared client handle. `execute` forwards to
9//! `tools/call` and renders the MCP content frames as text. Every failure is a
10//! recoverable `ToolResult::err`, never fatal: one broken server must not end
11//! a task run.
12//! Test: `super::tests::tool_tests`, `mcp_loader_e2e::end_to_end_dispatch_echoes_through_the_registry`.
13
14use std::sync::Arc;
15
16use async_trait::async_trait;
17use serde_json::{Value, json};
18use tokio::sync::Mutex;
19use trusty_common::stdio_mcp_client::{McpTool, StdioMcpClient};
20
21use crate::tools::traits::{ToolExecutor, ToolResult};
22
23/// Upper bound on a passed-through `inputSchema`, in bytes.
24///
25/// Why: the advertised schema is cloned into this tool and re-serialised on
26/// every `registry.schemas()` call, so a server advertising a huge one is an
27/// unbounded per-tool memory and CPU cost (#3266, the same bound
28/// `trusty_agents::tools::mcp_live` applies). 64 KiB is far above any
29/// legitimate schema observed in this workspace.
30/// Test: `super::tests::tool_tests::an_oversized_input_schema_is_rejected`.
31pub const MAX_INPUT_SCHEMA_BYTES: usize = 64 * 1024;
32
33/// Compose the registry name for one server's tool.
34///
35/// Why: `mcp__<server>__<tool>` is Claude Code's own convention, so a model
36/// already trained on that surface reads a `tcode` tool list the same way, and
37/// the `mcp__` prefix keeps a server's tool from ever colliding with a built-in.
38/// Test: `super::tests::tool_tests::composed_names_follow_the_claude_code_convention`.
39pub fn composed_name(server: &str, tool: &str) -> String {
40    format!("mcp__{server}__{tool}")
41}
42
43/// Build the OpenAI-shape function descriptor for one discovered tool.
44///
45/// Why: the server told us the real argument shape, so passing its
46/// `inputSchema` through gives the model accurate arguments instead of an
47/// unconstrained object.
48/// What: `Err` with a reason when the schema is over [`MAX_INPUT_SCHEMA_BYTES`]
49/// — the caller turns that into an issue and SKIPS the tool, per the #5428
50/// ruling. A server that advertises no object schema at all gets an
51/// empty-object one, which is a missing shape rather than an abusive one.
52/// Test: `super::tests::tool_tests::an_oversized_input_schema_is_rejected`,
53/// `super::tests::tool_tests::an_absent_input_schema_falls_back_to_an_open_object`.
54pub fn build_schema(server: &str, tool: &McpTool) -> Result<Value, String> {
55    let params = if tool.input_schema.is_object() {
56        let bytes = serde_json::to_vec(&tool.input_schema)
57            .map_err(|e| format!("its inputSchema could not be serialised: {e}"))?;
58        if bytes.len() > MAX_INPUT_SCHEMA_BYTES {
59            return Err(format!(
60                "its inputSchema is {} bytes, over the {MAX_INPUT_SCHEMA_BYTES}-byte cap",
61                bytes.len()
62            ));
63        }
64        tool.input_schema.clone()
65    } else {
66        json!({"type": "object", "properties": {}})
67    };
68    Ok(json!({
69        "type": "function",
70        "function": {
71            "name": composed_name(server, &tool.name),
72            "description": format!(
73                "[{server}] {}",
74                tool.description.clone().unwrap_or_default()
75            ),
76            "parameters": params,
77        }
78    }))
79}
80
81/// Render an MCP `tools/call` result as the text the model sees.
82///
83/// Why: MCP returns an array of content frames; the agent loop takes a string.
84/// What: joins every `text` frame with a newline. A result carrying no text
85/// frame renders as its own JSON, so a structured-only reply is still visible
86/// rather than reported as empty.
87/// Test: `super::tests::tool_tests::text_frames_are_joined`,
88/// `super::tests::tool_tests::a_frameless_result_renders_as_json`.
89pub fn render_result(result: &Value) -> String {
90    let frames: Vec<&str> = result
91        .get("content")
92        .and_then(Value::as_array)
93        .map(|items| {
94            items
95                .iter()
96                .filter_map(|item| item.get("text").and_then(Value::as_str))
97                .collect()
98        })
99        .unwrap_or_default();
100    if frames.is_empty() {
101        return result.to_string();
102    }
103    frames.join("\n")
104}
105
106/// Whether an MCP result carries the in-band `isError` flag.
107///
108/// Why: a server reports a tool-level failure as `isError: true` content, not
109/// as a JSON-RPC error, so `call_tool` returns `Ok` and the flag is the only
110/// signal the call actually failed.
111/// Test: `super::tests::tool_tests::the_in_band_error_flag_is_detected`.
112pub fn is_mcp_error(result: &Value) -> bool {
113    result
114        .get("isError")
115        .and_then(Value::as_bool)
116        .unwrap_or(false)
117}
118
119/// A `ToolExecutor` bridging one tool on one configured MCP server.
120///
121/// Why: the registry dispatches by name and knows nothing about MCP; this is
122/// the adapter that keeps it that way.
123/// What: `name` is the composed `mcp__<server>__<tool>` key the registry and
124/// the advertised schema both use; `remote` is the bare name the server itself
125/// answers to. The client is shared (`Arc<Mutex<_>>`) because one stdio pair
126/// carries one in-flight request at a time, and because every tool on a server
127/// must keep THAT server's child alive — dropping the last handle kills it.
128/// Test: `super::tests::tool_tests::execute_surfaces_a_broken_server_recoverably`,
129/// `mcp_loader_e2e::end_to_end_dispatch_echoes_through_the_registry`.
130pub struct McpBridgeTool {
131    name: String,
132    remote: String,
133    server: String,
134    schema: Value,
135    client: Arc<Mutex<StdioMcpClient>>,
136}
137
138impl McpBridgeTool {
139    /// Build one bridge tool, or say why the tool cannot be exposed.
140    ///
141    /// What: `Err` carries the reason [`build_schema`] refused, for the caller
142    /// to record as an issue.
143    /// Test: `super::tests::tool_tests::an_oversized_input_schema_is_rejected`.
144    pub fn new(
145        server: &str,
146        tool: &McpTool,
147        client: Arc<Mutex<StdioMcpClient>>,
148    ) -> Result<Self, String> {
149        Ok(Self {
150            name: composed_name(server, &tool.name),
151            remote: tool.name.clone(),
152            server: server.to_string(),
153            schema: build_schema(server, tool)?,
154            client,
155        })
156    }
157
158    /// The server this tool belongs to.
159    pub fn server(&self) -> &str {
160        &self.server
161    }
162}
163
164#[async_trait]
165impl ToolExecutor for McpBridgeTool {
166    fn name(&self) -> &str {
167        &self.name
168    }
169
170    fn schema(&self) -> Value {
171        self.schema.clone()
172    }
173
174    /// Forward the call to the server, recoverably.
175    ///
176    /// Why: an MCP server can die, hang or reject at any point in a run, and
177    /// none of those may end the agent loop — the model has to be able to read
178    /// the failure and choose something else.
179    /// What: a transport failure and an in-band `isError` both become
180    /// `ToolResult::err` naming the server and the tool, so the model can tell
181    /// "this connector is broken" from "my arguments were wrong".
182    /// Test: `super::tests::tool_tests::execute_surfaces_a_broken_server_recoverably`,
183    /// `mcp_loader_e2e::end_to_end_dispatch_echoes_through_the_registry`.
184    async fn execute(&self, args: Value) -> ToolResult {
185        let mut client = self.client.lock().await;
186        match client.call_tool(&self.remote, args).await {
187            Ok(result) if is_mcp_error(&result) => {
188                let detail = render_result(&result);
189                tracing::warn!(
190                    server = %self.server,
191                    tool = %self.remote,
192                    "mcp: tool reported an error",
193                );
194                ToolResult::err(format!(
195                    "MCP tool '{}' on server '{}' reported an error: {detail}",
196                    self.remote, self.server
197                ))
198            }
199            Ok(result) => ToolResult::ok(render_result(&result)),
200            Err(e) => {
201                tracing::warn!(
202                    server = %self.server,
203                    tool = %self.remote,
204                    error = %e,
205                    "mcp: tool call failed",
206                );
207                ToolResult::err(format!(
208                    "MCP tool '{}' on server '{}' failed: {e}",
209                    self.remote, self.server
210                ))
211            }
212        }
213    }
214}