1use 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
55pub const MCP_PROTOCOL_VERSION: &str = "2024-11-05";
61
62pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
64
65pub const MAX_FRAME_BYTES: usize = 16 * 1024 * 1024;
72
73fn tool_err(msg: impl Into<String>) -> RustyError {
75 RustyError::Tool(format!("mcp: {}", msg.into()))
76}
77
78#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct JsonRpcRequest {
85 pub jsonrpc: String,
87 pub id: u64,
89 pub method: String,
91 #[serde(skip_serializing_if = "Option::is_none")]
93 pub params: Option<Value>,
94}
95
96impl JsonRpcRequest {
97 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#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct JsonRpcNotification {
111 pub jsonrpc: String,
113 pub method: String,
115 #[serde(skip_serializing_if = "Option::is_none")]
117 pub params: Option<Value>,
118}
119
120impl JsonRpcNotification {
121 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#[derive(Debug, Clone, Serialize, Deserialize)]
133pub struct JsonRpcError {
134 pub code: i64,
136 pub message: String,
138 #[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#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct JsonRpcResponse {
152 pub jsonrpc: String,
154 pub id: Value,
156 #[serde(skip_serializing_if = "Option::is_none")]
158 pub result: Option<Value>,
159 #[serde(skip_serializing_if = "Option::is_none")]
161 pub error: Option<JsonRpcError>,
162}
163
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
170pub enum Framing {
171 #[default]
173 NewlineDelimited,
174 ContentLength,
176}
177
178async 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
199async 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 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); }
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; }
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); }
248 let trimmed = line.trim();
249 if trimmed.is_empty() {
250 break; }
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 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#[derive(Debug, Clone)]
283pub struct InitializeResult {
284 pub protocol_version: String,
286 pub server_name: String,
288 pub server_version: String,
290 pub capabilities: Value,
292}
293
294#[derive(Debug, Clone)]
296pub struct McpToolInfo {
297 pub name: String,
299 pub description: String,
301 pub input_schema: Value,
303}
304
305type 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
339async 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 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, Err(e) => {
383 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 pending.lock().await.clear();
401}
402
403#[derive(Clone)]
413pub struct McpClient {
414 inner: Arc<ClientInner>,
415}
416
417impl McpClient {
418 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 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 pub fn framing(&self) -> Framing {
467 self.inner.framing
468 }
469
470 pub fn is_initialized(&self) -> bool {
472 self.inner.initialized.load(Ordering::Relaxed)
473 }
474
475 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 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 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(¬ification)
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 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 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 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 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 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 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
709fn 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
724pub struct McpStdioClient;
730
731impl McpStdioClient {
732 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
765pub struct McpToolAdapter {
775 client: McpClient,
776 info: McpToolInfo,
777}
778
779impl McpToolAdapter {
780 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
805pub 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
830pub struct JournaledMcpTool {
853 info: McpToolInfo,
854 client: Option<McpClient>,
856 source: Option<crate::replay::ReplaySource>,
858 journal: crate::journal::Journal,
859 parent: String,
860 scope: String,
861}
862
863impl JournaledMcpTool {
864 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 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 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 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 _ => Err(tool_err("journaled MCP tool is neither live nor replaying")),
978 }
979 }
980}
981
982#[cfg(test)]
987mod tests {
988 use super::*;
989 use crate::tool::ToolRegistry;
990 use tokio::io::{duplex, DuplexStream};
991
992 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 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 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 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 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 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 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 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 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 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}