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::{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}
297
298impl Drop for Pipe {
299 fn drop(&mut self) {
300 #[cfg(unix)]
309 crate::tools::pgroup::kill_now(self.child.id());
310 let _ = self.child.kill();
311 let _ = self.child.wait();
312 }
313}
314
315const MAX_LINE: usize = 8 * 1024 * 1024;
320
321const LINE_QUEUE: usize = 64;
325
326enum Line {
328 Text(String),
329 TooLong(usize),
330}
331
332fn read_line_capped<R: BufRead>(reader: &mut R, max: usize) -> std::io::Result<Option<Line>> {
338 let mut kept: Vec<u8> = Vec::new();
339 let mut seen = 0usize;
340 let mut over = false;
341 loop {
342 let avail = reader.fill_buf()?;
343 if avail.is_empty() {
344 if seen == 0 {
345 return Ok(None);
346 }
347 break;
348 }
349 let newline = avail.iter().position(|b| *b == b'\n');
350 let take = newline.unwrap_or(avail.len());
351 seen += take;
352 if !over {
353 if kept.len() + take > max {
354 over = true;
355 kept.clear();
356 } else {
357 kept.extend_from_slice(&avail[..take]);
358 }
359 }
360 match newline {
361 Some(_) => {
362 reader.consume(take + 1);
363 break;
364 }
365 None => reader.consume(take),
366 }
367 }
368 if over {
369 return Ok(Some(Line::TooLong(seen)));
370 }
371 Ok(Some(Line::Text(
372 String::from_utf8_lossy(&kept).into_owned(),
373 )))
374}
375
376const CANCEL_TICK: Duration = Duration::from_millis(100);
379
380pub struct Server {
382 spec: Spec,
383 plugin_dir: PathBuf,
384 workspace: PathBuf,
385 timeout: Duration,
386 secrets: Secrets,
390 next_id: AtomicI64,
391 state: Mutex<Option<Conn>>,
392 handshake: Mutex<Option<Value>>,
396 stderr: Arc<Mutex<String>>,
397}
398
399impl std::fmt::Debug for Server {
400 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
401 f.debug_struct("mcp::Server")
402 .field("name", &self.spec.name)
403 .field("transport", &self.spec.transport.as_str())
404 .field("command", &self.spec.command)
405 .field("url", &self.spec.url)
406 .finish()
407 }
408}
409
410impl Server {
411 pub fn start(
415 spec: &Spec,
416 plugin_dir: &Path,
417 workspace: &Path,
418 default_timeout: Duration,
419 secrets: &Secrets,
420 ) -> Result<(Arc<Self>, Vec<RemoteTool>), String> {
421 let timeout = match spec.timeout_secs {
424 Some(secs) => crate::plugins::clamp_timeout(Some(secs)),
425 None => default_timeout,
426 };
427 let server = Arc::new(Self {
428 spec: spec.clone(),
429 plugin_dir: plugin_dir.to_path_buf(),
430 workspace: workspace.to_path_buf(),
431 timeout,
432 secrets: secrets.clone(),
433 next_id: AtomicI64::new(1),
434 state: Mutex::new(None),
435 handshake: Mutex::new(None),
436 stderr: Arc::new(Mutex::new(String::new())),
437 });
438 let tools = server.list_tools()?;
439 Ok((server, tools))
440 }
441
442 pub fn name(&self) -> &str {
443 &self.spec.name
444 }
445
446 pub fn prefix(&self) -> &str {
447 &self.spec.prefix
448 }
449
450 pub fn handshake(&self) -> Option<Value> {
452 self.handshake
453 .lock()
454 .unwrap_or_else(|e| e.into_inner())
455 .clone()
456 }
457
458 fn keep_handshake(&self, result: &Value) {
461 let mut slot = self.handshake.lock().unwrap_or_else(|e| e.into_inner());
462 if slot.is_none() {
463 *slot = Some(result.clone());
464 }
465 }
466
467 pub fn override_builtin(&self) -> bool {
468 self.spec.override_builtin
469 }
470
471 pub fn policy_for(&self, remote: &str) -> Policy {
473 self.spec
474 .policies
475 .get(remote)
476 .copied()
477 .unwrap_or(self.spec.policy)
478 }
479
480 fn list_tools(&self) -> Result<Vec<RemoteTool>, String> {
484 let mut out = Vec::new();
485 let mut cursor: Option<String> = None;
486 for _ in 0..16 {
487 let params = match &cursor {
488 Some(c) => json!({ "cursor": c }),
489 None => json!({}),
490 };
491 let result = self.request("tools/list", params, &crate::cancel::Cancel::new())?;
493 let page: Vec<RemoteTool> =
494 serde_json::from_value(result.get("tools").cloned().unwrap_or_else(|| json!([])))
495 .map_err(|e| {
496 format!("`tools/list` answered with tools this build cannot read: {e}")
497 })?;
498 out.extend(page);
499 cursor = result
500 .get("nextCursor")
501 .and_then(Value::as_str)
502 .map(str::to_string)
503 .filter(|c| !c.is_empty());
504 if cursor.is_none() {
505 break;
506 }
507 }
508 Ok(out)
509 }
510
511 pub fn call_tool(&self, remote: &str, args: &Value) -> Result<String, String> {
513 self.call_tool_unless(remote, args, &crate::cancel::Cancel::new())
514 }
515
516 pub fn call_tool_unless(
522 &self,
523 remote: &str,
524 args: &Value,
525 cancel: &crate::cancel::Cancel,
526 ) -> Result<String, String> {
527 let result = self.request(
528 "tools/call",
529 json!({ "name": remote, "arguments": args }),
530 cancel,
531 )?;
532 let text = content_text(&result);
533 if result
534 .get("isError")
535 .and_then(Value::as_bool)
536 .unwrap_or(false)
537 {
538 return Err(if text.is_empty() {
541 "the tool reported a failure without a message".to_string()
542 } else {
543 text
544 });
545 }
546 Ok(text)
547 }
548
549 fn request(
550 &self,
551 method: &str,
552 params: Value,
553 cancel: &crate::cancel::Cancel,
554 ) -> Result<Value, String> {
555 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
556 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
557 self.ensure(&mut guard)?;
558 let message = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });
559 let (outcome, poison) = match guard.as_mut().expect("ensure left a connection") {
560 Conn::Pipe(pipe) => self.exchange_pipe(pipe, id, method, &message, cancel),
561 Conn::Http(http) => (
564 self.exchange_http(http, id, method, &message, cancel),
565 false,
566 ),
567 };
568 if poison {
569 *guard = None;
572 }
573 outcome
574 }
575
576 fn write_stdin(
592 &self,
593 stdin: &mut std::process::ChildStdin,
594 message: &str,
595 ) -> std::io::Result<()> {
596 #[cfg(unix)]
597 unsafe {
600 static SIGPIPE_SWAP: std::sync::Mutex<()> = std::sync::Mutex::new(());
601 let _guard = SIGPIPE_SWAP.lock().unwrap_or_else(|e| e.into_inner());
602 let previous = libc::signal(libc::SIGPIPE, libc::SIG_IGN);
603 let result = writeln!(stdin, "{message}").and_then(|_| stdin.flush());
604 libc::signal(libc::SIGPIPE, previous);
605 result
606 }
607 #[cfg(not(unix))]
608 {
609 writeln!(stdin, "{message}").and_then(|_| stdin.flush())
610 }
611 }
612
613 fn exchange_pipe(
615 &self,
616 pipe: &mut Pipe,
617 id: i64,
618 method: &str,
619 message: &Value,
620 cancel: &crate::cancel::Cancel,
621 ) -> (Result<Value, String>, bool) {
622 if let Err(e) = self.write_stdin(&mut pipe.stdin, &message.to_string()) {
623 return (
624 Err(format!(
625 "could not send `{method}`: {e}{}",
626 self.stderr_tail_soon()
627 )),
628 true,
629 );
630 }
631 let deadline = Instant::now() + self.timeout;
632 loop {
633 if cancel.is_cancelled() {
634 return (
635 Err(format!(
636 "`{method}` was cancelled before the server answered; it has been stopped"
637 )),
638 true,
639 );
640 }
641 let left = deadline
642 .saturating_duration_since(Instant::now())
643 .min(CANCEL_TICK);
644 match pipe.rx.recv_timeout(left) {
645 Ok(value) => match answer_to(&value, id, method) {
646 Answer::NotMine => continue,
647 Answer::Unparsable(why) => {
648 return (
649 Err(format!("the server wrote a line that is not JSON: {why}")),
650 true,
651 )
652 }
653 Answer::Value(result) => return (Ok(result), false),
654 Answer::Failed(why) => return (Err(why), false),
655 },
656 Err(RecvTimeoutError::Timeout) => {
657 if Instant::now() < deadline {
660 continue;
661 }
662 return (
663 Err(format!(
664 "the server did not answer `{method}` within {}s; it has been stopped \
665 and will be started again on the next call",
666 self.timeout.as_secs()
667 )),
668 true,
669 );
670 }
671 Err(RecvTimeoutError::Disconnected) => {
672 return (
673 Err(format!(
674 "the server exited while `{method}` was in flight{}",
675 self.stderr_tail()
676 )),
677 true,
678 )
679 }
680 }
681 }
682 }
683
684 fn exchange_http(
689 &self,
690 http: &mut Http,
691 id: i64,
692 method: &str,
693 message: &Value,
694 cancel: &crate::cancel::Cancel,
695 ) -> Result<Value, String> {
696 let reply = self.post(http, message, Some(id), cancel)?;
697 match answer_to(&reply.value, id, method) {
698 Answer::Value(result) => Ok(result),
699 Answer::Failed(why) => Err(why),
700 Answer::Unparsable(why) => Err(format!("the server answered `{method}` with {why}")),
701 Answer::NotMine => Err(format!(
704 "`{method}` was answered with a message for another id; this build speaks one \
705 request per post"
706 )),
707 }
708 }
709
710 fn ensure(&self, slot: &mut Option<Conn>) -> Result<(), String> {
713 let alive = match slot.as_mut() {
714 Some(Conn::Pipe(pipe)) => matches!(pipe.child.try_wait(), Ok(None)),
717 Some(Conn::Http(_)) => true,
720 None => false,
721 };
722 if !alive {
723 *slot = None;
724 }
725 if slot.is_none() {
726 *slot = Some(self.connect()?);
727 }
728 Ok(())
729 }
730
731 fn connect(&self) -> Result<Conn, String> {
734 self.spec.validate()?;
735 match self.spec.transport {
736 Transport::Stdio => Ok(Conn::Pipe(self.start_pipe()?)),
737 Transport::Http => Ok(Conn::Http(self.start_http()?)),
738 }
739 }
740
741 fn start_http(&self) -> Result<Http, String> {
745 let url = self
746 .spec
747 .url
748 .as_deref()
749 .map(str::trim)
750 .filter(|u| !u.is_empty())
751 .ok_or("`transport = \"http\"` with no `url` to post to")?
752 .to_string();
753 let token = self.spec.token(&self.secrets)?;
754 let client = reqwest::Client::builder()
755 .user_agent(concat!("eclipse/", env!("CARGO_PKG_VERSION")))
756 .build()
757 .map_err(|e| format!("could not build an HTTP client: {e}"))?;
758 let mut http = Http {
759 client,
760 url,
761 session: None,
762 token,
763 };
764 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
765 let init = json!({
766 "jsonrpc": "2.0",
767 "id": id,
768 "method": "initialize",
769 "params": {
770 "protocolVersion": PROTOCOL,
771 "capabilities": {},
772 "clientInfo": { "name": "eclipse", "version": env!("CARGO_PKG_VERSION") },
773 }
774 });
775 let reply = self.post(&mut http, &init, Some(id), &crate::cancel::Cancel::new())?;
776 if let Some(session) = reply.session {
779 http.session = Some(session);
780 }
781 if let Some(err) = reply.value.get("error") {
782 return Err(format!(
783 "`initialize` was refused: {}",
784 err.get("message")
785 .and_then(Value::as_str)
786 .unwrap_or("no message")
787 ));
788 }
789 match answer_to(&reply.value, id, "initialize") {
790 Answer::Value(result) => {
791 if result
792 .get("protocolVersion")
793 .and_then(Value::as_str)
794 .is_none()
795 {
796 return Err("`initialize` answered without a protocolVersion".into());
797 }
798 self.keep_handshake(&result);
799 }
800 Answer::Failed(why) => return Err(why),
801 Answer::Unparsable(why) => {
802 return Err(format!(
803 "`initialize` was answered with a body this build cannot read: {why}"
804 ))
805 }
806 Answer::NotMine => {
807 return Err("`initialize` was answered with a message for another id".into())
808 }
809 }
810 let ready = json!({ "jsonrpc": "2.0", "method": "notifications/initialized" });
811 self.post(&mut http, &ready, None, &crate::cancel::Cancel::new())?;
812 Ok(http)
813 }
814
815 fn post(
823 &self,
824 http: &mut Http,
825 message: &Value,
826 id: Option<i64>,
827 cancel: &crate::cancel::Cancel,
828 ) -> Result<Reply, String> {
829 let client = http.client.clone();
830 let url = http.url.clone();
831 let session = http.session.clone();
832 let token = http.token.clone();
833 let body = message.clone();
834 let timeout = self.timeout;
835 let (tx, rx) = mpsc::channel::<Result<Reply, String>>();
836 std::thread::spawn(move || {
837 let _ = tx.send(over_http(client, url, session, token, body, id, timeout));
838 });
839 let deadline = Instant::now() + timeout + Duration::from_secs(2);
842 loop {
843 if cancel.is_cancelled() {
844 return Err("the request was cancelled before the server answered".to_string());
845 }
846 let left = deadline
847 .saturating_duration_since(Instant::now())
848 .min(CANCEL_TICK);
849 match rx.recv_timeout(left) {
850 Ok(outcome) => return outcome,
851 Err(RecvTimeoutError::Timeout) => {
852 if Instant::now() < deadline {
853 continue;
854 }
855 return Err(format!(
856 "the server did not answer within {}s",
857 timeout.as_secs()
858 ));
859 }
860 Err(RecvTimeoutError::Disconnected) => {
861 return Err("the HTTP exchange ended without an answer".to_string())
862 }
863 }
864 }
865 }
866
867 fn start_pipe(&self) -> Result<Pipe, String> {
871 let mut cmd = Command::new(&self.spec.command);
872 cmd.args(&self.spec.args)
873 .current_dir(self.cwd())
874 .env_clear()
875 .stdin(Stdio::piped())
876 .stdout(Stdio::piped())
877 .stderr(Stdio::piped());
878 for key in crate::plugins::INHERITED_ENV {
879 if let Ok(v) = std::env::var(key) {
880 cmd.env(key, v);
881 }
882 }
883 for key in &self.spec.env {
884 if let Ok(v) = std::env::var(key) {
885 cmd.env(key, v);
886 }
887 }
888 cmd.env("ECLIPSE_PLUGIN_DIR", &self.plugin_dir)
889 .env("ECLIPSE_WORKSPACE", &self.workspace);
890 #[cfg(unix)]
893 cmd.process_group(0);
894 let mut child = cmd
895 .spawn()
896 .map_err(|e| format!("could not start `{}`: {e}", self.spec.command))?;
897 let stdin = child.stdin.take().ok_or("no stdin on the server process")?;
898 let stdout = child
899 .stdout
900 .take()
901 .ok_or("no stdout on the server process")?;
902 if let Some(mut err) = child.stderr.take() {
906 let keep = Arc::clone(&self.stderr);
907 std::thread::spawn(move || {
908 let mut buf = [0u8; 1024];
909 loop {
910 match std::io::Read::read(&mut err, &mut buf) {
911 Ok(0) | Err(_) => break,
912 Ok(n) => {
913 let text = String::from_utf8_lossy(&buf[..n]).into_owned();
914 let mut slot = keep.lock().unwrap_or_else(|e| e.into_inner());
915 slot.push_str(&text);
916 if slot.len() > STDERR_KEEP {
917 let cut = slot.len() - STDERR_KEEP;
918 slot.drain(..cut);
919 }
920 }
921 }
922 }
923 });
924 }
925 let (tx, rx) = mpsc::sync_channel(LINE_QUEUE);
926 std::thread::spawn(move || {
927 let mut reader = BufReader::new(stdout);
928 loop {
929 let line = match read_line_capped(&mut reader, MAX_LINE) {
930 Ok(Some(Line::Text(line))) => line,
931 Ok(Some(Line::TooLong(bytes))) => {
935 if tx
936 .send(json!({
937 "eclipse_unparsable": format!(
938 "a line of {bytes} bytes is over the {MAX_LINE}-byte limit and was dropped"
939 )
940 }))
941 .is_err()
942 {
943 break;
944 }
945 continue;
946 }
947 Ok(None) | Err(_) => break,
948 };
949 if line.trim().is_empty() {
950 continue;
951 }
952 match serde_json::from_str::<Value>(&line) {
955 Ok(value) => {
956 if tx.send(value).is_err() {
957 break;
958 }
959 }
960 Err(e) => {
961 let _ = tx.send(json!({
962 "eclipse_unparsable": format!("{e}: {}", clip(&line, 200))
963 }));
964 }
965 }
966 }
967 });
968 let mut pipe = Pipe { child, stdin, rx };
969 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
970 let init = json!({
971 "jsonrpc": "2.0",
972 "id": id,
973 "method": "initialize",
974 "params": {
975 "protocolVersion": PROTOCOL,
976 "capabilities": {},
977 "clientInfo": { "name": "eclipse", "version": env!("CARGO_PKG_VERSION") },
978 }
979 });
980 self.write_stdin(&mut pipe.stdin, &init.to_string())
981 .map_err(|e| {
982 format!(
983 "could not send `initialize`: {e}{}",
984 self.stderr_tail_soon()
985 )
986 })?;
987 let answer = wait_for(&mut pipe, id, self.timeout, &self.stderr)?;
988 if let Some(result) = answer.get("result") {
989 if result
990 .get("protocolVersion")
991 .and_then(Value::as_str)
992 .is_none()
993 {
994 return Err("`initialize` answered without a protocolVersion".into());
995 }
996 self.keep_handshake(result);
997 }
998 let ready = json!({ "jsonrpc": "2.0", "method": "notifications/initialized" });
1001 self.write_stdin(&mut pipe.stdin, &ready.to_string())
1002 .map_err(|e| format!("could not finish the handshake: {e}"))?;
1003 Ok(pipe)
1004 }
1005
1006 fn cwd(&self) -> PathBuf {
1007 match self.spec.cwd {
1008 crate::plugins::Cwd::Plugin => self.plugin_dir.clone(),
1009 crate::plugins::Cwd::Workspace => self.workspace.clone(),
1010 }
1011 }
1012
1013 fn stderr_tail_soon(&self) -> String {
1018 let mut tail = self.stderr_tail();
1019 for _ in 0..50 {
1023 if !tail.is_empty() {
1024 break;
1025 }
1026 std::thread::sleep(Duration::from_millis(10));
1027 tail = self.stderr_tail();
1028 }
1029 tail
1030 }
1031
1032 fn stderr_tail(&self) -> String {
1033 let slot = self.stderr.lock().unwrap_or_else(|e| e.into_inner());
1034 let tail = slot.trim();
1035 if tail.is_empty() {
1036 String::new()
1037 } else {
1038 format!("; the server said: {}", clip(tail, 600))
1039 }
1040 }
1041}
1042
1043struct Reply {
1045 value: Value,
1046 session: Option<String>,
1047}
1048
1049fn over_http(
1051 client: reqwest::Client,
1052 url: String,
1053 session: Option<String>,
1054 token: Option<String>,
1055 body: Value,
1056 id: Option<i64>,
1057 timeout: Duration,
1058) -> Result<Reply, String> {
1059 let runtime = tokio::runtime::Builder::new_current_thread()
1060 .enable_all()
1061 .build()
1062 .map_err(|e| format!("could not start an HTTP runtime: {e}"))?;
1063 runtime.block_on(async move {
1064 let mut request = client
1065 .post(&url)
1066 .header(
1067 reqwest::header::ACCEPT,
1068 "application/json, text/event-stream",
1069 )
1070 .timeout(timeout)
1071 .json(&body);
1072 if let Some(session) = session.as_deref() {
1073 request = request.header("mcp-session-id", session);
1074 }
1075 if let Some(token) = token.as_deref() {
1076 request = request.bearer_auth(token);
1077 }
1078 let response = request
1079 .send()
1080 .await
1081 .map_err(|e| format!("could not post to {url}: {e:?}"))?;
1082 let status = response.status();
1083 let issued = response
1084 .headers()
1085 .get("mcp-session-id")
1086 .and_then(|v| v.to_str().ok())
1087 .filter(|v| !v.is_empty())
1088 .map(str::to_string);
1089 let streamed = response
1090 .headers()
1091 .get(reqwest::header::CONTENT_TYPE)
1092 .and_then(|v| v.to_str().ok())
1093 .map(|v| v.contains("text/event-stream"))
1094 .unwrap_or(false);
1095 let text = response
1096 .text()
1097 .await
1098 .map_err(|e| format!("could not read the answer from {url}: {e}"))?;
1099 let session = issued.or(session);
1100 if !status.is_success() {
1101 return Err(format!(
1103 "the server answered HTTP {}: {}",
1104 status.as_u16(),
1105 if text.trim().is_empty() {
1106 "no body".to_string()
1107 } else {
1108 clip(text.trim(), 400)
1109 }
1110 ));
1111 }
1112 if text.trim().is_empty() {
1113 return Ok(Reply {
1115 value: Value::Null,
1116 session,
1117 });
1118 }
1119 let value = if streamed {
1120 sse_payload(&text, id)
1121 } else {
1122 serde_json::from_str::<Value>(text.trim()).map_err(|e| {
1123 format!(
1124 "the server answered with a body that is not JSON-RPC ({e}): {}",
1125 clip(text.trim(), 200)
1126 )
1127 })?
1128 };
1129 Ok(Reply { value, session })
1130 })
1131}
1132
1133fn sse_payload(text: &str, id: Option<i64>) -> Value {
1139 let mut last = Value::Null;
1140 for event in text.split("\n\n") {
1141 let mut data = String::new();
1142 for line in event.lines() {
1143 let line = line.strip_suffix('\r').unwrap_or(line);
1144 if let Some(rest) = line.strip_prefix("data:") {
1145 if !data.is_empty() {
1146 data.push('\n');
1147 }
1148 data.push_str(rest.trim_start());
1149 }
1150 }
1151 if data.trim().is_empty() {
1152 continue;
1153 }
1154 let Ok(value) = serde_json::from_str::<Value>(data.trim()) else {
1155 continue;
1156 };
1157 if let Some(id) = id {
1158 if value.get("id").and_then(Value::as_i64) == Some(id) {
1159 return value;
1160 }
1161 }
1162 last = value;
1163 }
1164 last
1165}
1166
1167enum Answer {
1169 NotMine,
1173 Unparsable(String),
1175 Value(Value),
1177 Failed(String),
1179}
1180
1181fn answer_to(value: &Value, id: i64, method: &str) -> Answer {
1182 if let Some(why) = value.get("eclipse_unparsable").and_then(Value::as_str) {
1183 return Answer::Unparsable(why.to_string());
1184 }
1185 if value.get("id").and_then(Value::as_i64) != Some(id) {
1186 return Answer::NotMine;
1187 }
1188 if let Some(err) = value.get("error") {
1189 let message = err
1190 .get("message")
1191 .and_then(Value::as_str)
1192 .unwrap_or("no message");
1193 return Answer::Failed(format!("{method} failed: {message}"));
1194 }
1195 Answer::Value(value.get("result").cloned().unwrap_or(Value::Null))
1196}
1197
1198fn wait_for(
1200 pipe: &mut Pipe,
1201 id: i64,
1202 timeout: Duration,
1203 stderr: &Arc<Mutex<String>>,
1204) -> Result<Value, String> {
1205 let deadline = Instant::now() + timeout;
1206 loop {
1207 let left = deadline.saturating_duration_since(Instant::now());
1208 match pipe.rx.recv_timeout(left) {
1209 Ok(value) => {
1210 if let Some(why) = value.get("eclipse_unparsable").and_then(Value::as_str) {
1211 return Err(format!("the server wrote a line that is not JSON: {why}"));
1212 }
1213 if value.get("id").and_then(Value::as_i64) != Some(id) {
1214 continue;
1215 }
1216 if let Some(err) = value.get("error") {
1217 return Err(format!(
1218 "`initialize` was refused: {}",
1219 err.get("message")
1220 .and_then(Value::as_str)
1221 .unwrap_or("no message")
1222 ));
1223 }
1224 return Ok(value);
1225 }
1226 Err(RecvTimeoutError::Timeout) => {
1227 let tail = stderr.lock().unwrap_or_else(|e| e.into_inner()).clone();
1228 return Err(format!(
1229 "the server did not answer `initialize` within {}s{}",
1230 timeout.as_secs(),
1231 if tail.trim().is_empty() {
1232 String::new()
1233 } else {
1234 format!("; it said: {}", clip(tail.trim(), 600))
1235 }
1236 ));
1237 }
1238 Err(RecvTimeoutError::Disconnected) => {
1239 let tail = stderr.lock().unwrap_or_else(|e| e.into_inner()).clone();
1240 return Err(format!(
1241 "the server exited during the handshake{}",
1242 if tail.trim().is_empty() {
1243 String::new()
1244 } else {
1245 format!("; it said: {}", clip(tail.trim(), 600))
1246 }
1247 ));
1248 }
1249 }
1250 }
1251}
1252
1253fn content_text(result: &Value) -> String {
1257 let Some(items) = result.get("content").and_then(Value::as_array) else {
1258 if let Some(text) = result.get("content").and_then(Value::as_str) {
1260 return text.to_string();
1261 }
1262 if let Some(structured) = result.get("structuredContent") {
1263 return structured.to_string();
1264 }
1265 return String::new();
1266 };
1267 let mut parts = Vec::new();
1268 for item in items {
1269 let kind = item
1270 .get("type")
1271 .and_then(Value::as_str)
1272 .unwrap_or("unknown");
1273 if kind == "text" {
1274 if let Some(text) = item.get("text").and_then(Value::as_str) {
1275 parts.push(text.to_string());
1276 }
1277 } else {
1278 parts.push(format!("[{kind} content from an MCP server is not shown]"));
1279 }
1280 }
1281 parts.join("\n")
1282}
1283
1284fn clip(text: &str, max: usize) -> String {
1285 if text.chars().count() <= max {
1286 return text.to_string();
1287 }
1288 let head: String = text.chars().take(max).collect();
1289 format!("{head}…")
1290}
1291
1292pub struct McpTool {
1294 name: String,
1296 remote: String,
1298 description: String,
1299 parameters: Value,
1300 plugin: String,
1301 server: Arc<Server>,
1302}
1303
1304pub const TOOL_NAME_MAX: usize = 64;
1307
1308pub const DESCRIPTION_MAX: usize = 2000;
1311
1312pub const SCHEMA_MAX: usize = 16 * 1024;
1314
1315pub fn sanitize_tool_name(name: &str) -> String {
1323 let cleaned: String = name
1324 .chars()
1325 .map(|c| {
1326 if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
1327 c
1328 } else {
1329 '_'
1330 }
1331 })
1332 .collect();
1333 cleaned.chars().take(TOOL_NAME_MAX).collect()
1334}
1335
1336fn cap_text(text: &str, max: usize) -> String {
1339 if text.chars().count() <= max {
1340 return text.to_string();
1341 }
1342 let mut out: String = text.chars().take(max).collect();
1343 out.push_str("… [truncated]");
1344 out
1345}
1346
1347impl McpTool {
1348 async fn call_unless(
1352 &self,
1353 args: Value,
1354 cancel: crate::cancel::Cancel,
1355 ) -> Result<String, ToolError> {
1356 let server = Arc::clone(&self.server);
1357 let remote = self.remote.clone();
1358 let out =
1359 tokio::task::spawn_blocking(move || server.call_tool_unless(&remote, &args, &cancel))
1360 .await
1361 .map_err(|e| ToolError::Failed(format!("the MCP call did not finish: {e}")))?;
1362 out.map_err(ToolError::Failed)
1363 }
1364
1365 pub fn new(server: Arc<Server>, remote: &RemoteTool) -> Self {
1366 let name = sanitize_tool_name(&format!("{}{}", server.prefix(), remote.name));
1373 let description = if remote.description.trim().is_empty() {
1374 format!("`{}` on the `{}` MCP server", remote.name, server.name())
1375 } else {
1376 cap_text(&remote.description, DESCRIPTION_MAX)
1377 };
1378 let parameters = remote
1379 .input_schema
1380 .clone()
1381 .unwrap_or_else(|| json!({ "type": "object", "properties": {} }));
1382 let over_cap = serde_json::to_string(¶meters).map_or(0, |s| s.len()) > SCHEMA_MAX;
1387 let parameters = if over_cap {
1388 json!({ "type": "object", "properties": {} })
1389 } else {
1390 parameters
1391 };
1392 let description = if over_cap {
1393 format!(
1394 "{description} [its input schema is over {SCHEMA_MAX} bytes and was not included; \
1395 the tool takes a JSON object]"
1396 )
1397 } else {
1398 description
1399 };
1400 Self {
1401 name,
1402 remote: remote.name.clone(),
1403 description,
1404 parameters,
1405 plugin: server.name().to_string(),
1406 server,
1407 }
1408 }
1409 pub fn server_name(&self) -> &str {
1411 &self.plugin
1412 }
1413}
1414
1415#[async_trait::async_trait]
1416impl Tool for McpTool {
1417 fn name(&self) -> &str {
1418 &self.name
1419 }
1420
1421 fn description(&self) -> &str {
1422 &self.description
1423 }
1424
1425 fn parameters(&self) -> Value {
1426 self.parameters.clone()
1427 }
1428
1429 fn describe_call(&self, args: &Value) -> String {
1430 format!(
1433 "{} (mcp: {}) {}",
1434 self.remote,
1435 self.plugin,
1436 clip(&args.to_string(), 200)
1437 )
1438 }
1439
1440 async fn call(&self, args: Value) -> Result<String, ToolError> {
1441 self.call_unless(args, crate::cancel::Cancel::new()).await
1442 }
1443
1444 async fn call_scoped(
1445 &self,
1446 args: Value,
1447 scope: &crate::tools::CallScope<'_>,
1448 ) -> Result<String, ToolError> {
1449 self.call_unless(args, scope.run.cancel.clone()).await
1452 }
1453}
1454
1455#[cfg(test)]
1456mod tests {
1457 use super::*;
1458 use std::path::PathBuf;
1459
1460 const DEFAULT_TEST_TIMEOUT: Duration = Duration::from_secs(10);
1463
1464 const FAKE: &str = r#"#!/usr/bin/env python3
1468import json, sys, time
1469
1470def send(obj):
1471 sys.stdout.write(json.dumps(obj) + "\n"); sys.stdout.flush()
1472
1473for line in sys.stdin:
1474 line = line.strip()
1475 if not line:
1476 continue
1477 msg = json.loads(line)
1478 mid, method = msg.get("id"), msg.get("method")
1479 params = msg.get("params") or {}
1480 if method == "initialize":
1481 send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2024-11-05",
1482 "capabilities": {"tools": {}}, "serverInfo": {"name": "fake", "version": "0"}}})
1483 elif method == "notifications/initialized":
1484 pass
1485 elif method == "tools/list":
1486 if params.get("cursor"):
1487 send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
1488 {"name": "fail_tool", "description": "Always fails"}]}})
1489 else:
1490 send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
1491 {"name": "echo_text", "description": "Echo the text back",
1492 "inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}}}],
1493 "nextCursor": "page-2"}})
1494 elif method == "tools/call":
1495 name, args = params.get("name"), params.get("arguments") or {}
1496 if name == "echo_text":
1497 if args.get("sleep"):
1498 time.sleep(30)
1499 send({"jsonrpc": "2.0", "id": mid, "result": {"content": [
1500 {"type": "text", "text": "echo: " + str(args.get("text", ""))}]}})
1501 elif name == "fail_tool":
1502 send({"jsonrpc": "2.0", "id": mid, "result": {
1503 "content": [{"type": "text", "text": "the disk is on fire"}], "isError": True}})
1504 else:
1505 send({"jsonrpc": "2.0", "id": mid, "result": {"content": []}})
1506 elif mid is not None:
1507 send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "no such method"}})
1508"#;
1509
1510 struct FakeHttp {
1517 port: u16,
1518 seen: Arc<Mutex<Vec<(String, String)>>>,
1519 stop: Arc<std::sync::atomic::AtomicBool>,
1520 }
1521
1522 impl Drop for FakeHttp {
1523 fn drop(&mut self) {
1524 self.stop.store(true, Ordering::SeqCst);
1525 let _ = std::net::TcpStream::connect(("127.0.0.1", self.port));
1527 }
1528 }
1529
1530 impl FakeHttp {
1531 fn start(token: Option<String>, status: Option<u16>) -> Self {
1533 let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a port");
1534 let port = listener.local_addr().unwrap().port();
1535 let seen = Arc::new(Mutex::new(Vec::new()));
1536 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1537 let (log, flag) = (Arc::clone(&seen), Arc::clone(&stop));
1538 std::thread::spawn(move || {
1539 for stream in listener.incoming() {
1540 if flag.load(Ordering::SeqCst) {
1541 break;
1542 }
1543 let Ok(mut stream) = stream else { continue };
1544 let (head, body) = read_http(&mut stream);
1545 log.lock()
1546 .unwrap_or_else(|e| e.into_inner())
1547 .push((head.clone(), body.clone()));
1548 let reply = answer_http(&head, &body, token.as_deref(), status);
1549 let _ = std::io::Write::write_all(&mut stream, reply.as_bytes());
1550 let _ = std::io::Write::flush(&mut stream);
1551 }
1552 });
1553 FakeHttp { port, seen, stop }
1554 }
1555
1556 fn url(&self, path: &str) -> String {
1557 format!("http://127.0.0.1:{}{path}", self.port)
1558 }
1559
1560 fn requests(&self) -> Vec<(String, String)> {
1561 self.seen.lock().unwrap_or_else(|e| e.into_inner()).clone()
1562 }
1563 }
1564
1565 fn read_http(stream: &mut std::net::TcpStream) -> (String, String) {
1567 use std::io::Read;
1568 let mut head = Vec::new();
1569 let mut byte = [0u8; 1];
1570 while head.len() < 64 * 1024 {
1571 match stream.read(&mut byte) {
1572 Ok(0) | Err(_) => {
1573 return (String::from_utf8_lossy(&head).into_owned(), String::new())
1574 }
1575 Ok(_) => {
1576 head.push(byte[0]);
1577 if head.ends_with(b"\r\n\r\n") {
1578 break;
1579 }
1580 }
1581 }
1582 }
1583 let head = String::from_utf8_lossy(&head).into_owned();
1584 let length = head
1585 .lines()
1586 .find_map(|line| {
1587 let (name, value) = line.split_once(':')?;
1588 name.eq_ignore_ascii_case("content-length")
1589 .then(|| value.trim().parse::<usize>().ok())
1590 .flatten()
1591 })
1592 .unwrap_or(0);
1593 let mut body = vec![0u8; length];
1594 let mut got = 0;
1595 while got < length {
1596 match stream.read(&mut body[got..]) {
1597 Ok(0) | Err(_) => break,
1598 Ok(n) => got += n,
1599 }
1600 }
1601 body.truncate(got);
1602 (head, String::from_utf8_lossy(&body).into_owned())
1603 }
1604
1605 fn header<'a>(head: &'a str, name: &str) -> Option<&'a str> {
1606 head.lines().find_map(|line| {
1607 let (key, value) = line.split_once(':')?;
1608 key.eq_ignore_ascii_case(name).then(|| value.trim())
1609 })
1610 }
1611
1612 fn answer_http(head: &str, body: &str, token: Option<&str>, status: Option<u16>) -> String {
1613 let message: Value = serde_json::from_str(body).unwrap_or(Value::Null);
1614 let id = message.get("id").cloned().unwrap_or(Value::Null);
1615 let method = message.get("method").and_then(Value::as_str).unwrap_or("");
1616 if let Some(token) = token {
1617 let sent = header(head, "authorization").unwrap_or("<>");
1618 if sent != format!("Bearer {token}") {
1619 return http_reply(
1620 401,
1621 "application/json",
1622 &json!({ "error": "unauthorized" }).to_string(),
1623 "",
1624 );
1625 }
1626 }
1627 if let Some(status) = status {
1628 return http_reply(status, "application/json", "", "");
1629 }
1630 if method != "initialize" && header(head, "mcp-session-id").is_none() {
1633 return http_reply(400, "application/json", "", "");
1634 }
1635 match method {
1636 "initialize" => {
1637 let extra = "mcp-session-id: test-session\r\n";
1638 http_reply(
1639 200,
1640 "application/json",
1641 &json!({ "jsonrpc": "2.0", "id": id, "result": {
1642 "protocolVersion": "2024-11-05",
1643 "capabilities": { "tools": {} },
1644 "serverInfo": { "name": "fake-http", "version": "0" } } })
1645 .to_string(),
1646 extra,
1647 )
1648 }
1649 "notifications/initialized" => http_reply(202, "text/plain", "", ""),
1651 "tools/list" => {
1652 let page = message
1653 .get("params")
1654 .and_then(|p| p.get("cursor"))
1655 .and_then(Value::as_str)
1656 .map(str::to_string);
1657 let result = match page.as_deref() {
1658 Some("page-2") => json!({ "tools": [
1659 { "name": "fail_tool", "description": "Always fails" }] }),
1660 _ => json!({ "tools": [
1661 { "name": "echo_text", "description": "Echo the text back",
1662 "inputSchema": { "type": "object",
1663 "properties": { "text": { "type": "string" } } } }],
1664 "nextCursor": "page-2" }),
1665 };
1666 let event = format!(
1669 ": keep-alive\n\ndata: {}\n\n",
1670 json!({ "jsonrpc": "2.0", "id": id, "result": result })
1671 );
1672 http_reply(200, "text/event-stream", &event, "")
1673 }
1674 "tools/call" => {
1675 let name = message
1676 .get("params")
1677 .and_then(|p| p.get("name"))
1678 .and_then(Value::as_str)
1679 .unwrap_or("");
1680 let text = message
1681 .get("params")
1682 .and_then(|p| p.get("arguments"))
1683 .and_then(|a| a.get("text"))
1684 .and_then(Value::as_str)
1685 .unwrap_or("");
1686 let result = if name == "fail_tool" {
1687 json!({ "content": [{ "type": "text", "text": "the disk is on fire" }],
1688 "isError": true })
1689 } else {
1690 json!({ "content": [{ "type": "text", "text": format!("echo: {text}") }] })
1691 };
1692 http_reply(
1693 200,
1694 "application/json",
1695 &json!({ "jsonrpc": "2.0", "id": id, "result": result }).to_string(),
1696 "",
1697 )
1698 }
1699 _ => http_reply(
1700 200,
1701 "application/json",
1702 &json!({ "jsonrpc": "2.0", "id": id,
1703 "error": { "code": -32601, "message": "no such method" } })
1704 .to_string(),
1705 "",
1706 ),
1707 }
1708 }
1709
1710 fn http_reply(status: u16, kind: &str, body: &str, extra: &str) -> String {
1711 format!(
1712 "HTTP/1.1 {status} OK\r\nContent-Type: {kind}\r\nContent-Length: {}\r\n{extra}Connection: close\r\n\r\n{body}",
1713 body.len()
1714 )
1715 }
1716
1717 fn http_spec(url: &str) -> Spec {
1719 Spec {
1720 name: "ha".into(),
1721 transport: Transport::Http,
1722 command: String::new(),
1723 args: Vec::new(),
1724 env: Vec::new(),
1725 cwd: crate::plugins::Cwd::Workspace,
1726 url: Some(url.to_string()),
1727 token_env: None,
1728 timeout_secs: Some(10),
1729 policy: Policy::Allow,
1730 policies: BTreeMap::new(),
1731 prefix: String::new(),
1732 override_builtin: false,
1733 disabled: false,
1734 }
1735 }
1736
1737 const DIES: &str = r#"#!/usr/bin/env python3
1740import sys
1741sys.stderr.write("could not open the database: /nope\n")
1742sys.exit(3)
1743"#;
1744
1745 fn have_python() -> bool {
1746 std::process::Command::new("python3")
1747 .arg("--version")
1748 .output()
1749 .map(|o| o.status.success())
1750 .unwrap_or(false)
1751 }
1752
1753 fn script(dir: &Path, name: &str, body: &str) -> PathBuf {
1754 let path = dir.join(name);
1755 std::fs::write(&path, body).unwrap();
1756 #[cfg(unix)]
1757 {
1758 use std::os::unix::fs::PermissionsExt;
1759 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
1760 }
1761 path
1762 }
1763
1764 fn spec(script: &Path, timeout_secs: u64) -> Spec {
1765 Spec {
1766 name: "fake".into(),
1767 transport: Transport::Stdio,
1768 command: "python3".into(),
1769 args: vec![script.to_string_lossy().into_owned()],
1770 url: None,
1771 token_env: None,
1772 env: Vec::new(),
1773 cwd: crate::plugins::Cwd::Plugin,
1774 timeout_secs: Some(timeout_secs),
1775 policy: Policy::Ask,
1776 policies: Default::default(),
1777 prefix: String::new(),
1778 override_builtin: false,
1779 disabled: false,
1780 }
1781 }
1782
1783 #[test]
1788 fn a_remote_tool_name_is_made_safe_for_a_request() {
1789 assert_eq!(sanitize_tool_name("get repo"), "get_repo");
1791 assert_eq!(sanitize_tool_name("a.b"), "a_b");
1792 assert_eq!(sanitize_tool_name("日本"), "__");
1793 assert_eq!(sanitize_tool_name("read_file"), "read_file");
1794 let long = "x".repeat(200);
1796 assert_eq!(sanitize_tool_name(&long).chars().count(), TOOL_NAME_MAX);
1797 assert_eq!(
1798 sanitize_tool_name(&format!("{}_tail", "y".repeat(63)))
1799 .chars()
1800 .count(),
1801 TOOL_NAME_MAX
1802 );
1803
1804 let long_desc = "d".repeat(DESCRIPTION_MAX * 2);
1806 let capped = cap_text(&long_desc, DESCRIPTION_MAX);
1807 assert!(capped.starts_with(&"d".repeat(DESCRIPTION_MAX)));
1808 assert!(capped.ends_with("[truncated]"), "{capped}");
1809 assert_eq!(cap_text("short", DESCRIPTION_MAX), "short");
1810 }
1811
1812 #[test]
1815 fn the_wire_keeps_the_name_the_server_published() {
1816 if !have_python() {
1817 return;
1818 }
1819 let dir = tempfile::tempdir().unwrap();
1820 let path = script(dir.path(), "fake.py", FAKE);
1821 let (server, _tools) = Server::start(
1822 &spec(&path, 10),
1823 dir.path(),
1824 dir.path(),
1825 DEFAULT_TEST_TIMEOUT,
1826 &Secrets::new(),
1827 )
1828 .expect("the fake server starts");
1829 let remote = RemoteTool {
1830 name: "get repo".into(),
1831 description: "Read a repository".into(),
1832 input_schema: None,
1833 };
1834 let tool = McpTool::new(Arc::clone(&server), &remote);
1835 assert_eq!(tool.name(), "get_repo");
1836 assert_eq!(
1837 tool.remote, "get repo",
1838 "the server is asked for the name it published, not the sanitised one"
1839 );
1840 }
1841
1842 #[test]
1846 fn a_line_over_the_cap_is_counted_and_dropped_not_buffered() {
1847 let big = vec![b'x'; MAX_LINE * 4];
1849 let mut reader = BufReader::new(&big[..]);
1850 match read_line_capped(&mut reader, MAX_LINE).unwrap() {
1851 Some(Line::TooLong(bytes)) => assert_eq!(bytes, MAX_LINE * 4),
1852 Some(Line::Text(t)) => panic!("kept {} bytes of it", t.len()),
1853 None => panic!("nothing read at all"),
1854 }
1855 let mut reader = BufReader::new(&b"{\"a\":1}\n{\"b\":2}\n"[..]);
1857 match read_line_capped(&mut reader, MAX_LINE).unwrap() {
1858 Some(Line::Text(text)) => assert_eq!(text, "{\"a\":1}"),
1859 other => panic!("{:?}", other.is_some()),
1860 }
1861 match read_line_capped(&mut reader, MAX_LINE).unwrap() {
1862 Some(Line::Text(text)) => assert_eq!(text, "{\"b\":2}"),
1863 _ => panic!("the second line did not survive"),
1864 }
1865 assert!(read_line_capped(&mut reader, MAX_LINE).unwrap().is_none());
1866 }
1867
1868 #[cfg(unix)]
1873 #[test]
1874 fn dropping_a_connection_kills_the_grandchild_holding_the_pipe() {
1875 if !have_python() {
1876 return;
1877 }
1878 let dir = tempfile::tempdir().unwrap();
1879 let fake = script(dir.path(), "fake.py", FAKE);
1880 let pid_file = dir.path().join("grandchild.pid");
1881 let wrapper = format!(
1882 "#!/bin/sh\nsleep 300 &\necho $! > {}\nexec python3 {}\n",
1883 pid_file.display(),
1884 fake.display()
1885 );
1886 let path = script(dir.path(), "wrapper.sh", &wrapper);
1887 let mut spec = spec(&fake, 10);
1888 spec.command = "sh".into();
1889 spec.args = vec![path.to_string_lossy().into_owned()];
1890 let (server, tools) = Server::start(
1891 &spec,
1892 dir.path(),
1893 dir.path(),
1894 DEFAULT_TEST_TIMEOUT,
1895 &Secrets::new(),
1896 )
1897 .expect("the wrapped server still speaks the protocol");
1898 assert_eq!(tools.len(), 2);
1899 let pid: u32 = std::fs::read_to_string(&pid_file)
1900 .expect("the wrapper recorded its child")
1901 .trim()
1902 .parse()
1903 .expect("a pid");
1904 assert!(pid_alive(pid), "the grandchild is running");
1905
1906 drop(server);
1907
1908 let mut waited = Duration::ZERO;
1915 while pid_alive(pid) && waited < Duration::from_secs(10) {
1916 std::thread::sleep(Duration::from_millis(20));
1917 waited += Duration::from_millis(20);
1918 }
1919 assert!(
1920 !pid_alive(pid),
1921 "the grandchild outlived the connection: still alive after {waited:?}"
1922 );
1923 }
1924
1925 #[cfg(unix)]
1926 fn pid_alive(pid: u32) -> bool {
1927 let Ok(pid) = libc::pid_t::try_from(pid) else {
1928 return false;
1929 };
1930 let rc = unsafe { libc::kill(pid, 0) };
1932 if rc != 0 {
1933 return false;
1934 }
1935 match std::fs::read_to_string(format!("/proc/{pid}/stat")) {
1937 Ok(stat) => match stat.rsplit_once(')') {
1938 Some((_, rest)) => !rest.trim_start().starts_with('Z'),
1939 None => true,
1940 },
1941 Err(_) => false,
1942 }
1943 }
1944
1945 #[test]
1946 fn a_server_is_listed_across_pages_and_its_tools_can_be_called() {
1947 if !have_python() {
1948 return;
1949 }
1950 let dir = tempfile::tempdir().unwrap();
1951 let path = script(dir.path(), "fake.py", FAKE);
1952 let (server, tools) = Server::start(
1953 &spec(&path, 10),
1954 dir.path(),
1955 dir.path(),
1956 DEFAULT_TEST_TIMEOUT,
1957 &Secrets::new(),
1958 )
1959 .expect("the fake server starts");
1960 let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
1962 assert_eq!(names, ["echo_text", "fail_tool"]);
1963 let echo = tools.iter().find(|t| t.name == "echo_text").unwrap();
1964 assert_eq!(echo.description, "Echo the text back");
1965 assert_eq!(echo.input_schema.as_ref().unwrap()["type"], "object");
1966
1967 let out = server
1969 .call_tool("echo_text", &json!({"text": "one"}))
1970 .unwrap();
1971 assert_eq!(out, "echo: one");
1972 let out = server
1973 .call_tool("echo_text", &json!({"text": "two"}))
1974 .unwrap();
1975 assert_eq!(out, "echo: two");
1976
1977 let err = server.call_tool("fail_tool", &json!({})).unwrap_err();
1979 assert_eq!(err, "the disk is on fire");
1980 }
1981
1982 #[test]
1985 fn an_http_entry_lists_across_pages_calls_a_tool_and_carries_the_session_id() {
1986 let fake = FakeHttp::start(None, None);
1987 let dir = tempfile::tempdir().unwrap();
1988 let (server, tools) = Server::start(
1989 &http_spec(&fake.url("/api/mcp")),
1990 dir.path(),
1991 dir.path(),
1992 DEFAULT_TEST_TIMEOUT,
1993 &Secrets::new(),
1994 )
1995 .expect("the HTTP server handshakes");
1996 let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
1997 assert_eq!(names, ["echo_text", "fail_tool"], "both pages arrived");
1998 assert_eq!(
1999 tools[0].input_schema.as_ref().unwrap()["type"],
2000 "object",
2001 "the schema survives the event-stream framing"
2002 );
2003
2004 assert_eq!(
2005 server
2006 .call_tool("echo_text", &json!({ "text": "ha" }))
2007 .unwrap(),
2008 "echo: ha"
2009 );
2010 assert_eq!(
2013 server.call_tool("fail_tool", &json!({})).unwrap_err(),
2014 "the disk is on fire"
2015 );
2016
2017 let requests = fake.requests();
2018 assert_eq!(requests.len(), 6, "initialize, ready, two pages, two calls");
2019 for (head, _) in requests.iter().skip(1) {
2022 assert_eq!(
2023 header(head, "mcp-session-id"),
2024 Some("test-session"),
2025 "{head}"
2026 );
2027 }
2028 assert_eq!(
2029 header(&requests[0].0, "accept"),
2030 Some("application/json, text/event-stream"),
2031 "the client has to say it can read both, or a server may answer neither"
2032 );
2033 assert!(
2034 requests[0].1.contains("\"initialize\""),
2035 "{}",
2036 requests[0].1
2037 );
2038 assert!(
2040 requests[3].1.contains("\"cursor\""),
2041 "the second page is asked for by cursor: {}",
2042 requests[3].1
2043 );
2044 }
2045
2046 #[test]
2048 fn a_401_is_reported_as_a_status_and_not_as_a_timeout() {
2049 let fake = FakeHttp::start(Some("s3cret".into()), None);
2050 let dir = tempfile::tempdir().unwrap();
2051 let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_SET");
2054 let mut spec = http_spec(&fake.url("/api/mcp"));
2055 spec.token_env = Some(key.clone());
2056 std::env::set_var(&key, "wrong");
2057 let err = Server::start(
2058 &spec,
2059 dir.path(),
2060 dir.path(),
2061 DEFAULT_TEST_TIMEOUT,
2062 &Secrets::new(),
2063 )
2064 .expect_err("401 is not a handshake");
2065 assert!(err.contains("401"), "the status is the report: {err}");
2066 assert!(!err.contains("did not answer"), "{err}");
2067
2068 std::env::set_var(&key, "s3cret");
2070 Server::start(
2071 &spec,
2072 dir.path(),
2073 dir.path(),
2074 DEFAULT_TEST_TIMEOUT,
2075 &Secrets::new(),
2076 )
2077 .expect("the right token handshakes");
2078 std::env::remove_var(&key);
2079 }
2080
2081 #[test]
2086 fn a_token_stored_only_in_dotenv_connects_and_is_what_the_client_sends() {
2087 let fake = FakeHttp::start(Some("from-file".into()), None);
2088 let dir = tempfile::tempdir().unwrap();
2089 let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_DOTENV");
2090 std::env::remove_var(&key);
2091 let mut spec = http_spec(&fake.url("/api/mcp"));
2092 spec.token_env = Some(key.clone());
2093 let mut secrets = Secrets::new();
2094 secrets.insert(key, "from-file".to_string());
2095
2096 Server::start(
2097 &spec,
2098 dir.path(),
2099 dir.path(),
2100 DEFAULT_TEST_TIMEOUT,
2101 &secrets,
2102 )
2103 .expect("a token kept in `.env` is a token this build can send");
2104
2105 let sent = fake
2106 .requests()
2107 .into_iter()
2108 .find_map(|(head, _)| header(&head, "authorization").map(str::to_string))
2109 .expect("the handshake carries an Authorization header");
2110 assert_eq!(sent, "Bearer from-file", "the value from `.env`, verbatim");
2111 }
2112
2113 #[test]
2116 fn the_environment_wins_over_dotenv_for_a_token_variable() {
2117 let fake = FakeHttp::start(Some("from-env".into()), None);
2118 let dir = tempfile::tempdir().unwrap();
2119 let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_BOTH");
2120 let mut spec = http_spec(&fake.url("/api/mcp"));
2121 spec.token_env = Some(key.clone());
2122 let mut secrets = Secrets::new();
2123 secrets.insert(key.clone(), "from-file".to_string());
2124 std::env::set_var(&key, "from-env");
2125
2126 let started = Server::start(
2127 &spec,
2128 dir.path(),
2129 dir.path(),
2130 DEFAULT_TEST_TIMEOUT,
2131 &secrets,
2132 );
2133 std::env::remove_var(&key);
2134 started.expect("the environment's value is the one used");
2135
2136 let sent = fake
2137 .requests()
2138 .into_iter()
2139 .find_map(|(head, _)| header(&head, "authorization").map(str::to_string))
2140 .expect("the handshake carries an Authorization header");
2141 assert_eq!(
2142 sent, "Bearer from-env",
2143 "the environment wins over the file"
2144 );
2145 }
2146
2147 #[test]
2150 fn an_empty_dotenv_token_is_absent_and_the_refusal_prints_no_secret() {
2151 let fake = FakeHttp::start(Some("s3cret".into()), None);
2152 let dir = tempfile::tempdir().unwrap();
2153 let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_EMPTY");
2154 std::env::remove_var(&key);
2155 let mut spec = http_spec(&fake.url("/api/mcp"));
2156 spec.token_env = Some(key.clone());
2157 let mut secrets = Secrets::new();
2158 secrets.insert(key.clone(), String::new());
2159 secrets.insert(format!("{key}_NEIGHBOUR"), "s3cret".to_string());
2160
2161 let err = Server::start(
2162 &spec,
2163 dir.path(),
2164 dir.path(),
2165 DEFAULT_TEST_TIMEOUT,
2166 &secrets,
2167 )
2168 .expect_err("an empty value is not a token");
2169 assert!(err.contains(&key), "{err}");
2170 assert!(
2171 err.contains("never reads a token from the manifest"),
2172 "{err}"
2173 );
2174 assert!(
2175 !err.contains("s3cret"),
2176 "a refusal is not a place for a value: {err}"
2177 );
2178 }
2179
2180 #[test]
2183 fn a_token_variable_that_is_not_set_is_named_in_the_error() {
2184 let fake = FakeHttp::start(Some("s3cret".into()), None);
2185 let dir = tempfile::tempdir().unwrap();
2186 let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_UNSET");
2187 let mut spec = http_spec(&fake.url("/api/mcp"));
2188 spec.token_env = Some(key.clone());
2189 std::env::remove_var(&key);
2190 let err = Server::start(
2191 &spec,
2192 dir.path(),
2193 dir.path(),
2194 DEFAULT_TEST_TIMEOUT,
2195 &Secrets::new(),
2196 )
2197 .expect_err("no token, no connection");
2198 assert!(err.contains(&key), "{err}");
2199 assert!(
2200 err.contains("never reads a token from the manifest"),
2201 "{err}"
2202 );
2203 }
2204
2205 #[test]
2207 fn a_manifest_that_mixes_transports_is_refused_naming_both() {
2208 let old: Spec = toml::from_str(
2210 "name = \"fs\"\ncommand = \"mcp-server-filesystem\"\nargs = [\"/tmp\"]\n",
2211 )
2212 .expect("an entry with no transport is a stdio entry");
2213 assert_eq!(old.transport, Transport::Stdio);
2214 assert!(old.validate().is_ok());
2215
2216 let mut both = http_spec("http://127.0.0.1:1/api/mcp");
2217 both.command = "mcp-server".into();
2218 let why = both.validate().unwrap_err();
2219 assert!(why.contains("command"), "{why}");
2220 assert!(why.contains("url"), "{why}");
2221 assert!(why.contains("stdio") && why.contains("http"), "{why}");
2222
2223 let mut no_url = http_spec("http://127.0.0.1:1/api/mcp");
2224 no_url.url = None;
2225 assert!(no_url.validate().unwrap_err().contains("no `url`"));
2226
2227 let mut no_command = old.clone();
2228 no_command.command = String::new();
2229 assert!(no_command
2230 .validate()
2231 .unwrap_err()
2232 .contains("no `command` given"));
2233
2234 let mut stray = old.clone();
2236 stray.url = Some("http://127.0.0.1:1/api/mcp".into());
2237 let why = stray.validate().unwrap_err();
2238 assert!(why.contains("command"), "{why}");
2239 assert!(why.contains("http"), "{why}");
2240
2241 let mut bad = http_spec("127.0.0.1:1/api/mcp");
2243 bad.transport = Transport::Http;
2244 assert!(bad.validate().unwrap_err().contains("not an http://"));
2245 }
2246
2247 #[test]
2250 fn an_event_stream_is_read_as_json_rpc() {
2251 let text = ": keep-alive\r\n\r\n\
2252 data: {\"jsonrpc\":\"2.0\",\"id\":7,\r\n\
2253 data: \"result\":{\"ok\":true}}\r\n\r\n";
2254 let value = sse_payload(text, Some(7));
2255 assert_eq!(value["id"], 7);
2256 assert_eq!(value["result"]["ok"], true);
2257
2258 assert_eq!(sse_payload(text, Some(8))["id"], 7);
2260 assert_eq!(sse_payload(": nothing\r\n\r\n", Some(1)), Value::Null);
2261 assert_eq!(sse_payload(text, None)["id"], 7);
2263 }
2264
2265 #[test]
2266 fn a_hanging_server_times_out_and_the_next_call_starts_a_fresh_one() {
2267 if !have_python() {
2268 return;
2269 }
2270 let dir = tempfile::tempdir().unwrap();
2271 let path = script(dir.path(), "fake.py", FAKE);
2272 let (server, _tools) = Server::start(
2273 &spec(&path, 1),
2274 dir.path(),
2275 dir.path(),
2276 DEFAULT_TEST_TIMEOUT,
2277 &Secrets::new(),
2278 )
2279 .expect("the fake server starts");
2280
2281 let started = std::time::Instant::now();
2282 let err = server
2283 .call_tool("echo_text", &json!({"text": "x", "sleep": true}))
2284 .unwrap_err();
2285 assert!(
2286 err.contains("did not answer") && err.contains("1s"),
2287 "the timeout names itself: {err}"
2288 );
2289 assert!(
2290 started.elapsed() < Duration::from_secs(5),
2291 "a hung call returns at the timeout, not when the server wakes up"
2292 );
2293
2294 let out = server
2296 .call_tool("echo_text", &json!({"text": "after"}))
2297 .unwrap();
2298 assert_eq!(out, "echo: after");
2299 }
2300
2301 #[test]
2302 fn a_server_that_dies_is_an_error_with_its_own_stderr() {
2303 if !have_python() {
2304 return;
2305 }
2306 let dir = tempfile::tempdir().unwrap();
2307 let path = script(dir.path(), "dies.py", DIES);
2308 let err = Server::start(
2309 &spec(&path, 5),
2310 dir.path(),
2311 dir.path(),
2312 DEFAULT_TEST_TIMEOUT,
2313 &Secrets::new(),
2314 )
2315 .expect_err("a server that exits during the handshake cannot be used");
2316 assert!(
2317 err.contains("could not open the database"),
2318 "the server's own complaint is the error, not a timeout: {err}"
2319 );
2320 }
2321
2322 #[test]
2323 fn a_policy_override_can_allow_one_tool_and_leave_the_rest_asking() {
2324 let dir = tempfile::tempdir().unwrap();
2325 let mut s = spec(Path::new("/bin/true"), 5);
2326 s.policies.insert("read_text_file".into(), Policy::Allow);
2327 let (server, _) = (
2330 Arc::new(Server {
2331 spec: s.clone(),
2332 plugin_dir: dir.path().to_path_buf(),
2333 workspace: dir.path().to_path_buf(),
2334 timeout: Duration::from_secs(5),
2335 secrets: Secrets::new(),
2336 next_id: AtomicI64::new(1),
2337 state: Mutex::new(None),
2338 handshake: Mutex::new(None),
2339 stderr: Arc::new(Mutex::new(String::new())),
2340 }),
2341 (),
2342 );
2343 assert_eq!(server.policy_for("read_text_file"), Policy::Allow);
2344 assert_eq!(server.policy_for("write_file"), Policy::Ask);
2345 }
2346
2347 #[test]
2348 fn a_cancelled_run_stops_waiting_for_a_server() {
2349 if !have_python() {
2353 return;
2354 }
2355 let dir = tempfile::tempdir().unwrap();
2356 let path = script(dir.path(), "fake.py", FAKE);
2357 let (server, _tools) = Server::start(
2358 &spec(&path, 60),
2359 dir.path(),
2360 dir.path(),
2361 DEFAULT_TEST_TIMEOUT,
2362 &Secrets::new(),
2363 )
2364 .expect("the fake server starts");
2365 let cancel = crate::cancel::Cancel::new();
2366 let flag = cancel.clone();
2367 let canceller = std::thread::spawn(move || {
2368 std::thread::sleep(Duration::from_millis(150));
2369 flag.cancel();
2370 });
2371 let started = std::time::Instant::now();
2372 let err = server
2373 .call_tool_unless("echo_text", &json!({"text": "x", "sleep": true}), &cancel)
2374 .unwrap_err();
2375 canceller.join().unwrap();
2376 assert!(err.contains("cancelled"), "the reason is the cancel: {err}");
2377 assert!(
2378 started.elapsed() < Duration::from_secs(5),
2379 "the wait ended at the cancel, not at the 60 s timeout: {:.2}s",
2380 started.elapsed().as_secs_f32()
2381 );
2382 let out = server
2384 .call_tool("echo_text", &json!({"text": "after"}))
2385 .unwrap();
2386 assert_eq!(out, "echo: after");
2387 }
2388
2389 #[test]
2390 fn a_result_that_is_not_text_says_so_instead_of_disappearing() {
2391 let text = content_text(&json!({"content": [
2392 {"type": "text", "text": "a"},
2393 {"type": "image", "data": "…"},
2394 {"type": "text", "text": "b"}
2395 ]}));
2396 assert_eq!(
2397 text,
2398 "a\n[image content from an MCP server is not shown]\nb"
2399 );
2400 }
2401}