Skip to main content

eclipse_core/
mcp.rs

1//! MCP: model tools from a server that speaks JSON-RPC, over a pipe or over HTTP.
2//!
3//! Three messages do all the work — `initialize`, `tools/list`, `tools/call` — and everything else
4//! in the protocol (resources, prompts, sampling, roots) is deliberately not implemented: this build
5//! adds tools, and a half-implemented capability is worse than an absent one.
6//!
7//! **Two transports, one shape.** `transport = "stdio"` (the default) starts a process per `[[mcp]]`
8//! entry and speaks newline-delimited JSON-RPC to its stdin/stdout. `transport = "http"` posts the
9//! same messages to `url` — Streamable HTTP, a JSON body or an event stream back, `Mcp-Session-Id`
10//! carried once the server hands one out (`#502`). The reason is not symmetry: a server that speaks
11//! only HTTP (Home Assistant's `mcp_server`) cannot be reached at all otherwise, and the alternative
12//! — spawning `uvx mcp-proxy` to fake a pipe over HTTP — is a second runtime dependency for a
13//! transport this build can speak itself.
14//!
15//! Three decisions worth knowing:
16//!
17//! * **One connection, serialised.** A stdio server is a single pipe: two questions on it at once
18//!   have no way to say which answer is whose beyond the id, and most servers are single-threaded
19//!   anyway. Calls take a mutex, so `[tools] concurrency` buys nothing for MCP and nothing breaks.
20//! * **The server outlives the call, not the process.** It is spawned on first use and killed when
21//!   the agent process ends (or when a call times out, which poisons the pipe). The next call after
22//!   a crash starts it again, so a server that segfaults costs one failed call, not a dead session.
23//! * **Blocking I/O, called from `spawn_blocking`.** The registry is async; the pipe is not. Reading
24//!   a line has no timeout in std, so the timeout is a `recv_timeout` on a channel fed by a reader
25//!   thread — and on timeout the child is killed, which is the only way to unblock a stuck read
26//!   without leaking a thread per hung server.
27
28use 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
43/// The MCP revision this client was written against. A server that answers with another one is
44/// used as it is: `tools/list` and `tools/call` have not changed shape, and refusing an unknown
45/// revision would break on every minor revision for no gain.
46pub const PROTOCOL: &str = "2024-11-05";
47
48/// The `.env` values the config loaded, as a `token_env` variable resolves them (`#516`).
49///
50/// A token variable is looked up in the process environment **first** and here **second** — the
51/// order `doctor`'s credential check and `auth::Credentials::resolve` already use. The order is
52/// the point: a secret stored where eclipse says secrets live must be found by every reader, not
53/// by most of them, and the environment has to stay the way to override one file for one run.
54pub type Secrets = BTreeMap<String, String>;
55
56/// How much of a server's stderr is kept for an error message. Enough to see a stack trace start.
57const STDERR_KEEP: usize = 4_000;
58
59/// How this build reaches a server (`#502`).
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, serde::Serialize)]
61#[serde(rename_all = "lowercase")]
62pub enum Transport {
63    /// A process this build starts, spoken to over its stdin/stdout in newline-delimited JSON-RPC.
64    #[default]
65    Stdio,
66    /// Streamable HTTP: one `POST` per message, answered with a JSON body or an event stream.
67    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/// One `[[mcp]]` entry — in a plugin manifest, or in `config.toml` (`#352`).
80///
81/// Serializing it back out is what lets `config show` print the file it loaded, and what lets
82/// `eclipse mcp add` write an entry the loader reads again.
83#[derive(Debug, Clone, PartialEq, Deserialize, serde::Serialize)]
84#[serde(deny_unknown_fields)]
85pub struct Spec {
86    /// The server's name in `source = "plugin:mcp:<name>"` and in messages.
87    pub name: String,
88    /// How to reach it. The default is what every manifest written before `#502` means.
89    #[serde(default)]
90    pub transport: Transport,
91    /// The program to start, for `transport = "stdio"`. Refused on the HTTP transport.
92    #[serde(default)]
93    pub command: String,
94    #[serde(default)]
95    pub args: Vec<String>,
96    /// Names copied from the agent's environment (never `KEY=VALUE`, so a manifest cannot carry a
97    /// secret and cannot overwrite `PATH` with something it ships).
98    #[serde(default)]
99    pub env: Vec<String>,
100    /// Where the server runs. Defaults to the workspace, like a plugin command.
101    #[serde(default)]
102    pub cwd: crate::plugins::Cwd,
103    /// The endpoint for `transport = "http"`. Required there, refused on stdio.
104    #[serde(default)]
105    pub url: Option<String>,
106    /// The **name of an environment variable** holding a bearer token (`token_env = "HA_TOKEN"`).
107    ///
108    /// Never the token itself: `env` already refuses `KEY=VALUE` so a manifest cannot carry a
109    /// secret, and that property has to survive the HTTP transport or a manifest becomes a place
110    /// where credentials are written down (`#502`).
111    #[serde(default)]
112    pub token_env: Option<String>,
113    /// Ceiling for one call, clamped like any plugin timeout.
114    #[serde(default)]
115    pub timeout_secs: Option<u64>,
116    /// Policy for every tool this server offers; `ask` unless the manifest says otherwise.
117    #[serde(default = "default_policy")]
118    pub policy: Policy,
119    /// Per-tool overrides, by the name the *server* uses: `policies = { read_text_file = "allow" }`.
120    #[serde(default)]
121    pub policies: BTreeMap<String, Policy>,
122    /// Prefix for the registered name, for servers whose tool names are too generic to live beside
123    /// `shell` and `write_file` (`prefix = "fs_"`).
124    #[serde(default)]
125    pub prefix: String,
126    /// Replace a built-in or another plugin's tool of the same name.
127    #[serde(default, rename = "override")]
128    pub override_builtin: bool,
129    /// Do not start this server at all.
130    #[serde(default)]
131    pub disabled: bool,
132}
133
134fn default_policy() -> Policy {
135    Policy::Ask
136}
137
138impl Spec {
139    /// The one place a `[[mcp]]` entry is checked (`#502`), for the transport it names *and* for
140    /// the fields that belong to the other one. An entry that mixes them is refused with a reason
141    /// naming both, rather than a half-ignored setting that looks configured and is not.
142    ///
143    /// The messages use backticks, not quotes: they are read in a terminal next to the file they
144    /// are about, and a key name is clearer in the same style the rest of the errors use.
145    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    /// The token, read from the variable `token_env` names: the process environment first, the
188    /// `secrets` the config loaded from `.env` second (`#516`).
189    ///
190    /// `Ok(None)` when the entry asks for no token; an entry that names a variable neither place
191    /// sets is an error, because the alternative is a 401 that reads like a server problem. The
192    /// refusal names the variable and never the value — a token in an error message is a token in
193    /// a log. An empty value is absent, exactly as `Dotenv::load` treats it.
194    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    /// The variable `token_env` names, trimmed, or `None` when the entry asks for no token.
210    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    /// Where [`Self::token`] would read the token from — the one-word answer a listing shows
218    /// (`#517`), so a server that cannot authenticate says so where it is listed rather than only
219    /// when somebody presses *test*. Never the value.
220    pub fn token_source(&self, secrets: &Secrets) -> TokenSource {
221        let Some(key) = self.token_key() else {
222            return TokenSource::NotUsed;
223        };
224        // The same order, and the same "empty is absent" rule, as `token`: one lookup, described.
225        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/// Where a `token_env` variable resolves, as a word (`#517`). The value itself is never carried
236/// past [`Spec::token`].
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238pub enum TokenSource {
239    /// The entry asks for no token.
240    NotUsed,
241    /// It resolves from the process environment.
242    Env,
243    /// It resolves from the `.env` the config loaded.
244    Dotenv,
245    /// It is named and resolves nowhere: this server cannot authenticate as configured.
246    Unset,
247}
248
249impl TokenSource {
250    /// The word a listing prints. `unset` is the one that means "this will fail".
251    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/// A tool as the server described it, before this build puts it in the registry.
262#[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
271/// A connection to one server: a pipe into a process, or an HTTP endpoint.
272enum Conn {
273    Pipe(Pipe),
274    Http(Http),
275}
276
277/// A process this build started, spoken to in newline-delimited JSON-RPC.
278struct Pipe {
279    child: Child,
280    stdin: ChildStdin,
281    /// Messages the reader thread has parsed and handed over, in arrival order.
282    rx: mpsc::Receiver<Value>,
283}
284
285/// A Streamable HTTP session (`#502`).
286///
287/// There is no process and no pipe: each message is its own `POST`, and the only state the protocol
288/// keeps between them is the session id the server may hand out on `initialize`.
289struct Http {
290    client: reqwest::Client,
291    url: String,
292    /// `Mcp-Session-Id`, once the server has given one out.
293    session: Option<String>,
294    /// The bearer token, already read from the variable `token_env` named.
295    token: Option<String>,
296}
297
298impl Drop for Pipe {
299    fn drop(&mut self) {
300        // Dropping a `Child` leaves it running, so a connection that ends — a timeout, a crash, the
301        // agent exiting — has to say so. This is the only place a server process dies.
302        //
303        // `#418`: killing the *direct* child was not enough. A server started through `npx` or
304        // `sh -c` is a grandchild, it inherits the stdout pipe, and it outlives its parent — so the
305        // reader thread stayed blocked on a pipe nobody would ever write to again, for the life of
306        // the process. The server is started in its own process group, so the group and the tree go
307        // together, and the direct child is still killed for the group-less (non-unix) path.
308        #[cfg(unix)]
309        crate::tools::pgroup::kill_now(self.child.id());
310        let _ = self.child.kill();
311        let _ = self.child.wait();
312    }
313}
314
315/// The longest line a server may send. A JSON-RPC message is a line, and a tool result can be
316/// large — but not gigabytes: `BufReader::lines()` allocated whatever arrived with no newline in
317/// sight, so a server that never sent one could exhaust memory before any cap was consulted
318/// (`#418`). Past this the line is discarded and reported, not buffered.
319const MAX_LINE: usize = 8 * 1024 * 1024;
320
321/// How many parsed messages may wait between the reader thread and the request that reads them.
322/// Unbounded was the default, which let a chatty server queue without limit; a full queue now stops
323/// the reader, which stops the server on its next write — back-pressure instead of growth.
324const LINE_QUEUE: usize = 64;
325
326/// One line, or the fact that it was too long to keep.
327enum Line {
328    Text(String),
329    TooLong(usize),
330}
331
332/// Read one `\n`-terminated line without ever holding more than `max` bytes of it.
333///
334/// `read_until` and `lines()` both grow a `Vec` to whatever the writer sent; this consumes the
335/// buffer as it goes and keeps counting after the cap, so a server that writes a gigabyte without a
336/// newline costs a counter rather than the rest of the machine's memory.
337fn 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
376/// How long a wait may run before it looks at the cancellation flag again. A tool call is a blocking
377/// read on a pipe, so this is the granularity at which a cancelled run stops waiting for one.
378const CANCEL_TICK: Duration = Duration::from_millis(100);
379
380/// One MCP server, shared by the tools it offers.
381pub struct Server {
382    spec: Spec,
383    plugin_dir: PathBuf,
384    workspace: PathBuf,
385    timeout: Duration,
386    /// Where a `token_env` variable is looked up when the process environment does not set it —
387    /// the `.env` values the config loaded (`#516`). Held here because the token is read at
388    /// connect time, which is after the registry that built this server is gone.
389    secrets: Secrets,
390    next_id: AtomicI64,
391    state: Mutex<Option<Conn>>,
392    /// What the server answered `initialize` with — `protocolVersion`, and its own name and
393    /// version. Kept because `eclipse mcp test` is asked to *prove* a server works, and "it listed
394    /// three tools" says nothing about which protocol it speaks (`#352`).
395    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    /// Start a server and ask it what it can do. Blocking on purpose: this runs while a registry is
412    /// being built, outside any turn, and a manifest that names a broken server should say so at
413    /// startup rather than at the first tool call.
414    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        // The server's own `timeout_secs` wins; `[plugins] mcp_timeout_secs` is the machine-wide
422        // default for the ones that do not say. Both are clamped the same way.
423        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    /// The `initialize` result, if the handshake got that far.
451    pub fn handshake(&self) -> Option<Value> {
452        self.handshake
453            .lock()
454            .unwrap_or_else(|e| e.into_inner())
455            .clone()
456    }
457
458    /// Remember the handshake for `mcp test`. First answer wins: a server is started once per
459    /// process, so nothing legitimately writes a second one.
460    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    /// The policy a remote tool gets: its own override, else the server's.
472    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    /// `tools/list`, following `nextCursor` because a server with more than one page of tools is
481    /// not rare (a filesystem server can offer a dozen) and stopping at page one would silently
482    /// hide the rest.
483    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            // Listing happens before a run exists: no flag to honour.
492            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    /// `tools/call`, from a thread that is allowed to block.
512    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    /// [`call_tool`](Self::call_tool) with a run's cancellation flag.
517    ///
518    /// A tool call is not interruptible — it is a blocking read on a pipe — but *waiting* for it is.
519    /// When the run is cancelled the answer has nowhere to go, so the wait stops, the connection is
520    /// dropped (which kills the server) and the caller gets the reason.
521    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            // The server said the *tool* failed. That is a tool error, not a transport error, and
539            // the model reads it as one.
540            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            // An HTTP session has no pipe to poison: a failed post leaves nothing half-read, so
562            // the next call posts again and finds out for itself (`#502`).
563            Conn::Http(http) => (
564                self.exchange_http(http, id, method, &message, cancel),
565                false,
566            ),
567        };
568        if poison {
569            // Dropping the connection kills the process; the answer to this id may still be on
570            // the pipe and every later request would read it.
571            *guard = None;
572        }
573        outcome
574    }
575
576    /// Write one message to the server's stdin without letting a dead server kill the process.
577    ///
578    /// The CLI sets `SIGPIPE` to `SIG_DFL` on purpose (so `eclipse … | head` exits quietly instead
579    /// of panicking on a closed stdout). The cost is that a write to a pipe whose reader has gone
580    /// is a *signal*, not an `EPIPE` error — a server that exits before we finish writing to it
581    /// takes the whole agent down with it, silently. That is now the ordinary case, not a corner:
582    /// `eclipse mcp list` starts every server it lists, so one broken entry killed the command
583    /// that was supposed to report it.
584    ///
585    /// Blocking the signal with `pthread_sigmask` does **not** fix this: a signal is delivered to
586    /// any thread that has it unblocked, and the runtime has reader threads by the time a server is
587    /// started. So the disposition is switched to `SIG_IGN` for the duration of the write — which
588    /// discards the signal instead of queueing it — and put back afterwards. Ignored signals are
589    /// dropped rather than left pending, so nothing is delivered late. The lock is there because
590    /// swapping a process-wide disposition twice is not something two writers may interleave.
591    fn write_stdin(
592        &self,
593        stdin: &mut std::process::ChildStdin,
594        message: &str,
595    ) -> std::io::Result<()> {
596        #[cfg(unix)]
597        // SAFETY: `signal` with `SIG_IGN`, a previously returned handler, or `SIG_DFL` is sound for
598        // any disposition; the lock keeps the swap from interleaving with another writer's.
599        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    /// One exchange on a pipe, and whether it poisoned it.
614    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                    // A short tick, so a cancel is noticed while waiting. Only the real deadline is
658                    // the server's failure.
659                    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    /// One exchange over Streamable HTTP (`#502`).
685    ///
686    /// The message is posted as the whole body; the answer is either a JSON body or an event
687    /// stream, and both are parsed here so `request` does not have to care which arrived.
688    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            // A server that answers a request with a notification and nothing else has not
702            // answered it. Say that rather than looping for an answer that is not coming.
703            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    /// A connection, or a new one: a server that died (crashed, was killed) is replaced here, which
711    /// is what makes "crash restarts on next call" true without any supervision thread.
712    fn ensure(&self, slot: &mut Option<Conn>) -> Result<(), String> {
713        let alive = match slot.as_mut() {
714            // A process that exited — crash, kill, `sh -c` that never started the real server — is
715            // replaced here, which is what makes "a crash costs one call" true without a supervisor.
716            Some(Conn::Pipe(pipe)) => matches!(pipe.child.try_wait(), Ok(None)),
717            // An HTTP session has no process to watch: whether it still works is what the next
718            // post finds out (`#502`).
719            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    /// Open the connection the entry asks for — a process, or an HTTP session — and say hello on
732    /// it. A connection is only published once it has answered `initialize`.
733    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    /// The Streamable HTTP handshake (`#502`): `initialize`, keep the session id it hands out, then
742    /// `notifications/initialized` — carried *with* that id, because a server that issued one
743    /// rejects the next post without it.
744    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        // Before anything else: a server that handed out a session id wants it on every later
777        // post, the notification included.
778        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    /// One `POST` carrying `message`, and whatever came back (`#502`).
816    ///
817    /// The exchange runs on a runtime of its own in a thread of its own. This module is synchronous
818    /// by design — a pipe has no other option — so the async client is confined to the one place
819    /// that needs it instead of leaking a runtime requirement into every caller. The calling thread
820    /// waits on a channel with the same tick the pipe uses, so a cancelled run stops waiting here
821    /// exactly as it stops there.
822    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        // The runtime enforces `timeout` on the request itself; this is the ceiling for a thread
840        // that never gets that far, so a hung connect is still a bounded wait.
841        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    /// Start the process and say hello to it. The handshake lives here rather than in `request`
868    /// because `request` holds the state mutex and taking it again from inside `ensure` would
869    /// deadlock (std mutexes are not reentrant).
870    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        // `#418`: its own process group, so `Conn::drop` can take the whole tree down. Without it a
891        // server started through `npx` leaves a grandchild holding the pipe.
892        #[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        // A server's stderr is its log. Reading it on a thread keeps a chatty server from filling the
903        // pipe and blocking on its own writes, and keeps the tail for the error message when
904        // something goes wrong.
905        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                    // A line this build cannot keep is a message the caller never sees; saying so is
932                    // better than a request that waits out its timeout for an answer already thrown
933                    // away (`#418`).
934                    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                // A server that writes a line this build cannot parse is not silent: the caller
953                // gets "not JSON" rather than a timeout three minutes later.
954                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        // Required by the protocol once the client is satisfied, and servers do wait for it before
999        // answering `tools/list`.
1000        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    /// [`stderr_tail`](Self::stderr_tail) for a pipe that has just failed: the reader thread may not
1014    /// have been scheduled yet, and "Broken pipe" alone is a much worse error than the server's own
1015    /// complaint that follows it a millisecond later. Waits up to 200 ms, and only when the tail is
1016    /// still empty.
1017    fn stderr_tail_soon(&self) -> String {
1018        let mut tail = self.stderr_tail();
1019        // 200 ms was not always enough for a thread to be *scheduled* on a loaded machine, and the
1020        // test that asserts this text went red about once a full-suite run. Half a second costs
1021        // nothing on the happy path — the loop breaks as soon as there is something to say.
1022        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
1043/// The answer to one POST: the JSON-RPC message, and the session id the server may have issued.
1044struct Reply {
1045    value: Value,
1046    session: Option<String>,
1047}
1048
1049/// The whole HTTP exchange, on a runtime this thread builds and drops (`#502`).
1050fn 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            // No child process and no stderr to harvest: the status and the body *are* the report.
1102            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            // A notification is answered with `202 Accepted` and no body; that is a success.
1114            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
1133/// The JSON-RPC message inside an event stream.
1134///
1135/// Streamable HTTP answers a `POST` with `text/event-stream`: one event per message, its JSON on
1136/// `data:` lines. This picks the message whose id is `id`, and for a notification — which carries
1137/// no id — the last message in the stream. An event with no `data:` is a keep-alive or a comment.
1138fn 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
1167/// What a message from a server is, with respect to the request being waited for.
1168enum Answer {
1169    /// Not this request's answer: a notification (`notifications/tools/list_changed`), or the
1170    /// answer to a message this build has already given up on. On a pipe both arrive at the same
1171    /// place and the id is the only thing that says which is which.
1172    NotMine,
1173    /// A line that could not be parsed as JSON.
1174    Unparsable(String),
1175    /// The answer.
1176    Value(Value),
1177    /// The server's own error for this request.
1178    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
1198/// Wait for the answer to `id` on a connection that is not yet in `state` (the handshake).
1199fn 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
1253/// The text a `tools/call` result carries. Anything that is not text (an image, an embedded
1254/// resource) is named rather than dropped: silently losing half an answer is worse than saying the
1255/// dashboard cannot show it.
1256fn content_text(result: &Value) -> String {
1257    let Some(items) = result.get("content").and_then(Value::as_array) else {
1258        // Some servers answer with a bare string or with `structuredContent`; take what is there.
1259        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
1292/// A tool the agent can call, implemented by a remote MCP server.
1293pub struct McpTool {
1294    /// The name this build registered (`prefix` + the server's name).
1295    name: String,
1296    /// The name the server knows.
1297    remote: String,
1298    description: String,
1299    parameters: Value,
1300    plugin: String,
1301    server: Arc<Server>,
1302}
1303
1304/// The most a tool name may be. OpenAI-compatible endpoints cap it at 64 characters and reject the
1305/// whole request past it — the same ceiling the config's tool ids live under.
1306pub const TOOL_NAME_MAX: usize = 64;
1307
1308/// What a remote description is cut to. A description is worth a sentence or two of prompt; a
1309/// server that sends its whole README should not get to charge that to every request.
1310pub const DESCRIPTION_MAX: usize = 2000;
1311
1312/// What a remote input schema may serialize to. See `McpTool::new` for what happens past it.
1313pub const SCHEMA_MAX: usize = 16 * 1024;
1314
1315/// A remote tool name, made safe to put in a chat request.
1316///
1317/// A third-party server names its own tools, and a name is not a private detail: it is copied into
1318/// the `tools` array of every request, and one name outside `[A-Za-z0-9_-]` makes an
1319/// OpenAI-compatible endpoint reject the entire request — so the agent is unusable and the error
1320/// names the model, not the server. Anything outside the alphabet becomes `_`, and the result is
1321/// truncated to `TOOL_NAME_MAX`; the raw name still goes to the server on the wire.
1322pub 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
1336/// Text cut to at most `max` **chars**, with a mark saying it was cut, so a truncated description
1337/// cannot be mistaken for the whole one.
1338fn 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    /// The one path a call goes through. The pipe blocks, so it runs on a blocking thread — and the
1349    /// run's cancellation flag travels with it, because a cancelled run must not sit here for a
1350    /// minute waiting for an answer nothing will read.
1351    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        // `#373`: a remote name goes into the `tools` array of every chat request, and an
1367        // OpenAI-compatible server rejects the *whole request* with a 400 on the first name outside
1368        // `[A-Za-z0-9_-]` — one third-party server, one advertised `a.b` or `get repo`, and the
1369        // session is unusable with an error that names no server. Plugin command tools are already
1370        // held to that alphabet; a server's tools are held to it here, and the raw name is kept for
1371        // the wire (`remote`), which is the only place it is correct.
1372        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        // A tool's schema is copied into the prompt verbatim; a server that ships a megabyte of it
1383        // costs that much of every request in the session. Past the cap the model is told the tool
1384        // takes an object and the description says so — better than a prompt nobody can afford, and
1385        // better than a silent downgrade the model has no way to notice.
1386        let over_cap = serde_json::to_string(&parameters).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    /// A server's own name, for a message that has to name where a tool came from.
1410    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        // The prompt has to say *which* server this is going to: `read_text_file` is a harmless name
1431        // on a filesystem server and something else entirely elsewhere.
1432        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        // The run's own flag: a cancelled run must not sit waiting for a server that is still
1450        // thinking, and the answer would have nowhere to go anyway.
1451        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    /// The default a `[[mcp]]` entry with no `timeout_secs` would get. The tests all state their
1461    /// own ceiling in the spec, so this only has to be a sane number.
1462    const DEFAULT_TEST_TIMEOUT: Duration = Duration::from_secs(10);
1463
1464    /// A server that speaks just enough of the protocol, so the client can be tested without a
1465    /// network or a real MCP implementation. `sleep` on a call hangs it, which is what a timeout is
1466    /// for; two pages of tools exercise `nextCursor`.
1467    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    /// A Streamable HTTP server, hand-rolled on a socket (`#502`).
1511    ///
1512    /// The subject here is the *transport*, not MCP: what a real server does with a message is
1513    /// already covered by `FAKE`. So this answers from the request line and the body alone, and it
1514    /// answers in the two shapes the protocol allows — a JSON body for `tools/call`, an event
1515    /// stream for `tools/list` — so both parsers are exercised by one passing run.
1516    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            // Unblock the accept: a connection that is never answered is the thread's exit ticket.
1526            let _ = std::net::TcpStream::connect(("127.0.0.1", self.port));
1527        }
1528    }
1529
1530    impl FakeHttp {
1531        /// `token`: when set, the server answers 401 unless the request carries it.
1532        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    /// Read one request: the head, and `Content-Length` bytes of body.
1566    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        // The session id is the whole point of the handshake: everything after `initialize` must
1631        // carry it back.
1632        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            // A notification is answered with an accepted-and-empty body.
1650            "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                // An event stream, with a keep-alive comment first: a parser that treats every
1667                // line as a message would answer with null here.
1668                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    /// An HTTP entry with the fields the transport needs, and nothing else.
1718    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    /// A server that dies before saying anything: the failure has to arrive as an error with the
1738    /// reason, not as a hang.
1739    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    /// `#373`: a remote server names its own tools, and that name is copied into the `tools` array of
1784    /// every chat request. An OpenAI-compatible endpoint rejects the *whole request* on the first name
1785    /// outside `[A-Za-z0-9_-]`, so one third-party server advertising `get repo` left the agent
1786    /// unusable for the session with an error naming the model rather than the server.
1787    #[test]
1788    fn a_remote_tool_name_is_made_safe_for_a_request() {
1789        // The alphabet is the one plugin command tools are already held to.
1790        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        // Long names are cut, not rejected: a 64-character ceiling is what the endpoint enforces.
1795        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        // A description and a schema are copied into the prompt too.
1805        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    /// The name the endpoint sees is safe; the name the *server* is asked for is the one it
1813    /// published — those are two different strings and both have to be right.
1814    #[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    /// `#418`: `BufReader::lines()` grew a `Vec` to whatever the writer sent, so a server that wrote
1843    /// a gigabyte without a newline cost a gigabyte before any cap was consulted. The reader keeps
1844    /// at most `MAX_LINE` bytes and counts the rest.
1845    #[test]
1846    fn a_line_over_the_cap_is_counted_and_dropped_not_buffered() {
1847        // A line that never ends, 4× the cap.
1848        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        // And an ordinary line still arrives whole, with the newline consumed.
1856        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    /// `#418`: killing only the direct child left the real server running when it was started
1869    /// through `npx`/`sh -c` — the grandchild held the stdout pipe, so the reader thread stayed
1870    /// blocked on it for the life of the process. The server is in its own process group now and
1871    /// the drop takes the tree with it.
1872    #[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        // The group kill is synchronous inside `Drop`, but a pid can linger as a zombie if it was
1909        // not reaped by its own parent; `pid_alive` treats a zombie as gone. What this asserts is
1910        // that the tree is gone — not that it went in the same second. The window used to be one
1911        // second, which failed about once in ten whole-suite runs on a loaded runner (`#432`) while
1912        // never failing alone: a pid is reaped when its own parent dies, and under contention that
1913        // bookkeeping is not what the scheduler is spending its time on.
1914        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        // SAFETY: signal 0 asks the kernel whether the pid exists.
1931        let rc = unsafe { libc::kill(pid, 0) };
1932        if rc != 0 {
1933            return false;
1934        }
1935        // A zombie still answers signal 0; read its state and call it gone.
1936        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        // Both pages: stopping at the first would have hidden `fail_tool` entirely.
1961        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        // One connection for both calls: the second answer must not be read from the first's pipe.
1968        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        // A tool that reports failure is an error the model reads, with the server's own words.
1978        let err = server.call_tool("fail_tool", &json!({})).unwrap_err();
1979        assert_eq!(err, "the disk is on fire");
1980    }
1981
1982    /// `#502`: the transport itself — list across two pages over an event stream, call over a JSON
1983    /// body, and the session id carried back on every post after `initialize`.
1984    #[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        // A tool that reports failure is an error the model reads, with the server's own words —
2011        // the same as on stdio, because that decision is above the transport.
2012        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        // Every post after the handshake carries the id the server issued, or the fake answers
2020        // 400 — which is why the calls above would have failed rather than passed.
2021        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        // Page two is a `cursor` in the request: the client has to send back what it was given.
2039        assert!(
2040            requests[3].1.contains("\"cursor\""),
2041            "the second page is asked for by cursor: {}",
2042            requests[3].1
2043        );
2044    }
2045
2046    /// A server that does not accept us says so with its status, not with a timeout.
2047    #[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        // A name built at runtime, so this stays a test detail rather than a variable the build
2052        // is documented to read (`every_environment_variable_the_build_reads_is_classified`).
2053        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        // The right token gets through — the same entry, one variable changed.
2069        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    /// `#516`: a token in `.env` is a token. The config parses that file into `Dotenv.values` and
2082    /// never touches the process environment, so `token_env` used to be the one credential that
2083    /// could not see a secret stored where eclipse says secrets live. The assertion is on what
2084    /// went over the wire, not on a log.
2085    #[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    /// The other half of the order: the process environment wins, so one run can override one
2114    /// file without editing it.
2115    #[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    /// An empty value is absent, as it is in `Dotenv::load` — and the refusal names the variable
2148    /// without printing any other secret that happens to be resolved.
2149    #[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    /// A variable the environment does not set is an error naming it: the alternative is a 401
2181    /// that reads like the server's fault.
2182    #[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    /// The one place a `[[mcp]]` entry is checked, both ways round.
2206    #[test]
2207    fn a_manifest_that_mixes_transports_is_refused_naming_both() {
2208        // Default is stdio, so every manifest written before `#502` still means what it meant.
2209        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        // A stdio entry with a url is a mix too, and says which half to drop.
2235        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        // A scheme this client cannot speak is refused before anything is posted.
2242        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    /// The event-stream parser: a keep-alive, a comment, and a message split over two `data:` lines
2248    /// with CRLF endings — the shapes a real server puts on the wire.
2249    #[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        // A message for another id is not the answer to this one, and null is not an answer at all.
2259        assert_eq!(sse_payload(text, Some(8))["id"], 7);
2260        assert_eq!(sse_payload(": nothing\r\n\r\n", Some(1)), Value::Null);
2261        // No id asked for — a notification's answer — means the last message wins.
2262        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        // The poisoned connection was killed, so this is a new process talking to the same server.
2295        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        // No server is started here: the policy is manifest data, and asking for it should not
2328        // need a process.
2329        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        // The fake hangs a call for 30 s. A cancelled run cannot interrupt a blocking read, but it
2350        // must stop *waiting*: the answer has nowhere to go, and the next call starts a fresh server
2351        // anyway.
2352        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        // A server stopped for a cancel is a server stopped: the next call starts another one.
2383        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}