Skip to main content

rusty_agent_runtime/
mcp.rs

1//! MCP (Model Context Protocol) client support.
2//!
3//! This module lets Rusty Core agents call tools hosted by **any MCP
4//! server**. It provides:
5//!
6//! - JSON-RPC 2.0 framing types ([`JsonRpcRequest`], [`JsonRpcResponse`],
7//!   [`JsonRpcNotification`], [`JsonRpcError`]) with `serde` support.
8//! - A transport-generic [`McpClient`] over tokio `AsyncRead`/`AsyncWrite`,
9//!   supporting both **newline-delimited JSON** (MCP stdio) and **LSP-style
10//!   `Content-Length` headers** ([`Framing`]). Every request carries a
11//!   timeout; a background reader task routes responses to their waiters.
12//! - [`McpStdioClient::spawn`] to launch an MCP server as a child process
13//!   with piped stdin/stdout.
14//! - [`McpToolAdapter`], which wraps a single MCP tool as a Rusty Core
15//!   [`Tool`], and [`McpClient::into_tools`], which lists the server's tools
16//!   and returns them as `Vec<Arc<dyn Tool>>` for direct registration in a
17//!   [`crate::tool::ToolRegistry`].
18//!
19//! All failures map to [`RustyError::Tool`] with an `mcp:` context
20//! prefix.
21//!
22//! ```no_run
23//! # async fn demo() -> rusty_agent_runtime::error::Result<()> {
24//! use rusty_agent_runtime::mcp::McpStdioClient;
25//!
26//! let client = McpStdioClient::spawn("npx", &["-y", "@modelcontextprotocol/server-everything"])?;
27//! client.initialize().await?;
28//! let tools = client.into_tools().await?;
29//! // register into a ToolRegistry and hand to a ReAct agent...
30//! # let _ = tools;
31//! client.shutdown().await?;
32//! # Ok(())
33//! # }
34//! ```
35
36use std::collections::HashMap;
37use std::io;
38use std::process::Stdio;
39use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
40use std::sync::{Arc, Mutex as StdMutex};
41use std::time::Duration;
42
43use async_trait::async_trait;
44use serde::{Deserialize, Serialize};
45use serde_json::{json, Value};
46use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader};
47use tokio::process::{Child, Command};
48use tokio::sync::{oneshot, Mutex};
49use tokio::task::JoinHandle;
50use tokio::time::timeout;
51
52use crate::error::{Result, RustyError};
53use crate::tool::Tool;
54
55/// The MCP protocol revision this client requests during `initialize`.
56///
57/// `2024-11-05` is the most widely implemented revision. The revision the
58/// server answers with is **recorded, not validated**: this client performs
59/// no compatibility negotiation beyond sending this value.
60pub const MCP_PROTOCOL_VERSION: &str = "2024-11-05";
61
62/// Default per-request timeout.
63pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
64
65/// Maximum size of a single inbound frame (bytes), for both framings.
66///
67/// The peer is untrusted: without a cap, a hostile or buggy server could
68/// declare `Content-Length: 4_000_000_000` (or stream one unterminated line)
69/// and turn it into a multi-GiB host allocation. Oversized frames are
70/// rejected *before* any length-driven allocation happens.
71pub const MAX_FRAME_BYTES: usize = 16 * 1024 * 1024;
72
73/// Build an [`RustyError::Tool`] with an `mcp:` context prefix.
74fn tool_err(msg: impl Into<String>) -> RustyError {
75    RustyError::Tool(format!("mcp: {}", msg.into()))
76}
77
78// ---------------------------------------------------------------------------
79// JSON-RPC 2.0 framing types
80// ---------------------------------------------------------------------------
81
82/// A JSON-RPC 2.0 request.
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct JsonRpcRequest {
85    /// Always `"2.0"`.
86    pub jsonrpc: String,
87    /// Request identifier (this client uses monotonically increasing integers).
88    pub id: u64,
89    /// Method name, e.g. `"tools/call"`.
90    pub method: String,
91    /// Structured parameters.
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub params: Option<Value>,
94}
95
96impl JsonRpcRequest {
97    /// A `"2.0"` request with parameters.
98    pub fn new(id: u64, method: impl Into<String>, params: Value) -> Self {
99        Self {
100            jsonrpc: "2.0".to_owned(),
101            id,
102            method: method.into(),
103            params: Some(params),
104        }
105    }
106}
107
108/// A JSON-RPC 2.0 notification (no `id`, no response expected).
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct JsonRpcNotification {
111    /// Always `"2.0"`.
112    pub jsonrpc: String,
113    /// Method name, e.g. `"notifications/initialized"`.
114    pub method: String,
115    /// Structured parameters.
116    #[serde(skip_serializing_if = "Option::is_none")]
117    pub params: Option<Value>,
118}
119
120impl JsonRpcNotification {
121    /// A `"2.0"` notification with parameters.
122    pub fn new(method: impl Into<String>, params: Value) -> Self {
123        Self {
124            jsonrpc: "2.0".to_owned(),
125            method: method.into(),
126            params: Some(params),
127        }
128    }
129}
130
131/// A JSON-RPC 2.0 error object.
132#[derive(Debug, Clone, Serialize, Deserialize)]
133pub struct JsonRpcError {
134    /// Error code (e.g. `-32602` invalid params, `-32603` internal error).
135    pub code: i64,
136    /// Human-readable message.
137    pub message: String,
138    /// Optional structured data.
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub data: Option<Value>,
141}
142
143impl std::fmt::Display for JsonRpcError {
144    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145        write!(f, "JSON-RPC error {}: {}", self.code, self.message)
146    }
147}
148
149/// A JSON-RPC 2.0 response. Exactly one of `result` / `error` is present.
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct JsonRpcResponse {
152    /// Always `"2.0"`.
153    pub jsonrpc: String,
154    /// Echoed request identifier.
155    pub id: Value,
156    /// Success payload.
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub result: Option<Value>,
159    /// Failure payload.
160    #[serde(skip_serializing_if = "Option::is_none")]
161    pub error: Option<JsonRpcError>,
162}
163
164// ---------------------------------------------------------------------------
165// Wire framing
166// ---------------------------------------------------------------------------
167
168/// How JSON-RPC messages are framed on the byte stream.
169#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
170pub enum Framing {
171    /// One JSON object per line — the MCP stdio transport.
172    #[default]
173    NewlineDelimited,
174    /// LSP-style `Content-Length: N\r\n\r\n<body>` headers.
175    ContentLength,
176}
177
178/// Write one framed JSON message.
179async fn write_framed<W>(writer: &mut W, framing: Framing, value: &Value) -> io::Result<()>
180where
181    W: AsyncWrite + Unpin + ?Sized,
182{
183    let body =
184        serde_json::to_vec(value).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
185    match framing {
186        Framing::NewlineDelimited => {
187            writer.write_all(&body).await?;
188            writer.write_all(b"\n").await?;
189        }
190        Framing::ContentLength => {
191            let header = format!("Content-Length: {}\r\n\r\n", body.len());
192            writer.write_all(header.as_bytes()).await?;
193            writer.write_all(&body).await?;
194        }
195    }
196    writer.flush().await
197}
198
199/// Read one framed JSON message. Returns `Ok(None)` on clean EOF.
200///
201/// Bounded by [`MAX_FRAME_BYTES`]: an oversized `Content-Length` header or
202/// an over-long unterminated line is an `InvalidData` error, never an
203/// allocation.
204async fn read_framed<R>(reader: &mut BufReader<R>, framing: Framing) -> io::Result<Option<Value>>
205where
206    R: AsyncRead + Unpin,
207{
208    match framing {
209        Framing::NewlineDelimited => {
210            let mut line = String::new();
211            loop {
212                line.clear();
213                // Read through a `take` adapter so a peer that never
214                // terminates its line cannot grow the buffer past the cap.
215                let n = (&mut *reader)
216                    .take(MAX_FRAME_BYTES as u64 + 1)
217                    .read_line(&mut line)
218                    .await?;
219                if n == 0 {
220                    return Ok(None); // EOF
221                }
222                if line.len() > MAX_FRAME_BYTES {
223                    return Err(io::Error::new(
224                        io::ErrorKind::InvalidData,
225                        format!(
226                            "newline-delimited frame exceeds the {MAX_FRAME_BYTES}-byte frame cap"
227                        ),
228                    ));
229                }
230                let trimmed = line.trim();
231                if trimmed.is_empty() {
232                    continue; // tolerate blank lines
233                }
234                let value = serde_json::from_str(trimmed)
235                    .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
236                return Ok(Some(value));
237            }
238        }
239        Framing::ContentLength => {
240            let mut content_length: Option<usize> = None;
241            let mut line = String::new();
242            loop {
243                line.clear();
244                let n = reader.read_line(&mut line).await?;
245                if n == 0 {
246                    return Ok(None); // EOF before/inside headers
247                }
248                let trimmed = line.trim();
249                if trimmed.is_empty() {
250                    break; // end of headers
251                }
252                if let Some((name, val)) = trimmed.split_once(':') {
253                    if name.trim().eq_ignore_ascii_case("content-length") {
254                        content_length = val.trim().parse().ok();
255                    }
256                }
257            }
258            let len = content_length.ok_or_else(|| {
259                io::Error::new(io::ErrorKind::InvalidData, "missing Content-Length header")
260            })?;
261            if len > MAX_FRAME_BYTES {
262                // Reject before trusting the peer's length with an allocation.
263                return Err(io::Error::new(
264                    io::ErrorKind::InvalidData,
265                    format!("Content-Length {len} exceeds the {MAX_FRAME_BYTES}-byte frame cap"),
266                ));
267            }
268            let mut body = vec![0u8; len];
269            reader.read_exact(&mut body).await?;
270            let value = serde_json::from_slice(&body)
271                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
272            Ok(Some(value))
273        }
274    }
275}
276
277// ---------------------------------------------------------------------------
278// MCP metadata types
279// ---------------------------------------------------------------------------
280
281/// The parsed result of the MCP `initialize` handshake.
282#[derive(Debug, Clone)]
283pub struct InitializeResult {
284    /// Protocol revision the server will use.
285    pub protocol_version: String,
286    /// Server implementation name (`serverInfo.name`).
287    pub server_name: String,
288    /// Server implementation version (`serverInfo.version`).
289    pub server_version: String,
290    /// Raw server capabilities object.
291    pub capabilities: Value,
292}
293
294/// Metadata for one MCP tool, as returned by `tools/list`.
295#[derive(Debug, Clone)]
296pub struct McpToolInfo {
297    /// Tool name.
298    pub name: String,
299    /// Human/model-facing description (may be empty).
300    pub description: String,
301    /// JSON Schema for the tool's arguments (`inputSchema`).
302    pub input_schema: Value,
303}
304
305// ---------------------------------------------------------------------------
306// McpClient
307// ---------------------------------------------------------------------------
308
309type BoxedWriter = Box<dyn AsyncWrite + Unpin + Send>;
310type PendingMap = HashMap<u64, oneshot::Sender<Value>>;
311
312struct ClientInner {
313    framing: Framing,
314    writer: Arc<Mutex<BoxedWriter>>,
315    pending: Arc<Mutex<PendingMap>>,
316    next_id: AtomicU64,
317    closed: AtomicBool,
318    initialized: AtomicBool,
319    request_timeout: StdMutex<Duration>,
320    reader_handle: StdMutex<Option<JoinHandle<()>>>,
321    child: StdMutex<Option<Child>>,
322}
323
324impl Drop for ClientInner {
325    fn drop(&mut self) {
326        if let Ok(mut guard) = self.reader_handle.lock() {
327            if let Some(handle) = guard.take() {
328                handle.abort();
329            }
330        }
331        if let Ok(mut guard) = self.child.lock() {
332            if let Some(mut child) = guard.take() {
333                let _ = child.start_kill();
334            }
335        }
336    }
337}
338
339/// Background task: reads framed messages from the server and routes them.
340///
341/// - Responses (`id` + `result`/`error`) are delivered to the matching
342///   pending oneshot.
343/// - Server-initiated requests (`method` + `id`) get a `-32601` reply, since
344///   this client serves no methods.
345/// - Notifications (`method`, no `id`) are ignored.
346///
347/// On EOF or a fatal read error the task drains `pending`, waking all waiters
348/// with a "connection closed" error.
349async fn reader_loop<R>(
350    reader: R,
351    framing: Framing,
352    pending: Arc<Mutex<PendingMap>>,
353    writer: Arc<Mutex<BoxedWriter>>,
354) where
355    R: AsyncRead + Unpin,
356{
357    let mut reader = BufReader::new(reader);
358    loop {
359        match read_framed(&mut reader, framing).await {
360            Ok(Some(msg)) => {
361                if msg.get("method").is_some() {
362                    if let Some(id) = msg.get("id") {
363                        let reply = json!({
364                            "jsonrpc": "2.0",
365                            "id": id.clone(),
366                            "error": {"code": -32601, "message": "method not found"},
367                        });
368                        let mut w = writer.lock().await;
369                        if write_framed(&mut **w, framing, &reply).await.is_err() {
370                            break;
371                        }
372                    }
373                    // else: notification — ignore.
374                } else if let Some(id) = msg.get("id").and_then(Value::as_u64) {
375                    let tx = pending.lock().await.remove(&id);
376                    if let Some(tx) = tx {
377                        let _ = tx.send(msg);
378                    }
379                }
380            }
381            Ok(None) => break, // clean EOF
382            Err(e) => {
383                // Newline framing is self-resyncing: a malformed or oversized
384                // frame costs one line, not the whole session. IO errors and
385                // Content-Length desync are fatal — the stream can no longer
386                // be trusted, so pending waiters are woken below.
387                if framing == Framing::NewlineDelimited && e.kind() == io::ErrorKind::InvalidData {
388                    tracing::warn!(
389                        error = %e,
390                        "mcp: dropping malformed frame; resyncing on the next line"
391                    );
392                    continue;
393                }
394                tracing::warn!(error = %e, "mcp: reader task terminating on fatal read error");
395                break;
396            }
397        }
398    }
399    // Wake every waiter: dropping the senders makes the receivers fail.
400    pending.lock().await.clear();
401}
402
403/// A transport-generic MCP client over a tokio byte stream.
404///
405/// Cheap to clone (all state is shared); clones see the same connection.
406/// Use [`McpClient::connect`] for an arbitrary transport or
407/// [`McpStdioClient::spawn`] for a child-process stdio server.
408///
409/// Lifecycle: `connect` → [`initialize`](McpClient::initialize) →
410/// [`list_tools`](McpClient::list_tools) / [`call_tool`](McpClient::call_tool)
411/// / [`into_tools`](McpClient::into_tools) → [`shutdown`](McpClient::shutdown).
412#[derive(Clone)]
413pub struct McpClient {
414    inner: Arc<ClientInner>,
415}
416
417impl McpClient {
418    /// Connect over an arbitrary transport using newline-delimited framing
419    /// (the MCP stdio convention).
420    pub fn connect<R, W>(reader: R, writer: W) -> Self
421    where
422        R: AsyncRead + Unpin + Send + 'static,
423        W: AsyncWrite + Unpin + Send + 'static,
424    {
425        Self::connect_with_framing(reader, writer, Framing::NewlineDelimited)
426    }
427
428    /// Connect over an arbitrary transport with explicit framing.
429    pub fn connect_with_framing<R, W>(reader: R, writer: W, framing: Framing) -> Self
430    where
431        R: AsyncRead + Unpin + Send + 'static,
432        W: AsyncWrite + Unpin + Send + 'static,
433    {
434        Self::connect_inner(reader, writer, framing, None)
435    }
436
437    fn connect_inner<R, W>(reader: R, writer: W, framing: Framing, child: Option<Child>) -> Self
438    where
439        R: AsyncRead + Unpin + Send + 'static,
440        W: AsyncWrite + Unpin + Send + 'static,
441    {
442        let pending: Arc<Mutex<PendingMap>> = Arc::new(Mutex::new(HashMap::new()));
443        let writer: Arc<Mutex<BoxedWriter>> = Arc::new(Mutex::new(Box::new(writer)));
444        let handle = tokio::spawn(reader_loop(
445            reader,
446            framing,
447            Arc::clone(&pending),
448            Arc::clone(&writer),
449        ));
450        Self {
451            inner: Arc::new(ClientInner {
452                framing,
453                writer,
454                pending,
455                next_id: AtomicU64::new(1),
456                closed: AtomicBool::new(false),
457                initialized: AtomicBool::new(false),
458                request_timeout: StdMutex::new(DEFAULT_REQUEST_TIMEOUT),
459                reader_handle: StdMutex::new(Some(handle)),
460                child: StdMutex::new(child),
461            }),
462        }
463    }
464
465    /// The wire framing in use.
466    pub fn framing(&self) -> Framing {
467        self.inner.framing
468    }
469
470    /// `true` once [`initialize`](McpClient::initialize) has completed.
471    pub fn is_initialized(&self) -> bool {
472        self.inner.initialized.load(Ordering::Relaxed)
473    }
474
475    /// Override the per-request timeout (default: 30 s).
476    pub fn set_request_timeout(&self, timeout: Duration) {
477        if let Ok(mut guard) = self.inner.request_timeout.lock() {
478            *guard = timeout;
479        }
480    }
481
482    fn request_timeout(&self) -> Duration {
483        self.inner
484            .request_timeout
485            .lock()
486            .map(|d| *d)
487            .unwrap_or(DEFAULT_REQUEST_TIMEOUT)
488    }
489
490    fn ensure_open(&self) -> Result<()> {
491        if self.inner.closed.load(Ordering::Relaxed) {
492            return Err(tool_err("client is shut down"));
493        }
494        Ok(())
495    }
496
497    fn ensure_initialized(&self) -> Result<()> {
498        if !self.is_initialized() {
499            return Err(tool_err(
500                "client is not initialized; call `initialize()` first",
501            ));
502        }
503        Ok(())
504    }
505
506    /// Send a request and await its response, with timeout and JSON-RPC
507    /// error mapping.
508    async fn request(&self, method: &str, params: Value) -> Result<Value> {
509        self.ensure_open()?;
510        let id = self.inner.next_id.fetch_add(1, Ordering::Relaxed);
511        let request = JsonRpcRequest::new(id, method, params);
512        let encoded = serde_json::to_value(&request)
513            .map_err(|e| tool_err(format!("failed to encode `{method}` request: {e}")))?;
514
515        let (tx, rx) = oneshot::channel();
516        self.inner.pending.lock().await.insert(id, tx);
517
518        {
519            let mut w = self.inner.writer.lock().await;
520            if let Err(e) = write_framed(&mut **w, self.inner.framing, &encoded).await {
521                self.inner.pending.lock().await.remove(&id);
522                return Err(tool_err(format!("failed to send `{method}` request: {e}")));
523            }
524        }
525
526        let raw = match timeout(self.request_timeout(), rx).await {
527            Ok(Ok(value)) => value,
528            Ok(Err(_)) => {
529                return Err(tool_err(format!(
530                    "connection closed while awaiting `{method}` response"
531                )));
532            }
533            Err(_) => {
534                self.inner.pending.lock().await.remove(&id);
535                return Err(tool_err(format!(
536                    "`{method}` request timed out after {:?}",
537                    self.request_timeout()
538                )));
539            }
540        };
541
542        let response: JsonRpcResponse = serde_json::from_value(raw)
543            .map_err(|e| tool_err(format!("malformed response to `{method}`: {e}")))?;
544        if let Some(error) = response.error {
545            return Err(tool_err(format!(
546                "`{method}` failed (code {}): {}",
547                error.code, error.message
548            )));
549        }
550        response.result.ok_or_else(|| {
551            tool_err(format!(
552                "`{method}` response carried neither result nor error"
553            ))
554        })
555    }
556
557    /// Send a notification (no response expected).
558    async fn notify(&self, method: &str, params: Value) -> Result<()> {
559        self.ensure_open()?;
560        let notification = JsonRpcNotification::new(method, params);
561        let encoded = serde_json::to_value(&notification)
562            .map_err(|e| tool_err(format!("failed to encode `{method}` notification: {e}")))?;
563        let mut w = self.inner.writer.lock().await;
564        write_framed(&mut **w, self.inner.framing, &encoded)
565            .await
566            .map_err(|e| tool_err(format!("failed to send `{method}` notification: {e}")))
567    }
568
569    /// Perform the MCP `initialize` handshake: negotiate the protocol
570    /// revision, advertise `clientInfo`/capabilities, then send the
571    /// `notifications/initialized` notification.
572    pub async fn initialize(&self) -> Result<InitializeResult> {
573        let params = json!({
574            "protocolVersion": MCP_PROTOCOL_VERSION,
575            "capabilities": {},
576            "clientInfo": {
577                "name": "rusty-core",
578                "version": env!("CARGO_PKG_VERSION"),
579            },
580        });
581        let result = self.request("initialize", params).await?;
582
583        let protocol_version = result
584            .get("protocolVersion")
585            .and_then(Value::as_str)
586            .unwrap_or("unknown")
587            .to_owned();
588        let server_info = result.get("serverInfo");
589        let server_name = server_info
590            .and_then(|i| i.get("name"))
591            .and_then(Value::as_str)
592            .unwrap_or("unknown")
593            .to_owned();
594        let server_version = server_info
595            .and_then(|i| i.get("version"))
596            .and_then(Value::as_str)
597            .unwrap_or("unknown")
598            .to_owned();
599        let capabilities = result.get("capabilities").cloned().unwrap_or(Value::Null);
600
601        self.notify("notifications/initialized", json!({})).await?;
602        self.inner.initialized.store(true, Ordering::Relaxed);
603
604        Ok(InitializeResult {
605            protocol_version,
606            server_name,
607            server_version,
608            capabilities,
609        })
610    }
611
612    /// List the server's tools (`tools/list`).
613    pub async fn list_tools(&self) -> Result<Vec<McpToolInfo>> {
614        self.ensure_initialized()?;
615        let result = self.request("tools/list", json!({})).await?;
616        let tools = result
617            .get("tools")
618            .and_then(Value::as_array)
619            .ok_or_else(|| tool_err("`tools/list` result missing `tools` array"))?;
620        tools
621            .iter()
622            .map(|t| {
623                let name = t
624                    .get("name")
625                    .and_then(Value::as_str)
626                    .ok_or_else(|| tool_err("`tools/list` entry missing `name`"))?;
627                Ok(McpToolInfo {
628                    name: name.to_owned(),
629                    description: t
630                        .get("description")
631                        .and_then(Value::as_str)
632                        .unwrap_or("")
633                        .to_owned(),
634                    input_schema: match t.get("inputSchema") {
635                        Some(schema) => schema.clone(),
636                        None => {
637                            // The spec requires inputSchema; synthesize a
638                            // permissive schema rather than drop the tool,
639                            // but make the fabrication visible.
640                            tracing::warn!(
641                                tool = name,
642                                "mcp: `tools/list` entry omitted `inputSchema`; \
643                                 defaulting to a permissive object schema"
644                            );
645                            json!({"type": "object"})
646                        }
647                    },
648                })
649            })
650            .collect()
651    }
652
653    /// Call a tool (`tools/call`).
654    ///
655    /// On success returns the concatenated `text` content items as a
656    /// [`Value::String`] (the common case), or the raw result object if the
657    /// server returned no text content. A result with `isError: true` maps to
658    /// [`RustyError::Tool`].
659    pub async fn call_tool(&self, name: &str, arguments: Value) -> Result<Value> {
660        self.ensure_initialized()?;
661        let result = self
662            .request("tools/call", json!({"name": name, "arguments": arguments}))
663            .await?;
664
665        let text = extract_text_content(&result);
666        let is_error = result
667            .get("isError")
668            .and_then(Value::as_bool)
669            .unwrap_or(false);
670        if is_error {
671            let detail = text.unwrap_or_else(|| result.to_string());
672            return Err(tool_err(format!("tool `{name}` reported error: {detail}")));
673        }
674        match text {
675            Some(t) => Ok(Value::String(t)),
676            None => Ok(result),
677        }
678    }
679
680    /// List the server's tools and wrap each as a Rusty Core [`Tool`],
681    /// ready for [`crate::tool::ToolRegistry::register_shared`].
682    pub async fn into_tools(&self) -> Result<Vec<Arc<dyn Tool>>> {
683        let infos = self.list_tools().await?;
684        Ok(infos
685            .into_iter()
686            .map(|info| Arc::new(McpToolAdapter::new(self.clone(), info)) as Arc<dyn Tool>)
687            .collect())
688    }
689
690    /// Cleanly shut the client down: stop the reader task, fail pending
691    /// requests, and kill the child process (for stdio clients). Idempotent.
692    pub async fn shutdown(&self) -> Result<()> {
693        self.inner.closed.store(true, Ordering::Relaxed);
694        if let Ok(mut guard) = self.inner.reader_handle.lock() {
695            if let Some(handle) = guard.take() {
696                handle.abort();
697            }
698        }
699        if let Ok(mut guard) = self.inner.child.lock() {
700            if let Some(mut child) = guard.take() {
701                let _ = child.start_kill();
702            }
703        }
704        self.inner.pending.lock().await.clear();
705        Ok(())
706    }
707}
708
709/// Extract concatenated `text` content items from a `tools/call` result.
710fn extract_text_content(result: &Value) -> Option<String> {
711    let content = result.get("content")?.as_array()?;
712    let texts: Vec<&str> = content
713        .iter()
714        .filter(|item| item.get("type").and_then(Value::as_str) == Some("text"))
715        .filter_map(|item| item.get("text").and_then(Value::as_str))
716        .collect();
717    if texts.is_empty() {
718        None
719    } else {
720        Some(texts.join("\n"))
721    }
722}
723
724// ---------------------------------------------------------------------------
725// Stdio transport
726// ---------------------------------------------------------------------------
727
728/// Factory for MCP clients backed by a child-process stdio transport.
729pub struct McpStdioClient;
730
731impl McpStdioClient {
732    /// Spawn `command args...` as a child process with piped stdin/stdout
733    /// (stderr is discarded) and return an [`McpClient`] connected to it
734    /// using newline-delimited framing, per the MCP stdio transport.
735    ///
736    /// The child is killed on [`McpClient::shutdown`] and when the last
737    /// client handle drops (`kill_on_drop`).
738    pub fn spawn<S: AsRef<str>>(command: S, args: &[S]) -> Result<McpClient> {
739        let mut cmd = Command::new(command.as_ref());
740        cmd.args(args.iter().map(AsRef::as_ref))
741            .stdin(Stdio::piped())
742            .stdout(Stdio::piped())
743            .stderr(Stdio::null())
744            .kill_on_drop(true);
745        let mut child = cmd
746            .spawn()
747            .map_err(|e| tool_err(format!("failed to spawn `{}`: {e}", command.as_ref())))?;
748        let stdout = child
749            .stdout
750            .take()
751            .ok_or_else(|| tool_err("child stdout was not piped"))?;
752        let stdin = child
753            .stdin
754            .take()
755            .ok_or_else(|| tool_err("child stdin was not piped"))?;
756        Ok(McpClient::connect_inner(
757            stdout,
758            stdin,
759            Framing::NewlineDelimited,
760            Some(child),
761        ))
762    }
763}
764
765// ---------------------------------------------------------------------------
766// Tool adapter
767// ---------------------------------------------------------------------------
768
769/// Wraps one MCP tool as a Rusty Core [`Tool`].
770///
771/// `name` / `description` / `parameters_schema` come from the server's
772/// `tools/list` metadata; [`Tool::call`] issues `tools/call` and extracts the
773/// text content.
774pub struct McpToolAdapter {
775    client: McpClient,
776    info: McpToolInfo,
777}
778
779impl McpToolAdapter {
780    /// An adapter for `info` that dispatches through `client`.
781    pub fn new(client: McpClient, info: McpToolInfo) -> Self {
782        Self { client, info }
783    }
784}
785
786#[async_trait]
787impl Tool for McpToolAdapter {
788    fn name(&self) -> &str {
789        &self.info.name
790    }
791
792    fn description(&self) -> &str {
793        &self.info.description
794    }
795
796    fn parameters_schema(&self) -> Value {
797        self.info.input_schema.clone()
798    }
799
800    async fn call(&self, args: Value) -> Result<Value> {
801        self.client.call_tool(&self.info.name, args).await
802    }
803}
804
805// ---------------------------------------------------------------------------
806// Journaled MCP tools (R0.9 Rusty Capsules, wave 4)
807// ---------------------------------------------------------------------------
808
809/// The deterministic identity of one journaled MCP tool call.
810///
811/// Derived — never minted — over `(scope, tool name, canonical arguments)`
812/// through the shared [`crate::effects::derive_effect_id`] construction,
813/// hashing the canonical [`crate::replay::tool_call_request`] payload so
814/// the id commits to exactly what the journal records. The key doubles as
815/// the replay lookup identity: a recovering run re-derives the id of the
816/// call it was about to issue, and [`JournaledMcpTool::replaying`] serves
817/// the journaled response instead of re-issuing the call.
818pub fn mcp_tool_effect_id(
819    scope: &str,
820    tool_name: &str,
821    arguments: &Value,
822) -> crate::effects::EffectId {
823    let request = crate::replay::tool_call_request(tool_name, arguments);
824    let input_hash = crate::record::PayloadRef::inline(request)
825        .content_hash()
826        .expect("a serde_json::Value always serializes");
827    crate::effects::derive_effect_id(scope, &format!("mcp_tool:{tool_name}"), &input_hash, None)
828}
829
830/// An MCP tool that leaves evidence (R0.9 wave 4): the durable half of the
831/// MCP client bridge.
832///
833/// Live ([`JournaledMcpTool::new`]), every call is dispatched through the
834/// wrapped [`McpClient`] and journaled as a
835/// [`RunEventKind::ToolCall`](crate::record::RunEventKind::ToolCall)
836/// event in the canonical [`crate::replay::tool_call_request`] shape — the
837/// same shape [`crate::replay::RecordingTool`] writes, so journals produced
838/// here are exact-replay servable. The call's identity is
839/// [`mcp_tool_effect_id`], reported through [`Tool::idempotency_key`].
840///
841/// Replaying ([`JournaledMcpTool::replaying`]), the tool holds **no client
842/// at all** — not a disconnected one, none — so a replayed run cannot
843/// respawn the stdio server (or reopen any transport) by construction; the
844/// type makes the zero-outbound guarantee rather than promising it. Calls
845/// are served from the recorded journal's [`crate::replay::ReplaySource`]
846/// by canonical request hash and re-journaled into the replay run, the
847/// [`crate::replay::ReplayingTool`] precedent.
848///
849/// The wrapper changes the evidence posture, not the effect class: an MCP
850/// call is arbitrary remote work, so [`Tool::effect`] stays the adapter's
851/// [`crate::record::Effect::NonIdempotent`] default.
852pub struct JournaledMcpTool {
853    info: McpToolInfo,
854    /// The live transport; `None` in replay mode (see the type docs).
855    client: Option<McpClient>,
856    /// The recorded journal's serving cursor; `Some` in replay mode.
857    source: Option<crate::replay::ReplaySource>,
858    journal: crate::journal::Journal,
859    parent: String,
860    scope: String,
861}
862
863impl JournaledMcpTool {
864    /// The live half: dispatch `info`'s tool through `client`, journaling
865    /// every call into `journal` under causal parent `parent` (the invoking
866    /// node's node-input event id, delivered via
867    /// [`crate::journal::PARENT_EVENT_KEY`]). `scope` names the run scope
868    /// the effect id derives under — conventionally the run id.
869    pub fn new(
870        client: McpClient,
871        info: McpToolInfo,
872        scope: impl Into<String>,
873        journal: crate::journal::Journal,
874        parent: impl Into<String>,
875    ) -> Self {
876        Self {
877            info,
878            client: Some(client),
879            source: None,
880            journal,
881            parent: parent.into(),
882            scope: scope.into(),
883        }
884    }
885
886    /// The replaying half: serve calls from `source` (built over the
887    /// recorded run's verified snapshot), re-journaling into the replay
888    /// run's `journal` under `parent`. No client is taken — a replayed run
889    /// never respawns the server.
890    pub fn replaying(
891        info: McpToolInfo,
892        scope: impl Into<String>,
893        source: crate::replay::ReplaySource,
894        journal: crate::journal::Journal,
895        parent: impl Into<String>,
896    ) -> Self {
897        Self {
898            info,
899            client: None,
900            source: Some(source),
901            journal,
902            parent: parent.into(),
903            scope: scope.into(),
904        }
905    }
906
907    /// This call's derived identity ([`mcp_tool_effect_id`]).
908    pub fn effect_id(&self, arguments: &Value) -> crate::effects::EffectId {
909        mcp_tool_effect_id(&self.scope, &self.info.name, arguments)
910    }
911}
912
913#[async_trait]
914impl Tool for JournaledMcpTool {
915    fn name(&self) -> &str {
916        &self.info.name
917    }
918
919    fn description(&self) -> &str {
920        &self.info.description
921    }
922
923    fn parameters_schema(&self) -> Value {
924        self.info.input_schema.clone()
925    }
926
927    fn idempotency_key(&self, args: &Value) -> Option<String> {
928        Some(self.effect_id(args).as_str().to_string())
929    }
930
931    async fn call(&self, args: Value) -> Result<Value> {
932        let request = crate::replay::tool_call_request(&self.info.name, &args);
933        match (&self.client, &self.source) {
934            (Some(client), None) => {
935                let result = client.call_tool(&self.info.name, args).await;
936                // The journaled shape is RecordingTool's exactly: success
937                // carries the verbatim response; failure carries
938                // `{"error": msg}` under EventStatus::Error — so either way
939                // the event is servable by exact replay.
940                let mut draft = crate::journal::EventDraft::new(
941                    crate::record::RunEventKind::ToolCall,
942                    <Self as Tool>::effect(self),
943                )
944                .input(request)
945                .parent(self.parent.clone());
946                match &result {
947                    Ok(value) => {
948                        draft = draft.output(value.clone());
949                    }
950                    Err(error) => {
951                        draft = draft
952                            .output(json!({ "error": error.to_string() }))
953                            .status(crate::record::EventStatus::Error);
954                    }
955                }
956                self.journal.record(draft);
957                result
958            }
959            (None, Some(source)) => {
960                let served = source
961                    .serve(crate::record::RunEventKind::ToolCall, &request)
962                    .map_err(|e| tool_err(format!("replay serve failed: {e}")))?;
963                served.rejournal(&self.journal, self.parent.clone());
964                if served.event.status == crate::record::EventStatus::Error {
965                    let message = served
966                        .output
967                        .as_ref()
968                        .and_then(|value| value.get("error"))
969                        .and_then(Value::as_str)
970                        .unwrap_or("recorded tool call failed");
971                    return Err(tool_err(message));
972                }
973                Ok(served.output.unwrap_or(Value::Null))
974            }
975            // The two constructors set exactly one half; this arm is
976            // unreachable by construction.
977            _ => Err(tool_err("journaled MCP tool is neither live nor replaying")),
978        }
979    }
980}
981
982// ---------------------------------------------------------------------------
983// Tests
984// ---------------------------------------------------------------------------
985
986#[cfg(test)]
987mod tests {
988    use super::*;
989    use crate::tool::ToolRegistry;
990    use tokio::io::{duplex, DuplexStream};
991
992    /// A scripted mock MCP server speaking the full handshake.
993    async fn run_mock_server(stream: DuplexStream, framing: Framing) {
994        let (read, mut write) = tokio::io::split(stream);
995        let mut reader = BufReader::new(read);
996        while let Ok(Some(msg)) = read_framed(&mut reader, framing).await {
997            let id = msg.get("id").cloned();
998            let method = msg.get("method").and_then(Value::as_str).unwrap_or("");
999            let response = match method {
1000                "notifications/initialized" => None,
1001                "initialize" => Some(json!({
1002                    "jsonrpc": "2.0",
1003                    "id": id,
1004                    "result": {
1005                        "protocolVersion": MCP_PROTOCOL_VERSION,
1006                        "capabilities": {"tools": {}},
1007                        "serverInfo": {"name": "mock-mcp", "version": "0.0.1"},
1008                    }
1009                })),
1010                "tools/list" => Some(json!({
1011                    "jsonrpc": "2.0",
1012                    "id": id,
1013                    "result": {
1014                        "tools": [
1015                            {
1016                                "name": "echo",
1017                                "description": "Echoes text back.",
1018                                "inputSchema": {
1019                                    "type": "object",
1020                                    "properties": {"text": {"type": "string"}},
1021                                    "required": ["text"]
1022                                }
1023                            },
1024                            {
1025                                "name": "fail_rpc",
1026                                "description": "Fails at the JSON-RPC layer.",
1027                                "inputSchema": {"type": "object"}
1028                            },
1029                            {
1030                                "name": "error_tool",
1031                                "description": "Reports a tool-level error.",
1032                                "inputSchema": {"type": "object"}
1033                            },
1034                            {
1035                                "name": "slow",
1036                                "description": "Responds slowly.",
1037                                "inputSchema": {"type": "object"}
1038                            }
1039                        ]
1040                    }
1041                })),
1042                "tools/call" => {
1043                    let name = msg
1044                        .pointer("/params/name")
1045                        .and_then(Value::as_str)
1046                        .unwrap_or("");
1047                    match name {
1048                        "echo" => Some(json!({
1049                            "jsonrpc": "2.0",
1050                            "id": id,
1051                            "result": {"content": [{"type": "text", "text": "hello from echo"}]}
1052                        })),
1053                        "error_tool" => Some(json!({
1054                            "jsonrpc": "2.0",
1055                            "id": id,
1056                            "result": {
1057                                "content": [{"type": "text", "text": "invalid widget id"}],
1058                                "isError": true
1059                            }
1060                        })),
1061                        "fail_rpc" => Some(json!({
1062                            "jsonrpc": "2.0",
1063                            "id": id,
1064                            "error": {"code": -32602, "message": "invalid params: missing `widget_id`"}
1065                        })),
1066                        "slow" => {
1067                            tokio::time::sleep(Duration::from_millis(500)).await;
1068                            Some(json!({
1069                                "jsonrpc": "2.0",
1070                                "id": id,
1071                                "result": {"content": [{"type": "text", "text": "too late"}]}
1072                            }))
1073                        }
1074                        _ => Some(json!({
1075                            "jsonrpc": "2.0",
1076                            "id": id,
1077                            "error": {"code": -32601, "message": "unknown tool"}
1078                        })),
1079                    }
1080                }
1081                _ => id.map(|i| {
1082                    json!({
1083                        "jsonrpc": "2.0",
1084                        "id": i,
1085                        "error": {"code": -32601, "message": "method not found"}
1086                    })
1087                }),
1088            };
1089            if let Some(resp) = response {
1090                write_framed(&mut write, framing, &resp)
1091                    .await
1092                    .expect("mock server write");
1093            }
1094        }
1095    }
1096
1097    /// A client connected to a scripted mock server over an in-memory
1098    /// full-duplex transport.
1099    fn client_and_mock(framing: Framing) -> (McpClient, JoinHandle<()>) {
1100        let (client_stream, server_stream) = duplex(64 * 1024);
1101        let handle = tokio::spawn(run_mock_server(server_stream, framing));
1102        let (read, write) = tokio::io::split(client_stream);
1103        (
1104            McpClient::connect_with_framing(read, write, framing),
1105            handle,
1106        )
1107    }
1108
1109    async fn initialized_client(framing: Framing) -> (McpClient, JoinHandle<()>) {
1110        let (client, handle) = client_and_mock(framing);
1111        client.initialize().await.expect("initialize");
1112        (client, handle)
1113    }
1114
1115    #[tokio::test]
1116    async fn initialize_handshake_returns_server_info() {
1117        let (client, _mock) = client_and_mock(Framing::NewlineDelimited);
1118        assert!(!client.is_initialized());
1119        let info = client.initialize().await.expect("initialize");
1120        assert_eq!(info.protocol_version, MCP_PROTOCOL_VERSION);
1121        assert_eq!(info.server_name, "mock-mcp");
1122        assert_eq!(info.server_version, "0.0.1");
1123        assert!(info.capabilities.get("tools").is_some());
1124        assert!(client.is_initialized());
1125        client.shutdown().await.expect("shutdown");
1126    }
1127
1128    #[tokio::test]
1129    async fn requests_before_initialize_are_rejected() {
1130        let (client, _mock) = client_and_mock(Framing::NewlineDelimited);
1131        let err = client.list_tools().await.unwrap_err();
1132        assert!(matches!(err, RustyError::Tool(_)));
1133        assert!(err.to_string().contains("initialize"));
1134    }
1135
1136    #[tokio::test]
1137    async fn tools_list_parses_metadata() {
1138        let (client, _mock) = initialized_client(Framing::NewlineDelimited).await;
1139        let tools = client.list_tools().await.expect("tools/list");
1140        assert_eq!(tools.len(), 4);
1141        let echo = tools.iter().find(|t| t.name == "echo").expect("echo tool");
1142        assert_eq!(echo.description, "Echoes text back.");
1143        assert_eq!(echo.input_schema["type"], json!("object"));
1144        assert!(echo.input_schema["properties"]["text"].is_object());
1145        assert_eq!(echo.input_schema["required"], json!(["text"]));
1146    }
1147
1148    #[tokio::test]
1149    async fn tools_call_extracts_text_content() {
1150        let (client, _mock) = initialized_client(Framing::NewlineDelimited).await;
1151        let value = client
1152            .call_tool("echo", json!({"text": "hi"}))
1153            .await
1154            .expect("tools/call");
1155        assert_eq!(value, json!("hello from echo"));
1156    }
1157
1158    #[tokio::test]
1159    async fn json_rpc_and_tool_errors_map_to_tool_variant() {
1160        let (client, _mock) = initialized_client(Framing::NewlineDelimited).await;
1161
1162        // JSON-RPC-level error.
1163        let err = client.call_tool("fail_rpc", json!({})).await.unwrap_err();
1164        match err {
1165            RustyError::Tool(msg) => {
1166                assert!(msg.contains("-32602"), "got: {msg}");
1167                assert!(msg.contains("invalid params"), "got: {msg}");
1168            }
1169            other => panic!("expected Tool error, got: {other}"),
1170        }
1171
1172        // Tool-level error (`isError: true`).
1173        let err = client.call_tool("error_tool", json!({})).await.unwrap_err();
1174        assert!(matches!(err, RustyError::Tool(_)));
1175        assert!(err.to_string().contains("invalid widget id"));
1176    }
1177
1178    #[tokio::test]
1179    async fn request_timeout_aborts_pending_call() {
1180        let (client, _mock) = client_and_mock(Framing::NewlineDelimited);
1181        client.set_request_timeout(Duration::from_millis(50));
1182        client.initialize().await.expect("initialize");
1183        let err = client.call_tool("slow", json!({})).await.unwrap_err();
1184        assert!(matches!(err, RustyError::Tool(_)));
1185        assert!(err.to_string().contains("timed out"), "got: {err}");
1186    }
1187
1188    #[tokio::test]
1189    async fn into_tools_produces_registry_ready_adapters() {
1190        let (client, _mock) = initialized_client(Framing::NewlineDelimited).await;
1191        let tools = client.into_tools().await.expect("into_tools");
1192        assert_eq!(tools.len(), 4);
1193
1194        let mut registry = ToolRegistry::new();
1195        for tool in tools {
1196            registry.register_shared(tool);
1197        }
1198        assert!(registry.contains("echo"));
1199        assert!(registry.contains("fail_rpc"));
1200
1201        let echo = registry.get("echo").expect("echo registered");
1202        assert_eq!(echo.name(), "echo");
1203        assert_eq!(echo.description(), "Echoes text back.");
1204        assert!(echo.parameters_schema()["properties"]["text"].is_object());
1205
1206        let out = echo
1207            .call(json!({"text": "yo"}))
1208            .await
1209            .expect("adapter call");
1210        assert_eq!(out, json!("hello from echo"));
1211
1212        // Registry schemas remain OpenAI-shaped with the MCP tool inside.
1213        let schemas = registry.schemas();
1214        assert!(schemas
1215            .iter()
1216            .any(|s| s["function"]["name"] == json!("echo")));
1217    }
1218
1219    #[tokio::test]
1220    async fn content_length_framing_roundtrip() {
1221        let (client, _mock) = initialized_client(Framing::ContentLength).await;
1222        assert_eq!(client.framing(), Framing::ContentLength);
1223        let value = client
1224            .call_tool("echo", json!({"text": "framed"}))
1225            .await
1226            .expect("tools/call over Content-Length framing");
1227        assert_eq!(value, json!("hello from echo"));
1228        client.shutdown().await.expect("shutdown");
1229    }
1230
1231    #[tokio::test]
1232    async fn content_length_cap_rejects_giant_frame_before_allocating() {
1233        // A peer-declared 4 GB frame must be rejected, not allocated.
1234        let bytes = b"Content-Length: 4000000000\r\n\r\n";
1235        let mut reader = BufReader::new(&bytes[..]);
1236        let err = read_framed(&mut reader, Framing::ContentLength)
1237            .await
1238            .unwrap_err();
1239        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1240        assert!(err.to_string().contains("frame cap"), "got: {err}");
1241    }
1242
1243    #[tokio::test]
1244    async fn newline_cap_bounds_unterminated_lines() {
1245        // No newline anywhere: the buffer must stop at the cap.
1246        let bytes = vec![b'a'; MAX_FRAME_BYTES + 8];
1247        let mut reader = BufReader::new(&bytes[..]);
1248        let err = read_framed(&mut reader, Framing::NewlineDelimited)
1249            .await
1250            .unwrap_err();
1251        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1252        assert!(err.to_string().contains("frame cap"), "got: {err}");
1253    }
1254
1255    #[tokio::test]
1256    async fn malformed_newline_frame_is_dropped_and_session_survives() {
1257        let (client_stream, mut server) = duplex(64 * 1024);
1258        let server_task = tokio::spawn(async move {
1259            // A garbage line first: must not brick the client session.
1260            server
1261                .write_all(b"this is not json at all\n")
1262                .await
1263                .expect("write garbage");
1264            let (read, mut write) = tokio::io::split(server);
1265            let mut reader = BufReader::new(read);
1266            // Then a normal initialize handshake.
1267            let msg = read_framed(&mut reader, Framing::NewlineDelimited)
1268                .await
1269                .expect("read initialize")
1270                .expect("initialize frame");
1271            let id = msg.get("id").cloned();
1272            write_framed(
1273                &mut write,
1274                Framing::NewlineDelimited,
1275                &json!({
1276                    "jsonrpc": "2.0",
1277                    "id": id,
1278                    "result": {
1279                        "protocolVersion": MCP_PROTOCOL_VERSION,
1280                        "capabilities": {},
1281                        "serverInfo": {"name": "resync-mock", "version": "0"},
1282                    }
1283                }),
1284            )
1285            .await
1286            .expect("write initialize result");
1287            // Drain the initialized notification so the pipe stays open.
1288            let _ = read_framed(&mut reader, Framing::NewlineDelimited).await;
1289        });
1290
1291        let (read, write) = tokio::io::split(client_stream);
1292        let client = McpClient::connect(read, write);
1293        let info = client
1294            .initialize()
1295            .await
1296            .expect("initialize must survive a leading malformed frame");
1297        assert_eq!(info.server_name, "resync-mock");
1298        client.shutdown().await.expect("shutdown");
1299        server_task.await.expect("server task");
1300    }
1301
1302    #[tokio::test]
1303    async fn stdio_spawn_of_missing_command_errors() {
1304        let args: [&str; 0] = [];
1305        let result = McpStdioClient::spawn("rusty-no-such-mcp-server-zzz", &args);
1306        match result {
1307            Err(err) => {
1308                assert!(matches!(err, RustyError::Tool(_)));
1309                assert!(err.to_string().contains("failed to spawn"));
1310            }
1311            Ok(_) => panic!("spawning a nonexistent command should fail"),
1312        }
1313    }
1314}