use crate::config::Policy;
use crate::tools::{Tool, ToolError};
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::io::{BufRead, BufReader, Write};
#[cfg(unix)]
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
pub const PROTOCOL: &str = "2024-11-05";
pub type Secrets = BTreeMap<String, String>;
const STDERR_KEEP: usize = 4_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Transport {
#[default]
Stdio,
Http,
}
impl Transport {
pub fn as_str(&self) -> &'static str {
match self {
Transport::Stdio => "stdio",
Transport::Http => "http",
}
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct Spec {
pub name: String,
#[serde(default)]
pub transport: Transport,
#[serde(default)]
pub command: String,
#[serde(default)]
pub args: Vec<String>,
#[serde(default)]
pub env: Vec<String>,
#[serde(default)]
pub cwd: crate::plugins::Cwd,
#[serde(default)]
pub url: Option<String>,
#[serde(default)]
pub token_env: Option<String>,
#[serde(default)]
pub timeout_secs: Option<u64>,
#[serde(default = "default_policy")]
pub policy: Policy,
#[serde(default)]
pub policies: BTreeMap<String, Policy>,
#[serde(default)]
pub prefix: String,
#[serde(default, rename = "override")]
pub override_builtin: bool,
#[serde(default)]
pub disabled: bool,
}
fn default_policy() -> Policy {
Policy::Ask
}
impl Spec {
pub fn validate(&self) -> Result<(), String> {
let url = self.url.as_deref().map(str::trim).filter(|u| !u.is_empty());
let command = self.command.trim();
match self.transport {
Transport::Stdio => {
if url.is_some() {
return Err(
"`url` belongs to the http transport, and this entry is stdio: a stdio \
server names `command`"
.to_string(),
);
}
if command.is_empty() {
return Err(
"no `command` given (an endpoint would need `transport = http` and a \
`url`)"
.to_string(),
);
}
Ok(())
}
Transport::Http => {
if !command.is_empty() || !self.args.is_empty() {
return Err(
"`command`/`args` belong to the stdio transport, and this entry is http: \
an HTTP server names `url`"
.to_string(),
);
}
let Some(url) = url else {
return Err("`transport = http` with no `url` to post to".to_string());
};
if !(url.starts_with("http://") || url.starts_with("https://")) {
return Err(format!(
"`url` = {url:?} is not an http:// or https:// endpoint"
));
}
Ok(())
}
}
}
fn token(&self, secrets: &Secrets) -> Result<Option<String>, String> {
let Some(key) = self.token_key() else {
return Ok(None);
};
match self.token_source(secrets) {
TokenSource::NotUsed => Ok(None),
TokenSource::Env => Ok(std::env::var(key).ok()),
TokenSource::Dotenv => Ok(secrets.get(key).cloned()),
TokenSource::Unset => Err(format!(
"`token_env = {key:?}` names a variable that is set neither in the environment nor \
in `.env` (or is empty); this build never reads a token from the manifest itself"
)),
}
}
fn token_key(&self) -> Option<&str> {
self.token_env
.as_deref()
.map(str::trim)
.filter(|k| !k.is_empty())
}
pub fn token_source(&self, secrets: &Secrets) -> TokenSource {
let Some(key) = self.token_key() else {
return TokenSource::NotUsed;
};
if std::env::var(key).is_ok_and(|v| !v.trim().is_empty()) {
TokenSource::Env
} else if secrets.get(key).is_some_and(|v| !v.trim().is_empty()) {
TokenSource::Dotenv
} else {
TokenSource::Unset
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TokenSource {
NotUsed,
Env,
Dotenv,
Unset,
}
impl TokenSource {
pub fn as_str(&self) -> &'static str {
match self {
TokenSource::NotUsed => "none",
TokenSource::Env => "env",
TokenSource::Dotenv => ".env",
TokenSource::Unset => "unset",
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct RemoteTool {
pub name: String,
#[serde(default)]
pub description: String,
#[serde(default, rename = "inputSchema")]
pub input_schema: Option<Value>,
}
enum Conn {
Pipe(Pipe),
Http(Http),
}
struct Pipe {
child: Child,
stdin: ChildStdin,
rx: mpsc::Receiver<Value>,
}
struct Http {
client: reqwest::Client,
url: String,
session: Option<String>,
token: Option<String>,
expired: Arc<AtomicBool>,
}
impl Drop for Pipe {
fn drop(&mut self) {
#[cfg(unix)]
crate::tools::pgroup::kill_now(self.child.id());
let _ = self.child.kill();
let _ = self.child.wait();
}
}
const MAX_LINE: usize = 8 * 1024 * 1024;
const LINE_QUEUE: usize = 64;
enum Line {
Text(String),
TooLong(usize),
}
fn read_line_capped<R: BufRead>(reader: &mut R, max: usize) -> std::io::Result<Option<Line>> {
let mut kept: Vec<u8> = Vec::new();
let mut seen = 0usize;
let mut over = false;
loop {
let avail = reader.fill_buf()?;
if avail.is_empty() {
if seen == 0 {
return Ok(None);
}
break;
}
let newline = avail.iter().position(|b| *b == b'\n');
let take = newline.unwrap_or(avail.len());
seen += take;
if !over {
if kept.len() + take > max {
over = true;
kept.clear();
} else {
kept.extend_from_slice(&avail[..take]);
}
}
match newline {
Some(_) => {
reader.consume(take + 1);
break;
}
None => reader.consume(take),
}
}
if over {
return Ok(Some(Line::TooLong(seen)));
}
Ok(Some(Line::Text(
String::from_utf8_lossy(&kept).into_owned(),
)))
}
const CANCEL_TICK: Duration = Duration::from_millis(100);
pub struct Server {
spec: Spec,
plugin_dir: PathBuf,
workspace: PathBuf,
timeout: Duration,
secrets: Secrets,
next_id: AtomicI64,
state: Mutex<Option<Conn>>,
handshake: Mutex<Option<Value>>,
stderr: Arc<Mutex<String>>,
}
impl std::fmt::Debug for Server {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("mcp::Server")
.field("name", &self.spec.name)
.field("transport", &self.spec.transport.as_str())
.field("command", &self.spec.command)
.field("url", &self.spec.url)
.finish()
}
}
impl Server {
pub fn start(
spec: &Spec,
plugin_dir: &Path,
workspace: &Path,
default_timeout: Duration,
secrets: &Secrets,
) -> Result<(Arc<Self>, Vec<RemoteTool>), String> {
let timeout = match spec.timeout_secs {
Some(secs) => crate::plugins::clamp_timeout(Some(secs)),
None => default_timeout,
};
let server = Arc::new(Self {
spec: spec.clone(),
plugin_dir: plugin_dir.to_path_buf(),
workspace: workspace.to_path_buf(),
timeout,
secrets: secrets.clone(),
next_id: AtomicI64::new(1),
state: Mutex::new(None),
handshake: Mutex::new(None),
stderr: Arc::new(Mutex::new(String::new())),
});
let tools = server.list_tools()?;
Ok((server, tools))
}
pub fn name(&self) -> &str {
&self.spec.name
}
pub fn prefix(&self) -> &str {
&self.spec.prefix
}
pub fn handshake(&self) -> Option<Value> {
self.handshake
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
fn keep_handshake(&self, result: &Value) {
let mut slot = self.handshake.lock().unwrap_or_else(|e| e.into_inner());
if slot.is_none() {
*slot = Some(result.clone());
}
}
pub fn override_builtin(&self) -> bool {
self.spec.override_builtin
}
pub fn policy_for(&self, remote: &str) -> Policy {
self.spec
.policies
.get(remote)
.copied()
.unwrap_or(self.spec.policy)
}
fn list_tools(&self) -> Result<Vec<RemoteTool>, String> {
let mut out = Vec::new();
let mut cursor: Option<String> = None;
for _ in 0..16 {
let params = match &cursor {
Some(c) => json!({ "cursor": c }),
None => json!({}),
};
let result = self.request("tools/list", params, &crate::cancel::Cancel::new())?;
let page: Vec<RemoteTool> =
serde_json::from_value(result.get("tools").cloned().unwrap_or_else(|| json!([])))
.map_err(|e| {
format!("`tools/list` answered with tools this build cannot read: {e}")
})?;
out.extend(page);
cursor = result
.get("nextCursor")
.and_then(Value::as_str)
.map(str::to_string)
.filter(|c| !c.is_empty());
if cursor.is_none() {
break;
}
}
Ok(out)
}
pub fn call_tool(&self, remote: &str, args: &Value) -> Result<String, String> {
self.call_tool_unless(remote, args, &crate::cancel::Cancel::new())
}
pub fn call_tool_unless(
&self,
remote: &str,
args: &Value,
cancel: &crate::cancel::Cancel,
) -> Result<String, String> {
let result = self.request(
"tools/call",
json!({ "name": remote, "arguments": args }),
cancel,
)?;
let text = content_text(&result);
if result
.get("isError")
.and_then(Value::as_bool)
.unwrap_or(false)
{
return Err(if text.is_empty() {
"the tool reported a failure without a message".to_string()
} else {
text
});
}
Ok(text)
}
fn request(
&self,
method: &str,
params: Value,
cancel: &crate::cancel::Cancel,
) -> Result<Value, String> {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
self.ensure(&mut guard)?;
let message = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });
let (outcome, poison) = match guard.as_mut().expect("ensure left a connection") {
Conn::Pipe(pipe) => self.exchange_pipe(pipe, id, method, &message, cancel),
Conn::Http(http) => self.exchange_http(http, id, method, &message, cancel),
};
if poison {
*guard = None;
}
outcome
}
fn write_stdin(
&self,
stdin: &mut std::process::ChildStdin,
message: &str,
) -> std::io::Result<()> {
#[cfg(unix)]
unsafe {
static SIGPIPE_SWAP: std::sync::Mutex<()> = std::sync::Mutex::new(());
let _guard = SIGPIPE_SWAP.lock().unwrap_or_else(|e| e.into_inner());
let previous = libc::signal(libc::SIGPIPE, libc::SIG_IGN);
let result = writeln!(stdin, "{message}").and_then(|_| stdin.flush());
libc::signal(libc::SIGPIPE, previous);
result
}
#[cfg(not(unix))]
{
writeln!(stdin, "{message}").and_then(|_| stdin.flush())
}
}
fn exchange_pipe(
&self,
pipe: &mut Pipe,
id: i64,
method: &str,
message: &Value,
cancel: &crate::cancel::Cancel,
) -> (Result<Value, String>, bool) {
if let Err(e) = self.write_stdin(&mut pipe.stdin, &message.to_string()) {
return (
Err(format!(
"could not send `{method}`: {e}{}",
self.stderr_tail_soon()
)),
true,
);
}
let deadline = Instant::now() + self.timeout;
loop {
if cancel.is_cancelled() {
return (
Err(format!(
"`{method}` was cancelled before the server answered; it has been stopped"
)),
true,
);
}
let left = deadline
.saturating_duration_since(Instant::now())
.min(CANCEL_TICK);
match pipe.rx.recv_timeout(left) {
Ok(value) => match answer_to(&value, id, method) {
Answer::NotMine => continue,
Answer::Unparsable(why) => {
return (
Err(format!("the server wrote a line that is not JSON: {why}")),
true,
)
}
Answer::Value(result) => return (Ok(result), false),
Answer::Failed(why) => return (Err(why), false),
},
Err(RecvTimeoutError::Timeout) => {
if Instant::now() < deadline {
continue;
}
return (
Err(format!(
"the server did not answer `{method}` within {}s; it has been stopped \
and will be started again on the next call",
self.timeout.as_secs()
)),
true,
);
}
Err(RecvTimeoutError::Disconnected) => {
return (
Err(format!(
"the server exited while `{method}` was in flight{}",
self.stderr_tail()
)),
true,
)
}
}
}
}
fn exchange_http(
&self,
http: &mut Http,
id: i64,
method: &str,
message: &Value,
cancel: &crate::cancel::Cancel,
) -> (Result<Value, String>, bool) {
let reply = match self.post(http, message, Some(id), cancel) {
Ok(reply) => reply,
Err(message) => return (Err(message), http.expired.load(Ordering::Relaxed)),
};
let outcome = match answer_to(&reply.value, id, method) {
Answer::Value(result) => Ok(result),
Answer::Failed(why) => Err(why),
Answer::Unparsable(why) => Err(format!("the server answered `{method}` with {why}")),
Answer::NotMine => Err(format!(
"`{method}` was answered with a message for another id; this build speaks one \
request per post"
)),
};
(outcome, http.expired.load(Ordering::Relaxed))
}
fn ensure(&self, slot: &mut Option<Conn>) -> Result<(), String> {
let alive = match slot.as_mut() {
Some(Conn::Pipe(pipe)) => matches!(pipe.child.try_wait(), Ok(None)),
Some(Conn::Http(_)) => true,
None => false,
};
if !alive {
*slot = None;
}
if slot.is_none() {
*slot = Some(self.connect()?);
}
Ok(())
}
fn connect(&self) -> Result<Conn, String> {
self.spec.validate()?;
match self.spec.transport {
Transport::Stdio => Ok(Conn::Pipe(self.start_pipe()?)),
Transport::Http => Ok(Conn::Http(self.start_http()?)),
}
}
fn start_http(&self) -> Result<Http, String> {
let url = self
.spec
.url
.as_deref()
.map(str::trim)
.filter(|u| !u.is_empty())
.ok_or("`transport = \"http\"` with no `url` to post to")?
.to_string();
let token = self.spec.token(&self.secrets)?;
let client = reqwest::Client::builder()
.user_agent(concat!("eclipse/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(|e| format!("could not build an HTTP client: {e}"))?;
let mut http = Http {
client,
url,
session: None,
token,
expired: Arc::new(AtomicBool::new(false)),
};
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let init = json!({
"jsonrpc": "2.0",
"id": id,
"method": "initialize",
"params": {
"protocolVersion": PROTOCOL,
"capabilities": {},
"clientInfo": { "name": "eclipse", "version": env!("CARGO_PKG_VERSION") },
}
});
let reply = self.post(&mut http, &init, Some(id), &crate::cancel::Cancel::new())?;
if let Some(session) = reply.session {
http.session = Some(session);
}
if let Some(err) = reply.value.get("error") {
return Err(format!(
"`initialize` was refused: {}",
err.get("message")
.and_then(Value::as_str)
.unwrap_or("no message")
));
}
match answer_to(&reply.value, id, "initialize") {
Answer::Value(result) => {
if result
.get("protocolVersion")
.and_then(Value::as_str)
.is_none()
{
return Err("`initialize` answered without a protocolVersion".into());
}
self.keep_handshake(&result);
}
Answer::Failed(why) => return Err(why),
Answer::Unparsable(why) => {
return Err(format!(
"`initialize` was answered with a body this build cannot read: {why}"
))
}
Answer::NotMine => {
return Err("`initialize` was answered with a message for another id".into())
}
}
let ready = json!({ "jsonrpc": "2.0", "method": "notifications/initialized" });
self.post(&mut http, &ready, None, &crate::cancel::Cancel::new())?;
Ok(http)
}
fn post(
&self,
http: &mut Http,
message: &Value,
id: Option<i64>,
cancel: &crate::cancel::Cancel,
) -> Result<Reply, String> {
let exchange = Exchange {
client: http.client.clone(),
url: http.url.clone(),
session: http.session.clone(),
token: http.token.clone(),
expired: http.expired.clone(),
};
let body = message.clone();
let timeout = self.timeout;
let (tx, rx) = mpsc::channel::<Result<Reply, String>>();
std::thread::spawn(move || {
let _ = tx.send(over_http(exchange, body, id, timeout));
});
let deadline = Instant::now() + timeout + Duration::from_secs(2);
loop {
if cancel.is_cancelled() {
return Err("the request was cancelled before the server answered".to_string());
}
let left = deadline
.saturating_duration_since(Instant::now())
.min(CANCEL_TICK);
match rx.recv_timeout(left) {
Ok(outcome) => return outcome,
Err(RecvTimeoutError::Timeout) => {
if Instant::now() < deadline {
continue;
}
return Err(format!(
"the server did not answer within {}s",
timeout.as_secs()
));
}
Err(RecvTimeoutError::Disconnected) => {
return Err("the HTTP exchange ended without an answer".to_string())
}
}
}
}
fn start_pipe(&self) -> Result<Pipe, String> {
let mut cmd = Command::new(&self.spec.command);
cmd.args(&self.spec.args)
.current_dir(self.cwd())
.env_clear()
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
for key in crate::plugins::INHERITED_ENV {
if let Ok(v) = std::env::var(key) {
cmd.env(key, v);
}
}
for key in &self.spec.env {
if let Ok(v) = std::env::var(key) {
cmd.env(key, v);
}
}
cmd.env("ECLIPSE_PLUGIN_DIR", &self.plugin_dir)
.env("ECLIPSE_WORKSPACE", &self.workspace);
#[cfg(unix)]
cmd.process_group(0);
let mut child = cmd
.spawn()
.map_err(|e| format!("could not start `{}`: {e}", self.spec.command))?;
let stdin = child.stdin.take().ok_or("no stdin on the server process")?;
let stdout = child
.stdout
.take()
.ok_or("no stdout on the server process")?;
if let Some(mut err) = child.stderr.take() {
let keep = Arc::clone(&self.stderr);
std::thread::spawn(move || {
let mut buf = [0u8; 1024];
loop {
match std::io::Read::read(&mut err, &mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
let text = String::from_utf8_lossy(&buf[..n]).into_owned();
let mut slot = keep.lock().unwrap_or_else(|e| e.into_inner());
slot.push_str(&text);
keep_tail(&mut slot, STDERR_KEEP);
}
}
}
});
}
let (tx, rx) = mpsc::sync_channel(LINE_QUEUE);
std::thread::spawn(move || {
let mut reader = BufReader::new(stdout);
loop {
let line = match read_line_capped(&mut reader, MAX_LINE) {
Ok(Some(Line::Text(line))) => line,
Ok(Some(Line::TooLong(bytes))) => {
if tx
.send(json!({
"eclipse_unparsable": format!(
"a line of {bytes} bytes is over the {MAX_LINE}-byte limit and was dropped"
)
}))
.is_err()
{
break;
}
continue;
}
Ok(None) | Err(_) => break,
};
if line.trim().is_empty() {
continue;
}
match serde_json::from_str::<Value>(&line) {
Ok(value) => {
if tx.send(value).is_err() {
break;
}
}
Err(e) => {
let _ = tx.send(json!({
"eclipse_unparsable": format!("{e}: {}", clip(&line, 200))
}));
}
}
}
});
let mut pipe = Pipe { child, stdin, rx };
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let init = json!({
"jsonrpc": "2.0",
"id": id,
"method": "initialize",
"params": {
"protocolVersion": PROTOCOL,
"capabilities": {},
"clientInfo": { "name": "eclipse", "version": env!("CARGO_PKG_VERSION") },
}
});
self.write_stdin(&mut pipe.stdin, &init.to_string())
.map_err(|e| {
format!(
"could not send `initialize`: {e}{}",
self.stderr_tail_soon()
)
})?;
let answer = wait_for(&mut pipe, id, self.timeout, &self.stderr)?;
if let Some(result) = answer.get("result") {
if result
.get("protocolVersion")
.and_then(Value::as_str)
.is_none()
{
return Err("`initialize` answered without a protocolVersion".into());
}
self.keep_handshake(result);
}
let ready = json!({ "jsonrpc": "2.0", "method": "notifications/initialized" });
self.write_stdin(&mut pipe.stdin, &ready.to_string())
.map_err(|e| format!("could not finish the handshake: {e}"))?;
Ok(pipe)
}
fn cwd(&self) -> PathBuf {
match self.spec.cwd {
crate::plugins::Cwd::Plugin => self.plugin_dir.clone(),
crate::plugins::Cwd::Workspace => self.workspace.clone(),
}
}
fn stderr_tail_soon(&self) -> String {
let mut tail = self.stderr_tail();
for _ in 0..50 {
if !tail.is_empty() {
break;
}
std::thread::sleep(Duration::from_millis(10));
tail = self.stderr_tail();
}
tail
}
fn stderr_tail(&self) -> String {
let slot = self.stderr.lock().unwrap_or_else(|e| e.into_inner());
let tail = slot.trim();
if tail.is_empty() {
String::new()
} else {
format!("; the server said: {}", clip(tail, 600))
}
}
}
struct Reply {
value: Value,
session: Option<String>,
}
struct Exchange {
client: reqwest::Client,
url: String,
session: Option<String>,
token: Option<String>,
expired: Arc<AtomicBool>,
}
fn over_http(
exchange: Exchange,
body: Value,
id: Option<i64>,
timeout: Duration,
) -> Result<Reply, String> {
let Exchange {
client,
url,
session,
token,
expired,
} = exchange;
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| format!("could not start an HTTP runtime: {e}"))?;
runtime.block_on(async move {
let mut request = client
.post(&url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.timeout(timeout)
.json(&body);
if let Some(session) = session.as_deref() {
request = request.header("mcp-session-id", session);
}
if let Some(token) = token.as_deref() {
request = request.bearer_auth(token);
}
let response = request
.send()
.await
.map_err(|e| format!("could not post to {url}: {e:?}"))?;
let status = response.status();
let issued = response
.headers()
.get("mcp-session-id")
.and_then(|v| v.to_str().ok())
.filter(|v| !v.is_empty())
.map(str::to_string);
let streamed = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(|v| v.contains("text/event-stream"))
.unwrap_or(false);
let mut response = response;
let mut text = String::new();
while let Some(bytes) = response
.chunk()
.await
.map_err(|e| format!("could not read the answer from {url}: {e}"))?
{
if text.len() + bytes.len() > MAX_LINE {
return Err(format!(
"the server answered with more than {} MiB: {url}",
MAX_LINE / (1024 * 1024)
));
}
text.push_str(&String::from_utf8_lossy(&bytes));
}
let session = issued.or(session);
if status == reqwest::StatusCode::NOT_FOUND && session.is_some() {
expired.store(true, Ordering::Relaxed);
}
if !status.is_success() {
return Err(format!(
"the server answered HTTP {}: {}",
status.as_u16(),
if text.trim().is_empty() {
"no body".to_string()
} else {
clip(text.trim(), 400)
}
));
}
if text.trim().is_empty() {
return Ok(Reply {
value: Value::Null,
session,
});
}
let value = if streamed {
sse_payload(&text, id)
} else {
serde_json::from_str::<Value>(text.trim()).map_err(|e| {
format!(
"the server answered with a body that is not JSON-RPC ({e}): {}",
clip(text.trim(), 200)
)
})?
};
Ok(Reply { value, session })
})
}
fn sse_payload(text: &str, id: Option<i64>) -> Value {
let text = text.replace("\r\n", "\n").replace('\r', "\n");
let mut last = Value::Null;
for event in text.split("\n\n") {
let mut data = String::new();
for line in event.lines() {
if let Some(rest) = line.strip_prefix("data:") {
if !data.is_empty() {
data.push('\n');
}
data.push_str(rest.trim_start());
}
}
if data.trim().is_empty() {
continue;
}
let Ok(value) = serde_json::from_str::<Value>(data.trim()) else {
continue;
};
if let Some(id) = id {
if value.get("id").and_then(Value::as_i64) == Some(id) {
return value;
}
}
last = value;
}
last
}
enum Answer {
NotMine,
Unparsable(String),
Value(Value),
Failed(String),
}
fn answer_to(value: &Value, id: i64, method: &str) -> Answer {
if let Some(why) = value.get("eclipse_unparsable").and_then(Value::as_str) {
return Answer::Unparsable(why.to_string());
}
if value.get("id").and_then(Value::as_i64) != Some(id) {
return Answer::NotMine;
}
if let Some(err) = value.get("error") {
let message = err
.get("message")
.and_then(Value::as_str)
.unwrap_or("no message");
return Answer::Failed(format!("{method} failed: {message}"));
}
Answer::Value(value.get("result").cloned().unwrap_or(Value::Null))
}
fn wait_for(
pipe: &mut Pipe,
id: i64,
timeout: Duration,
stderr: &Arc<Mutex<String>>,
) -> Result<Value, String> {
let deadline = Instant::now() + timeout;
loop {
let left = deadline.saturating_duration_since(Instant::now());
match pipe.rx.recv_timeout(left) {
Ok(value) => {
if let Some(why) = value.get("eclipse_unparsable").and_then(Value::as_str) {
return Err(format!("the server wrote a line that is not JSON: {why}"));
}
if value.get("id").and_then(Value::as_i64) != Some(id) {
continue;
}
if let Some(err) = value.get("error") {
return Err(format!(
"`initialize` was refused: {}",
err.get("message")
.and_then(Value::as_str)
.unwrap_or("no message")
));
}
return Ok(value);
}
Err(RecvTimeoutError::Timeout) => {
let tail = stderr.lock().unwrap_or_else(|e| e.into_inner()).clone();
return Err(format!(
"the server did not answer `initialize` within {}s{}",
timeout.as_secs(),
if tail.trim().is_empty() {
String::new()
} else {
format!("; it said: {}", clip(tail.trim(), 600))
}
));
}
Err(RecvTimeoutError::Disconnected) => {
let tail = stderr.lock().unwrap_or_else(|e| e.into_inner()).clone();
return Err(format!(
"the server exited during the handshake{}",
if tail.trim().is_empty() {
String::new()
} else {
format!("; it said: {}", clip(tail.trim(), 600))
}
));
}
}
}
}
fn content_text(result: &Value) -> String {
let Some(items) = result.get("content").and_then(Value::as_array) else {
if let Some(text) = result.get("content").and_then(Value::as_str) {
return text.to_string();
}
if let Some(structured) = result.get("structuredContent") {
return structured.to_string();
}
return String::new();
};
let mut parts = Vec::new();
for item in items {
let kind = item
.get("type")
.and_then(Value::as_str)
.unwrap_or("unknown");
if kind == "text" {
if let Some(text) = item.get("text").and_then(Value::as_str) {
parts.push(text.to_string());
}
} else {
parts.push(format!("[{kind} content from an MCP server is not shown]"));
}
}
parts.join("\n")
}
fn keep_tail(slot: &mut String, keep: usize) {
if slot.len() <= keep {
return;
}
let mut cut = slot.len() - keep;
while !slot.is_char_boundary(cut) {
cut += 1;
}
slot.drain(..cut);
}
fn clip(text: &str, max: usize) -> String {
if text.chars().count() <= max {
return text.to_string();
}
let head: String = text.chars().take(max).collect();
format!("{head}…")
}
pub struct McpTool {
name: String,
remote: String,
description: String,
parameters: Value,
plugin: String,
server: Arc<Server>,
}
pub const TOOL_NAME_MAX: usize = 64;
pub const DESCRIPTION_MAX: usize = 2000;
pub const SCHEMA_MAX: usize = 16 * 1024;
pub fn sanitize_tool_name(name: &str) -> String {
let cleaned: String = name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
c
} else {
'_'
}
})
.collect();
cleaned.chars().take(TOOL_NAME_MAX).collect()
}
fn cap_text(text: &str, max: usize) -> String {
if text.chars().count() <= max {
return text.to_string();
}
let mut out: String = text.chars().take(max).collect();
out.push_str("… [truncated]");
out
}
impl McpTool {
async fn call_unless(
&self,
args: Value,
cancel: crate::cancel::Cancel,
) -> Result<String, ToolError> {
let server = Arc::clone(&self.server);
let remote = self.remote.clone();
let out =
tokio::task::spawn_blocking(move || server.call_tool_unless(&remote, &args, &cancel))
.await
.map_err(|e| ToolError::Failed(format!("the MCP call did not finish: {e}")))?;
out.map_err(ToolError::Failed)
}
pub fn new(server: Arc<Server>, remote: &RemoteTool) -> Self {
let name = sanitize_tool_name(&format!("{}{}", server.prefix(), remote.name));
let description = if remote.description.trim().is_empty() {
format!("`{}` on the `{}` MCP server", remote.name, server.name())
} else {
cap_text(&remote.description, DESCRIPTION_MAX)
};
let parameters = remote
.input_schema
.clone()
.unwrap_or_else(|| json!({ "type": "object", "properties": {} }));
let over_cap = serde_json::to_string(¶meters).map_or(0, |s| s.len()) > SCHEMA_MAX;
let parameters = if over_cap {
json!({ "type": "object", "properties": {} })
} else {
parameters
};
let description = if over_cap {
format!(
"{description} [its input schema is over {SCHEMA_MAX} bytes and was not included; \
the tool takes a JSON object]"
)
} else {
description
};
Self {
name,
remote: remote.name.clone(),
description,
parameters,
plugin: server.name().to_string(),
server,
}
}
pub fn server_name(&self) -> &str {
&self.plugin
}
}
#[async_trait::async_trait]
impl Tool for McpTool {
fn name(&self) -> &str {
&self.name
}
fn description(&self) -> &str {
&self.description
}
fn parameters(&self) -> Value {
self.parameters.clone()
}
fn describe_call(&self, args: &Value) -> String {
format!(
"{} (mcp: {}) {}",
self.remote,
self.plugin,
clip(&args.to_string(), 200)
)
}
async fn call(&self, args: Value) -> Result<String, ToolError> {
self.call_unless(args, crate::cancel::Cancel::new()).await
}
async fn call_scoped(
&self,
args: Value,
scope: &crate::tools::CallScope<'_>,
) -> Result<String, ToolError> {
self.call_unless(args, scope.run.cancel.clone()).await
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
const DEFAULT_TEST_TIMEOUT: Duration = Duration::from_secs(10);
const FAKE: &str = r#"#!/usr/bin/env python3
import json, sys, time
def send(obj):
sys.stdout.write(json.dumps(obj) + "\n"); sys.stdout.flush()
for line in sys.stdin:
line = line.strip()
if not line:
continue
msg = json.loads(line)
mid, method = msg.get("id"), msg.get("method")
params = msg.get("params") or {}
if method == "initialize":
send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2024-11-05",
"capabilities": {"tools": {}}, "serverInfo": {"name": "fake", "version": "0"}}})
elif method == "notifications/initialized":
pass
elif method == "tools/list":
if params.get("cursor"):
send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
{"name": "fail_tool", "description": "Always fails"}]}})
else:
send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
{"name": "echo_text", "description": "Echo the text back",
"inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}}}],
"nextCursor": "page-2"}})
elif method == "tools/call":
name, args = params.get("name"), params.get("arguments") or {}
if name == "echo_text":
if args.get("sleep"):
time.sleep(30)
send({"jsonrpc": "2.0", "id": mid, "result": {"content": [
{"type": "text", "text": "echo: " + str(args.get("text", ""))}]}})
elif name == "fail_tool":
send({"jsonrpc": "2.0", "id": mid, "result": {
"content": [{"type": "text", "text": "the disk is on fire"}], "isError": True}})
else:
send({"jsonrpc": "2.0", "id": mid, "result": {"content": []}})
elif mid is not None:
send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "no such method"}})
"#;
struct FakeHttp {
port: u16,
seen: Arc<Mutex<Vec<(String, String)>>>,
stop: Arc<std::sync::atomic::AtomicBool>,
forgetful: Arc<std::sync::atomic::AtomicBool>,
}
impl Drop for FakeHttp {
fn drop(&mut self) {
self.stop.store(true, Ordering::SeqCst);
let _ = std::net::TcpStream::connect(("127.0.0.1", self.port));
}
}
impl FakeHttp {
fn forget_sessions(&self) {
self.forgetful.store(true, Ordering::SeqCst);
}
fn start(token: Option<String>, status: Option<u16>) -> Self {
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a port");
let port = listener.local_addr().unwrap().port();
let seen = Arc::new(Mutex::new(Vec::new()));
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
let forgetful = Arc::new(std::sync::atomic::AtomicBool::new(false));
let (log, flag) = (Arc::clone(&seen), Arc::clone(&stop));
let forget = Arc::clone(&forgetful);
std::thread::spawn(move || {
for stream in listener.incoming() {
if flag.load(Ordering::SeqCst) {
break;
}
let Ok(mut stream) = stream else { continue };
let (head, body) = read_http(&mut stream);
log.lock()
.unwrap_or_else(|e| e.into_inner())
.push((head.clone(), body.clone()));
let reply = answer_http(&head, &body, token.as_deref(), status, &forget);
let _ = std::io::Write::write_all(&mut stream, reply.as_bytes());
let _ = std::io::Write::flush(&mut stream);
}
});
FakeHttp {
port,
seen,
stop,
forgetful,
}
}
fn url(&self, path: &str) -> String {
format!("http://127.0.0.1:{}{path}", self.port)
}
fn requests(&self) -> Vec<(String, String)> {
self.seen.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
}
fn read_http(stream: &mut std::net::TcpStream) -> (String, String) {
use std::io::Read;
let mut head = Vec::new();
let mut byte = [0u8; 1];
while head.len() < 64 * 1024 {
match stream.read(&mut byte) {
Ok(0) | Err(_) => {
return (String::from_utf8_lossy(&head).into_owned(), String::new())
}
Ok(_) => {
head.push(byte[0]);
if head.ends_with(b"\r\n\r\n") {
break;
}
}
}
}
let head = String::from_utf8_lossy(&head).into_owned();
let length = head
.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("content-length")
.then(|| value.trim().parse::<usize>().ok())
.flatten()
})
.unwrap_or(0);
let mut body = vec![0u8; length];
let mut got = 0;
while got < length {
match stream.read(&mut body[got..]) {
Ok(0) | Err(_) => break,
Ok(n) => got += n,
}
}
body.truncate(got);
(head, String::from_utf8_lossy(&body).into_owned())
}
fn header<'a>(head: &'a str, name: &str) -> Option<&'a str> {
head.lines().find_map(|line| {
let (key, value) = line.split_once(':')?;
key.eq_ignore_ascii_case(name).then(|| value.trim())
})
}
fn answer_http(
head: &str,
body: &str,
token: Option<&str>,
status: Option<u16>,
forgetful: &std::sync::atomic::AtomicBool,
) -> String {
let message: Value = serde_json::from_str(body).unwrap_or(Value::Null);
let id = message.get("id").cloned().unwrap_or(Value::Null);
let method = message.get("method").and_then(Value::as_str).unwrap_or("");
if let Some(token) = token {
let sent = header(head, "authorization").unwrap_or("<>");
if sent != format!("Bearer {token}") {
return http_reply(
401,
"application/json",
&json!({ "error": "unauthorized" }).to_string(),
"",
);
}
}
if let Some(status) = status {
return http_reply(status, "application/json", "", "");
}
if forgetful.load(Ordering::SeqCst) && method != "initialize" {
return http_reply(404, "application/json", "", "");
}
if method != "initialize" && header(head, "mcp-session-id").is_none() {
return http_reply(400, "application/json", "", "");
}
match method {
"initialize" => {
let extra = "mcp-session-id: test-session\r\n";
http_reply(
200,
"application/json",
&json!({ "jsonrpc": "2.0", "id": id, "result": {
"protocolVersion": "2024-11-05",
"capabilities": { "tools": {} },
"serverInfo": { "name": "fake-http", "version": "0" } } })
.to_string(),
extra,
)
}
"notifications/initialized" => http_reply(202, "text/plain", "", ""),
"tools/list" => {
let page = message
.get("params")
.and_then(|p| p.get("cursor"))
.and_then(Value::as_str)
.map(str::to_string);
let result = match page.as_deref() {
Some("page-2") => json!({ "tools": [
{ "name": "fail_tool", "description": "Always fails" }] }),
_ => json!({ "tools": [
{ "name": "echo_text", "description": "Echo the text back",
"inputSchema": { "type": "object",
"properties": { "text": { "type": "string" } } } }],
"nextCursor": "page-2" }),
};
let event = format!(
": keep-alive\n\ndata: {}\n\n",
json!({ "jsonrpc": "2.0", "id": id, "result": result })
);
http_reply(200, "text/event-stream", &event, "")
}
"tools/call" => {
let name = message
.get("params")
.and_then(|p| p.get("name"))
.and_then(Value::as_str)
.unwrap_or("");
let text = message
.get("params")
.and_then(|p| p.get("arguments"))
.and_then(|a| a.get("text"))
.and_then(Value::as_str)
.unwrap_or("");
let result = if name == "fail_tool" {
json!({ "content": [{ "type": "text", "text": "the disk is on fire" }],
"isError": true })
} else {
json!({ "content": [{ "type": "text", "text": format!("echo: {text}") }] })
};
http_reply(
200,
"application/json",
&json!({ "jsonrpc": "2.0", "id": id, "result": result }).to_string(),
"",
)
}
_ => http_reply(
200,
"application/json",
&json!({ "jsonrpc": "2.0", "id": id,
"error": { "code": -32601, "message": "no such method" } })
.to_string(),
"",
),
}
}
fn http_reply(status: u16, kind: &str, body: &str, extra: &str) -> String {
format!(
"HTTP/1.1 {status} OK\r\nContent-Type: {kind}\r\nContent-Length: {}\r\n{extra}Connection: close\r\n\r\n{body}",
body.len()
)
}
fn http_spec(url: &str) -> Spec {
Spec {
name: "ha".into(),
transport: Transport::Http,
command: String::new(),
args: Vec::new(),
env: Vec::new(),
cwd: crate::plugins::Cwd::Workspace,
url: Some(url.to_string()),
token_env: None,
timeout_secs: Some(10),
policy: Policy::Allow,
policies: BTreeMap::new(),
prefix: String::new(),
override_builtin: false,
disabled: false,
}
}
const DIES: &str = r#"#!/usr/bin/env python3
import sys
sys.stderr.write("could not open the database: /nope\n")
sys.exit(3)
"#;
fn have_python() -> bool {
std::process::Command::new("python3")
.arg("--version")
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
fn script(dir: &Path, name: &str, body: &str) -> PathBuf {
let path = dir.join(name);
std::fs::write(&path, body).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
path
}
fn spec(script: &Path, timeout_secs: u64) -> Spec {
Spec {
name: "fake".into(),
transport: Transport::Stdio,
command: "python3".into(),
args: vec![script.to_string_lossy().into_owned()],
url: None,
token_env: None,
env: Vec::new(),
cwd: crate::plugins::Cwd::Plugin,
timeout_secs: Some(timeout_secs),
policy: Policy::Ask,
policies: Default::default(),
prefix: String::new(),
override_builtin: false,
disabled: false,
}
}
#[test]
fn a_remote_tool_name_is_made_safe_for_a_request() {
assert_eq!(sanitize_tool_name("get repo"), "get_repo");
assert_eq!(sanitize_tool_name("a.b"), "a_b");
assert_eq!(sanitize_tool_name("日本"), "__");
assert_eq!(sanitize_tool_name("read_file"), "read_file");
let long = "x".repeat(200);
assert_eq!(sanitize_tool_name(&long).chars().count(), TOOL_NAME_MAX);
assert_eq!(
sanitize_tool_name(&format!("{}_tail", "y".repeat(63)))
.chars()
.count(),
TOOL_NAME_MAX
);
let long_desc = "d".repeat(DESCRIPTION_MAX * 2);
let capped = cap_text(&long_desc, DESCRIPTION_MAX);
assert!(capped.starts_with(&"d".repeat(DESCRIPTION_MAX)));
assert!(capped.ends_with("[truncated]"), "{capped}");
assert_eq!(cap_text("short", DESCRIPTION_MAX), "short");
}
#[test]
fn the_wire_keeps_the_name_the_server_published() {
if !have_python() {
return;
}
let dir = tempfile::tempdir().unwrap();
let path = script(dir.path(), "fake.py", FAKE);
let (server, _tools) = Server::start(
&spec(&path, 10),
dir.path(),
dir.path(),
DEFAULT_TEST_TIMEOUT,
&Secrets::new(),
)
.expect("the fake server starts");
let remote = RemoteTool {
name: "get repo".into(),
description: "Read a repository".into(),
input_schema: None,
};
let tool = McpTool::new(Arc::clone(&server), &remote);
assert_eq!(tool.name(), "get_repo");
assert_eq!(
tool.remote, "get repo",
"the server is asked for the name it published, not the sanitised one"
);
}
#[test]
fn a_line_over_the_cap_is_counted_and_dropped_not_buffered() {
let big = vec![b'x'; MAX_LINE * 4];
let mut reader = BufReader::new(&big[..]);
match read_line_capped(&mut reader, MAX_LINE).unwrap() {
Some(Line::TooLong(bytes)) => assert_eq!(bytes, MAX_LINE * 4),
Some(Line::Text(t)) => panic!("kept {} bytes of it", t.len()),
None => panic!("nothing read at all"),
}
let mut reader = BufReader::new(&b"{\"a\":1}\n{\"b\":2}\n"[..]);
match read_line_capped(&mut reader, MAX_LINE).unwrap() {
Some(Line::Text(text)) => assert_eq!(text, "{\"a\":1}"),
other => panic!("{:?}", other.is_some()),
}
match read_line_capped(&mut reader, MAX_LINE).unwrap() {
Some(Line::Text(text)) => assert_eq!(text, "{\"b\":2}"),
_ => panic!("the second line did not survive"),
}
assert!(read_line_capped(&mut reader, MAX_LINE).unwrap().is_none());
}
#[cfg(unix)]
#[test]
fn dropping_a_connection_kills_the_grandchild_holding_the_pipe() {
if !have_python() {
return;
}
let dir = tempfile::tempdir().unwrap();
let fake = script(dir.path(), "fake.py", FAKE);
let pid_file = dir.path().join("grandchild.pid");
let wrapper = format!(
"#!/bin/sh\nsleep 300 &\necho $! > {}\nexec python3 {}\n",
pid_file.display(),
fake.display()
);
let path = script(dir.path(), "wrapper.sh", &wrapper);
let mut spec = spec(&fake, 10);
spec.command = "sh".into();
spec.args = vec![path.to_string_lossy().into_owned()];
let (server, tools) = Server::start(
&spec,
dir.path(),
dir.path(),
DEFAULT_TEST_TIMEOUT,
&Secrets::new(),
)
.expect("the wrapped server still speaks the protocol");
assert_eq!(tools.len(), 2);
let pid: u32 = std::fs::read_to_string(&pid_file)
.expect("the wrapper recorded its child")
.trim()
.parse()
.expect("a pid");
assert!(pid_alive(pid), "the grandchild is running");
drop(server);
let mut waited = Duration::ZERO;
while pid_alive(pid) && waited < Duration::from_secs(10) {
std::thread::sleep(Duration::from_millis(20));
waited += Duration::from_millis(20);
}
assert!(
!pid_alive(pid),
"the grandchild outlived the connection: still alive after {waited:?}"
);
}
#[cfg(unix)]
fn pid_alive(pid: u32) -> bool {
let Ok(pid) = libc::pid_t::try_from(pid) else {
return false;
};
let rc = unsafe { libc::kill(pid, 0) };
if rc != 0 {
return false;
}
match std::fs::read_to_string(format!("/proc/{pid}/stat")) {
Ok(stat) => match stat.rsplit_once(')') {
Some((_, rest)) => !rest.trim_start().starts_with('Z'),
None => true,
},
Err(_) => false,
}
}
#[test]
fn a_server_is_listed_across_pages_and_its_tools_can_be_called() {
if !have_python() {
return;
}
let dir = tempfile::tempdir().unwrap();
let path = script(dir.path(), "fake.py", FAKE);
let (server, tools) = Server::start(
&spec(&path, 10),
dir.path(),
dir.path(),
DEFAULT_TEST_TIMEOUT,
&Secrets::new(),
)
.expect("the fake server starts");
let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
assert_eq!(names, ["echo_text", "fail_tool"]);
let echo = tools.iter().find(|t| t.name == "echo_text").unwrap();
assert_eq!(echo.description, "Echo the text back");
assert_eq!(echo.input_schema.as_ref().unwrap()["type"], "object");
let out = server
.call_tool("echo_text", &json!({"text": "one"}))
.unwrap();
assert_eq!(out, "echo: one");
let out = server
.call_tool("echo_text", &json!({"text": "two"}))
.unwrap();
assert_eq!(out, "echo: two");
let err = server.call_tool("fail_tool", &json!({})).unwrap_err();
assert_eq!(err, "the disk is on fire");
}
#[test]
fn an_http_entry_lists_across_pages_calls_a_tool_and_carries_the_session_id() {
let fake = FakeHttp::start(None, None);
let dir = tempfile::tempdir().unwrap();
let (server, tools) = Server::start(
&http_spec(&fake.url("/api/mcp")),
dir.path(),
dir.path(),
DEFAULT_TEST_TIMEOUT,
&Secrets::new(),
)
.expect("the HTTP server handshakes");
let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
assert_eq!(names, ["echo_text", "fail_tool"], "both pages arrived");
assert_eq!(
tools[0].input_schema.as_ref().unwrap()["type"],
"object",
"the schema survives the event-stream framing"
);
assert_eq!(
server
.call_tool("echo_text", &json!({ "text": "ha" }))
.unwrap(),
"echo: ha"
);
assert_eq!(
server.call_tool("fail_tool", &json!({})).unwrap_err(),
"the disk is on fire"
);
let requests = fake.requests();
assert_eq!(requests.len(), 6, "initialize, ready, two pages, two calls");
for (head, _) in requests.iter().skip(1) {
assert_eq!(
header(head, "mcp-session-id"),
Some("test-session"),
"{head}"
);
}
assert_eq!(
header(&requests[0].0, "accept"),
Some("application/json, text/event-stream"),
"the client has to say it can read both, or a server may answer neither"
);
assert!(
requests[0].1.contains("\"initialize\""),
"{}",
requests[0].1
);
assert!(
requests[3].1.contains("\"cursor\""),
"the second page is asked for by cursor: {}",
requests[3].1
);
}
#[test]
fn a_401_is_reported_as_a_status_and_not_as_a_timeout() {
let fake = FakeHttp::start(Some("s3cret".into()), None);
let dir = tempfile::tempdir().unwrap();
let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_SET");
let mut spec = http_spec(&fake.url("/api/mcp"));
spec.token_env = Some(key.clone());
std::env::set_var(&key, "wrong");
let err = Server::start(
&spec,
dir.path(),
dir.path(),
DEFAULT_TEST_TIMEOUT,
&Secrets::new(),
)
.expect_err("401 is not a handshake");
assert!(err.contains("401"), "the status is the report: {err}");
assert!(!err.contains("did not answer"), "{err}");
std::env::set_var(&key, "s3cret");
Server::start(
&spec,
dir.path(),
dir.path(),
DEFAULT_TEST_TIMEOUT,
&Secrets::new(),
)
.expect("the right token handshakes");
std::env::remove_var(&key);
}
#[test]
fn a_token_stored_only_in_dotenv_connects_and_is_what_the_client_sends() {
let fake = FakeHttp::start(Some("from-file".into()), None);
let dir = tempfile::tempdir().unwrap();
let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_DOTENV");
std::env::remove_var(&key);
let mut spec = http_spec(&fake.url("/api/mcp"));
spec.token_env = Some(key.clone());
let mut secrets = Secrets::new();
secrets.insert(key, "from-file".to_string());
Server::start(
&spec,
dir.path(),
dir.path(),
DEFAULT_TEST_TIMEOUT,
&secrets,
)
.expect("a token kept in `.env` is a token this build can send");
let sent = fake
.requests()
.into_iter()
.find_map(|(head, _)| header(&head, "authorization").map(str::to_string))
.expect("the handshake carries an Authorization header");
assert_eq!(sent, "Bearer from-file", "the value from `.env`, verbatim");
}
#[test]
fn the_environment_wins_over_dotenv_for_a_token_variable() {
let fake = FakeHttp::start(Some("from-env".into()), None);
let dir = tempfile::tempdir().unwrap();
let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_BOTH");
let mut spec = http_spec(&fake.url("/api/mcp"));
spec.token_env = Some(key.clone());
let mut secrets = Secrets::new();
secrets.insert(key.clone(), "from-file".to_string());
std::env::set_var(&key, "from-env");
let started = Server::start(
&spec,
dir.path(),
dir.path(),
DEFAULT_TEST_TIMEOUT,
&secrets,
);
std::env::remove_var(&key);
started.expect("the environment's value is the one used");
let sent = fake
.requests()
.into_iter()
.find_map(|(head, _)| header(&head, "authorization").map(str::to_string))
.expect("the handshake carries an Authorization header");
assert_eq!(
sent, "Bearer from-env",
"the environment wins over the file"
);
}
#[test]
fn an_empty_dotenv_token_is_absent_and_the_refusal_prints_no_secret() {
let fake = FakeHttp::start(Some("s3cret".into()), None);
let dir = tempfile::tempdir().unwrap();
let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_EMPTY");
std::env::remove_var(&key);
let mut spec = http_spec(&fake.url("/api/mcp"));
spec.token_env = Some(key.clone());
let mut secrets = Secrets::new();
secrets.insert(key.clone(), String::new());
secrets.insert(format!("{key}_NEIGHBOUR"), "s3cret".to_string());
let err = Server::start(
&spec,
dir.path(),
dir.path(),
DEFAULT_TEST_TIMEOUT,
&secrets,
)
.expect_err("an empty value is not a token");
assert!(err.contains(&key), "{err}");
assert!(
err.contains("never reads a token from the manifest"),
"{err}"
);
assert!(
!err.contains("s3cret"),
"a refusal is not a place for a value: {err}"
);
}
#[test]
fn a_token_variable_that_is_not_set_is_named_in_the_error() {
let fake = FakeHttp::start(Some("s3cret".into()), None);
let dir = tempfile::tempdir().unwrap();
let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_UNSET");
let mut spec = http_spec(&fake.url("/api/mcp"));
spec.token_env = Some(key.clone());
std::env::remove_var(&key);
let err = Server::start(
&spec,
dir.path(),
dir.path(),
DEFAULT_TEST_TIMEOUT,
&Secrets::new(),
)
.expect_err("no token, no connection");
assert!(err.contains(&key), "{err}");
assert!(
err.contains("never reads a token from the manifest"),
"{err}"
);
}
#[test]
fn a_manifest_that_mixes_transports_is_refused_naming_both() {
let old: Spec = toml::from_str(
"name = \"fs\"\ncommand = \"mcp-server-filesystem\"\nargs = [\"/tmp\"]\n",
)
.expect("an entry with no transport is a stdio entry");
assert_eq!(old.transport, Transport::Stdio);
assert!(old.validate().is_ok());
let mut both = http_spec("http://127.0.0.1:1/api/mcp");
both.command = "mcp-server".into();
let why = both.validate().unwrap_err();
assert!(why.contains("command"), "{why}");
assert!(why.contains("url"), "{why}");
assert!(why.contains("stdio") && why.contains("http"), "{why}");
let mut no_url = http_spec("http://127.0.0.1:1/api/mcp");
no_url.url = None;
assert!(no_url.validate().unwrap_err().contains("no `url`"));
let mut no_command = old.clone();
no_command.command = String::new();
assert!(no_command
.validate()
.unwrap_err()
.contains("no `command` given"));
let mut stray = old.clone();
stray.url = Some("http://127.0.0.1:1/api/mcp".into());
let why = stray.validate().unwrap_err();
assert!(why.contains("command"), "{why}");
assert!(why.contains("http"), "{why}");
let mut bad = http_spec("127.0.0.1:1/api/mcp");
bad.transport = Transport::Http;
assert!(bad.validate().unwrap_err().contains("not an http://"));
}
#[test]
fn a_stderr_tail_is_cut_on_a_character_boundary() {
let mut slot = format!("0123456789ě{}", "x".repeat(STDERR_KEEP - 1));
let full = slot.len();
assert_eq!(full - STDERR_KEEP, 11, "the cut lands mid-character");
keep_tail(&mut slot, STDERR_KEEP);
assert!(slot.len() <= STDERR_KEEP, "{}", slot.len());
assert!(slot.ends_with('x'), "the tail is kept: {}", &slot[..4]);
}
#[test]
fn a_crlf_event_stream_with_a_notification_ahead_of_the_reply_is_split() {
let text = "event: message\r\n\
data: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/message\"}\r\n\r\n\
event: message\r\n\
data: {\"jsonrpc\":\"2.0\",\"id\":9,\"result\":{\"ok\":true}}\r\n\r\n";
let value = sse_payload(text, Some(9));
assert_eq!(
value["id"], 9,
"the reply was found behind the notification"
);
assert_eq!(value["result"]["ok"], true);
}
#[test]
fn a_404_on_the_session_makes_the_next_call_handshake_again() {
let fake = FakeHttp::start(None, None);
let dir = tempfile::tempdir().unwrap();
let (server, _tools) = Server::start(
&http_spec(&fake.url("/api/mcp")),
dir.path(),
dir.path(),
DEFAULT_TEST_TIMEOUT,
&Secrets::new(),
)
.expect("the handshake itself carries no session");
fake.forget_sessions();
let first = server.call_tool("echo_text", &json!({ "text": "ha" }));
assert!(first.is_err(), "the server has forgotten the session");
assert!(
first.unwrap_err().to_string().contains("404"),
"the status is the report"
);
let before = fake.seen.lock().unwrap().len();
let _ = server.call_tool("echo_text", &json!({ "text": "ha" }));
let seen = fake.seen.lock().unwrap();
let after: Vec<&String> = seen[before..].iter().map(|(_, body)| body).collect();
assert!(
after.iter().any(|b| b.contains("\"initialize\"")),
"the dead session was reused instead of replaced: {after:?}"
);
}
#[test]
fn an_event_stream_is_read_as_json_rpc() {
let text = ": keep-alive\r\n\r\n\
data: {\"jsonrpc\":\"2.0\",\"id\":7,\r\n\
data: \"result\":{\"ok\":true}}\r\n\r\n";
let value = sse_payload(text, Some(7));
assert_eq!(value["id"], 7);
assert_eq!(value["result"]["ok"], true);
assert_eq!(sse_payload(text, Some(8))["id"], 7);
assert_eq!(sse_payload(": nothing\r\n\r\n", Some(1)), Value::Null);
assert_eq!(sse_payload(text, None)["id"], 7);
}
#[test]
fn a_hanging_server_times_out_and_the_next_call_starts_a_fresh_one() {
if !have_python() {
return;
}
let dir = tempfile::tempdir().unwrap();
let path = script(dir.path(), "fake.py", FAKE);
let (server, _tools) = Server::start(
&spec(&path, 1),
dir.path(),
dir.path(),
DEFAULT_TEST_TIMEOUT,
&Secrets::new(),
)
.expect("the fake server starts");
let started = std::time::Instant::now();
let err = server
.call_tool("echo_text", &json!({"text": "x", "sleep": true}))
.unwrap_err();
assert!(
err.contains("did not answer") && err.contains("1s"),
"the timeout names itself: {err}"
);
assert!(
started.elapsed() < Duration::from_secs(5),
"a hung call returns at the timeout, not when the server wakes up"
);
let out = server
.call_tool("echo_text", &json!({"text": "after"}))
.unwrap();
assert_eq!(out, "echo: after");
}
#[test]
fn a_server_that_dies_is_an_error_with_its_own_stderr() {
if !have_python() {
return;
}
let dir = tempfile::tempdir().unwrap();
let path = script(dir.path(), "dies.py", DIES);
let err = Server::start(
&spec(&path, 5),
dir.path(),
dir.path(),
DEFAULT_TEST_TIMEOUT,
&Secrets::new(),
)
.expect_err("a server that exits during the handshake cannot be used");
assert!(
err.contains("could not open the database"),
"the server's own complaint is the error, not a timeout: {err}"
);
}
#[test]
fn a_policy_override_can_allow_one_tool_and_leave_the_rest_asking() {
let dir = tempfile::tempdir().unwrap();
let mut s = spec(Path::new("/bin/true"), 5);
s.policies.insert("read_text_file".into(), Policy::Allow);
let (server, _) = (
Arc::new(Server {
spec: s.clone(),
plugin_dir: dir.path().to_path_buf(),
workspace: dir.path().to_path_buf(),
timeout: Duration::from_secs(5),
secrets: Secrets::new(),
next_id: AtomicI64::new(1),
state: Mutex::new(None),
handshake: Mutex::new(None),
stderr: Arc::new(Mutex::new(String::new())),
}),
(),
);
assert_eq!(server.policy_for("read_text_file"), Policy::Allow);
assert_eq!(server.policy_for("write_file"), Policy::Ask);
}
#[test]
fn a_cancelled_run_stops_waiting_for_a_server() {
if !have_python() {
return;
}
let dir = tempfile::tempdir().unwrap();
let path = script(dir.path(), "fake.py", FAKE);
let (server, _tools) = Server::start(
&spec(&path, 60),
dir.path(),
dir.path(),
DEFAULT_TEST_TIMEOUT,
&Secrets::new(),
)
.expect("the fake server starts");
let cancel = crate::cancel::Cancel::new();
let flag = cancel.clone();
let canceller = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(150));
flag.cancel();
});
let started = std::time::Instant::now();
let err = server
.call_tool_unless("echo_text", &json!({"text": "x", "sleep": true}), &cancel)
.unwrap_err();
canceller.join().unwrap();
assert!(err.contains("cancelled"), "the reason is the cancel: {err}");
assert!(
started.elapsed() < Duration::from_secs(5),
"the wait ended at the cancel, not at the 60 s timeout: {:.2}s",
started.elapsed().as_secs_f32()
);
let out = server
.call_tool("echo_text", &json!({"text": "after"}))
.unwrap();
assert_eq!(out, "echo: after");
}
#[test]
fn a_result_that_is_not_text_says_so_instead_of_disappearing() {
let text = content_text(&json!({"content": [
{"type": "text", "text": "a"},
{"type": "image", "data": "…"},
{"type": "text", "text": "b"}
]}));
assert_eq!(
text,
"a\n[image content from an MCP server is not shown]\nb"
);
}
}