1use crate::config::Policy;
29use crate::tools::{Tool, ToolError};
30use serde::Deserialize;
31use serde_json::{json, Value};
32use std::collections::BTreeMap;
33use std::io::{BufRead, BufReader, Write};
34#[cfg(unix)]
35use std::os::unix::process::CommandExt;
36use std::path::{Path, PathBuf};
37use std::process::{Child, ChildStdin, Command, Stdio};
38use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
39use std::sync::mpsc::{self, RecvTimeoutError};
40use std::sync::{Arc, Mutex};
41use std::time::{Duration, Instant};
42
43pub const PROTOCOL: &str = "2024-11-05";
47
48pub type Secrets = BTreeMap<String, String>;
55
56const STDERR_KEEP: usize = 4_000;
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, serde::Serialize)]
61#[serde(rename_all = "lowercase")]
62pub enum Transport {
63 #[default]
65 Stdio,
66 Http,
68}
69
70impl Transport {
71 pub fn as_str(&self) -> &'static str {
72 match self {
73 Transport::Stdio => "stdio",
74 Transport::Http => "http",
75 }
76 }
77}
78
79#[derive(Debug, Clone, PartialEq, Deserialize, serde::Serialize)]
84#[serde(deny_unknown_fields)]
85pub struct Spec {
86 pub name: String,
88 #[serde(default)]
90 pub transport: Transport,
91 #[serde(default)]
93 pub command: String,
94 #[serde(default)]
95 pub args: Vec<String>,
96 #[serde(default)]
99 pub env: Vec<String>,
100 #[serde(default)]
102 pub cwd: crate::plugins::Cwd,
103 #[serde(default)]
105 pub url: Option<String>,
106 #[serde(default)]
112 pub token_env: Option<String>,
113 #[serde(default)]
115 pub timeout_secs: Option<u64>,
116 #[serde(default = "default_policy")]
118 pub policy: Policy,
119 #[serde(default)]
121 pub policies: BTreeMap<String, Policy>,
122 #[serde(default)]
125 pub prefix: String,
126 #[serde(default, rename = "override")]
128 pub override_builtin: bool,
129 #[serde(default)]
131 pub disabled: bool,
132}
133
134fn default_policy() -> Policy {
135 Policy::Ask
136}
137
138impl Spec {
139 pub fn validate(&self) -> Result<(), String> {
146 let url = self.url.as_deref().map(str::trim).filter(|u| !u.is_empty());
147 let command = self.command.trim();
148 match self.transport {
149 Transport::Stdio => {
150 if url.is_some() {
151 return Err(
152 "`url` belongs to the http transport, and this entry is stdio: a stdio \
153 server names `command`"
154 .to_string(),
155 );
156 }
157 if command.is_empty() {
158 return Err(
159 "no `command` given (an endpoint would need `transport = http` and a \
160 `url`)"
161 .to_string(),
162 );
163 }
164 Ok(())
165 }
166 Transport::Http => {
167 if !command.is_empty() || !self.args.is_empty() {
168 return Err(
169 "`command`/`args` belong to the stdio transport, and this entry is http: \
170 an HTTP server names `url`"
171 .to_string(),
172 );
173 }
174 let Some(url) = url else {
175 return Err("`transport = http` with no `url` to post to".to_string());
176 };
177 if !(url.starts_with("http://") || url.starts_with("https://")) {
178 return Err(format!(
179 "`url` = {url:?} is not an http:// or https:// endpoint"
180 ));
181 }
182 Ok(())
183 }
184 }
185 }
186
187 fn token(&self, secrets: &Secrets) -> Result<Option<String>, String> {
195 let Some(key) = self.token_key() else {
196 return Ok(None);
197 };
198 match self.token_source(secrets) {
199 TokenSource::NotUsed => Ok(None),
200 TokenSource::Env => Ok(std::env::var(key).ok()),
201 TokenSource::Dotenv => Ok(secrets.get(key).cloned()),
202 TokenSource::Unset => Err(format!(
203 "`token_env = {key:?}` names a variable that is set neither in the environment nor \
204 in `.env` (or is empty); this build never reads a token from the manifest itself"
205 )),
206 }
207 }
208
209 fn token_key(&self) -> Option<&str> {
211 self.token_env
212 .as_deref()
213 .map(str::trim)
214 .filter(|k| !k.is_empty())
215 }
216
217 pub fn token_source(&self, secrets: &Secrets) -> TokenSource {
221 let Some(key) = self.token_key() else {
222 return TokenSource::NotUsed;
223 };
224 if std::env::var(key).is_ok_and(|v| !v.trim().is_empty()) {
226 TokenSource::Env
227 } else if secrets.get(key).is_some_and(|v| !v.trim().is_empty()) {
228 TokenSource::Dotenv
229 } else {
230 TokenSource::Unset
231 }
232 }
233}
234
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238pub enum TokenSource {
239 NotUsed,
241 Env,
243 Dotenv,
245 Unset,
247}
248
249impl TokenSource {
250 pub fn as_str(&self) -> &'static str {
252 match self {
253 TokenSource::NotUsed => "none",
254 TokenSource::Env => "env",
255 TokenSource::Dotenv => ".env",
256 TokenSource::Unset => "unset",
257 }
258 }
259}
260
261#[derive(Debug, Clone, Deserialize)]
263pub struct RemoteTool {
264 pub name: String,
265 #[serde(default)]
266 pub description: String,
267 #[serde(default, rename = "inputSchema")]
268 pub input_schema: Option<Value>,
269}
270
271enum Conn {
273 Pipe(Pipe),
274 Http(Http),
275}
276
277struct Pipe {
279 child: Child,
280 stdin: ChildStdin,
281 rx: mpsc::Receiver<Value>,
283}
284
285struct Http {
290 client: reqwest::Client,
291 url: String,
292 session: Option<String>,
294 token: Option<String>,
296 expired: Arc<AtomicBool>,
300}
301
302impl Drop for Pipe {
303 fn drop(&mut self) {
304 #[cfg(unix)]
313 crate::tools::pgroup::kill_now(self.child.id());
314 let _ = self.child.kill();
315 let _ = self.child.wait();
316 }
317}
318
319const MAX_LINE: usize = 8 * 1024 * 1024;
324
325const LINE_QUEUE: usize = 64;
329
330enum Line {
332 Text(String),
333 TooLong(usize),
334}
335
336fn read_line_capped<R: BufRead>(reader: &mut R, max: usize) -> std::io::Result<Option<Line>> {
342 let mut kept: Vec<u8> = Vec::new();
343 let mut seen = 0usize;
344 let mut over = false;
345 loop {
346 let avail = reader.fill_buf()?;
347 if avail.is_empty() {
348 if seen == 0 {
349 return Ok(None);
350 }
351 break;
352 }
353 let newline = avail.iter().position(|b| *b == b'\n');
354 let take = newline.unwrap_or(avail.len());
355 seen += take;
356 if !over {
357 if kept.len() + take > max {
358 over = true;
359 kept.clear();
360 } else {
361 kept.extend_from_slice(&avail[..take]);
362 }
363 }
364 match newline {
365 Some(_) => {
366 reader.consume(take + 1);
367 break;
368 }
369 None => reader.consume(take),
370 }
371 }
372 if over {
373 return Ok(Some(Line::TooLong(seen)));
374 }
375 Ok(Some(Line::Text(
376 String::from_utf8_lossy(&kept).into_owned(),
377 )))
378}
379
380const CANCEL_TICK: Duration = Duration::from_millis(100);
383
384pub struct Server {
386 spec: Spec,
387 plugin_dir: PathBuf,
388 workspace: PathBuf,
389 timeout: Duration,
390 secrets: Secrets,
394 next_id: AtomicI64,
395 state: Mutex<Option<Conn>>,
396 handshake: Mutex<Option<Value>>,
400 stderr: Arc<Mutex<String>>,
401}
402
403impl std::fmt::Debug for Server {
404 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
405 f.debug_struct("mcp::Server")
406 .field("name", &self.spec.name)
407 .field("transport", &self.spec.transport.as_str())
408 .field("command", &self.spec.command)
409 .field("url", &self.spec.url)
410 .finish()
411 }
412}
413
414impl Server {
415 pub fn start(
419 spec: &Spec,
420 plugin_dir: &Path,
421 workspace: &Path,
422 default_timeout: Duration,
423 secrets: &Secrets,
424 ) -> Result<(Arc<Self>, Vec<RemoteTool>), String> {
425 let timeout = match spec.timeout_secs {
428 Some(secs) => crate::plugins::clamp_timeout(Some(secs)),
429 None => default_timeout,
430 };
431 let server = Arc::new(Self {
432 spec: spec.clone(),
433 plugin_dir: plugin_dir.to_path_buf(),
434 workspace: workspace.to_path_buf(),
435 timeout,
436 secrets: secrets.clone(),
437 next_id: AtomicI64::new(1),
438 state: Mutex::new(None),
439 handshake: Mutex::new(None),
440 stderr: Arc::new(Mutex::new(String::new())),
441 });
442 let tools = server.list_tools()?;
443 Ok((server, tools))
444 }
445
446 pub fn name(&self) -> &str {
447 &self.spec.name
448 }
449
450 pub fn prefix(&self) -> &str {
451 &self.spec.prefix
452 }
453
454 pub fn handshake(&self) -> Option<Value> {
456 self.handshake
457 .lock()
458 .unwrap_or_else(|e| e.into_inner())
459 .clone()
460 }
461
462 fn keep_handshake(&self, result: &Value) {
465 let mut slot = self.handshake.lock().unwrap_or_else(|e| e.into_inner());
466 if slot.is_none() {
467 *slot = Some(result.clone());
468 }
469 }
470
471 pub fn override_builtin(&self) -> bool {
472 self.spec.override_builtin
473 }
474
475 pub fn policy_for(&self, remote: &str) -> Policy {
477 self.spec
478 .policies
479 .get(remote)
480 .copied()
481 .unwrap_or(self.spec.policy)
482 }
483
484 fn list_tools(&self) -> Result<Vec<RemoteTool>, String> {
488 let mut out = Vec::new();
489 let mut cursor: Option<String> = None;
490 for _ in 0..16 {
491 let params = match &cursor {
492 Some(c) => json!({ "cursor": c }),
493 None => json!({}),
494 };
495 let result = self.request("tools/list", params, &crate::cancel::Cancel::new())?;
497 let page: Vec<RemoteTool> =
498 serde_json::from_value(result.get("tools").cloned().unwrap_or_else(|| json!([])))
499 .map_err(|e| {
500 format!("`tools/list` answered with tools this build cannot read: {e}")
501 })?;
502 out.extend(page);
503 cursor = result
504 .get("nextCursor")
505 .and_then(Value::as_str)
506 .map(str::to_string)
507 .filter(|c| !c.is_empty());
508 if cursor.is_none() {
509 break;
510 }
511 }
512 Ok(out)
513 }
514
515 pub fn call_tool(&self, remote: &str, args: &Value) -> Result<String, String> {
517 self.call_tool_unless(remote, args, &crate::cancel::Cancel::new())
518 }
519
520 pub fn call_tool_unless(
526 &self,
527 remote: &str,
528 args: &Value,
529 cancel: &crate::cancel::Cancel,
530 ) -> Result<String, String> {
531 let result = self.request(
532 "tools/call",
533 json!({ "name": remote, "arguments": args }),
534 cancel,
535 )?;
536 let text = content_text(&result);
537 if result
538 .get("isError")
539 .and_then(Value::as_bool)
540 .unwrap_or(false)
541 {
542 return Err(if text.is_empty() {
545 "the tool reported a failure without a message".to_string()
546 } else {
547 text
548 });
549 }
550 Ok(text)
551 }
552
553 fn request(
554 &self,
555 method: &str,
556 params: Value,
557 cancel: &crate::cancel::Cancel,
558 ) -> Result<Value, String> {
559 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
560 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
561 self.ensure(&mut guard)?;
562 let message = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });
563 let (outcome, poison) = match guard.as_mut().expect("ensure left a connection") {
564 Conn::Pipe(pipe) => self.exchange_pipe(pipe, id, method, &message, cancel),
565 Conn::Http(http) => self.exchange_http(http, id, method, &message, cancel),
569 };
570 if poison {
571 *guard = None;
574 }
575 outcome
576 }
577
578 fn write_stdin(
594 &self,
595 stdin: &mut std::process::ChildStdin,
596 message: &str,
597 ) -> std::io::Result<()> {
598 #[cfg(unix)]
599 unsafe {
602 static SIGPIPE_SWAP: std::sync::Mutex<()> = std::sync::Mutex::new(());
603 let _guard = SIGPIPE_SWAP.lock().unwrap_or_else(|e| e.into_inner());
604 let previous = libc::signal(libc::SIGPIPE, libc::SIG_IGN);
605 let result = writeln!(stdin, "{message}").and_then(|_| stdin.flush());
606 libc::signal(libc::SIGPIPE, previous);
607 result
608 }
609 #[cfg(not(unix))]
610 {
611 writeln!(stdin, "{message}").and_then(|_| stdin.flush())
612 }
613 }
614
615 fn exchange_pipe(
617 &self,
618 pipe: &mut Pipe,
619 id: i64,
620 method: &str,
621 message: &Value,
622 cancel: &crate::cancel::Cancel,
623 ) -> (Result<Value, String>, bool) {
624 if let Err(e) = self.write_stdin(&mut pipe.stdin, &message.to_string()) {
625 return (
626 Err(format!(
627 "could not send `{method}`: {e}{}",
628 self.stderr_tail_soon()
629 )),
630 true,
631 );
632 }
633 let deadline = Instant::now() + self.timeout;
634 loop {
635 if cancel.is_cancelled() {
636 return (
637 Err(format!(
638 "`{method}` was cancelled before the server answered; it has been stopped"
639 )),
640 true,
641 );
642 }
643 let left = deadline
644 .saturating_duration_since(Instant::now())
645 .min(CANCEL_TICK);
646 match pipe.rx.recv_timeout(left) {
647 Ok(value) => match answer_to(&value, id, method) {
648 Answer::NotMine => continue,
649 Answer::Unparsable(why) => {
650 return (
651 Err(format!("the server wrote a line that is not JSON: {why}")),
652 true,
653 )
654 }
655 Answer::Value(result) => return (Ok(result), false),
656 Answer::Failed(why) => return (Err(why), false),
657 },
658 Err(RecvTimeoutError::Timeout) => {
659 if Instant::now() < deadline {
662 continue;
663 }
664 return (
665 Err(format!(
666 "the server did not answer `{method}` within {}s; it has been stopped \
667 and will be started again on the next call",
668 self.timeout.as_secs()
669 )),
670 true,
671 );
672 }
673 Err(RecvTimeoutError::Disconnected) => {
674 return (
675 Err(format!(
676 "the server exited while `{method}` was in flight{}",
677 self.stderr_tail()
678 )),
679 true,
680 )
681 }
682 }
683 }
684 }
685
686 fn exchange_http(
691 &self,
692 http: &mut Http,
693 id: i64,
694 method: &str,
695 message: &Value,
696 cancel: &crate::cancel::Cancel,
697 ) -> (Result<Value, String>, bool) {
698 let reply = match self.post(http, message, Some(id), cancel) {
699 Ok(reply) => reply,
700 Err(message) => return (Err(message), http.expired.load(Ordering::Relaxed)),
701 };
702 let outcome = match answer_to(&reply.value, id, method) {
703 Answer::Value(result) => Ok(result),
704 Answer::Failed(why) => Err(why),
705 Answer::Unparsable(why) => Err(format!("the server answered `{method}` with {why}")),
706 Answer::NotMine => Err(format!(
709 "`{method}` was answered with a message for another id; this build speaks one \
710 request per post"
711 )),
712 };
713 (outcome, http.expired.load(Ordering::Relaxed))
714 }
715
716 fn ensure(&self, slot: &mut Option<Conn>) -> Result<(), String> {
719 let alive = match slot.as_mut() {
720 Some(Conn::Pipe(pipe)) => matches!(pipe.child.try_wait(), Ok(None)),
723 Some(Conn::Http(_)) => true,
726 None => false,
727 };
728 if !alive {
729 *slot = None;
730 }
731 if slot.is_none() {
732 *slot = Some(self.connect()?);
733 }
734 Ok(())
735 }
736
737 fn connect(&self) -> Result<Conn, String> {
740 self.spec.validate()?;
741 match self.spec.transport {
742 Transport::Stdio => Ok(Conn::Pipe(self.start_pipe()?)),
743 Transport::Http => Ok(Conn::Http(self.start_http()?)),
744 }
745 }
746
747 fn start_http(&self) -> Result<Http, String> {
751 let url = self
752 .spec
753 .url
754 .as_deref()
755 .map(str::trim)
756 .filter(|u| !u.is_empty())
757 .ok_or("`transport = \"http\"` with no `url` to post to")?
758 .to_string();
759 let token = self.spec.token(&self.secrets)?;
760 let client = reqwest::Client::builder()
761 .user_agent(concat!("eclipse/", env!("CARGO_PKG_VERSION")))
762 .build()
763 .map_err(|e| format!("could not build an HTTP client: {e}"))?;
764 let mut http = Http {
765 client,
766 url,
767 session: None,
768 token,
769 expired: Arc::new(AtomicBool::new(false)),
770 };
771 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
772 let init = json!({
773 "jsonrpc": "2.0",
774 "id": id,
775 "method": "initialize",
776 "params": {
777 "protocolVersion": PROTOCOL,
778 "capabilities": {},
779 "clientInfo": { "name": "eclipse", "version": env!("CARGO_PKG_VERSION") },
780 }
781 });
782 let reply = self.post(&mut http, &init, Some(id), &crate::cancel::Cancel::new())?;
783 if let Some(session) = reply.session {
786 http.session = Some(session);
787 }
788 if let Some(err) = reply.value.get("error") {
789 return Err(format!(
790 "`initialize` was refused: {}",
791 err.get("message")
792 .and_then(Value::as_str)
793 .unwrap_or("no message")
794 ));
795 }
796 match answer_to(&reply.value, id, "initialize") {
797 Answer::Value(result) => {
798 if result
799 .get("protocolVersion")
800 .and_then(Value::as_str)
801 .is_none()
802 {
803 return Err("`initialize` answered without a protocolVersion".into());
804 }
805 self.keep_handshake(&result);
806 }
807 Answer::Failed(why) => return Err(why),
808 Answer::Unparsable(why) => {
809 return Err(format!(
810 "`initialize` was answered with a body this build cannot read: {why}"
811 ))
812 }
813 Answer::NotMine => {
814 return Err("`initialize` was answered with a message for another id".into())
815 }
816 }
817 let ready = json!({ "jsonrpc": "2.0", "method": "notifications/initialized" });
818 self.post(&mut http, &ready, None, &crate::cancel::Cancel::new())?;
819 Ok(http)
820 }
821
822 fn post(
830 &self,
831 http: &mut Http,
832 message: &Value,
833 id: Option<i64>,
834 cancel: &crate::cancel::Cancel,
835 ) -> Result<Reply, String> {
836 let exchange = Exchange {
837 client: http.client.clone(),
838 url: http.url.clone(),
839 session: http.session.clone(),
840 token: http.token.clone(),
841 expired: http.expired.clone(),
842 };
843 let body = message.clone();
844 let timeout = self.timeout;
845 let (tx, rx) = mpsc::channel::<Result<Reply, String>>();
846 std::thread::spawn(move || {
847 let _ = tx.send(over_http(exchange, body, id, timeout));
848 });
849 let deadline = Instant::now() + timeout + Duration::from_secs(2);
852 loop {
853 if cancel.is_cancelled() {
854 return Err("the request was cancelled before the server answered".to_string());
855 }
856 let left = deadline
857 .saturating_duration_since(Instant::now())
858 .min(CANCEL_TICK);
859 match rx.recv_timeout(left) {
860 Ok(outcome) => return outcome,
861 Err(RecvTimeoutError::Timeout) => {
862 if Instant::now() < deadline {
863 continue;
864 }
865 return Err(format!(
866 "the server did not answer within {}s",
867 timeout.as_secs()
868 ));
869 }
870 Err(RecvTimeoutError::Disconnected) => {
871 return Err("the HTTP exchange ended without an answer".to_string())
872 }
873 }
874 }
875 }
876
877 fn start_pipe(&self) -> Result<Pipe, String> {
881 let mut cmd = Command::new(&self.spec.command);
882 cmd.args(&self.spec.args)
883 .current_dir(self.cwd())
884 .env_clear()
885 .stdin(Stdio::piped())
886 .stdout(Stdio::piped())
887 .stderr(Stdio::piped());
888 for key in crate::plugins::INHERITED_ENV {
889 if let Ok(v) = std::env::var(key) {
890 cmd.env(key, v);
891 }
892 }
893 for key in &self.spec.env {
894 if let Ok(v) = std::env::var(key) {
895 cmd.env(key, v);
896 }
897 }
898 cmd.env("ECLIPSE_PLUGIN_DIR", &self.plugin_dir)
899 .env("ECLIPSE_WORKSPACE", &self.workspace);
900 #[cfg(unix)]
903 cmd.process_group(0);
904 let mut child = cmd
905 .spawn()
906 .map_err(|e| format!("could not start `{}`: {e}", self.spec.command))?;
907 let stdin = child.stdin.take().ok_or("no stdin on the server process")?;
908 let stdout = child
909 .stdout
910 .take()
911 .ok_or("no stdout on the server process")?;
912 if let Some(mut err) = child.stderr.take() {
916 let keep = Arc::clone(&self.stderr);
917 std::thread::spawn(move || {
918 let mut buf = [0u8; 1024];
919 loop {
920 match std::io::Read::read(&mut err, &mut buf) {
921 Ok(0) | Err(_) => break,
922 Ok(n) => {
923 let text = String::from_utf8_lossy(&buf[..n]).into_owned();
924 let mut slot = keep.lock().unwrap_or_else(|e| e.into_inner());
925 slot.push_str(&text);
926 keep_tail(&mut slot, STDERR_KEEP);
927 }
928 }
929 }
930 });
931 }
932 let (tx, rx) = mpsc::sync_channel(LINE_QUEUE);
933 std::thread::spawn(move || {
934 let mut reader = BufReader::new(stdout);
935 loop {
936 let line = match read_line_capped(&mut reader, MAX_LINE) {
937 Ok(Some(Line::Text(line))) => line,
938 Ok(Some(Line::TooLong(bytes))) => {
942 if tx
943 .send(json!({
944 "eclipse_unparsable": format!(
945 "a line of {bytes} bytes is over the {MAX_LINE}-byte limit and was dropped"
946 )
947 }))
948 .is_err()
949 {
950 break;
951 }
952 continue;
953 }
954 Ok(None) | Err(_) => break,
955 };
956 if line.trim().is_empty() {
957 continue;
958 }
959 match serde_json::from_str::<Value>(&line) {
962 Ok(value) => {
963 if tx.send(value).is_err() {
964 break;
965 }
966 }
967 Err(e) => {
968 let _ = tx.send(json!({
969 "eclipse_unparsable": format!("{e}: {}", clip(&line, 200))
970 }));
971 }
972 }
973 }
974 });
975 let mut pipe = Pipe { child, stdin, rx };
976 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
977 let init = json!({
978 "jsonrpc": "2.0",
979 "id": id,
980 "method": "initialize",
981 "params": {
982 "protocolVersion": PROTOCOL,
983 "capabilities": {},
984 "clientInfo": { "name": "eclipse", "version": env!("CARGO_PKG_VERSION") },
985 }
986 });
987 self.write_stdin(&mut pipe.stdin, &init.to_string())
988 .map_err(|e| {
989 format!(
990 "could not send `initialize`: {e}{}",
991 self.stderr_tail_soon()
992 )
993 })?;
994 let answer = wait_for(&mut pipe, id, self.timeout, &self.stderr)?;
995 if let Some(result) = answer.get("result") {
996 if result
997 .get("protocolVersion")
998 .and_then(Value::as_str)
999 .is_none()
1000 {
1001 return Err("`initialize` answered without a protocolVersion".into());
1002 }
1003 self.keep_handshake(result);
1004 }
1005 let ready = json!({ "jsonrpc": "2.0", "method": "notifications/initialized" });
1008 self.write_stdin(&mut pipe.stdin, &ready.to_string())
1009 .map_err(|e| format!("could not finish the handshake: {e}"))?;
1010 Ok(pipe)
1011 }
1012
1013 fn cwd(&self) -> PathBuf {
1014 match self.spec.cwd {
1015 crate::plugins::Cwd::Plugin => self.plugin_dir.clone(),
1016 crate::plugins::Cwd::Workspace => self.workspace.clone(),
1017 }
1018 }
1019
1020 fn stderr_tail_soon(&self) -> String {
1025 let mut tail = self.stderr_tail();
1026 for _ in 0..50 {
1030 if !tail.is_empty() {
1031 break;
1032 }
1033 std::thread::sleep(Duration::from_millis(10));
1034 tail = self.stderr_tail();
1035 }
1036 tail
1037 }
1038
1039 fn stderr_tail(&self) -> String {
1040 let slot = self.stderr.lock().unwrap_or_else(|e| e.into_inner());
1041 let tail = slot.trim();
1042 if tail.is_empty() {
1043 String::new()
1044 } else {
1045 format!("; the server said: {}", clip(tail, 600))
1046 }
1047 }
1048}
1049
1050struct Reply {
1052 value: Value,
1053 session: Option<String>,
1054}
1055
1056struct Exchange {
1059 client: reqwest::Client,
1060 url: String,
1061 session: Option<String>,
1062 token: Option<String>,
1063 expired: Arc<AtomicBool>,
1064}
1065
1066fn over_http(
1068 exchange: Exchange,
1069 body: Value,
1070 id: Option<i64>,
1071 timeout: Duration,
1072) -> Result<Reply, String> {
1073 let Exchange {
1074 client,
1075 url,
1076 session,
1077 token,
1078 expired,
1079 } = exchange;
1080 let runtime = tokio::runtime::Builder::new_current_thread()
1081 .enable_all()
1082 .build()
1083 .map_err(|e| format!("could not start an HTTP runtime: {e}"))?;
1084 runtime.block_on(async move {
1085 let mut request = client
1086 .post(&url)
1087 .header(
1088 reqwest::header::ACCEPT,
1089 "application/json, text/event-stream",
1090 )
1091 .timeout(timeout)
1092 .json(&body);
1093 if let Some(session) = session.as_deref() {
1094 request = request.header("mcp-session-id", session);
1095 }
1096 if let Some(token) = token.as_deref() {
1097 request = request.bearer_auth(token);
1098 }
1099 let response = request
1100 .send()
1101 .await
1102 .map_err(|e| format!("could not post to {url}: {e:?}"))?;
1103 let status = response.status();
1104 let issued = response
1105 .headers()
1106 .get("mcp-session-id")
1107 .and_then(|v| v.to_str().ok())
1108 .filter(|v| !v.is_empty())
1109 .map(str::to_string);
1110 let streamed = response
1111 .headers()
1112 .get(reqwest::header::CONTENT_TYPE)
1113 .and_then(|v| v.to_str().ok())
1114 .map(|v| v.contains("text/event-stream"))
1115 .unwrap_or(false);
1116 let mut response = response;
1119 let mut text = String::new();
1120 while let Some(bytes) = response
1121 .chunk()
1122 .await
1123 .map_err(|e| format!("could not read the answer from {url}: {e}"))?
1124 {
1125 if text.len() + bytes.len() > MAX_LINE {
1126 return Err(format!(
1127 "the server answered with more than {} MiB: {url}",
1128 MAX_LINE / (1024 * 1024)
1129 ));
1130 }
1131 text.push_str(&String::from_utf8_lossy(&bytes));
1132 }
1133 let session = issued.or(session);
1134 if status == reqwest::StatusCode::NOT_FOUND && session.is_some() {
1135 expired.store(true, Ordering::Relaxed);
1139 }
1140 if !status.is_success() {
1141 return Err(format!(
1143 "the server answered HTTP {}: {}",
1144 status.as_u16(),
1145 if text.trim().is_empty() {
1146 "no body".to_string()
1147 } else {
1148 clip(text.trim(), 400)
1149 }
1150 ));
1151 }
1152 if text.trim().is_empty() {
1153 return Ok(Reply {
1155 value: Value::Null,
1156 session,
1157 });
1158 }
1159 let value = if streamed {
1160 sse_payload(&text, id)
1161 } else {
1162 serde_json::from_str::<Value>(text.trim()).map_err(|e| {
1163 format!(
1164 "the server answered with a body that is not JSON-RPC ({e}): {}",
1165 clip(text.trim(), 200)
1166 )
1167 })?
1168 };
1169 Ok(Reply { value, session })
1170 })
1171}
1172
1173fn sse_payload(text: &str, id: Option<i64>) -> Value {
1179 let text = text.replace("\r\n", "\n").replace('\r', "\n");
1184 let mut last = Value::Null;
1185 for event in text.split("\n\n") {
1186 let mut data = String::new();
1187 for line in event.lines() {
1188 if let Some(rest) = line.strip_prefix("data:") {
1189 if !data.is_empty() {
1190 data.push('\n');
1191 }
1192 data.push_str(rest.trim_start());
1193 }
1194 }
1195 if data.trim().is_empty() {
1196 continue;
1197 }
1198 let Ok(value) = serde_json::from_str::<Value>(data.trim()) else {
1199 continue;
1200 };
1201 if let Some(id) = id {
1202 if value.get("id").and_then(Value::as_i64) == Some(id) {
1203 return value;
1204 }
1205 }
1206 last = value;
1207 }
1208 last
1209}
1210
1211enum Answer {
1213 NotMine,
1217 Unparsable(String),
1219 Value(Value),
1221 Failed(String),
1223}
1224
1225fn answer_to(value: &Value, id: i64, method: &str) -> Answer {
1226 if let Some(why) = value.get("eclipse_unparsable").and_then(Value::as_str) {
1227 return Answer::Unparsable(why.to_string());
1228 }
1229 if value.get("id").and_then(Value::as_i64) != Some(id) {
1230 return Answer::NotMine;
1231 }
1232 if let Some(err) = value.get("error") {
1233 let message = err
1234 .get("message")
1235 .and_then(Value::as_str)
1236 .unwrap_or("no message");
1237 return Answer::Failed(format!("{method} failed: {message}"));
1238 }
1239 Answer::Value(value.get("result").cloned().unwrap_or(Value::Null))
1240}
1241
1242fn wait_for(
1244 pipe: &mut Pipe,
1245 id: i64,
1246 timeout: Duration,
1247 stderr: &Arc<Mutex<String>>,
1248) -> Result<Value, String> {
1249 let deadline = Instant::now() + timeout;
1250 loop {
1251 let left = deadline.saturating_duration_since(Instant::now());
1252 match pipe.rx.recv_timeout(left) {
1253 Ok(value) => {
1254 if let Some(why) = value.get("eclipse_unparsable").and_then(Value::as_str) {
1255 return Err(format!("the server wrote a line that is not JSON: {why}"));
1256 }
1257 if value.get("id").and_then(Value::as_i64) != Some(id) {
1258 continue;
1259 }
1260 if let Some(err) = value.get("error") {
1261 return Err(format!(
1262 "`initialize` was refused: {}",
1263 err.get("message")
1264 .and_then(Value::as_str)
1265 .unwrap_or("no message")
1266 ));
1267 }
1268 return Ok(value);
1269 }
1270 Err(RecvTimeoutError::Timeout) => {
1271 let tail = stderr.lock().unwrap_or_else(|e| e.into_inner()).clone();
1272 return Err(format!(
1273 "the server did not answer `initialize` within {}s{}",
1274 timeout.as_secs(),
1275 if tail.trim().is_empty() {
1276 String::new()
1277 } else {
1278 format!("; it said: {}", clip(tail.trim(), 600))
1279 }
1280 ));
1281 }
1282 Err(RecvTimeoutError::Disconnected) => {
1283 let tail = stderr.lock().unwrap_or_else(|e| e.into_inner()).clone();
1284 return Err(format!(
1285 "the server exited during the handshake{}",
1286 if tail.trim().is_empty() {
1287 String::new()
1288 } else {
1289 format!("; it said: {}", clip(tail.trim(), 600))
1290 }
1291 ));
1292 }
1293 }
1294 }
1295}
1296
1297fn content_text(result: &Value) -> String {
1301 let Some(items) = result.get("content").and_then(Value::as_array) else {
1302 if let Some(text) = result.get("content").and_then(Value::as_str) {
1304 return text.to_string();
1305 }
1306 if let Some(structured) = result.get("structuredContent") {
1307 return structured.to_string();
1308 }
1309 return String::new();
1310 };
1311 let mut parts = Vec::new();
1312 for item in items {
1313 let kind = item
1314 .get("type")
1315 .and_then(Value::as_str)
1316 .unwrap_or("unknown");
1317 if kind == "text" {
1318 if let Some(text) = item.get("text").and_then(Value::as_str) {
1319 parts.push(text.to_string());
1320 }
1321 } else {
1322 parts.push(format!("[{kind} content from an MCP server is not shown]"));
1323 }
1324 }
1325 parts.join("\n")
1326}
1327
1328fn keep_tail(slot: &mut String, keep: usize) {
1335 if slot.len() <= keep {
1336 return;
1337 }
1338 let mut cut = slot.len() - keep;
1339 while !slot.is_char_boundary(cut) {
1340 cut += 1;
1341 }
1342 slot.drain(..cut);
1343}
1344
1345fn clip(text: &str, max: usize) -> String {
1346 if text.chars().count() <= max {
1347 return text.to_string();
1348 }
1349 let head: String = text.chars().take(max).collect();
1350 format!("{head}…")
1351}
1352
1353pub struct McpTool {
1355 name: String,
1357 remote: String,
1359 description: String,
1360 parameters: Value,
1361 plugin: String,
1362 server: Arc<Server>,
1363}
1364
1365pub const TOOL_NAME_MAX: usize = 64;
1368
1369pub const DESCRIPTION_MAX: usize = 2000;
1372
1373pub const SCHEMA_MAX: usize = 16 * 1024;
1375
1376pub fn sanitize_tool_name(name: &str) -> String {
1384 let cleaned: String = name
1385 .chars()
1386 .map(|c| {
1387 if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
1388 c
1389 } else {
1390 '_'
1391 }
1392 })
1393 .collect();
1394 cleaned.chars().take(TOOL_NAME_MAX).collect()
1395}
1396
1397fn cap_text(text: &str, max: usize) -> String {
1400 if text.chars().count() <= max {
1401 return text.to_string();
1402 }
1403 let mut out: String = text.chars().take(max).collect();
1404 out.push_str("… [truncated]");
1405 out
1406}
1407
1408impl McpTool {
1409 async fn call_unless(
1413 &self,
1414 args: Value,
1415 cancel: crate::cancel::Cancel,
1416 ) -> Result<String, ToolError> {
1417 let server = Arc::clone(&self.server);
1418 let remote = self.remote.clone();
1419 let out =
1420 tokio::task::spawn_blocking(move || server.call_tool_unless(&remote, &args, &cancel))
1421 .await
1422 .map_err(|e| ToolError::Failed(format!("the MCP call did not finish: {e}")))?;
1423 out.map_err(ToolError::Failed)
1424 }
1425
1426 pub fn new(server: Arc<Server>, remote: &RemoteTool) -> Self {
1427 let name = sanitize_tool_name(&format!("{}{}", server.prefix(), remote.name));
1434 let description = if remote.description.trim().is_empty() {
1435 format!("`{}` on the `{}` MCP server", remote.name, server.name())
1436 } else {
1437 cap_text(&remote.description, DESCRIPTION_MAX)
1438 };
1439 let parameters = remote
1440 .input_schema
1441 .clone()
1442 .unwrap_or_else(|| json!({ "type": "object", "properties": {} }));
1443 let over_cap = serde_json::to_string(¶meters).map_or(0, |s| s.len()) > SCHEMA_MAX;
1448 let parameters = if over_cap {
1449 json!({ "type": "object", "properties": {} })
1450 } else {
1451 parameters
1452 };
1453 let description = if over_cap {
1454 format!(
1455 "{description} [its input schema is over {SCHEMA_MAX} bytes and was not included; \
1456 the tool takes a JSON object]"
1457 )
1458 } else {
1459 description
1460 };
1461 Self {
1462 name,
1463 remote: remote.name.clone(),
1464 description,
1465 parameters,
1466 plugin: server.name().to_string(),
1467 server,
1468 }
1469 }
1470 pub fn server_name(&self) -> &str {
1472 &self.plugin
1473 }
1474}
1475
1476#[async_trait::async_trait]
1477impl Tool for McpTool {
1478 fn name(&self) -> &str {
1479 &self.name
1480 }
1481
1482 fn description(&self) -> &str {
1483 &self.description
1484 }
1485
1486 fn parameters(&self) -> Value {
1487 self.parameters.clone()
1488 }
1489
1490 fn describe_call(&self, args: &Value) -> String {
1491 format!(
1494 "{} (mcp: {}) {}",
1495 self.remote,
1496 self.plugin,
1497 clip(&args.to_string(), 200)
1498 )
1499 }
1500
1501 async fn call(&self, args: Value) -> Result<String, ToolError> {
1502 self.call_unless(args, crate::cancel::Cancel::new()).await
1503 }
1504
1505 async fn call_scoped(
1506 &self,
1507 args: Value,
1508 scope: &crate::tools::CallScope<'_>,
1509 ) -> Result<String, ToolError> {
1510 self.call_unless(args, scope.run.cancel.clone()).await
1513 }
1514}
1515
1516#[cfg(test)]
1517mod tests {
1518 use super::*;
1519 use std::path::PathBuf;
1520
1521 const DEFAULT_TEST_TIMEOUT: Duration = Duration::from_secs(10);
1524
1525 const FAKE: &str = r#"#!/usr/bin/env python3
1529import json, sys, time
1530
1531def send(obj):
1532 sys.stdout.write(json.dumps(obj) + "\n"); sys.stdout.flush()
1533
1534for line in sys.stdin:
1535 line = line.strip()
1536 if not line:
1537 continue
1538 msg = json.loads(line)
1539 mid, method = msg.get("id"), msg.get("method")
1540 params = msg.get("params") or {}
1541 if method == "initialize":
1542 send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2024-11-05",
1543 "capabilities": {"tools": {}}, "serverInfo": {"name": "fake", "version": "0"}}})
1544 elif method == "notifications/initialized":
1545 pass
1546 elif method == "tools/list":
1547 if params.get("cursor"):
1548 send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
1549 {"name": "fail_tool", "description": "Always fails"}]}})
1550 else:
1551 send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
1552 {"name": "echo_text", "description": "Echo the text back",
1553 "inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}}}],
1554 "nextCursor": "page-2"}})
1555 elif method == "tools/call":
1556 name, args = params.get("name"), params.get("arguments") or {}
1557 if name == "echo_text":
1558 if args.get("sleep"):
1559 time.sleep(30)
1560 send({"jsonrpc": "2.0", "id": mid, "result": {"content": [
1561 {"type": "text", "text": "echo: " + str(args.get("text", ""))}]}})
1562 elif name == "fail_tool":
1563 send({"jsonrpc": "2.0", "id": mid, "result": {
1564 "content": [{"type": "text", "text": "the disk is on fire"}], "isError": True}})
1565 else:
1566 send({"jsonrpc": "2.0", "id": mid, "result": {"content": []}})
1567 elif mid is not None:
1568 send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "no such method"}})
1569"#;
1570
1571 struct FakeHttp {
1578 port: u16,
1579 seen: Arc<Mutex<Vec<(String, String)>>>,
1580 stop: Arc<std::sync::atomic::AtomicBool>,
1581 forgetful: Arc<std::sync::atomic::AtomicBool>,
1584 }
1585
1586 impl Drop for FakeHttp {
1587 fn drop(&mut self) {
1588 self.stop.store(true, Ordering::SeqCst);
1589 let _ = std::net::TcpStream::connect(("127.0.0.1", self.port));
1591 }
1592 }
1593
1594 impl FakeHttp {
1595 fn forget_sessions(&self) {
1597 self.forgetful.store(true, Ordering::SeqCst);
1598 }
1599
1600 fn start(token: Option<String>, status: Option<u16>) -> Self {
1602 let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a port");
1603 let port = listener.local_addr().unwrap().port();
1604 let seen = Arc::new(Mutex::new(Vec::new()));
1605 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1606 let forgetful = Arc::new(std::sync::atomic::AtomicBool::new(false));
1607 let (log, flag) = (Arc::clone(&seen), Arc::clone(&stop));
1608 let forget = Arc::clone(&forgetful);
1609 std::thread::spawn(move || {
1610 for stream in listener.incoming() {
1611 if flag.load(Ordering::SeqCst) {
1612 break;
1613 }
1614 let Ok(mut stream) = stream else { continue };
1615 let (head, body) = read_http(&mut stream);
1616 log.lock()
1617 .unwrap_or_else(|e| e.into_inner())
1618 .push((head.clone(), body.clone()));
1619 let reply = answer_http(&head, &body, token.as_deref(), status, &forget);
1620 let _ = std::io::Write::write_all(&mut stream, reply.as_bytes());
1621 let _ = std::io::Write::flush(&mut stream);
1622 }
1623 });
1624 FakeHttp {
1625 port,
1626 seen,
1627 stop,
1628 forgetful,
1629 }
1630 }
1631
1632 fn url(&self, path: &str) -> String {
1633 format!("http://127.0.0.1:{}{path}", self.port)
1634 }
1635
1636 fn requests(&self) -> Vec<(String, String)> {
1637 self.seen.lock().unwrap_or_else(|e| e.into_inner()).clone()
1638 }
1639 }
1640
1641 fn read_http(stream: &mut std::net::TcpStream) -> (String, String) {
1643 use std::io::Read;
1644 let mut head = Vec::new();
1645 let mut byte = [0u8; 1];
1646 while head.len() < 64 * 1024 {
1647 match stream.read(&mut byte) {
1648 Ok(0) | Err(_) => {
1649 return (String::from_utf8_lossy(&head).into_owned(), String::new())
1650 }
1651 Ok(_) => {
1652 head.push(byte[0]);
1653 if head.ends_with(b"\r\n\r\n") {
1654 break;
1655 }
1656 }
1657 }
1658 }
1659 let head = String::from_utf8_lossy(&head).into_owned();
1660 let length = head
1661 .lines()
1662 .find_map(|line| {
1663 let (name, value) = line.split_once(':')?;
1664 name.eq_ignore_ascii_case("content-length")
1665 .then(|| value.trim().parse::<usize>().ok())
1666 .flatten()
1667 })
1668 .unwrap_or(0);
1669 let mut body = vec![0u8; length];
1670 let mut got = 0;
1671 while got < length {
1672 match stream.read(&mut body[got..]) {
1673 Ok(0) | Err(_) => break,
1674 Ok(n) => got += n,
1675 }
1676 }
1677 body.truncate(got);
1678 (head, String::from_utf8_lossy(&body).into_owned())
1679 }
1680
1681 fn header<'a>(head: &'a str, name: &str) -> Option<&'a str> {
1682 head.lines().find_map(|line| {
1683 let (key, value) = line.split_once(':')?;
1684 key.eq_ignore_ascii_case(name).then(|| value.trim())
1685 })
1686 }
1687
1688 fn answer_http(
1689 head: &str,
1690 body: &str,
1691 token: Option<&str>,
1692 status: Option<u16>,
1693 forgetful: &std::sync::atomic::AtomicBool,
1694 ) -> String {
1695 let message: Value = serde_json::from_str(body).unwrap_or(Value::Null);
1696 let id = message.get("id").cloned().unwrap_or(Value::Null);
1697 let method = message.get("method").and_then(Value::as_str).unwrap_or("");
1698 if let Some(token) = token {
1699 let sent = header(head, "authorization").unwrap_or("<>");
1700 if sent != format!("Bearer {token}") {
1701 return http_reply(
1702 401,
1703 "application/json",
1704 &json!({ "error": "unauthorized" }).to_string(),
1705 "",
1706 );
1707 }
1708 }
1709 if let Some(status) = status {
1710 return http_reply(status, "application/json", "", "");
1711 }
1712 if forgetful.load(Ordering::SeqCst) && method != "initialize" {
1715 return http_reply(404, "application/json", "", "");
1716 }
1717 if method != "initialize" && header(head, "mcp-session-id").is_none() {
1720 return http_reply(400, "application/json", "", "");
1721 }
1722 match method {
1723 "initialize" => {
1724 let extra = "mcp-session-id: test-session\r\n";
1725 http_reply(
1726 200,
1727 "application/json",
1728 &json!({ "jsonrpc": "2.0", "id": id, "result": {
1729 "protocolVersion": "2024-11-05",
1730 "capabilities": { "tools": {} },
1731 "serverInfo": { "name": "fake-http", "version": "0" } } })
1732 .to_string(),
1733 extra,
1734 )
1735 }
1736 "notifications/initialized" => http_reply(202, "text/plain", "", ""),
1738 "tools/list" => {
1739 let page = message
1740 .get("params")
1741 .and_then(|p| p.get("cursor"))
1742 .and_then(Value::as_str)
1743 .map(str::to_string);
1744 let result = match page.as_deref() {
1745 Some("page-2") => json!({ "tools": [
1746 { "name": "fail_tool", "description": "Always fails" }] }),
1747 _ => json!({ "tools": [
1748 { "name": "echo_text", "description": "Echo the text back",
1749 "inputSchema": { "type": "object",
1750 "properties": { "text": { "type": "string" } } } }],
1751 "nextCursor": "page-2" }),
1752 };
1753 let event = format!(
1756 ": keep-alive\n\ndata: {}\n\n",
1757 json!({ "jsonrpc": "2.0", "id": id, "result": result })
1758 );
1759 http_reply(200, "text/event-stream", &event, "")
1760 }
1761 "tools/call" => {
1762 let name = message
1763 .get("params")
1764 .and_then(|p| p.get("name"))
1765 .and_then(Value::as_str)
1766 .unwrap_or("");
1767 let text = message
1768 .get("params")
1769 .and_then(|p| p.get("arguments"))
1770 .and_then(|a| a.get("text"))
1771 .and_then(Value::as_str)
1772 .unwrap_or("");
1773 let result = if name == "fail_tool" {
1774 json!({ "content": [{ "type": "text", "text": "the disk is on fire" }],
1775 "isError": true })
1776 } else {
1777 json!({ "content": [{ "type": "text", "text": format!("echo: {text}") }] })
1778 };
1779 http_reply(
1780 200,
1781 "application/json",
1782 &json!({ "jsonrpc": "2.0", "id": id, "result": result }).to_string(),
1783 "",
1784 )
1785 }
1786 _ => http_reply(
1787 200,
1788 "application/json",
1789 &json!({ "jsonrpc": "2.0", "id": id,
1790 "error": { "code": -32601, "message": "no such method" } })
1791 .to_string(),
1792 "",
1793 ),
1794 }
1795 }
1796
1797 fn http_reply(status: u16, kind: &str, body: &str, extra: &str) -> String {
1798 format!(
1799 "HTTP/1.1 {status} OK\r\nContent-Type: {kind}\r\nContent-Length: {}\r\n{extra}Connection: close\r\n\r\n{body}",
1800 body.len()
1801 )
1802 }
1803
1804 fn http_spec(url: &str) -> Spec {
1806 Spec {
1807 name: "ha".into(),
1808 transport: Transport::Http,
1809 command: String::new(),
1810 args: Vec::new(),
1811 env: Vec::new(),
1812 cwd: crate::plugins::Cwd::Workspace,
1813 url: Some(url.to_string()),
1814 token_env: None,
1815 timeout_secs: Some(10),
1816 policy: Policy::Allow,
1817 policies: BTreeMap::new(),
1818 prefix: String::new(),
1819 override_builtin: false,
1820 disabled: false,
1821 }
1822 }
1823
1824 const DIES: &str = r#"#!/usr/bin/env python3
1827import sys
1828sys.stderr.write("could not open the database: /nope\n")
1829sys.exit(3)
1830"#;
1831
1832 fn have_python() -> bool {
1833 std::process::Command::new("python3")
1834 .arg("--version")
1835 .output()
1836 .map(|o| o.status.success())
1837 .unwrap_or(false)
1838 }
1839
1840 fn script(dir: &Path, name: &str, body: &str) -> PathBuf {
1841 let path = dir.join(name);
1842 std::fs::write(&path, body).unwrap();
1843 #[cfg(unix)]
1844 {
1845 use std::os::unix::fs::PermissionsExt;
1846 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
1847 }
1848 path
1849 }
1850
1851 fn spec(script: &Path, timeout_secs: u64) -> Spec {
1852 Spec {
1853 name: "fake".into(),
1854 transport: Transport::Stdio,
1855 command: "python3".into(),
1856 args: vec![script.to_string_lossy().into_owned()],
1857 url: None,
1858 token_env: None,
1859 env: Vec::new(),
1860 cwd: crate::plugins::Cwd::Plugin,
1861 timeout_secs: Some(timeout_secs),
1862 policy: Policy::Ask,
1863 policies: Default::default(),
1864 prefix: String::new(),
1865 override_builtin: false,
1866 disabled: false,
1867 }
1868 }
1869
1870 #[test]
1875 fn a_remote_tool_name_is_made_safe_for_a_request() {
1876 assert_eq!(sanitize_tool_name("get repo"), "get_repo");
1878 assert_eq!(sanitize_tool_name("a.b"), "a_b");
1879 assert_eq!(sanitize_tool_name("日本"), "__");
1880 assert_eq!(sanitize_tool_name("read_file"), "read_file");
1881 let long = "x".repeat(200);
1883 assert_eq!(sanitize_tool_name(&long).chars().count(), TOOL_NAME_MAX);
1884 assert_eq!(
1885 sanitize_tool_name(&format!("{}_tail", "y".repeat(63)))
1886 .chars()
1887 .count(),
1888 TOOL_NAME_MAX
1889 );
1890
1891 let long_desc = "d".repeat(DESCRIPTION_MAX * 2);
1893 let capped = cap_text(&long_desc, DESCRIPTION_MAX);
1894 assert!(capped.starts_with(&"d".repeat(DESCRIPTION_MAX)));
1895 assert!(capped.ends_with("[truncated]"), "{capped}");
1896 assert_eq!(cap_text("short", DESCRIPTION_MAX), "short");
1897 }
1898
1899 #[test]
1902 fn the_wire_keeps_the_name_the_server_published() {
1903 if !have_python() {
1904 return;
1905 }
1906 let dir = tempfile::tempdir().unwrap();
1907 let path = script(dir.path(), "fake.py", FAKE);
1908 let (server, _tools) = Server::start(
1909 &spec(&path, 10),
1910 dir.path(),
1911 dir.path(),
1912 DEFAULT_TEST_TIMEOUT,
1913 &Secrets::new(),
1914 )
1915 .expect("the fake server starts");
1916 let remote = RemoteTool {
1917 name: "get repo".into(),
1918 description: "Read a repository".into(),
1919 input_schema: None,
1920 };
1921 let tool = McpTool::new(Arc::clone(&server), &remote);
1922 assert_eq!(tool.name(), "get_repo");
1923 assert_eq!(
1924 tool.remote, "get repo",
1925 "the server is asked for the name it published, not the sanitised one"
1926 );
1927 }
1928
1929 #[test]
1933 fn a_line_over_the_cap_is_counted_and_dropped_not_buffered() {
1934 let big = vec![b'x'; MAX_LINE * 4];
1936 let mut reader = BufReader::new(&big[..]);
1937 match read_line_capped(&mut reader, MAX_LINE).unwrap() {
1938 Some(Line::TooLong(bytes)) => assert_eq!(bytes, MAX_LINE * 4),
1939 Some(Line::Text(t)) => panic!("kept {} bytes of it", t.len()),
1940 None => panic!("nothing read at all"),
1941 }
1942 let mut reader = BufReader::new(&b"{\"a\":1}\n{\"b\":2}\n"[..]);
1944 match read_line_capped(&mut reader, MAX_LINE).unwrap() {
1945 Some(Line::Text(text)) => assert_eq!(text, "{\"a\":1}"),
1946 other => panic!("{:?}", other.is_some()),
1947 }
1948 match read_line_capped(&mut reader, MAX_LINE).unwrap() {
1949 Some(Line::Text(text)) => assert_eq!(text, "{\"b\":2}"),
1950 _ => panic!("the second line did not survive"),
1951 }
1952 assert!(read_line_capped(&mut reader, MAX_LINE).unwrap().is_none());
1953 }
1954
1955 #[cfg(unix)]
1960 #[test]
1961 fn dropping_a_connection_kills_the_grandchild_holding_the_pipe() {
1962 if !have_python() {
1963 return;
1964 }
1965 let dir = tempfile::tempdir().unwrap();
1966 let fake = script(dir.path(), "fake.py", FAKE);
1967 let pid_file = dir.path().join("grandchild.pid");
1968 let wrapper = format!(
1969 "#!/bin/sh\nsleep 300 &\necho $! > {}\nexec python3 {}\n",
1970 pid_file.display(),
1971 fake.display()
1972 );
1973 let path = script(dir.path(), "wrapper.sh", &wrapper);
1974 let mut spec = spec(&fake, 10);
1975 spec.command = "sh".into();
1976 spec.args = vec![path.to_string_lossy().into_owned()];
1977 let (server, tools) = Server::start(
1978 &spec,
1979 dir.path(),
1980 dir.path(),
1981 DEFAULT_TEST_TIMEOUT,
1982 &Secrets::new(),
1983 )
1984 .expect("the wrapped server still speaks the protocol");
1985 assert_eq!(tools.len(), 2);
1986 let pid: u32 = std::fs::read_to_string(&pid_file)
1987 .expect("the wrapper recorded its child")
1988 .trim()
1989 .parse()
1990 .expect("a pid");
1991 assert!(pid_alive(pid), "the grandchild is running");
1992
1993 drop(server);
1994
1995 let mut waited = Duration::ZERO;
2002 while pid_alive(pid) && waited < Duration::from_secs(10) {
2003 std::thread::sleep(Duration::from_millis(20));
2004 waited += Duration::from_millis(20);
2005 }
2006 assert!(
2007 !pid_alive(pid),
2008 "the grandchild outlived the connection: still alive after {waited:?}"
2009 );
2010 }
2011
2012 #[cfg(unix)]
2013 fn pid_alive(pid: u32) -> bool {
2014 let Ok(pid) = libc::pid_t::try_from(pid) else {
2015 return false;
2016 };
2017 let rc = unsafe { libc::kill(pid, 0) };
2019 if rc != 0 {
2020 return false;
2021 }
2022 match std::fs::read_to_string(format!("/proc/{pid}/stat")) {
2024 Ok(stat) => match stat.rsplit_once(')') {
2025 Some((_, rest)) => !rest.trim_start().starts_with('Z'),
2026 None => true,
2027 },
2028 Err(_) => false,
2029 }
2030 }
2031
2032 #[test]
2033 fn a_server_is_listed_across_pages_and_its_tools_can_be_called() {
2034 if !have_python() {
2035 return;
2036 }
2037 let dir = tempfile::tempdir().unwrap();
2038 let path = script(dir.path(), "fake.py", FAKE);
2039 let (server, tools) = Server::start(
2040 &spec(&path, 10),
2041 dir.path(),
2042 dir.path(),
2043 DEFAULT_TEST_TIMEOUT,
2044 &Secrets::new(),
2045 )
2046 .expect("the fake server starts");
2047 let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
2049 assert_eq!(names, ["echo_text", "fail_tool"]);
2050 let echo = tools.iter().find(|t| t.name == "echo_text").unwrap();
2051 assert_eq!(echo.description, "Echo the text back");
2052 assert_eq!(echo.input_schema.as_ref().unwrap()["type"], "object");
2053
2054 let out = server
2056 .call_tool("echo_text", &json!({"text": "one"}))
2057 .unwrap();
2058 assert_eq!(out, "echo: one");
2059 let out = server
2060 .call_tool("echo_text", &json!({"text": "two"}))
2061 .unwrap();
2062 assert_eq!(out, "echo: two");
2063
2064 let err = server.call_tool("fail_tool", &json!({})).unwrap_err();
2066 assert_eq!(err, "the disk is on fire");
2067 }
2068
2069 #[test]
2072 fn an_http_entry_lists_across_pages_calls_a_tool_and_carries_the_session_id() {
2073 let fake = FakeHttp::start(None, None);
2074 let dir = tempfile::tempdir().unwrap();
2075 let (server, tools) = Server::start(
2076 &http_spec(&fake.url("/api/mcp")),
2077 dir.path(),
2078 dir.path(),
2079 DEFAULT_TEST_TIMEOUT,
2080 &Secrets::new(),
2081 )
2082 .expect("the HTTP server handshakes");
2083 let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
2084 assert_eq!(names, ["echo_text", "fail_tool"], "both pages arrived");
2085 assert_eq!(
2086 tools[0].input_schema.as_ref().unwrap()["type"],
2087 "object",
2088 "the schema survives the event-stream framing"
2089 );
2090
2091 assert_eq!(
2092 server
2093 .call_tool("echo_text", &json!({ "text": "ha" }))
2094 .unwrap(),
2095 "echo: ha"
2096 );
2097 assert_eq!(
2100 server.call_tool("fail_tool", &json!({})).unwrap_err(),
2101 "the disk is on fire"
2102 );
2103
2104 let requests = fake.requests();
2105 assert_eq!(requests.len(), 6, "initialize, ready, two pages, two calls");
2106 for (head, _) in requests.iter().skip(1) {
2109 assert_eq!(
2110 header(head, "mcp-session-id"),
2111 Some("test-session"),
2112 "{head}"
2113 );
2114 }
2115 assert_eq!(
2116 header(&requests[0].0, "accept"),
2117 Some("application/json, text/event-stream"),
2118 "the client has to say it can read both, or a server may answer neither"
2119 );
2120 assert!(
2121 requests[0].1.contains("\"initialize\""),
2122 "{}",
2123 requests[0].1
2124 );
2125 assert!(
2127 requests[3].1.contains("\"cursor\""),
2128 "the second page is asked for by cursor: {}",
2129 requests[3].1
2130 );
2131 }
2132
2133 #[test]
2135 fn a_401_is_reported_as_a_status_and_not_as_a_timeout() {
2136 let fake = FakeHttp::start(Some("s3cret".into()), None);
2137 let dir = tempfile::tempdir().unwrap();
2138 let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_SET");
2141 let mut spec = http_spec(&fake.url("/api/mcp"));
2142 spec.token_env = Some(key.clone());
2143 std::env::set_var(&key, "wrong");
2144 let err = Server::start(
2145 &spec,
2146 dir.path(),
2147 dir.path(),
2148 DEFAULT_TEST_TIMEOUT,
2149 &Secrets::new(),
2150 )
2151 .expect_err("401 is not a handshake");
2152 assert!(err.contains("401"), "the status is the report: {err}");
2153 assert!(!err.contains("did not answer"), "{err}");
2154
2155 std::env::set_var(&key, "s3cret");
2157 Server::start(
2158 &spec,
2159 dir.path(),
2160 dir.path(),
2161 DEFAULT_TEST_TIMEOUT,
2162 &Secrets::new(),
2163 )
2164 .expect("the right token handshakes");
2165 std::env::remove_var(&key);
2166 }
2167
2168 #[test]
2173 fn a_token_stored_only_in_dotenv_connects_and_is_what_the_client_sends() {
2174 let fake = FakeHttp::start(Some("from-file".into()), None);
2175 let dir = tempfile::tempdir().unwrap();
2176 let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_DOTENV");
2177 std::env::remove_var(&key);
2178 let mut spec = http_spec(&fake.url("/api/mcp"));
2179 spec.token_env = Some(key.clone());
2180 let mut secrets = Secrets::new();
2181 secrets.insert(key, "from-file".to_string());
2182
2183 Server::start(
2184 &spec,
2185 dir.path(),
2186 dir.path(),
2187 DEFAULT_TEST_TIMEOUT,
2188 &secrets,
2189 )
2190 .expect("a token kept in `.env` is a token this build can send");
2191
2192 let sent = fake
2193 .requests()
2194 .into_iter()
2195 .find_map(|(head, _)| header(&head, "authorization").map(str::to_string))
2196 .expect("the handshake carries an Authorization header");
2197 assert_eq!(sent, "Bearer from-file", "the value from `.env`, verbatim");
2198 }
2199
2200 #[test]
2203 fn the_environment_wins_over_dotenv_for_a_token_variable() {
2204 let fake = FakeHttp::start(Some("from-env".into()), None);
2205 let dir = tempfile::tempdir().unwrap();
2206 let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_BOTH");
2207 let mut spec = http_spec(&fake.url("/api/mcp"));
2208 spec.token_env = Some(key.clone());
2209 let mut secrets = Secrets::new();
2210 secrets.insert(key.clone(), "from-file".to_string());
2211 std::env::set_var(&key, "from-env");
2212
2213 let started = Server::start(
2214 &spec,
2215 dir.path(),
2216 dir.path(),
2217 DEFAULT_TEST_TIMEOUT,
2218 &secrets,
2219 );
2220 std::env::remove_var(&key);
2221 started.expect("the environment's value is the one used");
2222
2223 let sent = fake
2224 .requests()
2225 .into_iter()
2226 .find_map(|(head, _)| header(&head, "authorization").map(str::to_string))
2227 .expect("the handshake carries an Authorization header");
2228 assert_eq!(
2229 sent, "Bearer from-env",
2230 "the environment wins over the file"
2231 );
2232 }
2233
2234 #[test]
2237 fn an_empty_dotenv_token_is_absent_and_the_refusal_prints_no_secret() {
2238 let fake = FakeHttp::start(Some("s3cret".into()), None);
2239 let dir = tempfile::tempdir().unwrap();
2240 let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_EMPTY");
2241 std::env::remove_var(&key);
2242 let mut spec = http_spec(&fake.url("/api/mcp"));
2243 spec.token_env = Some(key.clone());
2244 let mut secrets = Secrets::new();
2245 secrets.insert(key.clone(), String::new());
2246 secrets.insert(format!("{key}_NEIGHBOUR"), "s3cret".to_string());
2247
2248 let err = Server::start(
2249 &spec,
2250 dir.path(),
2251 dir.path(),
2252 DEFAULT_TEST_TIMEOUT,
2253 &secrets,
2254 )
2255 .expect_err("an empty value is not a token");
2256 assert!(err.contains(&key), "{err}");
2257 assert!(
2258 err.contains("never reads a token from the manifest"),
2259 "{err}"
2260 );
2261 assert!(
2262 !err.contains("s3cret"),
2263 "a refusal is not a place for a value: {err}"
2264 );
2265 }
2266
2267 #[test]
2270 fn a_token_variable_that_is_not_set_is_named_in_the_error() {
2271 let fake = FakeHttp::start(Some("s3cret".into()), None);
2272 let dir = tempfile::tempdir().unwrap();
2273 let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_UNSET");
2274 let mut spec = http_spec(&fake.url("/api/mcp"));
2275 spec.token_env = Some(key.clone());
2276 std::env::remove_var(&key);
2277 let err = Server::start(
2278 &spec,
2279 dir.path(),
2280 dir.path(),
2281 DEFAULT_TEST_TIMEOUT,
2282 &Secrets::new(),
2283 )
2284 .expect_err("no token, no connection");
2285 assert!(err.contains(&key), "{err}");
2286 assert!(
2287 err.contains("never reads a token from the manifest"),
2288 "{err}"
2289 );
2290 }
2291
2292 #[test]
2294 fn a_manifest_that_mixes_transports_is_refused_naming_both() {
2295 let old: Spec = toml::from_str(
2297 "name = \"fs\"\ncommand = \"mcp-server-filesystem\"\nargs = [\"/tmp\"]\n",
2298 )
2299 .expect("an entry with no transport is a stdio entry");
2300 assert_eq!(old.transport, Transport::Stdio);
2301 assert!(old.validate().is_ok());
2302
2303 let mut both = http_spec("http://127.0.0.1:1/api/mcp");
2304 both.command = "mcp-server".into();
2305 let why = both.validate().unwrap_err();
2306 assert!(why.contains("command"), "{why}");
2307 assert!(why.contains("url"), "{why}");
2308 assert!(why.contains("stdio") && why.contains("http"), "{why}");
2309
2310 let mut no_url = http_spec("http://127.0.0.1:1/api/mcp");
2311 no_url.url = None;
2312 assert!(no_url.validate().unwrap_err().contains("no `url`"));
2313
2314 let mut no_command = old.clone();
2315 no_command.command = String::new();
2316 assert!(no_command
2317 .validate()
2318 .unwrap_err()
2319 .contains("no `command` given"));
2320
2321 let mut stray = old.clone();
2323 stray.url = Some("http://127.0.0.1:1/api/mcp".into());
2324 let why = stray.validate().unwrap_err();
2325 assert!(why.contains("command"), "{why}");
2326 assert!(why.contains("http"), "{why}");
2327
2328 let mut bad = http_spec("127.0.0.1:1/api/mcp");
2330 bad.transport = Transport::Http;
2331 assert!(bad.validate().unwrap_err().contains("not an http://"));
2332 }
2333
2334 #[test]
2338 fn a_stderr_tail_is_cut_on_a_character_boundary() {
2339 let mut slot = format!("0123456789ě{}", "x".repeat(STDERR_KEEP - 1));
2341 let full = slot.len();
2342 assert_eq!(full - STDERR_KEEP, 11, "the cut lands mid-character");
2343 keep_tail(&mut slot, STDERR_KEEP);
2344 assert!(slot.len() <= STDERR_KEEP, "{}", slot.len());
2345 assert!(slot.ends_with('x'), "the tail is kept: {}", &slot[..4]);
2346 }
2347
2348 #[test]
2352 fn a_crlf_event_stream_with_a_notification_ahead_of_the_reply_is_split() {
2353 let text = "event: message\r\n\
2354 data: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/message\"}\r\n\r\n\
2355 event: message\r\n\
2356 data: {\"jsonrpc\":\"2.0\",\"id\":9,\"result\":{\"ok\":true}}\r\n\r\n";
2357 let value = sse_payload(text, Some(9));
2358 assert_eq!(
2359 value["id"], 9,
2360 "the reply was found behind the notification"
2361 );
2362 assert_eq!(value["result"]["ok"], true);
2363 }
2364
2365 #[test]
2369 fn a_404_on_the_session_makes_the_next_call_handshake_again() {
2370 let fake = FakeHttp::start(None, None);
2371 let dir = tempfile::tempdir().unwrap();
2372 let (server, _tools) = Server::start(
2373 &http_spec(&fake.url("/api/mcp")),
2374 dir.path(),
2375 dir.path(),
2376 DEFAULT_TEST_TIMEOUT,
2377 &Secrets::new(),
2378 )
2379 .expect("the handshake itself carries no session");
2380
2381 fake.forget_sessions();
2382 let first = server.call_tool("echo_text", &json!({ "text": "ha" }));
2383 assert!(first.is_err(), "the server has forgotten the session");
2384 assert!(
2385 first.unwrap_err().to_string().contains("404"),
2386 "the status is the report"
2387 );
2388
2389 let before = fake.seen.lock().unwrap().len();
2390 let _ = server.call_tool("echo_text", &json!({ "text": "ha" }));
2391 let seen = fake.seen.lock().unwrap();
2392 let after: Vec<&String> = seen[before..].iter().map(|(_, body)| body).collect();
2393 assert!(
2394 after.iter().any(|b| b.contains("\"initialize\"")),
2395 "the dead session was reused instead of replaced: {after:?}"
2396 );
2397 }
2398
2399 #[test]
2402 fn an_event_stream_is_read_as_json_rpc() {
2403 let text = ": keep-alive\r\n\r\n\
2404 data: {\"jsonrpc\":\"2.0\",\"id\":7,\r\n\
2405 data: \"result\":{\"ok\":true}}\r\n\r\n";
2406 let value = sse_payload(text, Some(7));
2407 assert_eq!(value["id"], 7);
2408 assert_eq!(value["result"]["ok"], true);
2409
2410 assert_eq!(sse_payload(text, Some(8))["id"], 7);
2412 assert_eq!(sse_payload(": nothing\r\n\r\n", Some(1)), Value::Null);
2413 assert_eq!(sse_payload(text, None)["id"], 7);
2415 }
2416
2417 #[test]
2418 fn a_hanging_server_times_out_and_the_next_call_starts_a_fresh_one() {
2419 if !have_python() {
2420 return;
2421 }
2422 let dir = tempfile::tempdir().unwrap();
2423 let path = script(dir.path(), "fake.py", FAKE);
2424 let (server, _tools) = Server::start(
2425 &spec(&path, 1),
2426 dir.path(),
2427 dir.path(),
2428 DEFAULT_TEST_TIMEOUT,
2429 &Secrets::new(),
2430 )
2431 .expect("the fake server starts");
2432
2433 let started = std::time::Instant::now();
2434 let err = server
2435 .call_tool("echo_text", &json!({"text": "x", "sleep": true}))
2436 .unwrap_err();
2437 assert!(
2438 err.contains("did not answer") && err.contains("1s"),
2439 "the timeout names itself: {err}"
2440 );
2441 assert!(
2442 started.elapsed() < Duration::from_secs(5),
2443 "a hung call returns at the timeout, not when the server wakes up"
2444 );
2445
2446 let out = server
2448 .call_tool("echo_text", &json!({"text": "after"}))
2449 .unwrap();
2450 assert_eq!(out, "echo: after");
2451 }
2452
2453 #[test]
2454 fn a_server_that_dies_is_an_error_with_its_own_stderr() {
2455 if !have_python() {
2456 return;
2457 }
2458 let dir = tempfile::tempdir().unwrap();
2459 let path = script(dir.path(), "dies.py", DIES);
2460 let err = Server::start(
2461 &spec(&path, 5),
2462 dir.path(),
2463 dir.path(),
2464 DEFAULT_TEST_TIMEOUT,
2465 &Secrets::new(),
2466 )
2467 .expect_err("a server that exits during the handshake cannot be used");
2468 assert!(
2469 err.contains("could not open the database"),
2470 "the server's own complaint is the error, not a timeout: {err}"
2471 );
2472 }
2473
2474 #[test]
2475 fn a_policy_override_can_allow_one_tool_and_leave_the_rest_asking() {
2476 let dir = tempfile::tempdir().unwrap();
2477 let mut s = spec(Path::new("/bin/true"), 5);
2478 s.policies.insert("read_text_file".into(), Policy::Allow);
2479 let (server, _) = (
2482 Arc::new(Server {
2483 spec: s.clone(),
2484 plugin_dir: dir.path().to_path_buf(),
2485 workspace: dir.path().to_path_buf(),
2486 timeout: Duration::from_secs(5),
2487 secrets: Secrets::new(),
2488 next_id: AtomicI64::new(1),
2489 state: Mutex::new(None),
2490 handshake: Mutex::new(None),
2491 stderr: Arc::new(Mutex::new(String::new())),
2492 }),
2493 (),
2494 );
2495 assert_eq!(server.policy_for("read_text_file"), Policy::Allow);
2496 assert_eq!(server.policy_for("write_file"), Policy::Ask);
2497 }
2498
2499 #[test]
2500 fn a_cancelled_run_stops_waiting_for_a_server() {
2501 if !have_python() {
2505 return;
2506 }
2507 let dir = tempfile::tempdir().unwrap();
2508 let path = script(dir.path(), "fake.py", FAKE);
2509 let (server, _tools) = Server::start(
2510 &spec(&path, 60),
2511 dir.path(),
2512 dir.path(),
2513 DEFAULT_TEST_TIMEOUT,
2514 &Secrets::new(),
2515 )
2516 .expect("the fake server starts");
2517 let cancel = crate::cancel::Cancel::new();
2518 let flag = cancel.clone();
2519 let canceller = std::thread::spawn(move || {
2520 std::thread::sleep(Duration::from_millis(150));
2521 flag.cancel();
2522 });
2523 let started = std::time::Instant::now();
2524 let err = server
2525 .call_tool_unless("echo_text", &json!({"text": "x", "sleep": true}), &cancel)
2526 .unwrap_err();
2527 canceller.join().unwrap();
2528 assert!(err.contains("cancelled"), "the reason is the cancel: {err}");
2529 assert!(
2530 started.elapsed() < Duration::from_secs(5),
2531 "the wait ended at the cancel, not at the 60 s timeout: {:.2}s",
2532 started.elapsed().as_secs_f32()
2533 );
2534 let out = server
2536 .call_tool("echo_text", &json!({"text": "after"}))
2537 .unwrap();
2538 assert_eq!(out, "echo: after");
2539 }
2540
2541 #[test]
2542 fn a_result_that_is_not_text_says_so_instead_of_disappearing() {
2543 let text = content_text(&json!({"content": [
2544 {"type": "text", "text": "a"},
2545 {"type": "image", "data": "…"},
2546 {"type": "text", "text": "b"}
2547 ]}));
2548 assert_eq!(
2549 text,
2550 "a\n[image content from an MCP server is not shown]\nb"
2551 );
2552 }
2553}